Coverage Report

Created: 2024-01-17 10:31

/src/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 "ExprConstShared.h"
36
#include "Interp/Context.h"
37
#include "Interp/Frame.h"
38
#include "Interp/State.h"
39
#include "clang/AST/APValue.h"
40
#include "clang/AST/ASTContext.h"
41
#include "clang/AST/ASTDiagnostic.h"
42
#include "clang/AST/ASTLambda.h"
43
#include "clang/AST/Attr.h"
44
#include "clang/AST/CXXInheritance.h"
45
#include "clang/AST/CharUnits.h"
46
#include "clang/AST/CurrentSourceLocExprScope.h"
47
#include "clang/AST/Expr.h"
48
#include "clang/AST/OSLog.h"
49
#include "clang/AST/OptionalDiagnostic.h"
50
#include "clang/AST/RecordLayout.h"
51
#include "clang/AST/StmtVisitor.h"
52
#include "clang/AST/TypeLoc.h"
53
#include "clang/Basic/Builtins.h"
54
#include "clang/Basic/DiagnosticSema.h"
55
#include "clang/Basic/TargetInfo.h"
56
#include "llvm/ADT/APFixedPoint.h"
57
#include "llvm/ADT/SmallBitVector.h"
58
#include "llvm/ADT/StringExtras.h"
59
#include "llvm/Support/Debug.h"
60
#include "llvm/Support/SaveAndRestore.h"
61
#include "llvm/Support/TimeProfiler.h"
62
#include "llvm/Support/raw_ostream.h"
63
#include <cstring>
64
#include <functional>
65
#include <optional>
66
67
#define DEBUG_TYPE "exprconstant"
68
69
using namespace clang;
70
using llvm::APFixedPoint;
71
using llvm::APInt;
72
using llvm::APSInt;
73
using llvm::APFloat;
74
using llvm::FixedPointSemantics;
75
76
namespace {
77
  struct LValue;
78
  class CallStackFrame;
79
  class EvalInfo;
80
81
  using SourceLocExprScopeGuard =
82
      CurrentSourceLocExprScope::SourceLocExprScopeGuard;
83
84
22
  static QualType getType(APValue::LValueBase B) {
85
22
    return B.getType();
86
22
  }
87
88
  /// Get an LValue path entry, which is known to not be an array index, as a
89
  /// field declaration.
90
0
  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
91
0
    return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
92
0
  }
93
  /// Get an LValue path entry, which is known to not be an array index, as a
94
  /// base class declaration.
95
0
  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
96
0
    return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
97
0
  }
98
  /// Determine whether this LValue path entry for a base class names a virtual
99
  /// base class.
100
0
  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
101
0
    return E.getAsBaseOrMember().getInt();
102
0
  }
103
104
  /// Given an expression, determine the type used to store the result of
105
  /// evaluating that expression.
106
0
  static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
107
0
    if (E->isPRValue())
108
0
      return E->getType();
109
0
    return Ctx.getLValueReferenceType(E->getType());
110
0
  }
111
112
  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113
0
  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114
0
    if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
115
0
      return DirectCallee->getAttr<AllocSizeAttr>();
116
0
    if (const Decl *IndirectCallee = CE->getCalleeDecl())
117
0
      return IndirectCallee->getAttr<AllocSizeAttr>();
118
0
    return nullptr;
119
0
  }
120
121
  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
122
  /// This will look through a single cast.
123
  ///
124
  /// Returns null if we couldn't unwrap a function with alloc_size.
125
0
  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
126
0
    if (!E->getType()->isPointerType())
127
0
      return nullptr;
128
129
0
    E = E->IgnoreParens();
130
    // If we're doing a variable assignment from e.g. malloc(N), there will
131
    // probably be a cast of some kind. In exotic cases, we might also see a
132
    // top-level ExprWithCleanups. Ignore them either way.
133
0
    if (const auto *FE = dyn_cast<FullExpr>(E))
134
0
      E = FE->getSubExpr()->IgnoreParens();
135
136
0
    if (const auto *Cast = dyn_cast<CastExpr>(E))
137
0
      E = Cast->getSubExpr()->IgnoreParens();
138
139
0
    if (const auto *CE = dyn_cast<CallExpr>(E))
140
0
      return getAllocSizeAttr(CE) ? CE : nullptr;
141
0
    return nullptr;
142
0
  }
143
144
  /// Determines whether or not the given Base contains a call to a function
145
  /// with the alloc_size attribute.
146
4
  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
147
4
    const auto *E = Base.dyn_cast<const Expr *>();
148
4
    return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
149
4
  }
150
151
  /// Determines whether the given kind of constant expression is only ever
152
  /// used for name mangling. If so, it's permitted to reference things that we
153
  /// can't generate code for (in particular, dllimported functions).
154
0
  static bool isForManglingOnly(ConstantExprKind Kind) {
155
0
    switch (Kind) {
156
0
    case ConstantExprKind::Normal:
157
0
    case ConstantExprKind::ClassTemplateArgument:
158
0
    case ConstantExprKind::ImmediateInvocation:
159
      // Note that non-type template arguments of class type are emitted as
160
      // template parameter objects.
161
0
      return false;
162
163
0
    case ConstantExprKind::NonClassTemplateArgument:
164
0
      return true;
165
0
    }
166
0
    llvm_unreachable("unknown ConstantExprKind");
167
0
  }
168
169
0
  static bool isTemplateArgument(ConstantExprKind Kind) {
170
0
    switch (Kind) {
171
0
    case ConstantExprKind::Normal:
172
0
    case ConstantExprKind::ImmediateInvocation:
173
0
      return false;
174
175
0
    case ConstantExprKind::ClassTemplateArgument:
176
0
    case ConstantExprKind::NonClassTemplateArgument:
177
0
      return true;
178
0
    }
179
0
    llvm_unreachable("unknown ConstantExprKind");
180
0
  }
181
182
  /// The bound to claim that an array of unknown bound has.
183
  /// The value in MostDerivedArraySize is undefined in this case. So, set it
184
  /// to an arbitrary value that's likely to loudly break things if it's used.
185
  static const uint64_t AssumedSizeForUnsizedArray =
186
      std::numeric_limits<uint64_t>::max() / 2;
187
188
  /// Determines if an LValue with the given LValueBase will have an unsized
189
  /// array in its designator.
190
  /// Find the path length and type of the most-derived subobject in the given
191
  /// path, and find the size of the containing array, if any.
192
  static unsigned
193
  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
194
                           ArrayRef<APValue::LValuePathEntry> Path,
195
                           uint64_t &ArraySize, QualType &Type, bool &IsArray,
196
4
                           bool &FirstEntryIsUnsizedArray) {
197
    // This only accepts LValueBases from APValues, and APValues don't support
198
    // arrays that lack size info.
199
4
    assert(!isBaseAnAllocSizeCall(Base) &&
200
4
           "Unsized arrays shouldn't appear here");
201
0
    unsigned MostDerivedLength = 0;
202
4
    Type = getType(Base);
203
204
4
    for (unsigned I = 0, N = Path.size(); I != N; ++I) {
205
0
      if (Type->isArrayType()) {
206
0
        const ArrayType *AT = Ctx.getAsArrayType(Type);
207
0
        Type = AT->getElementType();
208
0
        MostDerivedLength = I + 1;
209
0
        IsArray = true;
210
211
0
        if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
212
0
          ArraySize = CAT->getSize().getZExtValue();
213
0
        } else {
214
0
          assert(I == 0 && "unexpected unsized array designator");
215
0
          FirstEntryIsUnsizedArray = true;
216
0
          ArraySize = AssumedSizeForUnsizedArray;
217
0
        }
218
0
      } else if (Type->isAnyComplexType()) {
219
0
        const ComplexType *CT = Type->castAs<ComplexType>();
220
0
        Type = CT->getElementType();
221
0
        ArraySize = 2;
222
0
        MostDerivedLength = I + 1;
223
0
        IsArray = true;
224
0
      } else if (const FieldDecl *FD = getAsField(Path[I])) {
225
0
        Type = FD->getType();
226
0
        ArraySize = 0;
227
0
        MostDerivedLength = I + 1;
228
0
        IsArray = false;
229
0
      } else {
230
        // Path[I] describes a base class.
231
0
        ArraySize = 0;
232
0
        IsArray = false;
233
0
      }
234
0
    }
235
4
    return MostDerivedLength;
236
4
  }
237
238
  /// A path from a glvalue to a subobject of that glvalue.
239
  struct SubobjectDesignator {
240
    /// True if the subobject was named in a manner not supported by C++11. Such
241
    /// lvalues can still be folded, but they are not core constant expressions
242
    /// and we cannot perform lvalue-to-rvalue conversions on them.
243
    unsigned Invalid : 1;
244
245
    /// Is this a pointer one past the end of an object?
246
    unsigned IsOnePastTheEnd : 1;
247
248
    /// Indicator of whether the first entry is an unsized array.
249
    unsigned FirstEntryIsAnUnsizedArray : 1;
250
251
    /// Indicator of whether the most-derived object is an array element.
252
    unsigned MostDerivedIsArrayElement : 1;
253
254
    /// The length of the path to the most-derived object of which this is a
255
    /// subobject.
256
    unsigned MostDerivedPathLength : 28;
257
258
    /// The size of the array of which the most-derived object is an element.
259
    /// This will always be 0 if the most-derived object is not an array
260
    /// element. 0 is not an indicator of whether or not the most-derived object
261
    /// is an array, however, because 0-length arrays are allowed.
262
    ///
263
    /// If the current array is an unsized array, the value of this is
264
    /// undefined.
265
    uint64_t MostDerivedArraySize;
266
267
    /// The type of the most derived object referred to by this address.
268
    QualType MostDerivedType;
269
270
    typedef APValue::LValuePathEntry PathEntry;
271
272
    /// The entries on the path from the glvalue to the designated subobject.
273
    SmallVector<PathEntry, 8> Entries;
274
275
14
    SubobjectDesignator() : Invalid(true) {}
276
277
    explicit SubobjectDesignator(QualType T)
278
        : Invalid(false), IsOnePastTheEnd(false),
279
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280
          MostDerivedPathLength(0), MostDerivedArraySize(0),
281
9
          MostDerivedType(T) {}
282
283
    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
284
        : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
285
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
286
4
          MostDerivedPathLength(0), MostDerivedArraySize(0) {
287
4
      assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
288
4
      if (!Invalid) {
289
4
        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
290
4
        ArrayRef<PathEntry> VEntries = V.getLValuePath();
291
4
        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
292
4
        if (V.getLValueBase()) {
293
4
          bool IsArray = false;
294
4
          bool FirstIsUnsizedArray = false;
295
4
          MostDerivedPathLength = findMostDerivedSubobject(
296
4
              Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
297
4
              MostDerivedType, IsArray, FirstIsUnsizedArray);
298
4
          MostDerivedIsArrayElement = IsArray;
299
4
          FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
300
4
        }
301
4
      }
302
4
    }
303
304
    void truncate(ASTContext &Ctx, APValue::LValueBase Base,
305
0
                  unsigned NewLength) {
306
0
      if (Invalid)
307
0
        return;
308
309
0
      assert(Base && "cannot truncate path for null pointer");
310
0
      assert(NewLength <= Entries.size() && "not a truncation");
311
312
0
      if (NewLength == Entries.size())
313
0
        return;
314
0
      Entries.resize(NewLength);
315
316
0
      bool IsArray = false;
317
0
      bool FirstIsUnsizedArray = false;
318
0
      MostDerivedPathLength = findMostDerivedSubobject(
319
0
          Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
320
0
          FirstIsUnsizedArray);
321
0
      MostDerivedIsArrayElement = IsArray;
322
0
      FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323
0
    }
324
325
0
    void setInvalid() {
326
0
      Invalid = true;
327
0
      Entries.clear();
328
0
    }
329
330
    /// Determine whether the most derived subobject is an array without a
331
    /// known bound.
332
0
    bool isMostDerivedAnUnsizedArray() const {
333
0
      assert(!Invalid && "Calling this makes no sense on invalid designators");
334
0
      return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
335
0
    }
336
337
    /// Determine what the most derived array's size is. Results in an assertion
338
    /// failure if the most derived array lacks a size.
339
0
    uint64_t getMostDerivedArraySize() const {
340
0
      assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
341
0
      return MostDerivedArraySize;
342
0
    }
343
344
    /// Determine whether this is a one-past-the-end pointer.
345
0
    bool isOnePastTheEnd() const {
346
0
      assert(!Invalid);
347
0
      if (IsOnePastTheEnd)
348
0
        return true;
349
0
      if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
350
0
          Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
351
0
              MostDerivedArraySize)
352
0
        return true;
353
0
      return false;
354
0
    }
355
356
    /// Get the range of valid index adjustments in the form
357
    ///   {maximum value that can be subtracted from this pointer,
358
    ///    maximum value that can be added to this pointer}
359
0
    std::pair<uint64_t, uint64_t> validIndexAdjustments() {
360
0
      if (Invalid || isMostDerivedAnUnsizedArray())
361
0
        return {0, 0};
362
363
      // [expr.add]p4: For the purposes of these operators, a pointer to a
364
      // nonarray object behaves the same as a pointer to the first element of
365
      // an array of length one with the type of the object as its element type.
366
0
      bool IsArray = MostDerivedPathLength == Entries.size() &&
367
0
                     MostDerivedIsArrayElement;
368
0
      uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
369
0
                                    : (uint64_t)IsOnePastTheEnd;
370
0
      uint64_t ArraySize =
371
0
          IsArray ? getMostDerivedArraySize() : (uint64_t)1;
372
0
      return {ArrayIndex, ArraySize - ArrayIndex};
373
0
    }
374
375
    /// Check that this refers to a valid subobject.
376
0
    bool isValidSubobject() const {
377
0
      if (Invalid)
378
0
        return false;
379
0
      return !isOnePastTheEnd();
380
0
    }
381
    /// Check that this refers to a valid subobject, and if not, produce a
382
    /// relevant diagnostic and set the designator as invalid.
383
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
384
385
    /// Get the type of the designated object.
386
0
    QualType getType(ASTContext &Ctx) const {
387
0
      assert(!Invalid && "invalid designator has no subobject type");
388
0
      return MostDerivedPathLength == Entries.size()
389
0
                 ? MostDerivedType
390
0
                 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
391
0
    }
392
393
    /// Update this designator to refer to the first element within this array.
394
0
    void addArrayUnchecked(const ConstantArrayType *CAT) {
395
0
      Entries.push_back(PathEntry::ArrayIndex(0));
396
397
      // This is a most-derived object.
398
0
      MostDerivedType = CAT->getElementType();
399
0
      MostDerivedIsArrayElement = true;
400
0
      MostDerivedArraySize = CAT->getSize().getZExtValue();
401
0
      MostDerivedPathLength = Entries.size();
402
0
    }
403
    /// Update this designator to refer to the first element within the array of
404
    /// elements of type T. This is an array of unknown size.
405
0
    void addUnsizedArrayUnchecked(QualType ElemTy) {
406
0
      Entries.push_back(PathEntry::ArrayIndex(0));
407
408
0
      MostDerivedType = ElemTy;
409
0
      MostDerivedIsArrayElement = true;
410
      // The value in MostDerivedArraySize is undefined in this case. So, set it
411
      // to an arbitrary value that's likely to loudly break things if it's
412
      // used.
413
0
      MostDerivedArraySize = AssumedSizeForUnsizedArray;
414
0
      MostDerivedPathLength = Entries.size();
415
0
    }
416
    /// Update this designator to refer to the given base or member of this
417
    /// object.
418
0
    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
419
0
      Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
420
421
      // If this isn't a base class, it's a new most-derived object.
422
0
      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
423
0
        MostDerivedType = FD->getType();
424
0
        MostDerivedIsArrayElement = false;
425
0
        MostDerivedArraySize = 0;
426
0
        MostDerivedPathLength = Entries.size();
427
0
      }
428
0
    }
429
    /// Update this designator to refer to the given complex component.
430
0
    void addComplexUnchecked(QualType EltTy, bool Imag) {
431
0
      Entries.push_back(PathEntry::ArrayIndex(Imag));
432
433
      // This is technically a most-derived object, though in practice this
434
      // is unlikely to matter.
435
0
      MostDerivedType = EltTy;
436
0
      MostDerivedIsArrayElement = true;
437
0
      MostDerivedArraySize = 2;
438
0
      MostDerivedPathLength = Entries.size();
439
0
    }
440
    void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
441
    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
442
                                   const APSInt &N);
443
    /// Add N to the address of this subobject.
444
0
    void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
445
0
      if (Invalid || !N) return;
446
0
      uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
447
0
      if (isMostDerivedAnUnsizedArray()) {
448
0
        diagnoseUnsizedArrayPointerArithmetic(Info, E);
449
        // Can't verify -- trust that the user is doing the right thing (or if
450
        // not, trust that the caller will catch the bad behavior).
451
        // FIXME: Should we reject if this overflows, at least?
452
0
        Entries.back() = PathEntry::ArrayIndex(
453
0
            Entries.back().getAsArrayIndex() + TruncatedN);
454
0
        return;
455
0
      }
456
457
      // [expr.add]p4: For the purposes of these operators, a pointer to a
458
      // nonarray object behaves the same as a pointer to the first element of
459
      // an array of length one with the type of the object as its element type.
460
0
      bool IsArray = MostDerivedPathLength == Entries.size() &&
461
0
                     MostDerivedIsArrayElement;
462
0
      uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
463
0
                                    : (uint64_t)IsOnePastTheEnd;
464
0
      uint64_t ArraySize =
465
0
          IsArray ? getMostDerivedArraySize() : (uint64_t)1;
466
467
0
      if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
468
        // Calculate the actual index in a wide enough type, so we can include
469
        // it in the note.
470
0
        N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
471
0
        (llvm::APInt&)N += ArrayIndex;
472
0
        assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
473
0
        diagnosePointerArithmetic(Info, E, N);
474
0
        setInvalid();
475
0
        return;
476
0
      }
477
478
0
      ArrayIndex += TruncatedN;
479
0
      assert(ArrayIndex <= ArraySize &&
480
0
             "bounds check succeeded for out-of-bounds index");
481
482
0
      if (IsArray)
483
0
        Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
484
0
      else
485
0
        IsOnePastTheEnd = (ArrayIndex != 0);
486
0
    }
487
  };
488
489
  /// A scope at the end of which an object can need to be destroyed.
490
  enum class ScopeKind {
491
    Block,
492
    FullExpression,
493
    Call
494
  };
495
496
  /// A reference to a particular call and its arguments.
497
  struct CallRef {
498
18
    CallRef() : OrigCallee(), CallIndex(0), Version() {}
499
    CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
500
0
        : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
501
502
0
    explicit operator bool() const { return OrigCallee; }
503
504
    /// Get the parameter that the caller initialized, corresponding to the
505
    /// given parameter in the callee.
506
0
    const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
507
0
      return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
508
0
                        : PVD;
509
0
    }
510
511
    /// The callee at the point where the arguments were evaluated. This might
512
    /// be different from the actual callee (a different redeclaration, or a
513
    /// virtual override), but this function's parameters are the ones that
514
    /// appear in the parameter map.
515
    const FunctionDecl *OrigCallee;
516
    /// The call index of the frame that holds the argument values.
517
    unsigned CallIndex;
518
    /// The version of the parameters corresponding to this call.
519
    unsigned Version;
520
  };
521
522
  /// A stack frame in the constexpr call stack.
523
  class CallStackFrame : public interp::Frame {
524
  public:
525
    EvalInfo &Info;
526
527
    /// Parent - The caller of this stack frame.
528
    CallStackFrame *Caller;
529
530
    /// Callee - The function which was called.
531
    const FunctionDecl *Callee;
532
533
    /// This - The binding for the this pointer in this call, if any.
534
    const LValue *This;
535
536
    /// CallExpr - The syntactical structure of member function calls
537
    const Expr *CallExpr;
538
539
    /// Information on how to find the arguments to this call. Our arguments
540
    /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
541
    /// key and this value as the version.
542
    CallRef Arguments;
543
544
    /// Source location information about the default argument or default
545
    /// initializer expression we're evaluating, if any.
546
    CurrentSourceLocExprScope CurSourceLocExprScope;
547
548
    // Note that we intentionally use std::map here so that references to
549
    // values are stable.
550
    typedef std::pair<const void *, unsigned> MapKeyTy;
551
    typedef std::map<MapKeyTy, APValue> MapTy;
552
    /// Temporaries - Temporary lvalues materialized within this stack frame.
553
    MapTy Temporaries;
554
555
    /// CallRange - The source range of the call expression for this call.
556
    SourceRange CallRange;
557
558
    /// Index - The call index of this call.
559
    unsigned Index;
560
561
    /// The stack of integers for tracking version numbers for temporaries.
562
    SmallVector<unsigned, 2> TempVersionStack = {1};
563
    unsigned CurTempVersion = TempVersionStack.back();
564
565
0
    unsigned getTempVersion() const { return TempVersionStack.back(); }
566
567
0
    void pushTempVersion() {
568
0
      TempVersionStack.push_back(++CurTempVersion);
569
0
    }
570
571
0
    void popTempVersion() {
572
0
      TempVersionStack.pop_back();
573
0
    }
574
575
0
    CallRef createCall(const FunctionDecl *Callee) {
576
0
      return {Callee, Index, ++CurTempVersion};
577
0
    }
578
579
    // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
580
    // on the overall stack usage of deeply-recursing constexpr evaluations.
581
    // (We should cache this map rather than recomputing it repeatedly.)
582
    // But let's try this and see how it goes; we can look into caching the map
583
    // as a later change.
584
585
    /// LambdaCaptureFields - Mapping from captured variables/this to
586
    /// corresponding data members in the closure class.
587
    llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
588
    FieldDecl *LambdaThisCaptureField = nullptr;
589
590
    CallStackFrame(EvalInfo &Info, SourceRange CallRange,
591
                   const FunctionDecl *Callee, const LValue *This,
592
                   const Expr *CallExpr, CallRef Arguments);
593
    ~CallStackFrame();
594
595
    // Return the temporary for Key whose version number is Version.
596
0
    APValue *getTemporary(const void *Key, unsigned Version) {
597
0
      MapKeyTy KV(Key, Version);
598
0
      auto LB = Temporaries.lower_bound(KV);
599
0
      if (LB != Temporaries.end() && LB->first == KV)
600
0
        return &LB->second;
601
0
      return nullptr;
602
0
    }
603
604
    // Return the current temporary for Key in the map.
605
0
    APValue *getCurrentTemporary(const void *Key) {
606
0
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
607
0
      if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
608
0
        return &std::prev(UB)->second;
609
0
      return nullptr;
610
0
    }
611
612
    // Return the version number of the current temporary for Key.
613
0
    unsigned getCurrentTemporaryVersion(const void *Key) const {
614
0
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
615
0
      if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
616
0
        return std::prev(UB)->first.second;
617
0
      return 0;
618
0
    }
619
620
    /// Allocate storage for an object of type T in this stack frame.
621
    /// Populates LV with a handle to the created object. Key identifies
622
    /// the temporary within the stack frame, and must not be reused without
623
    /// bumping the temporary version number.
624
    template<typename KeyT>
625
    APValue &createTemporary(const KeyT *Key, QualType T,
626
                             ScopeKind Scope, LValue &LV);
627
628
    /// Allocate storage for a parameter of a function call made in this frame.
629
    APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
630
631
    void describe(llvm::raw_ostream &OS) const override;
632
633
0
    Frame *getCaller() const override { return Caller; }
634
0
    SourceRange getCallRange() const override { return CallRange; }
635
0
    const FunctionDecl *getCallee() const override { return Callee; }
636
637
0
    bool isStdFunction() const {
638
0
      for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
639
0
        if (DC->isStdNamespace())
640
0
          return true;
641
0
      return false;
642
0
    }
643
644
    /// Whether we're in a context where [[msvc::constexpr]] evaluation is
645
    /// permitted. See MSConstexprDocs for description of permitted contexts.
646
    bool CanEvalMSConstexpr = false;
647
648
  private:
649
    APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
650
                         ScopeKind Scope);
651
  };
652
653
  /// Temporarily override 'this'.
654
  class ThisOverrideRAII {
655
  public:
656
    ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
657
0
        : Frame(Frame), OldThis(Frame.This) {
658
0
      if (Enable)
659
0
        Frame.This = NewThis;
660
0
    }
661
0
    ~ThisOverrideRAII() {
662
0
      Frame.This = OldThis;
663
0
    }
664
  private:
665
    CallStackFrame &Frame;
666
    const LValue *OldThis;
667
  };
668
669
  // A shorthand time trace scope struct, prints source range, for example
670
  // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
671
  class ExprTimeTraceScope {
672
  public:
673
    ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
674
0
        : TimeScope(Name, [E, &Ctx] {
675
0
            return E->getSourceRange().printToString(Ctx.getSourceManager());
676
25
          }) {}
677
678
  private:
679
    llvm::TimeTraceScope TimeScope;
680
  };
681
682
  /// RAII object used to change the current ability of
683
  /// [[msvc::constexpr]] evaulation.
684
  struct MSConstexprContextRAII {
685
    CallStackFrame &Frame;
686
    bool OldValue;
687
    explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
688
0
        : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
689
0
      Frame.CanEvalMSConstexpr = Value;
690
0
    }
691
692
0
    ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
693
  };
694
}
695
696
static bool HandleDestruction(EvalInfo &Info, const Expr *E,
697
                              const LValue &This, QualType ThisType);
698
static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
699
                              APValue::LValueBase LVBase, APValue &Value,
700
                              QualType T);
701
702
namespace {
703
  /// A cleanup, and a flag indicating whether it is lifetime-extended.
704
  class Cleanup {
705
    llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
706
    APValue::LValueBase Base;
707
    QualType T;
708
709
  public:
710
    Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
711
            ScopeKind Scope)
712
0
        : Value(Val, Scope), Base(Base), T(T) {}
713
714
    /// Determine whether this cleanup should be performed at the end of the
715
    /// given kind of scope.
716
0
    bool isDestroyedAtEndOf(ScopeKind K) const {
717
0
      return (int)Value.getInt() >= (int)K;
718
0
    }
719
0
    bool endLifetime(EvalInfo &Info, bool RunDestructors) {
720
0
      if (RunDestructors) {
721
0
        SourceLocation Loc;
722
0
        if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
723
0
          Loc = VD->getLocation();
724
0
        else if (const Expr *E = Base.dyn_cast<const Expr*>())
725
0
          Loc = E->getExprLoc();
726
0
        return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
727
0
      }
728
0
      *Value.getPointer() = APValue();
729
0
      return true;
730
0
    }
731
732
0
    bool hasSideEffect() {
733
0
      return T.isDestructedType();
734
0
    }
735
  };
736
737
  /// A reference to an object whose construction we are currently evaluating.
738
  struct ObjectUnderConstruction {
739
    APValue::LValueBase Base;
740
    ArrayRef<APValue::LValuePathEntry> Path;
741
    friend bool operator==(const ObjectUnderConstruction &LHS,
742
0
                           const ObjectUnderConstruction &RHS) {
743
0
      return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
744
0
    }
745
0
    friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
746
0
      return llvm::hash_combine(Obj.Base, Obj.Path);
747
0
    }
748
  };
749
  enum class ConstructionPhase {
750
    None,
751
    Bases,
752
    AfterBases,
753
    AfterFields,
754
    Destroying,
755
    DestroyingBases
756
  };
757
}
758
759
namespace llvm {
760
template<> struct DenseMapInfo<ObjectUnderConstruction> {
761
  using Base = DenseMapInfo<APValue::LValueBase>;
762
0
  static ObjectUnderConstruction getEmptyKey() {
763
0
    return {Base::getEmptyKey(), {}}; }
764
0
  static ObjectUnderConstruction getTombstoneKey() {
765
0
    return {Base::getTombstoneKey(), {}};
766
0
  }
767
0
  static unsigned getHashValue(const ObjectUnderConstruction &Object) {
768
0
    return hash_value(Object);
769
0
  }
770
  static bool isEqual(const ObjectUnderConstruction &LHS,
771
0
                      const ObjectUnderConstruction &RHS) {
772
0
    return LHS == RHS;
773
0
  }
774
};
775
}
776
777
namespace {
778
  /// A dynamically-allocated heap object.
779
  struct DynAlloc {
780
    /// The value of this heap-allocated object.
781
    APValue Value;
782
    /// The allocating expression; used for diagnostics. Either a CXXNewExpr
783
    /// or a CallExpr (the latter is for direct calls to operator new inside
784
    /// std::allocator<T>::allocate).
785
    const Expr *AllocExpr = nullptr;
786
787
    enum Kind {
788
      New,
789
      ArrayNew,
790
      StdAllocator
791
    };
792
793
    /// Get the kind of the allocation. This must match between allocation
794
    /// and deallocation.
795
0
    Kind getKind() const {
796
0
      if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
797
0
        return NE->isArray() ? ArrayNew : New;
798
0
      assert(isa<CallExpr>(AllocExpr));
799
0
      return StdAllocator;
800
0
    }
801
  };
802
803
  struct DynAllocOrder {
804
0
    bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
805
0
      return L.getIndex() < R.getIndex();
806
0
    }
807
  };
808
809
  /// EvalInfo - This is a private struct used by the evaluator to capture
810
  /// information about a subexpression as it is folded.  It retains information
811
  /// about the AST context, but also maintains information about the folded
812
  /// expression.
813
  ///
814
  /// If an expression could be evaluated, it is still possible it is not a C
815
  /// "integer constant expression" or constant expression.  If not, this struct
816
  /// captures information about how and why not.
817
  ///
818
  /// One bit of information passed *into* the request for constant folding
819
  /// indicates whether the subexpression is "evaluated" or not according to C
820
  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
821
  /// evaluate the expression regardless of what the RHS is, but C only allows
822
  /// certain things in certain situations.
823
  class EvalInfo : public interp::State {
824
  public:
825
    ASTContext &Ctx;
826
827
    /// EvalStatus - Contains information about the evaluation.
828
    Expr::EvalStatus &EvalStatus;
829
830
    /// CurrentCall - The top of the constexpr call stack.
831
    CallStackFrame *CurrentCall;
832
833
    /// CallStackDepth - The number of calls in the call stack right now.
834
    unsigned CallStackDepth;
835
836
    /// NextCallIndex - The next call index to assign.
837
    unsigned NextCallIndex;
838
839
    /// StepsLeft - The remaining number of evaluation steps we're permitted
840
    /// to perform. This is essentially a limit for the number of statements
841
    /// we will evaluate.
842
    unsigned StepsLeft;
843
844
    /// Enable the experimental new constant interpreter. If an expression is
845
    /// not supported by the interpreter, an error is triggered.
846
    bool EnableNewConstInterp;
847
848
    /// BottomFrame - The frame in which evaluation started. This must be
849
    /// initialized after CurrentCall and CallStackDepth.
850
    CallStackFrame BottomFrame;
851
852
    /// A stack of values whose lifetimes end at the end of some surrounding
853
    /// evaluation frame.
854
    llvm::SmallVector<Cleanup, 16> CleanupStack;
855
856
    /// EvaluatingDecl - This is the declaration whose initializer is being
857
    /// evaluated, if any.
858
    APValue::LValueBase EvaluatingDecl;
859
860
    enum class EvaluatingDeclKind {
861
      None,
862
      /// We're evaluating the construction of EvaluatingDecl.
863
      Ctor,
864
      /// We're evaluating the destruction of EvaluatingDecl.
865
      Dtor,
866
    };
867
    EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
868
869
    /// EvaluatingDeclValue - This is the value being constructed for the
870
    /// declaration whose initializer is being evaluated, if any.
871
    APValue *EvaluatingDeclValue;
872
873
    /// Set of objects that are currently being constructed.
874
    llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
875
        ObjectsUnderConstruction;
876
877
    /// Current heap allocations, along with the location where each was
878
    /// allocated. We use std::map here because we need stable addresses
879
    /// for the stored APValues.
880
    std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
881
882
    /// The number of heap allocations performed so far in this evaluation.
883
    unsigned NumHeapAllocs = 0;
884
885
    struct EvaluatingConstructorRAII {
886
      EvalInfo &EI;
887
      ObjectUnderConstruction Object;
888
      bool DidInsert;
889
      EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
890
                                bool HasBases)
891
0
          : EI(EI), Object(Object) {
892
0
        DidInsert =
893
0
            EI.ObjectsUnderConstruction
894
0
                .insert({Object, HasBases ? ConstructionPhase::Bases
895
0
                                          : ConstructionPhase::AfterBases})
896
0
                .second;
897
0
      }
898
0
      void finishedConstructingBases() {
899
0
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
900
0
      }
901
0
      void finishedConstructingFields() {
902
0
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
903
0
      }
904
0
      ~EvaluatingConstructorRAII() {
905
0
        if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
906
0
      }
907
    };
908
909
    struct EvaluatingDestructorRAII {
910
      EvalInfo &EI;
911
      ObjectUnderConstruction Object;
912
      bool DidInsert;
913
      EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
914
0
          : EI(EI), Object(Object) {
915
0
        DidInsert = EI.ObjectsUnderConstruction
916
0
                        .insert({Object, ConstructionPhase::Destroying})
917
0
                        .second;
918
0
      }
919
0
      void startedDestroyingBases() {
920
0
        EI.ObjectsUnderConstruction[Object] =
921
0
            ConstructionPhase::DestroyingBases;
922
0
      }
923
0
      ~EvaluatingDestructorRAII() {
924
0
        if (DidInsert)
925
0
          EI.ObjectsUnderConstruction.erase(Object);
926
0
      }
927
    };
928
929
    ConstructionPhase
930
    isEvaluatingCtorDtor(APValue::LValueBase Base,
931
0
                         ArrayRef<APValue::LValuePathEntry> Path) {
932
0
      return ObjectsUnderConstruction.lookup({Base, Path});
933
0
    }
934
935
    /// If we're currently speculatively evaluating, the outermost call stack
936
    /// depth at which we can mutate state, otherwise 0.
937
    unsigned SpeculativeEvaluationDepth = 0;
938
939
    /// The current array initialization index, if we're performing array
940
    /// initialization.
941
    uint64_t ArrayInitIndex = -1;
942
943
    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
944
    /// notes attached to it will also be stored, otherwise they will not be.
945
    bool HasActiveDiagnostic;
946
947
    /// Have we emitted a diagnostic explaining why we couldn't constant
948
    /// fold (not just why it's not strictly a constant expression)?
949
    bool HasFoldFailureDiagnostic;
950
951
    /// Whether we're checking that an expression is a potential constant
952
    /// expression. If so, do not fail on constructs that could become constant
953
    /// later on (such as a use of an undefined global).
954
    bool CheckingPotentialConstantExpression = false;
955
956
    /// Whether we're checking for an expression that has undefined behavior.
957
    /// If so, we will produce warnings if we encounter an operation that is
958
    /// always undefined.
959
    ///
960
    /// Note that we still need to evaluate the expression normally when this
961
    /// is set; this is used when evaluating ICEs in C.
962
    bool CheckingForUndefinedBehavior = false;
963
964
    enum EvaluationMode {
965
      /// Evaluate as a constant expression. Stop if we find that the expression
966
      /// is not a constant expression.
967
      EM_ConstantExpression,
968
969
      /// Evaluate as a constant expression. Stop if we find that the expression
970
      /// is not a constant expression. Some expressions can be retried in the
971
      /// optimizer if we don't constant fold them here, but in an unevaluated
972
      /// context we try to fold them immediately since the optimizer never
973
      /// gets a chance to look at it.
974
      EM_ConstantExpressionUnevaluated,
975
976
      /// Fold the expression to a constant. Stop if we hit a side-effect that
977
      /// we can't model.
978
      EM_ConstantFold,
979
980
      /// Evaluate in any way we know how. Don't worry about side-effects that
981
      /// can't be modeled.
982
      EM_IgnoreSideEffects,
983
    } EvalMode;
984
985
    /// Are we checking whether the expression is a potential constant
986
    /// expression?
987
4
    bool checkingPotentialConstantExpression() const override  {
988
4
      return CheckingPotentialConstantExpression;
989
4
    }
990
991
    /// Are we checking an expression for overflow?
992
    // FIXME: We should check for any kind of undefined or suspicious behavior
993
    // in such constructs, not just overflow.
994
0
    bool checkingForUndefinedBehavior() const override {
995
0
      return CheckingForUndefinedBehavior;
996
0
    }
997
998
    EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
999
        : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1000
          CallStackDepth(0), NextCallIndex(1),
1001
          StepsLeft(C.getLangOpts().ConstexprStepLimit),
1002
          EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1003
          BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1004
                      /*This=*/nullptr,
1005
                      /*CallExpr=*/nullptr, CallRef()),
1006
          EvaluatingDecl((const ValueDecl *)nullptr),
1007
          EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1008
18
          HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1009
1010
18
    ~EvalInfo() {
1011
18
      discardCleanups();
1012
18
    }
1013
1014
19
    ASTContext &getCtx() const override { return Ctx; }
1015
1016
    void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1017
0
                           EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1018
0
      EvaluatingDecl = Base;
1019
0
      IsEvaluatingDecl = EDK;
1020
0
      EvaluatingDeclValue = &Value;
1021
0
    }
1022
1023
0
    bool CheckCallLimit(SourceLocation Loc) {
1024
      // Don't perform any constexpr calls (other than the call we're checking)
1025
      // when checking a potential constant expression.
1026
0
      if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1027
0
        return false;
1028
0
      if (NextCallIndex == 0) {
1029
        // NextCallIndex has wrapped around.
1030
0
        FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1031
0
        return false;
1032
0
      }
1033
0
      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1034
0
        return true;
1035
0
      FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1036
0
        << getLangOpts().ConstexprCallDepth;
1037
0
      return false;
1038
0
    }
1039
1040
    bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1041
0
                        uint64_t ElemCount, bool Diag) {
1042
      // FIXME: GH63562
1043
      // APValue stores array extents as unsigned,
1044
      // so anything that is greater that unsigned would overflow when
1045
      // constructing the array, we catch this here.
1046
0
      if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1047
0
          ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1048
0
        if (Diag)
1049
0
          FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1050
0
        return false;
1051
0
      }
1052
1053
      // FIXME: GH63562
1054
      // Arrays allocate an APValue per element.
1055
      // We use the number of constexpr steps as a proxy for the maximum size
1056
      // of arrays to avoid exhausting the system resources, as initialization
1057
      // of each element is likely to take some number of steps anyway.
1058
0
      uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1059
0
      if (ElemCount > Limit) {
1060
0
        if (Diag)
1061
0
          FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1062
0
              << ElemCount << Limit;
1063
0
        return false;
1064
0
      }
1065
0
      return true;
1066
0
    }
1067
1068
    std::pair<CallStackFrame *, unsigned>
1069
0
    getCallFrameAndDepth(unsigned CallIndex) {
1070
0
      assert(CallIndex && "no call index in getCallFrameAndDepth");
1071
      // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1072
      // be null in this loop.
1073
0
      unsigned Depth = CallStackDepth;
1074
0
      CallStackFrame *Frame = CurrentCall;
1075
0
      while (Frame->Index > CallIndex) {
1076
0
        Frame = Frame->Caller;
1077
0
        --Depth;
1078
0
      }
1079
0
      if (Frame->Index == CallIndex)
1080
0
        return {Frame, Depth};
1081
0
      return {nullptr, 0};
1082
0
    }
1083
1084
0
    bool nextStep(const Stmt *S) {
1085
0
      if (!StepsLeft) {
1086
0
        FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1087
0
        return false;
1088
0
      }
1089
0
      --StepsLeft;
1090
0
      return true;
1091
0
    }
1092
1093
    APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1094
1095
0
    std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1096
0
      std::optional<DynAlloc *> Result;
1097
0
      auto It = HeapAllocs.find(DA);
1098
0
      if (It != HeapAllocs.end())
1099
0
        Result = &It->second;
1100
0
      return Result;
1101
0
    }
1102
1103
    /// Get the allocated storage for the given parameter of the given call.
1104
0
    APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1105
0
      CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1106
0
      return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1107
0
                   : nullptr;
1108
0
    }
1109
1110
    /// Information about a stack frame for std::allocator<T>::[de]allocate.
1111
    struct StdAllocatorCaller {
1112
      unsigned FrameIndex;
1113
      QualType ElemType;
1114
0
      explicit operator bool() const { return FrameIndex != 0; };
1115
    };
1116
1117
0
    StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1118
0
      for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1119
0
           Call = Call->Caller) {
1120
0
        const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1121
0
        if (!MD)
1122
0
          continue;
1123
0
        const IdentifierInfo *FnII = MD->getIdentifier();
1124
0
        if (!FnII || !FnII->isStr(FnName))
1125
0
          continue;
1126
1127
0
        const auto *CTSD =
1128
0
            dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1129
0
        if (!CTSD)
1130
0
          continue;
1131
1132
0
        const IdentifierInfo *ClassII = CTSD->getIdentifier();
1133
0
        const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1134
0
        if (CTSD->isInStdNamespace() && ClassII &&
1135
0
            ClassII->isStr("allocator") && TAL.size() >= 1 &&
1136
0
            TAL[0].getKind() == TemplateArgument::Type)
1137
0
          return {Call->Index, TAL[0].getAsType()};
1138
0
      }
1139
1140
0
      return {};
1141
0
    }
1142
1143
0
    void performLifetimeExtension() {
1144
      // Disable the cleanups for lifetime-extended temporaries.
1145
0
      llvm::erase_if(CleanupStack, [](Cleanup &C) {
1146
0
        return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1147
0
      });
1148
0
    }
1149
1150
    /// Throw away any remaining cleanups at the end of evaluation. If any
1151
    /// cleanups would have had a side-effect, note that as an unmodeled
1152
    /// side-effect and return false. Otherwise, return true.
1153
18
    bool discardCleanups() {
1154
18
      for (Cleanup &C : CleanupStack) {
1155
0
        if (C.hasSideEffect() && !noteSideEffect()) {
1156
0
          CleanupStack.clear();
1157
0
          return false;
1158
0
        }
1159
0
      }
1160
18
      CleanupStack.clear();
1161
18
      return true;
1162
18
    }
1163
1164
  private:
1165
2
    interp::Frame *getCurrentFrame() override { return CurrentCall; }
1166
2
    const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1167
1168
0
    bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1169
11
    void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1170
1171
2
    void setFoldFailureDiagnostic(bool Flag) override {
1172
2
      HasFoldFailureDiagnostic = Flag;
1173
2
    }
1174
1175
17
    Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1176
1177
    // If we have a prior diagnostic, it will be noting that the expression
1178
    // isn't a constant expression. This diagnostic is more important,
1179
    // unless we require this evaluation to produce a constant expression.
1180
    //
1181
    // FIXME: We might want to show both diagnostics to the user in
1182
    // EM_ConstantFold mode.
1183
2
    bool hasPriorDiagnostic() override {
1184
2
      if (!EvalStatus.Diag->empty()) {
1185
0
        switch (EvalMode) {
1186
0
        case EM_ConstantFold:
1187
0
        case EM_IgnoreSideEffects:
1188
0
          if (!HasFoldFailureDiagnostic)
1189
0
            break;
1190
          // We've already failed to fold something. Keep that diagnostic.
1191
0
          [[fallthrough]];
1192
0
        case EM_ConstantExpression:
1193
0
        case EM_ConstantExpressionUnevaluated:
1194
0
          setActiveDiagnostic(false);
1195
0
          return true;
1196
0
        }
1197
0
      }
1198
2
      return false;
1199
2
    }
1200
1201
4
    unsigned getCallStackDepth() override { return CallStackDepth; }
1202
1203
  public:
1204
    /// Should we continue evaluation after encountering a side-effect that we
1205
    /// couldn't model?
1206
0
    bool keepEvaluatingAfterSideEffect() {
1207
0
      switch (EvalMode) {
1208
0
      case EM_IgnoreSideEffects:
1209
0
        return true;
1210
1211
0
      case EM_ConstantExpression:
1212
0
      case EM_ConstantExpressionUnevaluated:
1213
0
      case EM_ConstantFold:
1214
        // By default, assume any side effect might be valid in some other
1215
        // evaluation of this expression from a different context.
1216
0
        return checkingPotentialConstantExpression() ||
1217
0
               checkingForUndefinedBehavior();
1218
0
      }
1219
0
      llvm_unreachable("Missed EvalMode case");
1220
0
    }
1221
1222
    /// Note that we have had a side-effect, and determine whether we should
1223
    /// keep evaluating.
1224
0
    bool noteSideEffect() {
1225
0
      EvalStatus.HasSideEffects = true;
1226
0
      return keepEvaluatingAfterSideEffect();
1227
0
    }
1228
1229
    /// Should we continue evaluation after encountering undefined behavior?
1230
0
    bool keepEvaluatingAfterUndefinedBehavior() {
1231
0
      switch (EvalMode) {
1232
0
      case EM_IgnoreSideEffects:
1233
0
      case EM_ConstantFold:
1234
0
        return true;
1235
1236
0
      case EM_ConstantExpression:
1237
0
      case EM_ConstantExpressionUnevaluated:
1238
0
        return checkingForUndefinedBehavior();
1239
0
      }
1240
0
      llvm_unreachable("Missed EvalMode case");
1241
0
    }
1242
1243
    /// Note that we hit something that was technically undefined behavior, but
1244
    /// that we can evaluate past it (such as signed overflow or floating-point
1245
    /// division by zero.)
1246
0
    bool noteUndefinedBehavior() override {
1247
0
      EvalStatus.HasUndefinedBehavior = true;
1248
0
      return keepEvaluatingAfterUndefinedBehavior();
1249
0
    }
1250
1251
    /// Should we continue evaluation as much as possible after encountering a
1252
    /// construct which can't be reduced to a value?
1253
0
    bool keepEvaluatingAfterFailure() const override {
1254
0
      if (!StepsLeft)
1255
0
        return false;
1256
1257
0
      switch (EvalMode) {
1258
0
      case EM_ConstantExpression:
1259
0
      case EM_ConstantExpressionUnevaluated:
1260
0
      case EM_ConstantFold:
1261
0
      case EM_IgnoreSideEffects:
1262
0
        return checkingPotentialConstantExpression() ||
1263
0
               checkingForUndefinedBehavior();
1264
0
      }
1265
0
      llvm_unreachable("Missed EvalMode case");
1266
0
    }
1267
1268
    /// Notes that we failed to evaluate an expression that other expressions
1269
    /// directly depend on, and determine if we should keep evaluating. This
1270
    /// should only be called if we actually intend to keep evaluating.
1271
    ///
1272
    /// Call noteSideEffect() instead if we may be able to ignore the value that
1273
    /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1274
    ///
1275
    /// (Foo(), 1)      // use noteSideEffect
1276
    /// (Foo() || true) // use noteSideEffect
1277
    /// Foo() + 1       // use noteFailure
1278
0
    [[nodiscard]] bool noteFailure() {
1279
      // Failure when evaluating some expression often means there is some
1280
      // subexpression whose evaluation was skipped. Therefore, (because we
1281
      // don't track whether we skipped an expression when unwinding after an
1282
      // evaluation failure) every evaluation failure that bubbles up from a
1283
      // subexpression implies that a side-effect has potentially happened. We
1284
      // skip setting the HasSideEffects flag to true until we decide to
1285
      // continue evaluating after that point, which happens here.
1286
0
      bool KeepGoing = keepEvaluatingAfterFailure();
1287
0
      EvalStatus.HasSideEffects |= KeepGoing;
1288
0
      return KeepGoing;
1289
0
    }
1290
1291
    class ArrayInitLoopIndex {
1292
      EvalInfo &Info;
1293
      uint64_t OuterIndex;
1294
1295
    public:
1296
      ArrayInitLoopIndex(EvalInfo &Info)
1297
0
          : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1298
0
        Info.ArrayInitIndex = 0;
1299
0
      }
1300
0
      ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1301
1302
0
      operator uint64_t&() { return Info.ArrayInitIndex; }
1303
    };
1304
  };
1305
1306
  /// Object used to treat all foldable expressions as constant expressions.
1307
  struct FoldConstant {
1308
    EvalInfo &Info;
1309
    bool Enabled;
1310
    bool HadNoPriorDiags;
1311
    EvalInfo::EvaluationMode OldMode;
1312
1313
    explicit FoldConstant(EvalInfo &Info, bool Enabled)
1314
      : Info(Info),
1315
        Enabled(Enabled),
1316
        HadNoPriorDiags(Info.EvalStatus.Diag &&
1317
                        Info.EvalStatus.Diag->empty() &&
1318
                        !Info.EvalStatus.HasSideEffects),
1319
0
        OldMode(Info.EvalMode) {
1320
0
      if (Enabled)
1321
0
        Info.EvalMode = EvalInfo::EM_ConstantFold;
1322
0
    }
1323
0
    void keepDiagnostics() { Enabled = false; }
1324
0
    ~FoldConstant() {
1325
0
      if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1326
0
          !Info.EvalStatus.HasSideEffects)
1327
0
        Info.EvalStatus.Diag->clear();
1328
0
      Info.EvalMode = OldMode;
1329
0
    }
1330
  };
1331
1332
  /// RAII object used to set the current evaluation mode to ignore
1333
  /// side-effects.
1334
  struct IgnoreSideEffectsRAII {
1335
    EvalInfo &Info;
1336
    EvalInfo::EvaluationMode OldMode;
1337
    explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1338
0
        : Info(Info), OldMode(Info.EvalMode) {
1339
0
      Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1340
0
    }
1341
1342
0
    ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1343
  };
1344
1345
  /// RAII object used to optionally suppress diagnostics and side-effects from
1346
  /// a speculative evaluation.
1347
  class SpeculativeEvaluationRAII {
1348
    EvalInfo *Info = nullptr;
1349
    Expr::EvalStatus OldStatus;
1350
    unsigned OldSpeculativeEvaluationDepth = 0;
1351
1352
0
    void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1353
0
      Info = Other.Info;
1354
0
      OldStatus = Other.OldStatus;
1355
0
      OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1356
0
      Other.Info = nullptr;
1357
0
    }
1358
1359
0
    void maybeRestoreState() {
1360
0
      if (!Info)
1361
0
        return;
1362
1363
0
      Info->EvalStatus = OldStatus;
1364
0
      Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1365
0
    }
1366
1367
  public:
1368
0
    SpeculativeEvaluationRAII() = default;
1369
1370
    SpeculativeEvaluationRAII(
1371
        EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1372
        : Info(&Info), OldStatus(Info.EvalStatus),
1373
0
          OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1374
0
      Info.EvalStatus.Diag = NewDiag;
1375
0
      Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1376
0
    }
1377
1378
    SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1379
0
    SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1380
0
      moveFromAndCancel(std::move(Other));
1381
0
    }
1382
1383
0
    SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1384
0
      maybeRestoreState();
1385
0
      moveFromAndCancel(std::move(Other));
1386
0
      return *this;
1387
0
    }
1388
1389
0
    ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1390
  };
1391
1392
  /// RAII object wrapping a full-expression or block scope, and handling
1393
  /// the ending of the lifetime of temporaries created within it.
1394
  template<ScopeKind Kind>
1395
  class ScopeRAII {
1396
    EvalInfo &Info;
1397
    unsigned OldStackSize;
1398
  public:
1399
    ScopeRAII(EvalInfo &Info)
1400
0
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1401
      // Push a new temporary version. This is needed to distinguish between
1402
      // temporaries created in different iterations of a loop.
1403
0
      Info.CurrentCall->pushTempVersion();
1404
0
    }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::ScopeRAII((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::ScopeRAII((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::ScopeRAII((anonymous namespace)::EvalInfo&)
1405
0
    bool destroy(bool RunDestructors = true) {
1406
0
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1407
0
      OldStackSize = -1U;
1408
0
      return OK;
1409
0
    }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::destroy(bool)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::destroy(bool)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::destroy(bool)
1410
0
    ~ScopeRAII() {
1411
0
      if (OldStackSize != -1U)
1412
0
        destroy(false);
1413
      // Body moved to a static method to encourage the compiler to inline away
1414
      // instances of this class.
1415
0
      Info.CurrentCall->popTempVersion();
1416
0
    }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::~ScopeRAII()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::~ScopeRAII()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::~ScopeRAII()
1417
  private:
1418
    static bool cleanup(EvalInfo &Info, bool RunDestructors,
1419
0
                        unsigned OldStackSize) {
1420
0
      assert(OldStackSize <= Info.CleanupStack.size() &&
1421
0
             "running cleanups out of order?");
1422
1423
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1424
      // for a full-expression scope.
1425
0
      bool Success = true;
1426
0
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1427
0
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1428
0
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1429
0
            Success = false;
1430
0
            break;
1431
0
          }
1432
0
        }
1433
0
      }
1434
1435
      // Compact any retained cleanups.
1436
0
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1437
0
      if (Kind != ScopeKind::Block)
1438
0
        NewEnd =
1439
0
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1440
0
              return C.isDestroyedAtEndOf(Kind);
1441
0
            });
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::{lambda((anonymous namespace)::Cleanup&)#1}::operator()((anonymous namespace)::Cleanup&) const
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::{lambda((anonymous namespace)::Cleanup&)#1}::operator()((anonymous namespace)::Cleanup&) const
1442
0
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1443
0
      return Success;
1444
0
    }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
1445
  };
1446
  typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1447
  typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1448
  typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1449
}
1450
1451
bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1452
0
                                         CheckSubobjectKind CSK) {
1453
0
  if (Invalid)
1454
0
    return false;
1455
0
  if (isOnePastTheEnd()) {
1456
0
    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1457
0
      << CSK;
1458
0
    setInvalid();
1459
0
    return false;
1460
0
  }
1461
  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1462
  // must actually be at least one array element; even a VLA cannot have a
1463
  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1464
0
  return true;
1465
0
}
1466
1467
void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1468
0
                                                                const Expr *E) {
1469
0
  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1470
  // Do not set the designator as invalid: we can represent this situation,
1471
  // and correct handling of __builtin_object_size requires us to do so.
1472
0
}
1473
1474
void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1475
                                                    const Expr *E,
1476
0
                                                    const APSInt &N) {
1477
  // If we're complaining, we must be able to statically determine the size of
1478
  // the most derived array.
1479
0
  if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1480
0
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1481
0
      << N << /*array*/ 0
1482
0
      << static_cast<unsigned>(getMostDerivedArraySize());
1483
0
  else
1484
0
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1485
0
      << N << /*non-array*/ 1;
1486
0
  setInvalid();
1487
0
}
1488
1489
CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1490
                               const FunctionDecl *Callee, const LValue *This,
1491
                               const Expr *CallExpr, CallRef Call)
1492
    : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1493
      CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1494
18
      Index(Info.NextCallIndex++) {
1495
18
  Info.CurrentCall = this;
1496
18
  ++Info.CallStackDepth;
1497
18
}
1498
1499
18
CallStackFrame::~CallStackFrame() {
1500
18
  assert(Info.CurrentCall == this && "calls retired out of order");
1501
0
  --Info.CallStackDepth;
1502
18
  Info.CurrentCall = Caller;
1503
18
}
1504
1505
18
static bool isRead(AccessKinds AK) {
1506
18
  return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1507
18
}
1508
1509
3
static bool isModification(AccessKinds AK) {
1510
3
  switch (AK) {
1511
3
  case AK_Read:
1512
3
  case AK_ReadObjectRepresentation:
1513
3
  case AK_MemberCall:
1514
3
  case AK_DynamicCast:
1515
3
  case AK_TypeId:
1516
3
    return false;
1517
0
  case AK_Assign:
1518
0
  case AK_Increment:
1519
0
  case AK_Decrement:
1520
0
  case AK_Construct:
1521
0
  case AK_Destroy:
1522
0
    return true;
1523
3
  }
1524
0
  llvm_unreachable("unknown access kind");
1525
0
}
1526
1527
18
static bool isAnyAccess(AccessKinds AK) {
1528
18
  return isRead(AK) || isModification(AK);
1529
18
}
1530
1531
/// Is this an access per the C++ definition?
1532
9
static bool isFormalAccess(AccessKinds AK) {
1533
9
  return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1534
9
}
1535
1536
/// Is this kind of axcess valid on an indeterminate object value?
1537
0
static bool isValidIndeterminateAccess(AccessKinds AK) {
1538
0
  switch (AK) {
1539
0
  case AK_Read:
1540
0
  case AK_Increment:
1541
0
  case AK_Decrement:
1542
    // These need the object's value.
1543
0
    return false;
1544
1545
0
  case AK_ReadObjectRepresentation:
1546
0
  case AK_Assign:
1547
0
  case AK_Construct:
1548
0
  case AK_Destroy:
1549
    // Construction and destruction don't need the value.
1550
0
    return true;
1551
1552
0
  case AK_MemberCall:
1553
0
  case AK_DynamicCast:
1554
0
  case AK_TypeId:
1555
    // These aren't really meaningful on scalars.
1556
0
    return true;
1557
0
  }
1558
0
  llvm_unreachable("unknown access kind");
1559
0
}
1560
1561
namespace {
1562
  struct ComplexValue {
1563
  private:
1564
    bool IsInt;
1565
1566
  public:
1567
    APSInt IntReal, IntImag;
1568
    APFloat FloatReal, FloatImag;
1569
1570
0
    ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1571
1572
0
    void makeComplexFloat() { IsInt = false; }
1573
0
    bool isComplexFloat() const { return !IsInt; }
1574
0
    APFloat &getComplexFloatReal() { return FloatReal; }
1575
0
    APFloat &getComplexFloatImag() { return FloatImag; }
1576
1577
0
    void makeComplexInt() { IsInt = true; }
1578
0
    bool isComplexInt() const { return IsInt; }
1579
0
    APSInt &getComplexIntReal() { return IntReal; }
1580
0
    APSInt &getComplexIntImag() { return IntImag; }
1581
1582
0
    void moveInto(APValue &v) const {
1583
0
      if (isComplexFloat())
1584
0
        v = APValue(FloatReal, FloatImag);
1585
0
      else
1586
0
        v = APValue(IntReal, IntImag);
1587
0
    }
1588
0
    void setFrom(const APValue &v) {
1589
0
      assert(v.isComplexFloat() || v.isComplexInt());
1590
0
      if (v.isComplexFloat()) {
1591
0
        makeComplexFloat();
1592
0
        FloatReal = v.getComplexFloatReal();
1593
0
        FloatImag = v.getComplexFloatImag();
1594
0
      } else {
1595
0
        makeComplexInt();
1596
0
        IntReal = v.getComplexIntReal();
1597
0
        IntImag = v.getComplexIntImag();
1598
0
      }
1599
0
    }
1600
  };
1601
1602
  struct LValue {
1603
    APValue::LValueBase Base;
1604
    CharUnits Offset;
1605
    SubobjectDesignator Designator;
1606
    bool IsNullPtr : 1;
1607
    bool InvalidBase : 1;
1608
1609
0
    const APValue::LValueBase getLValueBase() const { return Base; }
1610
0
    CharUnits &getLValueOffset() { return Offset; }
1611
0
    const CharUnits &getLValueOffset() const { return Offset; }
1612
0
    SubobjectDesignator &getLValueDesignator() { return Designator; }
1613
0
    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1614
0
    bool isNullPointer() const { return IsNullPtr;}
1615
1616
9
    unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1617
0
    unsigned getLValueVersion() const { return Base.getVersion(); }
1618
1619
4
    void moveInto(APValue &V) const {
1620
4
      if (Designator.Invalid)
1621
0
        V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1622
4
      else {
1623
4
        assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1624
0
        V = APValue(Base, Offset, Designator.Entries,
1625
4
                    Designator.IsOnePastTheEnd, IsNullPtr);
1626
4
      }
1627
4
    }
1628
4
    void setFrom(ASTContext &Ctx, const APValue &V) {
1629
4
      assert(V.isLValue() && "Setting LValue from a non-LValue?");
1630
0
      Base = V.getLValueBase();
1631
4
      Offset = V.getLValueOffset();
1632
4
      InvalidBase = false;
1633
4
      Designator = SubobjectDesignator(Ctx, V);
1634
4
      IsNullPtr = V.isNullPointer();
1635
4
    }
1636
1637
9
    void set(APValue::LValueBase B, bool BInvalid = false) {
1638
9
#ifndef NDEBUG
1639
      // We only allow a few types of invalid bases. Enforce that here.
1640
9
      if (BInvalid) {
1641
0
        const auto *E = B.get<const Expr *>();
1642
0
        assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1643
0
               "Unexpected type of invalid base");
1644
0
      }
1645
0
#endif
1646
1647
0
      Base = B;
1648
9
      Offset = CharUnits::fromQuantity(0);
1649
9
      InvalidBase = BInvalid;
1650
9
      Designator = SubobjectDesignator(getType(B));
1651
9
      IsNullPtr = false;
1652
9
    }
1653
1654
0
    void setNull(ASTContext &Ctx, QualType PointerTy) {
1655
0
      Base = (const ValueDecl *)nullptr;
1656
0
      Offset =
1657
0
          CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1658
0
      InvalidBase = false;
1659
0
      Designator = SubobjectDesignator(PointerTy->getPointeeType());
1660
0
      IsNullPtr = true;
1661
0
    }
1662
1663
0
    void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1664
0
      set(B, true);
1665
0
    }
1666
1667
0
    std::string toString(ASTContext &Ctx, QualType T) const {
1668
0
      APValue Printable;
1669
0
      moveInto(Printable);
1670
0
      return Printable.getAsString(Ctx, T);
1671
0
    }
1672
1673
  private:
1674
    // Check that this LValue is not based on a null pointer. If it is, produce
1675
    // a diagnostic and mark the designator as invalid.
1676
    template <typename GenDiagType>
1677
0
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1678
0
      if (Designator.Invalid)
1679
0
        return false;
1680
0
      if (IsNullPtr) {
1681
0
        GenDiag();
1682
0
        Designator.setInvalid();
1683
0
        return false;
1684
0
      }
1685
0
      return true;
1686
0
    }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::{lambda()#1}>((anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::{lambda()#1} const&)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::{lambda()#1}>((anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::{lambda()#1} const&)
1687
1688
  public:
1689
    bool checkNullPointer(EvalInfo &Info, const Expr *E,
1690
0
                          CheckSubobjectKind CSK) {
1691
0
      return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1692
0
        Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1693
0
      });
1694
0
    }
1695
1696
    bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1697
0
                                       AccessKinds AK) {
1698
0
      return checkNullPointerDiagnosingWith([&Info, E, AK] {
1699
0
        Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1700
0
      });
1701
0
    }
1702
1703
    // Check this LValue refers to an object. If not, set the designator to be
1704
    // invalid and emit a diagnostic.
1705
0
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1706
0
      return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1707
0
             Designator.checkSubobject(Info, E, CSK);
1708
0
    }
1709
1710
    void addDecl(EvalInfo &Info, const Expr *E,
1711
0
                 const Decl *D, bool Virtual = false) {
1712
0
      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1713
0
        Designator.addDeclUnchecked(D, Virtual);
1714
0
    }
1715
0
    void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1716
0
      if (!Designator.Entries.empty()) {
1717
0
        Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1718
0
        Designator.setInvalid();
1719
0
        return;
1720
0
      }
1721
0
      if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1722
0
        assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1723
0
        Designator.FirstEntryIsAnUnsizedArray = true;
1724
0
        Designator.addUnsizedArrayUnchecked(ElemTy);
1725
0
      }
1726
0
    }
1727
0
    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1728
0
      if (checkSubobject(Info, E, CSK_ArrayToPointer))
1729
0
        Designator.addArrayUnchecked(CAT);
1730
0
    }
1731
0
    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1732
0
      if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1733
0
        Designator.addComplexUnchecked(EltTy, Imag);
1734
0
    }
1735
0
    void clearIsNullPointer() {
1736
0
      IsNullPtr = false;
1737
0
    }
1738
    void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1739
0
                              const APSInt &Index, CharUnits ElementSize) {
1740
      // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1741
      // but we're not required to diagnose it and it's valid in C++.)
1742
0
      if (!Index)
1743
0
        return;
1744
1745
      // Compute the new offset in the appropriate width, wrapping at 64 bits.
1746
      // FIXME: When compiling for a 32-bit target, we should use 32-bit
1747
      // offsets.
1748
0
      uint64_t Offset64 = Offset.getQuantity();
1749
0
      uint64_t ElemSize64 = ElementSize.getQuantity();
1750
0
      uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1751
0
      Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1752
1753
0
      if (checkNullPointer(Info, E, CSK_ArrayIndex))
1754
0
        Designator.adjustIndex(Info, E, Index);
1755
0
      clearIsNullPointer();
1756
0
    }
1757
0
    void adjustOffset(CharUnits N) {
1758
0
      Offset += N;
1759
0
      if (N.getQuantity())
1760
0
        clearIsNullPointer();
1761
0
    }
1762
  };
1763
1764
  struct MemberPtr {
1765
0
    MemberPtr() {}
1766
    explicit MemberPtr(const ValueDecl *Decl)
1767
0
        : DeclAndIsDerivedMember(Decl, false) {}
1768
1769
    /// The member or (direct or indirect) field referred to by this member
1770
    /// pointer, or 0 if this is a null member pointer.
1771
0
    const ValueDecl *getDecl() const {
1772
0
      return DeclAndIsDerivedMember.getPointer();
1773
0
    }
1774
    /// Is this actually a member of some type derived from the relevant class?
1775
0
    bool isDerivedMember() const {
1776
0
      return DeclAndIsDerivedMember.getInt();
1777
0
    }
1778
    /// Get the class which the declaration actually lives in.
1779
0
    const CXXRecordDecl *getContainingRecord() const {
1780
0
      return cast<CXXRecordDecl>(
1781
0
          DeclAndIsDerivedMember.getPointer()->getDeclContext());
1782
0
    }
1783
1784
0
    void moveInto(APValue &V) const {
1785
0
      V = APValue(getDecl(), isDerivedMember(), Path);
1786
0
    }
1787
0
    void setFrom(const APValue &V) {
1788
0
      assert(V.isMemberPointer());
1789
0
      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1790
0
      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1791
0
      Path.clear();
1792
0
      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1793
0
      Path.insert(Path.end(), P.begin(), P.end());
1794
0
    }
1795
1796
    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1797
    /// whether the member is a member of some class derived from the class type
1798
    /// of the member pointer.
1799
    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1800
    /// Path - The path of base/derived classes from the member declaration's
1801
    /// class (exclusive) to the class type of the member pointer (inclusive).
1802
    SmallVector<const CXXRecordDecl*, 4> Path;
1803
1804
    /// Perform a cast towards the class of the Decl (either up or down the
1805
    /// hierarchy).
1806
0
    bool castBack(const CXXRecordDecl *Class) {
1807
0
      assert(!Path.empty());
1808
0
      const CXXRecordDecl *Expected;
1809
0
      if (Path.size() >= 2)
1810
0
        Expected = Path[Path.size() - 2];
1811
0
      else
1812
0
        Expected = getContainingRecord();
1813
0
      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1814
        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1815
        // if B does not contain the original member and is not a base or
1816
        // derived class of the class containing the original member, the result
1817
        // of the cast is undefined.
1818
        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1819
        // (D::*). We consider that to be a language defect.
1820
0
        return false;
1821
0
      }
1822
0
      Path.pop_back();
1823
0
      return true;
1824
0
    }
1825
    /// Perform a base-to-derived member pointer cast.
1826
0
    bool castToDerived(const CXXRecordDecl *Derived) {
1827
0
      if (!getDecl())
1828
0
        return true;
1829
0
      if (!isDerivedMember()) {
1830
0
        Path.push_back(Derived);
1831
0
        return true;
1832
0
      }
1833
0
      if (!castBack(Derived))
1834
0
        return false;
1835
0
      if (Path.empty())
1836
0
        DeclAndIsDerivedMember.setInt(false);
1837
0
      return true;
1838
0
    }
1839
    /// Perform a derived-to-base member pointer cast.
1840
0
    bool castToBase(const CXXRecordDecl *Base) {
1841
0
      if (!getDecl())
1842
0
        return true;
1843
0
      if (Path.empty())
1844
0
        DeclAndIsDerivedMember.setInt(true);
1845
0
      if (isDerivedMember()) {
1846
0
        Path.push_back(Base);
1847
0
        return true;
1848
0
      }
1849
0
      return castBack(Base);
1850
0
    }
1851
  };
1852
1853
  /// Compare two member pointers, which are assumed to be of the same type.
1854
0
  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1855
0
    if (!LHS.getDecl() || !RHS.getDecl())
1856
0
      return !LHS.getDecl() && !RHS.getDecl();
1857
0
    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1858
0
      return false;
1859
0
    return LHS.Path == RHS.Path;
1860
0
  }
1861
}
1862
1863
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1864
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1865
                            const LValue &This, const Expr *E,
1866
                            bool AllowNonLiteralTypes = false);
1867
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1868
                           bool InvalidBaseOK = false);
1869
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1870
                            bool InvalidBaseOK = false);
1871
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1872
                                  EvalInfo &Info);
1873
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1874
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1875
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1876
                                    EvalInfo &Info);
1877
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1878
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1879
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1880
                           EvalInfo &Info);
1881
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1882
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1883
                                  EvalInfo &Info);
1884
1885
/// Evaluate an integer or fixed point expression into an APResult.
1886
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1887
                                        EvalInfo &Info);
1888
1889
/// Evaluate only a fixed point expression into an APResult.
1890
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1891
                               EvalInfo &Info);
1892
1893
//===----------------------------------------------------------------------===//
1894
// Misc utilities
1895
//===----------------------------------------------------------------------===//
1896
1897
/// Negate an APSInt in place, converting it to a signed form if necessary, and
1898
/// preserving its value (by extending by up to one bit as needed).
1899
0
static void negateAsSigned(APSInt &Int) {
1900
0
  if (Int.isUnsigned() || Int.isMinSignedValue()) {
1901
0
    Int = Int.extend(Int.getBitWidth() + 1);
1902
0
    Int.setIsSigned(true);
1903
0
  }
1904
0
  Int = -Int;
1905
0
}
1906
1907
template<typename KeyT>
1908
APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1909
0
                                         ScopeKind Scope, LValue &LV) {
1910
0
  unsigned Version = getTempVersion();
1911
0
  APValue::LValueBase Base(Key, Index, Version);
1912
0
  LV.set(Base);
1913
0
  return createLocal(Base, Key, T, Scope);
1914
0
}
Unexecuted instantiation: ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::VarDecl>(clang::VarDecl const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Unexecuted instantiation: ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::OpaqueValueExpr>(clang::OpaqueValueExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Unexecuted instantiation: ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::Expr>(clang::Expr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Unexecuted instantiation: ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::MaterializeTemporaryExpr>(clang::MaterializeTemporaryExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
1915
1916
/// Allocate storage for a parameter of a function call made in this frame.
1917
APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1918
0
                                     LValue &LV) {
1919
0
  assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1920
0
  APValue::LValueBase Base(PVD, Index, Args.Version);
1921
0
  LV.set(Base);
1922
  // We always destroy parameters at the end of the call, even if we'd allow
1923
  // them to live to the end of the full-expression at runtime, in order to
1924
  // give portable results and match other compilers.
1925
0
  return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1926
0
}
1927
1928
APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1929
0
                                     QualType T, ScopeKind Scope) {
1930
0
  assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1931
0
  unsigned Version = Base.getVersion();
1932
0
  APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1933
0
  assert(Result.isAbsent() && "local created multiple times");
1934
1935
  // If we're creating a local immediately in the operand of a speculative
1936
  // evaluation, don't register a cleanup to be run outside the speculative
1937
  // evaluation context, since we won't actually be able to initialize this
1938
  // object.
1939
0
  if (Index <= Info.SpeculativeEvaluationDepth) {
1940
0
    if (T.isDestructedType())
1941
0
      Info.noteSideEffect();
1942
0
  } else {
1943
0
    Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1944
0
  }
1945
0
  return Result;
1946
0
}
1947
1948
0
APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1949
0
  if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1950
0
    FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1951
0
    return nullptr;
1952
0
  }
1953
1954
0
  DynamicAllocLValue DA(NumHeapAllocs++);
1955
0
  LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1956
0
  auto Result = HeapAllocs.emplace(std::piecewise_construct,
1957
0
                                   std::forward_as_tuple(DA), std::tuple<>());
1958
0
  assert(Result.second && "reused a heap alloc index?");
1959
0
  Result.first->second.AllocExpr = E;
1960
0
  return &Result.first->second.Value;
1961
0
}
1962
1963
/// Produce a string describing the given constexpr call.
1964
0
void CallStackFrame::describe(raw_ostream &Out) const {
1965
0
  unsigned ArgIndex = 0;
1966
0
  bool IsMemberCall =
1967
0
      isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1968
0
      cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1969
1970
0
  if (!IsMemberCall)
1971
0
    Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1972
0
                                 /*Qualified=*/false);
1973
1974
0
  if (This && IsMemberCall) {
1975
0
    if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1976
0
      const Expr *Object = MCE->getImplicitObjectArgument();
1977
0
      Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1978
0
                          /*Indentation=*/0);
1979
0
      if (Object->getType()->isPointerType())
1980
0
          Out << "->";
1981
0
      else
1982
0
          Out << ".";
1983
0
    } else if (const auto *OCE =
1984
0
                   dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1985
0
      OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1986
0
                                  Info.Ctx.getPrintingPolicy(),
1987
0
                                  /*Indentation=*/0);
1988
0
      Out << ".";
1989
0
    } else {
1990
0
      APValue Val;
1991
0
      This->moveInto(Val);
1992
0
      Val.printPretty(
1993
0
          Out, Info.Ctx,
1994
0
          Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
1995
0
      Out << ".";
1996
0
    }
1997
0
    Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1998
0
                                 /*Qualified=*/false);
1999
0
    IsMemberCall = false;
2000
0
  }
2001
2002
0
  Out << '(';
2003
2004
0
  for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2005
0
       E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2006
0
    if (ArgIndex > (unsigned)IsMemberCall)
2007
0
      Out << ", ";
2008
2009
0
    const ParmVarDecl *Param = *I;
2010
0
    APValue *V = Info.getParamSlot(Arguments, Param);
2011
0
    if (V)
2012
0
      V->printPretty(Out, Info.Ctx, Param->getType());
2013
0
    else
2014
0
      Out << "<...>";
2015
2016
0
    if (ArgIndex == 0 && IsMemberCall)
2017
0
      Out << "->" << *Callee << '(';
2018
0
  }
2019
2020
0
  Out << ')';
2021
0
}
2022
2023
/// Evaluate an expression to see if it had side-effects, and discard its
2024
/// result.
2025
/// \return \c true if the caller should keep evaluating.
2026
0
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2027
0
  assert(!E->isValueDependent());
2028
0
  APValue Scratch;
2029
0
  if (!Evaluate(Scratch, Info, E))
2030
    // We don't need the value, but we might have skipped a side effect here.
2031
0
    return Info.noteSideEffect();
2032
0
  return true;
2033
0
}
2034
2035
/// Should this call expression be treated as a no-op?
2036
0
static bool IsNoOpCall(const CallExpr *E) {
2037
0
  unsigned Builtin = E->getBuiltinCallee();
2038
0
  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2039
0
          Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2040
0
          Builtin == Builtin::BI__builtin_function_start);
2041
0
}
2042
2043
0
static bool IsGlobalLValue(APValue::LValueBase B) {
2044
  // C++11 [expr.const]p3 An address constant expression is a prvalue core
2045
  // constant expression of pointer type that evaluates to...
2046
2047
  // ... a null pointer value, or a prvalue core constant expression of type
2048
  // std::nullptr_t.
2049
0
  if (!B)
2050
0
    return true;
2051
2052
0
  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2053
    // ... the address of an object with static storage duration,
2054
0
    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2055
0
      return VD->hasGlobalStorage();
2056
0
    if (isa<TemplateParamObjectDecl>(D))
2057
0
      return true;
2058
    // ... the address of a function,
2059
    // ... the address of a GUID [MS extension],
2060
    // ... the address of an unnamed global constant
2061
0
    return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2062
0
  }
2063
2064
0
  if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2065
0
    return true;
2066
2067
0
  const Expr *E = B.get<const Expr*>();
2068
0
  switch (E->getStmtClass()) {
2069
0
  default:
2070
0
    return false;
2071
0
  case Expr::CompoundLiteralExprClass: {
2072
0
    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2073
0
    return CLE->isFileScope() && CLE->isLValue();
2074
0
  }
2075
0
  case Expr::MaterializeTemporaryExprClass:
2076
    // A materialized temporary might have been lifetime-extended to static
2077
    // storage duration.
2078
0
    return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2079
  // A string literal has static storage duration.
2080
0
  case Expr::StringLiteralClass:
2081
0
  case Expr::PredefinedExprClass:
2082
0
  case Expr::ObjCStringLiteralClass:
2083
0
  case Expr::ObjCEncodeExprClass:
2084
0
    return true;
2085
0
  case Expr::ObjCBoxedExprClass:
2086
0
    return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2087
0
  case Expr::CallExprClass:
2088
0
    return IsNoOpCall(cast<CallExpr>(E));
2089
  // For GCC compatibility, &&label has static storage duration.
2090
0
  case Expr::AddrLabelExprClass:
2091
0
    return true;
2092
  // A Block literal expression may be used as the initialization value for
2093
  // Block variables at global or local static scope.
2094
0
  case Expr::BlockExprClass:
2095
0
    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2096
  // The APValue generated from a __builtin_source_location will be emitted as a
2097
  // literal.
2098
0
  case Expr::SourceLocExprClass:
2099
0
    return true;
2100
0
  case Expr::ImplicitValueInitExprClass:
2101
    // FIXME:
2102
    // We can never form an lvalue with an implicit value initialization as its
2103
    // base through expression evaluation, so these only appear in one case: the
2104
    // implicit variable declaration we invent when checking whether a constexpr
2105
    // constructor can produce a constant expression. We must assume that such
2106
    // an expression might be a global lvalue.
2107
0
    return true;
2108
0
  }
2109
0
}
2110
2111
0
static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2112
0
  return LVal.Base.dyn_cast<const ValueDecl*>();
2113
0
}
2114
2115
0
static bool IsLiteralLValue(const LValue &Value) {
2116
0
  if (Value.getLValueCallIndex())
2117
0
    return false;
2118
0
  const Expr *E = Value.Base.dyn_cast<const Expr*>();
2119
0
  return E && !isa<MaterializeTemporaryExpr>(E);
2120
0
}
2121
2122
0
static bool IsWeakLValue(const LValue &Value) {
2123
0
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2124
0
  return Decl && Decl->isWeak();
2125
0
}
2126
2127
0
static bool isZeroSized(const LValue &Value) {
2128
0
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2129
0
  if (Decl && isa<VarDecl>(Decl)) {
2130
0
    QualType Ty = Decl->getType();
2131
0
    if (Ty->isArrayType())
2132
0
      return Ty->isIncompleteType() ||
2133
0
             Decl->getASTContext().getTypeSize(Ty) == 0;
2134
0
  }
2135
0
  return false;
2136
0
}
2137
2138
0
static bool HasSameBase(const LValue &A, const LValue &B) {
2139
0
  if (!A.getLValueBase())
2140
0
    return !B.getLValueBase();
2141
0
  if (!B.getLValueBase())
2142
0
    return false;
2143
2144
0
  if (A.getLValueBase().getOpaqueValue() !=
2145
0
      B.getLValueBase().getOpaqueValue())
2146
0
    return false;
2147
2148
0
  return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2149
0
         A.getLValueVersion() == B.getLValueVersion();
2150
0
}
2151
2152
0
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2153
0
  assert(Base && "no location for a null lvalue");
2154
0
  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2155
2156
  // For a parameter, find the corresponding call stack frame (if it still
2157
  // exists), and point at the parameter of the function definition we actually
2158
  // invoked.
2159
0
  if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2160
0
    unsigned Idx = PVD->getFunctionScopeIndex();
2161
0
    for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2162
0
      if (F->Arguments.CallIndex == Base.getCallIndex() &&
2163
0
          F->Arguments.Version == Base.getVersion() && F->Callee &&
2164
0
          Idx < F->Callee->getNumParams()) {
2165
0
        VD = F->Callee->getParamDecl(Idx);
2166
0
        break;
2167
0
      }
2168
0
    }
2169
0
  }
2170
2171
0
  if (VD)
2172
0
    Info.Note(VD->getLocation(), diag::note_declared_at);
2173
0
  else if (const Expr *E = Base.dyn_cast<const Expr*>())
2174
0
    Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2175
0
  else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2176
    // FIXME: Produce a note for dangling pointers too.
2177
0
    if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2178
0
      Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2179
0
                diag::note_constexpr_dynamic_alloc_here);
2180
0
  }
2181
2182
  // We have no information to show for a typeid(T) object.
2183
0
}
2184
2185
enum class CheckEvaluationResultKind {
2186
  ConstantExpression,
2187
  FullyInitialized,
2188
};
2189
2190
/// Materialized temporaries that we've already checked to determine if they're
2191
/// initializsed by a constant expression.
2192
using CheckedTemporaries =
2193
    llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2194
2195
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2196
                                  EvalInfo &Info, SourceLocation DiagLoc,
2197
                                  QualType Type, const APValue &Value,
2198
                                  ConstantExprKind Kind,
2199
                                  const FieldDecl *SubobjectDecl,
2200
                                  CheckedTemporaries &CheckedTemps);
2201
2202
/// Check that this reference or pointer core constant expression is a valid
2203
/// value for an address or reference constant expression. Return true if we
2204
/// can fold this expression, whether or not it's a constant expression.
2205
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2206
                                          QualType Type, const LValue &LVal,
2207
                                          ConstantExprKind Kind,
2208
0
                                          CheckedTemporaries &CheckedTemps) {
2209
0
  bool IsReferenceType = Type->isReferenceType();
2210
2211
0
  APValue::LValueBase Base = LVal.getLValueBase();
2212
0
  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2213
2214
0
  const Expr *BaseE = Base.dyn_cast<const Expr *>();
2215
0
  const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2216
2217
  // Additional restrictions apply in a template argument. We only enforce the
2218
  // C++20 restrictions here; additional syntactic and semantic restrictions
2219
  // are applied elsewhere.
2220
0
  if (isTemplateArgument(Kind)) {
2221
0
    int InvalidBaseKind = -1;
2222
0
    StringRef Ident;
2223
0
    if (Base.is<TypeInfoLValue>())
2224
0
      InvalidBaseKind = 0;
2225
0
    else if (isa_and_nonnull<StringLiteral>(BaseE))
2226
0
      InvalidBaseKind = 1;
2227
0
    else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2228
0
             isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2229
0
      InvalidBaseKind = 2;
2230
0
    else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2231
0
      InvalidBaseKind = 3;
2232
0
      Ident = PE->getIdentKindName();
2233
0
    }
2234
2235
0
    if (InvalidBaseKind != -1) {
2236
0
      Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2237
0
          << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2238
0
          << Ident;
2239
0
      return false;
2240
0
    }
2241
0
  }
2242
2243
0
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2244
0
      FD && FD->isImmediateFunction()) {
2245
0
    Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2246
0
        << !Type->isAnyPointerType();
2247
0
    Info.Note(FD->getLocation(), diag::note_declared_at);
2248
0
    return false;
2249
0
  }
2250
2251
  // Check that the object is a global. Note that the fake 'this' object we
2252
  // manufacture when checking potential constant expressions is conservatively
2253
  // assumed to be global here.
2254
0
  if (!IsGlobalLValue(Base)) {
2255
0
    if (Info.getLangOpts().CPlusPlus11) {
2256
0
      Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2257
0
          << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2258
0
          << BaseVD;
2259
0
      auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2260
0
      if (VarD && VarD->isConstexpr()) {
2261
        // Non-static local constexpr variables have unintuitive semantics:
2262
        //   constexpr int a = 1;
2263
        //   constexpr const int *p = &a;
2264
        // ... is invalid because the address of 'a' is not constant. Suggest
2265
        // adding a 'static' in this case.
2266
0
        Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2267
0
            << VarD
2268
0
            << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2269
0
      } else {
2270
0
        NoteLValueLocation(Info, Base);
2271
0
      }
2272
0
    } else {
2273
0
      Info.FFDiag(Loc);
2274
0
    }
2275
    // Don't allow references to temporaries to escape.
2276
0
    return false;
2277
0
  }
2278
0
  assert((Info.checkingPotentialConstantExpression() ||
2279
0
          LVal.getLValueCallIndex() == 0) &&
2280
0
         "have call index for global lvalue");
2281
2282
0
  if (Base.is<DynamicAllocLValue>()) {
2283
0
    Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2284
0
        << IsReferenceType << !Designator.Entries.empty();
2285
0
    NoteLValueLocation(Info, Base);
2286
0
    return false;
2287
0
  }
2288
2289
0
  if (BaseVD) {
2290
0
    if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2291
      // Check if this is a thread-local variable.
2292
0
      if (Var->getTLSKind())
2293
        // FIXME: Diagnostic!
2294
0
        return false;
2295
2296
      // A dllimport variable never acts like a constant, unless we're
2297
      // evaluating a value for use only in name mangling.
2298
0
      if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2299
        // FIXME: Diagnostic!
2300
0
        return false;
2301
2302
      // In CUDA/HIP device compilation, only device side variables have
2303
      // constant addresses.
2304
0
      if (Info.getCtx().getLangOpts().CUDA &&
2305
0
          Info.getCtx().getLangOpts().CUDAIsDevice &&
2306
0
          Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2307
0
        if ((!Var->hasAttr<CUDADeviceAttr>() &&
2308
0
             !Var->hasAttr<CUDAConstantAttr>() &&
2309
0
             !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2310
0
             !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2311
0
            Var->hasAttr<HIPManagedAttr>())
2312
0
          return false;
2313
0
      }
2314
0
    }
2315
0
    if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2316
      // __declspec(dllimport) must be handled very carefully:
2317
      // We must never initialize an expression with the thunk in C++.
2318
      // Doing otherwise would allow the same id-expression to yield
2319
      // different addresses for the same function in different translation
2320
      // units.  However, this means that we must dynamically initialize the
2321
      // expression with the contents of the import address table at runtime.
2322
      //
2323
      // The C language has no notion of ODR; furthermore, it has no notion of
2324
      // dynamic initialization.  This means that we are permitted to
2325
      // perform initialization with the address of the thunk.
2326
0
      if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2327
0
          FD->hasAttr<DLLImportAttr>())
2328
        // FIXME: Diagnostic!
2329
0
        return false;
2330
0
    }
2331
0
  } else if (const auto *MTE =
2332
0
                 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2333
0
    if (CheckedTemps.insert(MTE).second) {
2334
0
      QualType TempType = getType(Base);
2335
0
      if (TempType.isDestructedType()) {
2336
0
        Info.FFDiag(MTE->getExprLoc(),
2337
0
                    diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2338
0
            << TempType;
2339
0
        return false;
2340
0
      }
2341
2342
0
      APValue *V = MTE->getOrCreateValue(false);
2343
0
      assert(V && "evasluation result refers to uninitialised temporary");
2344
0
      if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2345
0
                                 Info, MTE->getExprLoc(), TempType, *V, Kind,
2346
0
                                 /*SubobjectDecl=*/nullptr, CheckedTemps))
2347
0
        return false;
2348
0
    }
2349
0
  }
2350
2351
  // Allow address constant expressions to be past-the-end pointers. This is
2352
  // an extension: the standard requires them to point to an object.
2353
0
  if (!IsReferenceType)
2354
0
    return true;
2355
2356
  // A reference constant expression must refer to an object.
2357
0
  if (!Base) {
2358
    // FIXME: diagnostic
2359
0
    Info.CCEDiag(Loc);
2360
0
    return true;
2361
0
  }
2362
2363
  // Does this refer one past the end of some object?
2364
0
  if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2365
0
    Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2366
0
      << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2367
0
    NoteLValueLocation(Info, Base);
2368
0
  }
2369
2370
0
  return true;
2371
0
}
2372
2373
/// Member pointers are constant expressions unless they point to a
2374
/// non-virtual dllimport member function.
2375
static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2376
                                                 SourceLocation Loc,
2377
                                                 QualType Type,
2378
                                                 const APValue &Value,
2379
0
                                                 ConstantExprKind Kind) {
2380
0
  const ValueDecl *Member = Value.getMemberPointerDecl();
2381
0
  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2382
0
  if (!FD)
2383
0
    return true;
2384
0
  if (FD->isImmediateFunction()) {
2385
0
    Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2386
0
    Info.Note(FD->getLocation(), diag::note_declared_at);
2387
0
    return false;
2388
0
  }
2389
0
  return isForManglingOnly(Kind) || FD->isVirtual() ||
2390
0
         !FD->hasAttr<DLLImportAttr>();
2391
0
}
2392
2393
/// Check that this core constant expression is of literal type, and if not,
2394
/// produce an appropriate diagnostic.
2395
static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2396
14
                             const LValue *This = nullptr) {
2397
14
  if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2398
14
    return true;
2399
2400
  // C++1y: A constant initializer for an object o [...] may also invoke
2401
  // constexpr constructors for o and its subobjects even if those objects
2402
  // are of non-literal class types.
2403
  //
2404
  // C++11 missed this detail for aggregates, so classes like this:
2405
  //   struct foo_t { union { int i; volatile int j; } u; };
2406
  // are not (obviously) initializable like so:
2407
  //   __attribute__((__require_constant_initialization__))
2408
  //   static const foo_t x = {{0}};
2409
  // because "i" is a subobject with non-literal initialization (due to the
2410
  // volatile member of the union). See:
2411
  //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2412
  // Therefore, we use the C++1y behavior.
2413
0
  if (This && Info.EvaluatingDecl == This->getLValueBase())
2414
0
    return true;
2415
2416
  // Prvalue constant expressions must be of literal types.
2417
0
  if (Info.getLangOpts().CPlusPlus11)
2418
0
    Info.FFDiag(E, diag::note_constexpr_nonliteral)
2419
0
      << E->getType();
2420
0
  else
2421
0
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2422
0
  return false;
2423
0
}
2424
2425
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2426
                                  EvalInfo &Info, SourceLocation DiagLoc,
2427
                                  QualType Type, const APValue &Value,
2428
                                  ConstantExprKind Kind,
2429
                                  const FieldDecl *SubobjectDecl,
2430
5
                                  CheckedTemporaries &CheckedTemps) {
2431
5
  if (!Value.hasValue()) {
2432
0
    if (SubobjectDecl) {
2433
0
      Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2434
0
          << /*(name)*/ 1 << SubobjectDecl;
2435
0
      Info.Note(SubobjectDecl->getLocation(),
2436
0
                diag::note_constexpr_subobject_declared_here);
2437
0
    } else {
2438
0
      Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2439
0
          << /*of type*/ 0 << Type;
2440
0
    }
2441
0
    return false;
2442
0
  }
2443
2444
  // We allow _Atomic(T) to be initialized from anything that T can be
2445
  // initialized from.
2446
5
  if (const AtomicType *AT = Type->getAs<AtomicType>())
2447
0
    Type = AT->getValueType();
2448
2449
  // Core issue 1454: For a literal constant expression of array or class type,
2450
  // each subobject of its value shall have been initialized by a constant
2451
  // expression.
2452
5
  if (Value.isArray()) {
2453
0
    QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2454
0
    for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2455
0
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2456
0
                                 Value.getArrayInitializedElt(I), Kind,
2457
0
                                 SubobjectDecl, CheckedTemps))
2458
0
        return false;
2459
0
    }
2460
0
    if (!Value.hasArrayFiller())
2461
0
      return true;
2462
0
    return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2463
0
                                 Value.getArrayFiller(), Kind, SubobjectDecl,
2464
0
                                 CheckedTemps);
2465
0
  }
2466
5
  if (Value.isUnion() && Value.getUnionField()) {
2467
0
    return CheckEvaluationResult(
2468
0
        CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2469
0
        Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2470
0
  }
2471
5
  if (Value.isStruct()) {
2472
0
    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2473
0
    if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2474
0
      unsigned BaseIndex = 0;
2475
0
      for (const CXXBaseSpecifier &BS : CD->bases()) {
2476
0
        const APValue &BaseValue = Value.getStructBase(BaseIndex);
2477
0
        if (!BaseValue.hasValue()) {
2478
0
          SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2479
0
          Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2480
0
              << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2481
0
          return false;
2482
0
        }
2483
0
        if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2484
0
                                   Kind, /*SubobjectDecl=*/nullptr,
2485
0
                                   CheckedTemps))
2486
0
          return false;
2487
0
        ++BaseIndex;
2488
0
      }
2489
0
    }
2490
0
    for (const auto *I : RD->fields()) {
2491
0
      if (I->isUnnamedBitfield())
2492
0
        continue;
2493
2494
0
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2495
0
                                 Value.getStructField(I->getFieldIndex()), Kind,
2496
0
                                 I, CheckedTemps))
2497
0
        return false;
2498
0
    }
2499
0
  }
2500
2501
5
  if (Value.isLValue() &&
2502
5
      CERK == CheckEvaluationResultKind::ConstantExpression) {
2503
0
    LValue LVal;
2504
0
    LVal.setFrom(Info.Ctx, Value);
2505
0
    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2506
0
                                         CheckedTemps);
2507
0
  }
2508
2509
5
  if (Value.isMemberPointer() &&
2510
5
      CERK == CheckEvaluationResultKind::ConstantExpression)
2511
0
    return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2512
2513
  // Everything else is fine.
2514
5
  return true;
2515
5
}
2516
2517
/// Check that this core constant expression value is a valid value for a
2518
/// constant expression. If not, report an appropriate diagnostic. Does not
2519
/// check that the expression is of literal type.
2520
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2521
                                    QualType Type, const APValue &Value,
2522
5
                                    ConstantExprKind Kind) {
2523
  // Nothing to check for a constant expression of type 'cv void'.
2524
5
  if (Type->isVoidType())
2525
0
    return true;
2526
2527
5
  CheckedTemporaries CheckedTemps;
2528
5
  return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2529
5
                               Info, DiagLoc, Type, Value, Kind,
2530
5
                               /*SubobjectDecl=*/nullptr, CheckedTemps);
2531
5
}
2532
2533
/// Check that this evaluated value is fully-initialized and can be loaded by
2534
/// an lvalue-to-rvalue conversion.
2535
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2536
0
                                  QualType Type, const APValue &Value) {
2537
0
  CheckedTemporaries CheckedTemps;
2538
0
  return CheckEvaluationResult(
2539
0
      CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2540
0
      ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2541
0
}
2542
2543
/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2544
/// "the allocated storage is deallocated within the evaluation".
2545
5
static bool CheckMemoryLeaks(EvalInfo &Info) {
2546
5
  if (!Info.HeapAllocs.empty()) {
2547
    // We can still fold to a constant despite a compile-time memory leak,
2548
    // so long as the heap allocation isn't referenced in the result (we check
2549
    // that in CheckConstantExpression).
2550
0
    Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2551
0
                 diag::note_constexpr_memory_leak)
2552
0
        << unsigned(Info.HeapAllocs.size() - 1);
2553
0
  }
2554
5
  return true;
2555
5
}
2556
2557
0
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2558
  // A null base expression indicates a null pointer.  These are always
2559
  // evaluatable, and they are false unless the offset is zero.
2560
0
  if (!Value.getLValueBase()) {
2561
    // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2562
0
    Result = !Value.getLValueOffset().isZero();
2563
0
    return true;
2564
0
  }
2565
2566
  // We have a non-null base.  These are generally known to be true, but if it's
2567
  // a weak declaration it can be null at runtime.
2568
0
  Result = true;
2569
0
  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2570
0
  return !Decl || !Decl->isWeak();
2571
0
}
2572
2573
0
static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2574
  // TODO: This function should produce notes if it fails.
2575
0
  switch (Val.getKind()) {
2576
0
  case APValue::None:
2577
0
  case APValue::Indeterminate:
2578
0
    return false;
2579
0
  case APValue::Int:
2580
0
    Result = Val.getInt().getBoolValue();
2581
0
    return true;
2582
0
  case APValue::FixedPoint:
2583
0
    Result = Val.getFixedPoint().getBoolValue();
2584
0
    return true;
2585
0
  case APValue::Float:
2586
0
    Result = !Val.getFloat().isZero();
2587
0
    return true;
2588
0
  case APValue::ComplexInt:
2589
0
    Result = Val.getComplexIntReal().getBoolValue() ||
2590
0
             Val.getComplexIntImag().getBoolValue();
2591
0
    return true;
2592
0
  case APValue::ComplexFloat:
2593
0
    Result = !Val.getComplexFloatReal().isZero() ||
2594
0
             !Val.getComplexFloatImag().isZero();
2595
0
    return true;
2596
0
  case APValue::LValue:
2597
0
    return EvalPointerValueAsBool(Val, Result);
2598
0
  case APValue::MemberPointer:
2599
0
    if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2600
0
      return false;
2601
0
    }
2602
0
    Result = Val.getMemberPointerDecl();
2603
0
    return true;
2604
0
  case APValue::Vector:
2605
0
  case APValue::Array:
2606
0
  case APValue::Struct:
2607
0
  case APValue::Union:
2608
0
  case APValue::AddrLabelDiff:
2609
0
    return false;
2610
0
  }
2611
2612
0
  llvm_unreachable("unknown APValue kind");
2613
0
}
2614
2615
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2616
0
                                       EvalInfo &Info) {
2617
0
  assert(!E->isValueDependent());
2618
0
  assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2619
0
  APValue Val;
2620
0
  if (!Evaluate(Val, Info, E))
2621
0
    return false;
2622
0
  return HandleConversionToBool(Val, Result);
2623
0
}
2624
2625
template<typename T>
2626
static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2627
0
                           const T &SrcValue, QualType DestType) {
2628
0
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2629
0
    << SrcValue << DestType;
2630
0
  return Info.noteUndefinedBehavior();
2631
0
}
Unexecuted instantiation: ExprConstant.cpp:bool HandleOverflow<llvm::APSInt>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, clang::QualType)
Unexecuted instantiation: ExprConstant.cpp:bool HandleOverflow<llvm::APFloat>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFloat const&, clang::QualType)
Unexecuted instantiation: ExprConstant.cpp:bool HandleOverflow<llvm::APFixedPoint>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFixedPoint const&, clang::QualType)
2632
2633
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2634
                                 QualType SrcType, const APFloat &Value,
2635
0
                                 QualType DestType, APSInt &Result) {
2636
0
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2637
  // Determine whether we are converting to unsigned or signed.
2638
0
  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2639
2640
0
  Result = APSInt(DestWidth, !DestSigned);
2641
0
  bool ignored;
2642
0
  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2643
0
      & APFloat::opInvalidOp)
2644
0
    return HandleOverflow(Info, E, Value, DestType);
2645
0
  return true;
2646
0
}
2647
2648
/// Get rounding mode to use in evaluation of the specified expression.
2649
///
2650
/// If rounding mode is unknown at compile time, still try to evaluate the
2651
/// expression. If the result is exact, it does not depend on rounding mode.
2652
/// So return "tonearest" mode instead of "dynamic".
2653
0
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2654
0
  llvm::RoundingMode RM =
2655
0
      E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2656
0
  if (RM == llvm::RoundingMode::Dynamic)
2657
0
    RM = llvm::RoundingMode::NearestTiesToEven;
2658
0
  return RM;
2659
0
}
2660
2661
/// Check if the given evaluation result is allowed for constant evaluation.
2662
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2663
0
                                     APFloat::opStatus St) {
2664
  // In a constant context, assume that any dynamic rounding mode or FP
2665
  // exception state matches the default floating-point environment.
2666
0
  if (Info.InConstantContext)
2667
0
    return true;
2668
2669
0
  FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2670
0
  if ((St & APFloat::opInexact) &&
2671
0
      FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2672
    // Inexact result means that it depends on rounding mode. If the requested
2673
    // mode is dynamic, the evaluation cannot be made in compile time.
2674
0
    Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2675
0
    return false;
2676
0
  }
2677
2678
0
  if ((St != APFloat::opOK) &&
2679
0
      (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2680
0
       FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2681
0
       FPO.getAllowFEnvAccess())) {
2682
0
    Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2683
0
    return false;
2684
0
  }
2685
2686
0
  if ((St & APFloat::opStatus::opInvalidOp) &&
2687
0
      FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2688
    // There is no usefully definable result.
2689
0
    Info.FFDiag(E);
2690
0
    return false;
2691
0
  }
2692
2693
  // FIXME: if:
2694
  // - evaluation triggered other FP exception, and
2695
  // - exception mode is not "ignore", and
2696
  // - the expression being evaluated is not a part of global variable
2697
  //   initializer,
2698
  // the evaluation probably need to be rejected.
2699
0
  return true;
2700
0
}
2701
2702
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2703
                                   QualType SrcType, QualType DestType,
2704
0
                                   APFloat &Result) {
2705
0
  assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2706
0
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2707
0
  APFloat::opStatus St;
2708
0
  APFloat Value = Result;
2709
0
  bool ignored;
2710
0
  St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2711
0
  return checkFloatingPointResult(Info, E, St);
2712
0
}
2713
2714
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2715
                                 QualType DestType, QualType SrcType,
2716
0
                                 const APSInt &Value) {
2717
0
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2718
  // Figure out if this is a truncate, extend or noop cast.
2719
  // If the input is signed, do a sign extend, noop, or truncate.
2720
0
  APSInt Result = Value.extOrTrunc(DestWidth);
2721
0
  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2722
0
  if (DestType->isBooleanType())
2723
0
    Result = Value.getBoolValue();
2724
0
  return Result;
2725
0
}
2726
2727
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2728
                                 const FPOptions FPO,
2729
                                 QualType SrcType, const APSInt &Value,
2730
0
                                 QualType DestType, APFloat &Result) {
2731
0
  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2732
0
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2733
0
  APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2734
0
  return checkFloatingPointResult(Info, E, St);
2735
0
}
2736
2737
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2738
0
                                  APValue &Value, const FieldDecl *FD) {
2739
0
  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2740
2741
0
  if (!Value.isInt()) {
2742
    // Trying to store a pointer-cast-to-integer into a bitfield.
2743
    // FIXME: In this case, we should provide the diagnostic for casting
2744
    // a pointer to an integer.
2745
0
    assert(Value.isLValue() && "integral value neither int nor lvalue?");
2746
0
    Info.FFDiag(E);
2747
0
    return false;
2748
0
  }
2749
2750
0
  APSInt &Int = Value.getInt();
2751
0
  unsigned OldBitWidth = Int.getBitWidth();
2752
0
  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2753
0
  if (NewBitWidth < OldBitWidth)
2754
0
    Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2755
0
  return true;
2756
0
}
2757
2758
/// Perform the given integer operation, which is known to need at most BitWidth
2759
/// bits, and check for overflow in the original type (if that type was not an
2760
/// unsigned type).
2761
template<typename Operation>
2762
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2763
                                 const APSInt &LHS, const APSInt &RHS,
2764
                                 unsigned BitWidth, Operation Op,
2765
0
                                 APSInt &Result) {
2766
0
  if (LHS.isUnsigned()) {
2767
0
    Result = Op(LHS, RHS);
2768
0
    return true;
2769
0
  }
2770
2771
0
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2772
0
  Result = Value.trunc(LHS.getBitWidth());
2773
0
  if (Result.extend(BitWidth) != Value) {
2774
0
    if (Info.checkingForUndefinedBehavior())
2775
0
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2776
0
                                       diag::warn_integer_constant_overflow)
2777
0
          << toString(Result, 10) << E->getType() << E->getSourceRange();
2778
0
    return HandleOverflow(Info, E, Value, E->getType());
2779
0
  }
2780
0
  return true;
2781
0
}
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
2782
2783
/// Perform the given binary integer operation.
2784
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2785
                              const APSInt &LHS, BinaryOperatorKind Opcode,
2786
0
                              APSInt RHS, APSInt &Result) {
2787
0
  bool HandleOverflowResult = true;
2788
0
  switch (Opcode) {
2789
0
  default:
2790
0
    Info.FFDiag(E);
2791
0
    return false;
2792
0
  case BO_Mul:
2793
0
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2794
0
                                std::multiplies<APSInt>(), Result);
2795
0
  case BO_Add:
2796
0
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2797
0
                                std::plus<APSInt>(), Result);
2798
0
  case BO_Sub:
2799
0
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2800
0
                                std::minus<APSInt>(), Result);
2801
0
  case BO_And: Result = LHS & RHS; return true;
2802
0
  case BO_Xor: Result = LHS ^ RHS; return true;
2803
0
  case BO_Or:  Result = LHS | RHS; return true;
2804
0
  case BO_Div:
2805
0
  case BO_Rem:
2806
0
    if (RHS == 0) {
2807
0
      Info.FFDiag(E, diag::note_expr_divide_by_zero)
2808
0
          << E->getRHS()->getSourceRange();
2809
0
      return false;
2810
0
    }
2811
    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2812
    // this operation and gives the two's complement result.
2813
0
    if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2814
0
        LHS.isMinSignedValue())
2815
0
      HandleOverflowResult = HandleOverflow(
2816
0
          Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2817
0
    Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2818
0
    return HandleOverflowResult;
2819
0
  case BO_Shl: {
2820
0
    if (Info.getLangOpts().OpenCL)
2821
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2822
0
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2823
0
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2824
0
                    RHS.isUnsigned());
2825
0
    else if (RHS.isSigned() && RHS.isNegative()) {
2826
      // During constant-folding, a negative shift is an opposite shift. Such
2827
      // a shift is not a constant expression.
2828
0
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2829
0
      RHS = -RHS;
2830
0
      goto shift_right;
2831
0
    }
2832
0
  shift_left:
2833
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2834
    // the shifted type.
2835
0
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2836
0
    if (SA != RHS) {
2837
0
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2838
0
        << RHS << E->getType() << LHS.getBitWidth();
2839
0
    } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2840
      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2841
      // operand, and must not overflow the corresponding unsigned type.
2842
      // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2843
      // E1 x 2^E2 module 2^N.
2844
0
      if (LHS.isNegative())
2845
0
        Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2846
0
      else if (LHS.countl_zero() < SA)
2847
0
        Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2848
0
    }
2849
0
    Result = LHS << SA;
2850
0
    return true;
2851
0
  }
2852
0
  case BO_Shr: {
2853
0
    if (Info.getLangOpts().OpenCL)
2854
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2855
0
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2856
0
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2857
0
                    RHS.isUnsigned());
2858
0
    else if (RHS.isSigned() && RHS.isNegative()) {
2859
      // During constant-folding, a negative shift is an opposite shift. Such a
2860
      // shift is not a constant expression.
2861
0
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2862
0
      RHS = -RHS;
2863
0
      goto shift_left;
2864
0
    }
2865
0
  shift_right:
2866
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2867
    // shifted type.
2868
0
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2869
0
    if (SA != RHS)
2870
0
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2871
0
        << RHS << E->getType() << LHS.getBitWidth();
2872
0
    Result = LHS >> SA;
2873
0
    return true;
2874
0
  }
2875
2876
0
  case BO_LT: Result = LHS < RHS; return true;
2877
0
  case BO_GT: Result = LHS > RHS; return true;
2878
0
  case BO_LE: Result = LHS <= RHS; return true;
2879
0
  case BO_GE: Result = LHS >= RHS; return true;
2880
0
  case BO_EQ: Result = LHS == RHS; return true;
2881
0
  case BO_NE: Result = LHS != RHS; return true;
2882
0
  case BO_Cmp:
2883
0
    llvm_unreachable("BO_Cmp should be handled elsewhere");
2884
0
  }
2885
0
}
2886
2887
/// Perform the given binary floating-point operation, in-place, on LHS.
2888
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2889
                                  APFloat &LHS, BinaryOperatorKind Opcode,
2890
0
                                  const APFloat &RHS) {
2891
0
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2892
0
  APFloat::opStatus St;
2893
0
  switch (Opcode) {
2894
0
  default:
2895
0
    Info.FFDiag(E);
2896
0
    return false;
2897
0
  case BO_Mul:
2898
0
    St = LHS.multiply(RHS, RM);
2899
0
    break;
2900
0
  case BO_Add:
2901
0
    St = LHS.add(RHS, RM);
2902
0
    break;
2903
0
  case BO_Sub:
2904
0
    St = LHS.subtract(RHS, RM);
2905
0
    break;
2906
0
  case BO_Div:
2907
    // [expr.mul]p4:
2908
    //   If the second operand of / or % is zero the behavior is undefined.
2909
0
    if (RHS.isZero())
2910
0
      Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2911
0
    St = LHS.divide(RHS, RM);
2912
0
    break;
2913
0
  }
2914
2915
  // [expr.pre]p4:
2916
  //   If during the evaluation of an expression, the result is not
2917
  //   mathematically defined [...], the behavior is undefined.
2918
  // FIXME: C++ rules require us to not conform to IEEE 754 here.
2919
0
  if (LHS.isNaN()) {
2920
0
    Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2921
0
    return Info.noteUndefinedBehavior();
2922
0
  }
2923
2924
0
  return checkFloatingPointResult(Info, E, St);
2925
0
}
2926
2927
static bool handleLogicalOpForVector(const APInt &LHSValue,
2928
                                     BinaryOperatorKind Opcode,
2929
0
                                     const APInt &RHSValue, APInt &Result) {
2930
0
  bool LHS = (LHSValue != 0);
2931
0
  bool RHS = (RHSValue != 0);
2932
2933
0
  if (Opcode == BO_LAnd)
2934
0
    Result = LHS && RHS;
2935
0
  else
2936
0
    Result = LHS || RHS;
2937
0
  return true;
2938
0
}
2939
static bool handleLogicalOpForVector(const APFloat &LHSValue,
2940
                                     BinaryOperatorKind Opcode,
2941
0
                                     const APFloat &RHSValue, APInt &Result) {
2942
0
  bool LHS = !LHSValue.isZero();
2943
0
  bool RHS = !RHSValue.isZero();
2944
2945
0
  if (Opcode == BO_LAnd)
2946
0
    Result = LHS && RHS;
2947
0
  else
2948
0
    Result = LHS || RHS;
2949
0
  return true;
2950
0
}
2951
2952
static bool handleLogicalOpForVector(const APValue &LHSValue,
2953
                                     BinaryOperatorKind Opcode,
2954
0
                                     const APValue &RHSValue, APInt &Result) {
2955
  // The result is always an int type, however operands match the first.
2956
0
  if (LHSValue.getKind() == APValue::Int)
2957
0
    return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2958
0
                                    RHSValue.getInt(), Result);
2959
0
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2960
0
  return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2961
0
                                  RHSValue.getFloat(), Result);
2962
0
}
2963
2964
template <typename APTy>
2965
static bool
2966
handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2967
0
                               const APTy &RHSValue, APInt &Result) {
2968
0
  switch (Opcode) {
2969
0
  default:
2970
0
    llvm_unreachable("unsupported binary operator");
2971
0
  case BO_EQ:
2972
0
    Result = (LHSValue == RHSValue);
2973
0
    break;
2974
0
  case BO_NE:
2975
0
    Result = (LHSValue != RHSValue);
2976
0
    break;
2977
0
  case BO_LT:
2978
0
    Result = (LHSValue < RHSValue);
2979
0
    break;
2980
0
  case BO_GT:
2981
0
    Result = (LHSValue > RHSValue);
2982
0
    break;
2983
0
  case BO_LE:
2984
0
    Result = (LHSValue <= RHSValue);
2985
0
    break;
2986
0
  case BO_GE:
2987
0
    Result = (LHSValue >= RHSValue);
2988
0
    break;
2989
0
  }
2990
2991
  // The boolean operations on these vector types use an instruction that
2992
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2993
  // to -1 to make sure that we produce the correct value.
2994
0
  Result.negate();
2995
2996
0
  return true;
2997
0
}
Unexecuted instantiation: ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APSInt>(llvm::APSInt const&, clang::BinaryOperatorKind, llvm::APSInt const&, llvm::APInt&)
Unexecuted instantiation: ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APFloat>(llvm::APFloat const&, clang::BinaryOperatorKind, llvm::APFloat const&, llvm::APInt&)
2998
2999
static bool handleCompareOpForVector(const APValue &LHSValue,
3000
                                     BinaryOperatorKind Opcode,
3001
0
                                     const APValue &RHSValue, APInt &Result) {
3002
  // The result is always an int type, however operands match the first.
3003
0
  if (LHSValue.getKind() == APValue::Int)
3004
0
    return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3005
0
                                          RHSValue.getInt(), Result);
3006
0
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3007
0
  return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3008
0
                                        RHSValue.getFloat(), Result);
3009
0
}
3010
3011
// Perform binary operations for vector types, in place on the LHS.
3012
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3013
                                    BinaryOperatorKind Opcode,
3014
                                    APValue &LHSValue,
3015
0
                                    const APValue &RHSValue) {
3016
0
  assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3017
0
         "Operation not supported on vector types");
3018
3019
0
  const auto *VT = E->getType()->castAs<VectorType>();
3020
0
  unsigned NumElements = VT->getNumElements();
3021
0
  QualType EltTy = VT->getElementType();
3022
3023
  // In the cases (typically C as I've observed) where we aren't evaluating
3024
  // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3025
  // just give up.
3026
0
  if (!LHSValue.isVector()) {
3027
0
    assert(LHSValue.isLValue() &&
3028
0
           "A vector result that isn't a vector OR uncalculated LValue");
3029
0
    Info.FFDiag(E);
3030
0
    return false;
3031
0
  }
3032
3033
0
  assert(LHSValue.getVectorLength() == NumElements &&
3034
0
         RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3035
3036
0
  SmallVector<APValue, 4> ResultElements;
3037
3038
0
  for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3039
0
    APValue LHSElt = LHSValue.getVectorElt(EltNum);
3040
0
    APValue RHSElt = RHSValue.getVectorElt(EltNum);
3041
3042
0
    if (EltTy->isIntegerType()) {
3043
0
      APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3044
0
                       EltTy->isUnsignedIntegerType()};
3045
0
      bool Success = true;
3046
3047
0
      if (BinaryOperator::isLogicalOp(Opcode))
3048
0
        Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3049
0
      else if (BinaryOperator::isComparisonOp(Opcode))
3050
0
        Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3051
0
      else
3052
0
        Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3053
0
                                    RHSElt.getInt(), EltResult);
3054
3055
0
      if (!Success) {
3056
0
        Info.FFDiag(E);
3057
0
        return false;
3058
0
      }
3059
0
      ResultElements.emplace_back(EltResult);
3060
3061
0
    } else if (EltTy->isFloatingType()) {
3062
0
      assert(LHSElt.getKind() == APValue::Float &&
3063
0
             RHSElt.getKind() == APValue::Float &&
3064
0
             "Mismatched LHS/RHS/Result Type");
3065
0
      APFloat LHSFloat = LHSElt.getFloat();
3066
3067
0
      if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3068
0
                                 RHSElt.getFloat())) {
3069
0
        Info.FFDiag(E);
3070
0
        return false;
3071
0
      }
3072
3073
0
      ResultElements.emplace_back(LHSFloat);
3074
0
    }
3075
0
  }
3076
3077
0
  LHSValue = APValue(ResultElements.data(), ResultElements.size());
3078
0
  return true;
3079
0
}
3080
3081
/// Cast an lvalue referring to a base subobject to a derived class, by
3082
/// truncating the lvalue's path to the given length.
3083
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3084
                               const RecordDecl *TruncatedType,
3085
0
                               unsigned TruncatedElements) {
3086
0
  SubobjectDesignator &D = Result.Designator;
3087
3088
  // Check we actually point to a derived class object.
3089
0
  if (TruncatedElements == D.Entries.size())
3090
0
    return true;
3091
0
  assert(TruncatedElements >= D.MostDerivedPathLength &&
3092
0
         "not casting to a derived class");
3093
0
  if (!Result.checkSubobject(Info, E, CSK_Derived))
3094
0
    return false;
3095
3096
  // Truncate the path to the subobject, and remove any derived-to-base offsets.
3097
0
  const RecordDecl *RD = TruncatedType;
3098
0
  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3099
0
    if (RD->isInvalidDecl()) return false;
3100
0
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3101
0
    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3102
0
    if (isVirtualBaseClass(D.Entries[I]))
3103
0
      Result.Offset -= Layout.getVBaseClassOffset(Base);
3104
0
    else
3105
0
      Result.Offset -= Layout.getBaseClassOffset(Base);
3106
0
    RD = Base;
3107
0
  }
3108
0
  D.Entries.resize(TruncatedElements);
3109
0
  return true;
3110
0
}
3111
3112
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3113
                                   const CXXRecordDecl *Derived,
3114
                                   const CXXRecordDecl *Base,
3115
0
                                   const ASTRecordLayout *RL = nullptr) {
3116
0
  if (!RL) {
3117
0
    if (Derived->isInvalidDecl()) return false;
3118
0
    RL = &Info.Ctx.getASTRecordLayout(Derived);
3119
0
  }
3120
3121
0
  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3122
0
  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3123
0
  return true;
3124
0
}
3125
3126
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3127
                             const CXXRecordDecl *DerivedDecl,
3128
0
                             const CXXBaseSpecifier *Base) {
3129
0
  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3130
3131
0
  if (!Base->isVirtual())
3132
0
    return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3133
3134
0
  SubobjectDesignator &D = Obj.Designator;
3135
0
  if (D.Invalid)
3136
0
    return false;
3137
3138
  // Extract most-derived object and corresponding type.
3139
0
  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3140
0
  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3141
0
    return false;
3142
3143
  // Find the virtual base class.
3144
0
  if (DerivedDecl->isInvalidDecl()) return false;
3145
0
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3146
0
  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3147
0
  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3148
0
  return true;
3149
0
}
3150
3151
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3152
0
                                 QualType Type, LValue &Result) {
3153
0
  for (CastExpr::path_const_iterator PathI = E->path_begin(),
3154
0
                                     PathE = E->path_end();
3155
0
       PathI != PathE; ++PathI) {
3156
0
    if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3157
0
                          *PathI))
3158
0
      return false;
3159
0
    Type = (*PathI)->getType();
3160
0
  }
3161
0
  return true;
3162
0
}
3163
3164
/// Cast an lvalue referring to a derived class to a known base subobject.
3165
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3166
                            const CXXRecordDecl *DerivedRD,
3167
0
                            const CXXRecordDecl *BaseRD) {
3168
0
  CXXBasePaths Paths(/*FindAmbiguities=*/false,
3169
0
                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
3170
0
  if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3171
0
    llvm_unreachable("Class must be derived from the passed in base class!");
3172
3173
0
  for (CXXBasePathElement &Elem : Paths.front())
3174
0
    if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3175
0
      return false;
3176
0
  return true;
3177
0
}
3178
3179
/// Update LVal to refer to the given field, which must be a member of the type
3180
/// currently described by LVal.
3181
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3182
                               const FieldDecl *FD,
3183
0
                               const ASTRecordLayout *RL = nullptr) {
3184
0
  if (!RL) {
3185
0
    if (FD->getParent()->isInvalidDecl()) return false;
3186
0
    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3187
0
  }
3188
3189
0
  unsigned I = FD->getFieldIndex();
3190
0
  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3191
0
  LVal.addDecl(Info, E, FD);
3192
0
  return true;
3193
0
}
3194
3195
/// Update LVal to refer to the given indirect field.
3196
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3197
                                       LValue &LVal,
3198
0
                                       const IndirectFieldDecl *IFD) {
3199
0
  for (const auto *C : IFD->chain())
3200
0
    if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3201
0
      return false;
3202
0
  return true;
3203
0
}
3204
3205
enum class SizeOfType {
3206
  SizeOf,
3207
  DataSizeOf,
3208
};
3209
3210
/// Get the size of the given type in char units.
3211
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3212
0
                         CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3213
  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3214
  // extension.
3215
0
  if (Type->isVoidType() || Type->isFunctionType()) {
3216
0
    Size = CharUnits::One();
3217
0
    return true;
3218
0
  }
3219
3220
0
  if (Type->isDependentType()) {
3221
0
    Info.FFDiag(Loc);
3222
0
    return false;
3223
0
  }
3224
3225
0
  if (!Type->isConstantSizeType()) {
3226
    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3227
    // FIXME: Better diagnostic.
3228
0
    Info.FFDiag(Loc);
3229
0
    return false;
3230
0
  }
3231
3232
0
  if (SOT == SizeOfType::SizeOf)
3233
0
    Size = Info.Ctx.getTypeSizeInChars(Type);
3234
0
  else
3235
0
    Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3236
0
  return true;
3237
0
}
3238
3239
/// Update a pointer value to model pointer arithmetic.
3240
/// \param Info - Information about the ongoing evaluation.
3241
/// \param E - The expression being evaluated, for diagnostic purposes.
3242
/// \param LVal - The pointer value to be updated.
3243
/// \param EltTy - The pointee type represented by LVal.
3244
/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3245
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3246
                                        LValue &LVal, QualType EltTy,
3247
0
                                        APSInt Adjustment) {
3248
0
  CharUnits SizeOfPointee;
3249
0
  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3250
0
    return false;
3251
3252
0
  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3253
0
  return true;
3254
0
}
3255
3256
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3257
                                        LValue &LVal, QualType EltTy,
3258
0
                                        int64_t Adjustment) {
3259
0
  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3260
0
                                     APSInt::get(Adjustment));
3261
0
}
3262
3263
/// Update an lvalue to refer to a component of a complex number.
3264
/// \param Info - Information about the ongoing evaluation.
3265
/// \param LVal - The lvalue to be updated.
3266
/// \param EltTy - The complex number's component type.
3267
/// \param Imag - False for the real component, true for the imaginary.
3268
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3269
                                       LValue &LVal, QualType EltTy,
3270
0
                                       bool Imag) {
3271
0
  if (Imag) {
3272
0
    CharUnits SizeOfComponent;
3273
0
    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3274
0
      return false;
3275
0
    LVal.Offset += SizeOfComponent;
3276
0
  }
3277
0
  LVal.addComplex(Info, E, EltTy, Imag);
3278
0
  return true;
3279
0
}
3280
3281
/// Try to evaluate the initializer for a variable declaration.
3282
///
3283
/// \param Info   Information about the ongoing evaluation.
3284
/// \param E      An expression to be used when printing diagnostics.
3285
/// \param VD     The variable whose initializer should be obtained.
3286
/// \param Version The version of the variable within the frame.
3287
/// \param Frame  The frame in which the variable was created. Must be null
3288
///               if this variable is not local to the evaluation.
3289
/// \param Result Filled in with a pointer to the value of the variable.
3290
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3291
                                const VarDecl *VD, CallStackFrame *Frame,
3292
0
                                unsigned Version, APValue *&Result) {
3293
0
  APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3294
3295
  // If this is a local variable, dig out its value.
3296
0
  if (Frame) {
3297
0
    Result = Frame->getTemporary(VD, Version);
3298
0
    if (Result)
3299
0
      return true;
3300
3301
0
    if (!isa<ParmVarDecl>(VD)) {
3302
      // Assume variables referenced within a lambda's call operator that were
3303
      // not declared within the call operator are captures and during checking
3304
      // of a potential constant expression, assume they are unknown constant
3305
      // expressions.
3306
0
      assert(isLambdaCallOperator(Frame->Callee) &&
3307
0
             (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3308
0
             "missing value for local variable");
3309
0
      if (Info.checkingPotentialConstantExpression())
3310
0
        return false;
3311
      // FIXME: This diagnostic is bogus; we do support captures. Is this code
3312
      // still reachable at all?
3313
0
      Info.FFDiag(E->getBeginLoc(),
3314
0
                  diag::note_unimplemented_constexpr_lambda_feature_ast)
3315
0
          << "captures not currently allowed";
3316
0
      return false;
3317
0
    }
3318
0
  }
3319
3320
  // If we're currently evaluating the initializer of this declaration, use that
3321
  // in-flight value.
3322
0
  if (Info.EvaluatingDecl == Base) {
3323
0
    Result = Info.EvaluatingDeclValue;
3324
0
    return true;
3325
0
  }
3326
3327
0
  if (isa<ParmVarDecl>(VD)) {
3328
    // Assume parameters of a potential constant expression are usable in
3329
    // constant expressions.
3330
0
    if (!Info.checkingPotentialConstantExpression() ||
3331
0
        !Info.CurrentCall->Callee ||
3332
0
        !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3333
0
      if (Info.getLangOpts().CPlusPlus11) {
3334
0
        Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3335
0
            << VD;
3336
0
        NoteLValueLocation(Info, Base);
3337
0
      } else {
3338
0
        Info.FFDiag(E);
3339
0
      }
3340
0
    }
3341
0
    return false;
3342
0
  }
3343
3344
0
  if (E->isValueDependent())
3345
0
    return false;
3346
3347
  // Dig out the initializer, and use the declaration which it's attached to.
3348
  // FIXME: We should eventually check whether the variable has a reachable
3349
  // initializing declaration.
3350
0
  const Expr *Init = VD->getAnyInitializer(VD);
3351
0
  if (!Init) {
3352
    // Don't diagnose during potential constant expression checking; an
3353
    // initializer might be added later.
3354
0
    if (!Info.checkingPotentialConstantExpression()) {
3355
0
      Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3356
0
        << VD;
3357
0
      NoteLValueLocation(Info, Base);
3358
0
    }
3359
0
    return false;
3360
0
  }
3361
3362
0
  if (Init->isValueDependent()) {
3363
    // The DeclRefExpr is not value-dependent, but the variable it refers to
3364
    // has a value-dependent initializer. This should only happen in
3365
    // constant-folding cases, where the variable is not actually of a suitable
3366
    // type for use in a constant expression (otherwise the DeclRefExpr would
3367
    // have been value-dependent too), so diagnose that.
3368
0
    assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3369
0
    if (!Info.checkingPotentialConstantExpression()) {
3370
0
      Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3371
0
                         ? diag::note_constexpr_ltor_non_constexpr
3372
0
                         : diag::note_constexpr_ltor_non_integral, 1)
3373
0
          << VD << VD->getType();
3374
0
      NoteLValueLocation(Info, Base);
3375
0
    }
3376
0
    return false;
3377
0
  }
3378
3379
  // Check that we can fold the initializer. In C++, we will have already done
3380
  // this in the cases where it matters for conformance.
3381
0
  if (!VD->evaluateValue()) {
3382
0
    Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3383
0
    NoteLValueLocation(Info, Base);
3384
0
    return false;
3385
0
  }
3386
3387
  // Check that the variable is actually usable in constant expressions. For a
3388
  // const integral variable or a reference, we might have a non-constant
3389
  // initializer that we can nonetheless evaluate the initializer for. Such
3390
  // variables are not usable in constant expressions. In C++98, the
3391
  // initializer also syntactically needs to be an ICE.
3392
  //
3393
  // FIXME: We don't diagnose cases that aren't potentially usable in constant
3394
  // expressions here; doing so would regress diagnostics for things like
3395
  // reading from a volatile constexpr variable.
3396
0
  if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3397
0
       VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3398
0
      ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3399
0
       !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3400
0
    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3401
0
    NoteLValueLocation(Info, Base);
3402
0
  }
3403
3404
  // Never use the initializer of a weak variable, not even for constant
3405
  // folding. We can't be sure that this is the definition that will be used.
3406
0
  if (VD->isWeak()) {
3407
0
    Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3408
0
    NoteLValueLocation(Info, Base);
3409
0
    return false;
3410
0
  }
3411
3412
0
  Result = VD->getEvaluatedValue();
3413
0
  return true;
3414
0
}
3415
3416
/// Get the base index of the given base class within an APValue representing
3417
/// the given derived class.
3418
static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3419
0
                             const CXXRecordDecl *Base) {
3420
0
  Base = Base->getCanonicalDecl();
3421
0
  unsigned Index = 0;
3422
0
  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3423
0
         E = Derived->bases_end(); I != E; ++I, ++Index) {
3424
0
    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3425
0
      return Index;
3426
0
  }
3427
3428
0
  llvm_unreachable("base class missing from derived class's bases list");
3429
0
}
3430
3431
/// Extract the value of a character from a string literal.
3432
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3433
0
                                            uint64_t Index) {
3434
0
  assert(!isa<SourceLocExpr>(Lit) &&
3435
0
         "SourceLocExpr should have already been converted to a StringLiteral");
3436
3437
  // FIXME: Support MakeStringConstant
3438
0
  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3439
0
    std::string Str;
3440
0
    Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3441
0
    assert(Index <= Str.size() && "Index too large");
3442
0
    return APSInt::getUnsigned(Str.c_str()[Index]);
3443
0
  }
3444
3445
0
  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3446
0
    Lit = PE->getFunctionName();
3447
0
  const StringLiteral *S = cast<StringLiteral>(Lit);
3448
0
  const ConstantArrayType *CAT =
3449
0
      Info.Ctx.getAsConstantArrayType(S->getType());
3450
0
  assert(CAT && "string literal isn't an array");
3451
0
  QualType CharType = CAT->getElementType();
3452
0
  assert(CharType->isIntegerType() && "unexpected character type");
3453
0
  APSInt Value(Info.Ctx.getTypeSize(CharType),
3454
0
               CharType->isUnsignedIntegerType());
3455
0
  if (Index < S->getLength())
3456
0
    Value = S->getCodeUnit(Index);
3457
0
  return Value;
3458
0
}
3459
3460
// Expand a string literal into an array of characters.
3461
//
3462
// FIXME: This is inefficient; we should probably introduce something similar
3463
// to the LLVM ConstantDataArray to make this cheaper.
3464
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3465
                                APValue &Result,
3466
0
                                QualType AllocType = QualType()) {
3467
0
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3468
0
      AllocType.isNull() ? S->getType() : AllocType);
3469
0
  assert(CAT && "string literal isn't an array");
3470
0
  QualType CharType = CAT->getElementType();
3471
0
  assert(CharType->isIntegerType() && "unexpected character type");
3472
3473
0
  unsigned Elts = CAT->getSize().getZExtValue();
3474
0
  Result = APValue(APValue::UninitArray(),
3475
0
                   std::min(S->getLength(), Elts), Elts);
3476
0
  APSInt Value(Info.Ctx.getTypeSize(CharType),
3477
0
               CharType->isUnsignedIntegerType());
3478
0
  if (Result.hasArrayFiller())
3479
0
    Result.getArrayFiller() = APValue(Value);
3480
0
  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3481
0
    Value = S->getCodeUnit(I);
3482
0
    Result.getArrayInitializedElt(I) = APValue(Value);
3483
0
  }
3484
0
}
3485
3486
// Expand an array so that it has more than Index filled elements.
3487
0
static void expandArray(APValue &Array, unsigned Index) {
3488
0
  unsigned Size = Array.getArraySize();
3489
0
  assert(Index < Size);
3490
3491
  // Always at least double the number of elements for which we store a value.
3492
0
  unsigned OldElts = Array.getArrayInitializedElts();
3493
0
  unsigned NewElts = std::max(Index+1, OldElts * 2);
3494
0
  NewElts = std::min(Size, std::max(NewElts, 8u));
3495
3496
  // Copy the data across.
3497
0
  APValue NewValue(APValue::UninitArray(), NewElts, Size);
3498
0
  for (unsigned I = 0; I != OldElts; ++I)
3499
0
    NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3500
0
  for (unsigned I = OldElts; I != NewElts; ++I)
3501
0
    NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3502
0
  if (NewValue.hasArrayFiller())
3503
0
    NewValue.getArrayFiller() = Array.getArrayFiller();
3504
0
  Array.swap(NewValue);
3505
0
}
3506
3507
/// Determine whether a type would actually be read by an lvalue-to-rvalue
3508
/// conversion. If it's of class type, we may assume that the copy operation
3509
/// is trivial. Note that this is never true for a union type with fields
3510
/// (because the copy always "reads" the active member) and always true for
3511
/// a non-class type.
3512
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3513
0
static bool isReadByLvalueToRvalueConversion(QualType T) {
3514
0
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3515
0
  return !RD || isReadByLvalueToRvalueConversion(RD);
3516
0
}
3517
0
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3518
  // FIXME: A trivial copy of a union copies the object representation, even if
3519
  // the union is empty.
3520
0
  if (RD->isUnion())
3521
0
    return !RD->field_empty();
3522
0
  if (RD->isEmpty())
3523
0
    return false;
3524
3525
0
  for (auto *Field : RD->fields())
3526
0
    if (!Field->isUnnamedBitfield() &&
3527
0
        isReadByLvalueToRvalueConversion(Field->getType()))
3528
0
      return true;
3529
3530
0
  for (auto &BaseSpec : RD->bases())
3531
0
    if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3532
0
      return true;
3533
3534
0
  return false;
3535
0
}
3536
3537
/// Diagnose an attempt to read from any unreadable field within the specified
3538
/// type, which might be a class type.
3539
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3540
0
                                  QualType T) {
3541
0
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3542
0
  if (!RD)
3543
0
    return false;
3544
3545
0
  if (!RD->hasMutableFields())
3546
0
    return false;
3547
3548
0
  for (auto *Field : RD->fields()) {
3549
    // If we're actually going to read this field in some way, then it can't
3550
    // be mutable. If we're in a union, then assigning to a mutable field
3551
    // (even an empty one) can change the active member, so that's not OK.
3552
    // FIXME: Add core issue number for the union case.
3553
0
    if (Field->isMutable() &&
3554
0
        (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3555
0
      Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3556
0
      Info.Note(Field->getLocation(), diag::note_declared_at);
3557
0
      return true;
3558
0
    }
3559
3560
0
    if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3561
0
      return true;
3562
0
  }
3563
3564
0
  for (auto &BaseSpec : RD->bases())
3565
0
    if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3566
0
      return true;
3567
3568
  // All mutable fields were empty, and thus not actually read.
3569
0
  return false;
3570
0
}
3571
3572
static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3573
                                        APValue::LValueBase Base,
3574
0
                                        bool MutableSubobject = false) {
3575
  // A temporary or transient heap allocation we created.
3576
0
  if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3577
0
    return true;
3578
3579
0
  switch (Info.IsEvaluatingDecl) {
3580
0
  case EvalInfo::EvaluatingDeclKind::None:
3581
0
    return false;
3582
3583
0
  case EvalInfo::EvaluatingDeclKind::Ctor:
3584
    // The variable whose initializer we're evaluating.
3585
0
    if (Info.EvaluatingDecl == Base)
3586
0
      return true;
3587
3588
    // A temporary lifetime-extended by the variable whose initializer we're
3589
    // evaluating.
3590
0
    if (auto *BaseE = Base.dyn_cast<const Expr *>())
3591
0
      if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3592
0
        return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3593
0
    return false;
3594
3595
0
  case EvalInfo::EvaluatingDeclKind::Dtor:
3596
    // C++2a [expr.const]p6:
3597
    //   [during constant destruction] the lifetime of a and its non-mutable
3598
    //   subobjects (but not its mutable subobjects) [are] considered to start
3599
    //   within e.
3600
0
    if (MutableSubobject || Base != Info.EvaluatingDecl)
3601
0
      return false;
3602
    // FIXME: We can meaningfully extend this to cover non-const objects, but
3603
    // we will need special handling: we should be able to access only
3604
    // subobjects of such objects that are themselves declared const.
3605
0
    QualType T = getType(Base);
3606
0
    return T.isConstQualified() || T->isReferenceType();
3607
0
  }
3608
3609
0
  llvm_unreachable("unknown evaluating decl kind");
3610
0
}
3611
3612
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3613
0
                           SourceLocation CallLoc = {}) {
3614
0
  return Info.CheckArraySize(
3615
0
      CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3616
0
      CAT->getNumAddressingBits(Info.Ctx), CAT->getSize().getZExtValue(),
3617
0
      /*Diag=*/true);
3618
0
}
3619
3620
namespace {
3621
/// A handle to a complete object (an object that is not a subobject of
3622
/// another object).
3623
struct CompleteObject {
3624
  /// The identity of the object.
3625
  APValue::LValueBase Base;
3626
  /// The value of the complete object.
3627
  APValue *Value;
3628
  /// The type of the complete object.
3629
  QualType Type;
3630
3631
9
  CompleteObject() : Value(nullptr) {}
3632
  CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3633
0
      : Base(Base), Value(Value), Type(Type) {}
3634
3635
0
  bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3636
    // If this isn't a "real" access (eg, if it's just accessing the type
3637
    // info), allow it. We assume the type doesn't change dynamically for
3638
    // subobjects of constexpr objects (even though we'd hit UB here if it
3639
    // did). FIXME: Is this right?
3640
0
    if (!isAnyAccess(AK))
3641
0
      return true;
3642
3643
    // In C++14 onwards, it is permitted to read a mutable member whose
3644
    // lifetime began within the evaluation.
3645
    // FIXME: Should we also allow this in C++11?
3646
0
    if (!Info.getLangOpts().CPlusPlus14)
3647
0
      return false;
3648
0
    return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3649
0
  }
3650
3651
9
  explicit operator bool() const { return !Type.isNull(); }
3652
};
3653
} // end anonymous namespace
3654
3655
static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3656
0
                                 bool IsMutable = false) {
3657
  // C++ [basic.type.qualifier]p1:
3658
  // - A const object is an object of type const T or a non-mutable subobject
3659
  //   of a const object.
3660
0
  if (ObjType.isConstQualified() && !IsMutable)
3661
0
    SubobjType.addConst();
3662
  // - A volatile object is an object of type const T or a subobject of a
3663
  //   volatile object.
3664
0
  if (ObjType.isVolatileQualified())
3665
0
    SubobjType.addVolatile();
3666
0
  return SubobjType;
3667
0
}
3668
3669
/// Find the designated sub-object of an rvalue.
3670
template<typename SubobjectHandler>
3671
typename SubobjectHandler::result_type
3672
findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3673
0
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3674
0
  if (Sub.Invalid)
3675
    // A diagnostic will have already been produced.
3676
0
    return handler.failed();
3677
0
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3678
0
    if (Info.getLangOpts().CPlusPlus11)
3679
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3680
0
                         ? diag::note_constexpr_access_past_end
3681
0
                         : diag::note_constexpr_access_unsized_array)
3682
0
          << handler.AccessKind;
3683
0
    else
3684
0
      Info.FFDiag(E);
3685
0
    return handler.failed();
3686
0
  }
3687
3688
0
  APValue *O = Obj.Value;
3689
0
  QualType ObjType = Obj.Type;
3690
0
  const FieldDecl *LastField = nullptr;
3691
0
  const FieldDecl *VolatileField = nullptr;
3692
3693
  // Walk the designator's path to find the subobject.
3694
0
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3695
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3696
0
    if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3697
0
        (O->isIndeterminate() &&
3698
0
         !isValidIndeterminateAccess(handler.AccessKind))) {
3699
0
      if (!Info.checkingPotentialConstantExpression())
3700
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3701
0
            << handler.AccessKind << O->isIndeterminate()
3702
0
            << E->getSourceRange();
3703
0
      return handler.failed();
3704
0
    }
3705
3706
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3707
    //    const and volatile semantics are not applied on an object under
3708
    //    {con,de}struction.
3709
0
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3710
0
        ObjType->isRecordType() &&
3711
0
        Info.isEvaluatingCtorDtor(
3712
0
            Obj.Base,
3713
0
            llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3714
0
            ConstructionPhase::None) {
3715
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3716
0
      ObjType.removeLocalConst();
3717
0
      ObjType.removeLocalVolatile();
3718
0
    }
3719
3720
    // If this is our last pass, check that the final object type is OK.
3721
0
    if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3722
      // Accesses to volatile objects are prohibited.
3723
0
      if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3724
0
        if (Info.getLangOpts().CPlusPlus) {
3725
0
          int DiagKind;
3726
0
          SourceLocation Loc;
3727
0
          const NamedDecl *Decl = nullptr;
3728
0
          if (VolatileField) {
3729
0
            DiagKind = 2;
3730
0
            Loc = VolatileField->getLocation();
3731
0
            Decl = VolatileField;
3732
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3733
0
            DiagKind = 1;
3734
0
            Loc = VD->getLocation();
3735
0
            Decl = VD;
3736
0
          } else {
3737
0
            DiagKind = 0;
3738
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3739
0
              Loc = E->getExprLoc();
3740
0
          }
3741
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3742
0
              << handler.AccessKind << DiagKind << Decl;
3743
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3744
0
        } else {
3745
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3746
0
        }
3747
0
        return handler.failed();
3748
0
      }
3749
3750
      // If we are reading an object of class type, there may still be more
3751
      // things we need to check: if there are any mutable subobjects, we
3752
      // cannot perform this read. (This only happens when performing a trivial
3753
      // copy or assignment.)
3754
0
      if (ObjType->isRecordType() &&
3755
0
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3756
0
          diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3757
0
        return handler.failed();
3758
0
    }
3759
3760
0
    if (I == N) {
3761
0
      if (!handler.found(*O, ObjType))
3762
0
        return false;
3763
3764
      // If we modified a bit-field, truncate it to the right width.
3765
0
      if (isModification(handler.AccessKind) &&
3766
0
          LastField && LastField->isBitField() &&
3767
0
          !truncateBitfieldValue(Info, E, *O, LastField))
3768
0
        return false;
3769
3770
0
      return true;
3771
0
    }
3772
3773
0
    LastField = nullptr;
3774
0
    if (ObjType->isArrayType()) {
3775
      // Next subobject is an array element.
3776
0
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3777
0
      assert(CAT && "vla in literal type?");
3778
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3779
0
      if (CAT->getSize().ule(Index)) {
3780
        // Note, it should not be possible to form a pointer with a valid
3781
        // designator which points more than one past the end of the array.
3782
0
        if (Info.getLangOpts().CPlusPlus11)
3783
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3784
0
            << handler.AccessKind;
3785
0
        else
3786
0
          Info.FFDiag(E);
3787
0
        return handler.failed();
3788
0
      }
3789
3790
0
      ObjType = CAT->getElementType();
3791
3792
0
      if (O->getArrayInitializedElts() > Index)
3793
0
        O = &O->getArrayInitializedElt(Index);
3794
0
      else if (!isRead(handler.AccessKind)) {
3795
0
        if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3796
0
          return handler.failed();
3797
3798
0
        expandArray(*O, Index);
3799
0
        O = &O->getArrayInitializedElt(Index);
3800
0
      } else
3801
0
        O = &O->getArrayFiller();
3802
0
    } else if (ObjType->isAnyComplexType()) {
3803
      // Next subobject is a complex number.
3804
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3805
0
      if (Index > 1) {
3806
0
        if (Info.getLangOpts().CPlusPlus11)
3807
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3808
0
            << handler.AccessKind;
3809
0
        else
3810
0
          Info.FFDiag(E);
3811
0
        return handler.failed();
3812
0
      }
3813
3814
0
      ObjType = getSubobjectType(
3815
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3816
3817
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3818
0
      if (O->isComplexInt()) {
3819
0
        return handler.found(Index ? O->getComplexIntImag()
3820
0
                                   : O->getComplexIntReal(), ObjType);
3821
0
      } else {
3822
0
        assert(O->isComplexFloat());
3823
0
        return handler.found(Index ? O->getComplexFloatImag()
3824
0
                                   : O->getComplexFloatReal(), ObjType);
3825
0
      }
3826
0
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3827
0
      if (Field->isMutable() &&
3828
0
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3829
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3830
0
          << handler.AccessKind << Field;
3831
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3832
0
        return handler.failed();
3833
0
      }
3834
3835
      // Next subobject is a class, struct or union field.
3836
0
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3837
0
      if (RD->isUnion()) {
3838
0
        const FieldDecl *UnionField = O->getUnionField();
3839
0
        if (!UnionField ||
3840
0
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3841
0
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3842
            // Placement new onto an inactive union member makes it active.
3843
0
            O->setUnion(Field, APValue());
3844
0
          } else {
3845
            // FIXME: If O->getUnionValue() is absent, report that there's no
3846
            // active union member rather than reporting the prior active union
3847
            // member. We'll need to fix nullptr_t to not use APValue() as its
3848
            // representation first.
3849
0
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3850
0
                << handler.AccessKind << Field << !UnionField << UnionField;
3851
0
            return handler.failed();
3852
0
          }
3853
0
        }
3854
0
        O = &O->getUnionValue();
3855
0
      } else
3856
0
        O = &O->getStructField(Field->getFieldIndex());
3857
3858
0
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3859
0
      LastField = Field;
3860
0
      if (Field->getType().isVolatileQualified())
3861
0
        VolatileField = Field;
3862
0
    } else {
3863
      // Next subobject is a base class.
3864
0
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3865
0
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3866
0
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3867
3868
0
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3869
0
    }
3870
0
  }
3871
0
}
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
3872
3873
namespace {
3874
struct ExtractSubobjectHandler {
3875
  EvalInfo &Info;
3876
  const Expr *E;
3877
  APValue &Result;
3878
  const AccessKinds AccessKind;
3879
3880
  typedef bool result_type;
3881
0
  bool failed() { return false; }
3882
0
  bool found(APValue &Subobj, QualType SubobjType) {
3883
0
    Result = Subobj;
3884
0
    if (AccessKind == AK_ReadObjectRepresentation)
3885
0
      return true;
3886
0
    return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3887
0
  }
3888
0
  bool found(APSInt &Value, QualType SubobjType) {
3889
0
    Result = APValue(Value);
3890
0
    return true;
3891
0
  }
3892
0
  bool found(APFloat &Value, QualType SubobjType) {
3893
0
    Result = APValue(Value);
3894
0
    return true;
3895
0
  }
3896
};
3897
} // end anonymous namespace
3898
3899
/// Extract the designated sub-object of an rvalue.
3900
static bool extractSubobject(EvalInfo &Info, const Expr *E,
3901
                             const CompleteObject &Obj,
3902
                             const SubobjectDesignator &Sub, APValue &Result,
3903
0
                             AccessKinds AK = AK_Read) {
3904
0
  assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3905
0
  ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3906
0
  return findSubobject(Info, E, Obj, Sub, Handler);
3907
0
}
3908
3909
namespace {
3910
struct ModifySubobjectHandler {
3911
  EvalInfo &Info;
3912
  APValue &NewVal;
3913
  const Expr *E;
3914
3915
  typedef bool result_type;
3916
  static const AccessKinds AccessKind = AK_Assign;
3917
3918
0
  bool checkConst(QualType QT) {
3919
    // Assigning to a const object has undefined behavior.
3920
0
    if (QT.isConstQualified()) {
3921
0
      Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3922
0
      return false;
3923
0
    }
3924
0
    return true;
3925
0
  }
3926
3927
0
  bool failed() { return false; }
3928
0
  bool found(APValue &Subobj, QualType SubobjType) {
3929
0
    if (!checkConst(SubobjType))
3930
0
      return false;
3931
    // We've been given ownership of NewVal, so just swap it in.
3932
0
    Subobj.swap(NewVal);
3933
0
    return true;
3934
0
  }
3935
0
  bool found(APSInt &Value, QualType SubobjType) {
3936
0
    if (!checkConst(SubobjType))
3937
0
      return false;
3938
0
    if (!NewVal.isInt()) {
3939
      // Maybe trying to write a cast pointer value into a complex?
3940
0
      Info.FFDiag(E);
3941
0
      return false;
3942
0
    }
3943
0
    Value = NewVal.getInt();
3944
0
    return true;
3945
0
  }
3946
0
  bool found(APFloat &Value, QualType SubobjType) {
3947
0
    if (!checkConst(SubobjType))
3948
0
      return false;
3949
0
    Value = NewVal.getFloat();
3950
0
    return true;
3951
0
  }
3952
};
3953
} // end anonymous namespace
3954
3955
const AccessKinds ModifySubobjectHandler::AccessKind;
3956
3957
/// Update the designated sub-object of an rvalue to the given value.
3958
static bool modifySubobject(EvalInfo &Info, const Expr *E,
3959
                            const CompleteObject &Obj,
3960
                            const SubobjectDesignator &Sub,
3961
0
                            APValue &NewVal) {
3962
0
  ModifySubobjectHandler Handler = { Info, NewVal, E };
3963
0
  return findSubobject(Info, E, Obj, Sub, Handler);
3964
0
}
3965
3966
/// Find the position where two subobject designators diverge, or equivalently
3967
/// the length of the common initial subsequence.
3968
static unsigned FindDesignatorMismatch(QualType ObjType,
3969
                                       const SubobjectDesignator &A,
3970
                                       const SubobjectDesignator &B,
3971
0
                                       bool &WasArrayIndex) {
3972
0
  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3973
0
  for (/**/; I != N; ++I) {
3974
0
    if (!ObjType.isNull() &&
3975
0
        (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3976
      // Next subobject is an array element.
3977
0
      if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3978
0
        WasArrayIndex = true;
3979
0
        return I;
3980
0
      }
3981
0
      if (ObjType->isAnyComplexType())
3982
0
        ObjType = ObjType->castAs<ComplexType>()->getElementType();
3983
0
      else
3984
0
        ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3985
0
    } else {
3986
0
      if (A.Entries[I].getAsBaseOrMember() !=
3987
0
          B.Entries[I].getAsBaseOrMember()) {
3988
0
        WasArrayIndex = false;
3989
0
        return I;
3990
0
      }
3991
0
      if (const FieldDecl *FD = getAsField(A.Entries[I]))
3992
        // Next subobject is a field.
3993
0
        ObjType = FD->getType();
3994
0
      else
3995
        // Next subobject is a base class.
3996
0
        ObjType = QualType();
3997
0
    }
3998
0
  }
3999
0
  WasArrayIndex = false;
4000
0
  return I;
4001
0
}
4002
4003
/// Determine whether the given subobject designators refer to elements of the
4004
/// same array object.
4005
static bool AreElementsOfSameArray(QualType ObjType,
4006
                                   const SubobjectDesignator &A,
4007
0
                                   const SubobjectDesignator &B) {
4008
0
  if (A.Entries.size() != B.Entries.size())
4009
0
    return false;
4010
4011
0
  bool IsArray = A.MostDerivedIsArrayElement;
4012
0
  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4013
    // A is a subobject of the array element.
4014
0
    return false;
4015
4016
  // If A (and B) designates an array element, the last entry will be the array
4017
  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4018
  // of length 1' case, and the entire path must match.
4019
0
  bool WasArrayIndex;
4020
0
  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4021
0
  return CommonLength >= A.Entries.size() - IsArray;
4022
0
}
4023
4024
/// Find the complete object to which an LValue refers.
4025
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4026
                                         AccessKinds AK, const LValue &LVal,
4027
9
                                         QualType LValType) {
4028
9
  if (LVal.InvalidBase) {
4029
0
    Info.FFDiag(E);
4030
0
    return CompleteObject();
4031
0
  }
4032
4033
9
  if (!LVal.Base) {
4034
0
    Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4035
0
    return CompleteObject();
4036
0
  }
4037
4038
9
  CallStackFrame *Frame = nullptr;
4039
9
  unsigned Depth = 0;
4040
9
  if (LVal.getLValueCallIndex()) {
4041
0
    std::tie(Frame, Depth) =
4042
0
        Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4043
0
    if (!Frame) {
4044
0
      Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4045
0
        << AK << LVal.Base.is<const ValueDecl*>();
4046
0
      NoteLValueLocation(Info, LVal.Base);
4047
0
      return CompleteObject();
4048
0
    }
4049
0
  }
4050
4051
9
  bool IsAccess = isAnyAccess(AK);
4052
4053
  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4054
  // is not a constant expression (even if the object is non-volatile). We also
4055
  // apply this rule to C++98, in order to conform to the expected 'volatile'
4056
  // semantics.
4057
9
  if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4058
0
    if (Info.getLangOpts().CPlusPlus)
4059
0
      Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4060
0
        << AK << LValType;
4061
0
    else
4062
0
      Info.FFDiag(E);
4063
0
    return CompleteObject();
4064
0
  }
4065
4066
  // Compute value storage location and type of base object.
4067
9
  APValue *BaseVal = nullptr;
4068
9
  QualType BaseType = getType(LVal.Base);
4069
4070
9
  if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4071
9
      lifetimeStartedInEvaluation(Info, LVal.Base)) {
4072
    // This is the object whose initializer we're evaluating, so its lifetime
4073
    // started in the current evaluation.
4074
0
    BaseVal = Info.EvaluatingDeclValue;
4075
9
  } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4076
    // Allow reading from a GUID declaration.
4077
9
    if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4078
0
      if (isModification(AK)) {
4079
        // All the remaining cases do not permit modification of the object.
4080
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4081
0
        return CompleteObject();
4082
0
      }
4083
0
      APValue &V = GD->getAsAPValue();
4084
0
      if (V.isAbsent()) {
4085
0
        Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4086
0
            << GD->getType();
4087
0
        return CompleteObject();
4088
0
      }
4089
0
      return CompleteObject(LVal.Base, &V, GD->getType());
4090
0
    }
4091
4092
    // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4093
9
    if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4094
0
      if (isModification(AK)) {
4095
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4096
0
        return CompleteObject();
4097
0
      }
4098
0
      return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4099
0
                            GCD->getType());
4100
0
    }
4101
4102
    // Allow reading from template parameter objects.
4103
9
    if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4104
0
      if (isModification(AK)) {
4105
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4106
0
        return CompleteObject();
4107
0
      }
4108
0
      return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4109
0
                            TPO->getType());
4110
0
    }
4111
4112
    // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4113
    // In C++11, constexpr, non-volatile variables initialized with constant
4114
    // expressions are constant expressions too. Inside constexpr functions,
4115
    // parameters are constant expressions even if they're non-const.
4116
    // In C++1y, objects local to a constant expression (those with a Frame) are
4117
    // both readable and writable inside constant expressions.
4118
    // In C, such things can also be folded, although they are not ICEs.
4119
9
    const VarDecl *VD = dyn_cast<VarDecl>(D);
4120
9
    if (VD) {
4121
9
      if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4122
1
        VD = VDef;
4123
9
    }
4124
9
    if (!VD || VD->isInvalidDecl()) {
4125
6
      Info.FFDiag(E);
4126
6
      return CompleteObject();
4127
6
    }
4128
4129
3
    bool IsConstant = BaseType.isConstant(Info.Ctx);
4130
4131
    // Unless we're looking at a local variable or argument in a constexpr call,
4132
    // the variable we're reading must be const.
4133
3
    if (!Frame) {
4134
3
      if (IsAccess && isa<ParmVarDecl>(VD)) {
4135
        // Access of a parameter that's not associated with a frame isn't going
4136
        // to work out, but we can leave it to evaluateVarDeclInit to provide a
4137
        // suitable diagnostic.
4138
3
      } else if (Info.getLangOpts().CPlusPlus14 &&
4139
3
                 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4140
        // OK, we can read and modify an object if we're in the process of
4141
        // evaluating its initializer, because its lifetime began in this
4142
        // evaluation.
4143
3
      } else if (isModification(AK)) {
4144
        // All the remaining cases do not permit modification of the object.
4145
0
        Info.FFDiag(E, diag::note_constexpr_modify_global);
4146
0
        return CompleteObject();
4147
3
      } else if (VD->isConstexpr()) {
4148
        // OK, we can read this variable.
4149
3
      } else if (BaseType->isIntegralOrEnumerationType()) {
4150
2
        if (!IsConstant) {
4151
2
          if (!IsAccess)
4152
0
            return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4153
2
          if (Info.getLangOpts().CPlusPlus) {
4154
0
            Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4155
0
            Info.Note(VD->getLocation(), diag::note_declared_at);
4156
2
          } else {
4157
2
            Info.FFDiag(E);
4158
2
          }
4159
2
          return CompleteObject();
4160
2
        }
4161
2
      } else if (!IsAccess) {
4162
0
        return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4163
1
      } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4164
1
                 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4165
        // This variable might end up being constexpr. Don't diagnose it yet.
4166
1
      } else if (IsConstant) {
4167
        // Keep evaluating to see what we can do. In particular, we support
4168
        // folding of const floating-point types, in order to make static const
4169
        // data members of such types (supported as an extension) more useful.
4170
0
        if (Info.getLangOpts().CPlusPlus) {
4171
0
          Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4172
0
                              ? diag::note_constexpr_ltor_non_constexpr
4173
0
                              : diag::note_constexpr_ltor_non_integral, 1)
4174
0
              << VD << BaseType;
4175
0
          Info.Note(VD->getLocation(), diag::note_declared_at);
4176
0
        } else {
4177
0
          Info.CCEDiag(E);
4178
0
        }
4179
1
      } else {
4180
        // Never allow reading a non-const value.
4181
1
        if (Info.getLangOpts().CPlusPlus) {
4182
0
          Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4183
0
                             ? diag::note_constexpr_ltor_non_constexpr
4184
0
                             : diag::note_constexpr_ltor_non_integral, 1)
4185
0
              << VD << BaseType;
4186
0
          Info.Note(VD->getLocation(), diag::note_declared_at);
4187
1
        } else {
4188
1
          Info.FFDiag(E);
4189
1
        }
4190
1
        return CompleteObject();
4191
1
      }
4192
3
    }
4193
4194
0
    if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4195
0
      return CompleteObject();
4196
0
  } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4197
0
    std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4198
0
    if (!Alloc) {
4199
0
      Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4200
0
      return CompleteObject();
4201
0
    }
4202
0
    return CompleteObject(LVal.Base, &(*Alloc)->Value,
4203
0
                          LVal.Base.getDynamicAllocType());
4204
0
  } else {
4205
0
    const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4206
4207
0
    if (!Frame) {
4208
0
      if (const MaterializeTemporaryExpr *MTE =
4209
0
              dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4210
0
        assert(MTE->getStorageDuration() == SD_Static &&
4211
0
               "should have a frame for a non-global materialized temporary");
4212
4213
        // C++20 [expr.const]p4: [DR2126]
4214
        //   An object or reference is usable in constant expressions if it is
4215
        //   - a temporary object of non-volatile const-qualified literal type
4216
        //     whose lifetime is extended to that of a variable that is usable
4217
        //     in constant expressions
4218
        //
4219
        // C++20 [expr.const]p5:
4220
        //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4221
        //   - a non-volatile glvalue that refers to an object that is usable
4222
        //     in constant expressions, or
4223
        //   - a non-volatile glvalue of literal type that refers to a
4224
        //     non-volatile object whose lifetime began within the evaluation
4225
        //     of E;
4226
        //
4227
        // C++11 misses the 'began within the evaluation of e' check and
4228
        // instead allows all temporaries, including things like:
4229
        //   int &&r = 1;
4230
        //   int x = ++r;
4231
        //   constexpr int k = r;
4232
        // Therefore we use the C++14-onwards rules in C++11 too.
4233
        //
4234
        // Note that temporaries whose lifetimes began while evaluating a
4235
        // variable's constructor are not usable while evaluating the
4236
        // corresponding destructor, not even if they're of const-qualified
4237
        // types.
4238
0
        if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4239
0
            !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4240
0
          if (!IsAccess)
4241
0
            return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4242
0
          Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4243
0
          Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4244
0
          return CompleteObject();
4245
0
        }
4246
4247
0
        BaseVal = MTE->getOrCreateValue(false);
4248
0
        assert(BaseVal && "got reference to unevaluated temporary");
4249
0
      } else {
4250
0
        if (!IsAccess)
4251
0
          return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4252
0
        APValue Val;
4253
0
        LVal.moveInto(Val);
4254
0
        Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4255
0
            << AK
4256
0
            << Val.getAsString(Info.Ctx,
4257
0
                               Info.Ctx.getLValueReferenceType(LValType));
4258
0
        NoteLValueLocation(Info, LVal.Base);
4259
0
        return CompleteObject();
4260
0
      }
4261
0
    } else {
4262
0
      BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4263
0
      assert(BaseVal && "missing value for temporary");
4264
0
    }
4265
0
  }
4266
4267
  // In C++14, we can't safely access any mutable state when we might be
4268
  // evaluating after an unmodeled side effect. Parameters are modeled as state
4269
  // in the caller, but aren't visible once the call returns, so they can be
4270
  // modified in a speculatively-evaluated call.
4271
  //
4272
  // FIXME: Not all local state is mutable. Allow local constant subobjects
4273
  // to be read here (but take care with 'mutable' fields).
4274
0
  unsigned VisibleDepth = Depth;
4275
0
  if (llvm::isa_and_nonnull<ParmVarDecl>(
4276
0
          LVal.Base.dyn_cast<const ValueDecl *>()))
4277
0
    ++VisibleDepth;
4278
0
  if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4279
0
       Info.EvalStatus.HasSideEffects) ||
4280
0
      (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4281
0
    return CompleteObject();
4282
4283
0
  return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4284
0
}
4285
4286
/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4287
/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4288
/// glvalue referred to by an entity of reference type.
4289
///
4290
/// \param Info - Information about the ongoing evaluation.
4291
/// \param Conv - The expression for which we are performing the conversion.
4292
///               Used for diagnostics.
4293
/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4294
///               case of a non-class type).
4295
/// \param LVal - The glvalue on which we are attempting to perform this action.
4296
/// \param RVal - The produced value will be placed here.
4297
/// \param WantObjectRepresentation - If true, we're looking for the object
4298
///               representation rather than the value, and in particular,
4299
///               there is no requirement that the result be fully initialized.
4300
static bool
4301
handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4302
                               const LValue &LVal, APValue &RVal,
4303
9
                               bool WantObjectRepresentation = false) {
4304
9
  if (LVal.Designator.Invalid)
4305
0
    return false;
4306
4307
  // Check for special cases where there is no existing APValue to look at.
4308
9
  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4309
4310
9
  AccessKinds AK =
4311
9
      WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4312
4313
9
  if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4314
0
    if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4315
      // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4316
      // initializer until now for such expressions. Such an expression can't be
4317
      // an ICE in C, so this only matters for fold.
4318
0
      if (Type.isVolatileQualified()) {
4319
0
        Info.FFDiag(Conv);
4320
0
        return false;
4321
0
      }
4322
4323
0
      APValue Lit;
4324
0
      if (!Evaluate(Lit, Info, CLE->getInitializer()))
4325
0
        return false;
4326
4327
      // According to GCC info page:
4328
      //
4329
      // 6.28 Compound Literals
4330
      //
4331
      // As an optimization, G++ sometimes gives array compound literals longer
4332
      // lifetimes: when the array either appears outside a function or has a
4333
      // const-qualified type. If foo and its initializer had elements of type
4334
      // char *const rather than char *, or if foo were a global variable, the
4335
      // array would have static storage duration. But it is probably safest
4336
      // just to avoid the use of array compound literals in C++ code.
4337
      //
4338
      // Obey that rule by checking constness for converted array types.
4339
4340
0
      QualType CLETy = CLE->getType();
4341
0
      if (CLETy->isArrayType() && !Type->isArrayType()) {
4342
0
        if (!CLETy.isConstant(Info.Ctx)) {
4343
0
          Info.FFDiag(Conv);
4344
0
          Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4345
0
          return false;
4346
0
        }
4347
0
      }
4348
4349
0
      CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4350
0
      return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4351
0
    } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4352
      // Special-case character extraction so we don't have to construct an
4353
      // APValue for the whole string.
4354
0
      assert(LVal.Designator.Entries.size() <= 1 &&
4355
0
             "Can only read characters from string literals");
4356
0
      if (LVal.Designator.Entries.empty()) {
4357
        // Fail for now for LValue to RValue conversion of an array.
4358
        // (This shouldn't show up in C/C++, but it could be triggered by a
4359
        // weird EvaluateAsRValue call from a tool.)
4360
0
        Info.FFDiag(Conv);
4361
0
        return false;
4362
0
      }
4363
0
      if (LVal.Designator.isOnePastTheEnd()) {
4364
0
        if (Info.getLangOpts().CPlusPlus11)
4365
0
          Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4366
0
        else
4367
0
          Info.FFDiag(Conv);
4368
0
        return false;
4369
0
      }
4370
0
      uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4371
0
      RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4372
0
      return true;
4373
0
    }
4374
0
  }
4375
4376
9
  CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4377
9
  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4378
9
}
4379
4380
/// Perform an assignment of Val to LVal. Takes ownership of Val.
4381
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4382
0
                             QualType LValType, APValue &Val) {
4383
0
  if (LVal.Designator.Invalid)
4384
0
    return false;
4385
4386
0
  if (!Info.getLangOpts().CPlusPlus14) {
4387
0
    Info.FFDiag(E);
4388
0
    return false;
4389
0
  }
4390
4391
0
  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4392
0
  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4393
0
}
4394
4395
namespace {
4396
struct CompoundAssignSubobjectHandler {
4397
  EvalInfo &Info;
4398
  const CompoundAssignOperator *E;
4399
  QualType PromotedLHSType;
4400
  BinaryOperatorKind Opcode;
4401
  const APValue &RHS;
4402
4403
  static const AccessKinds AccessKind = AK_Assign;
4404
4405
  typedef bool result_type;
4406
4407
0
  bool checkConst(QualType QT) {
4408
    // Assigning to a const object has undefined behavior.
4409
0
    if (QT.isConstQualified()) {
4410
0
      Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4411
0
      return false;
4412
0
    }
4413
0
    return true;
4414
0
  }
4415
4416
0
  bool failed() { return false; }
4417
0
  bool found(APValue &Subobj, QualType SubobjType) {
4418
0
    switch (Subobj.getKind()) {
4419
0
    case APValue::Int:
4420
0
      return found(Subobj.getInt(), SubobjType);
4421
0
    case APValue::Float:
4422
0
      return found(Subobj.getFloat(), SubobjType);
4423
0
    case APValue::ComplexInt:
4424
0
    case APValue::ComplexFloat:
4425
      // FIXME: Implement complex compound assignment.
4426
0
      Info.FFDiag(E);
4427
0
      return false;
4428
0
    case APValue::LValue:
4429
0
      return foundPointer(Subobj, SubobjType);
4430
0
    case APValue::Vector:
4431
0
      return foundVector(Subobj, SubobjType);
4432
0
    case APValue::Indeterminate:
4433
0
      Info.FFDiag(E, diag::note_constexpr_access_uninit)
4434
0
          << /*read of=*/0 << /*uninitialized object=*/1
4435
0
          << E->getLHS()->getSourceRange();
4436
0
      return false;
4437
0
    default:
4438
      // FIXME: can this happen?
4439
0
      Info.FFDiag(E);
4440
0
      return false;
4441
0
    }
4442
0
  }
4443
4444
0
  bool foundVector(APValue &Value, QualType SubobjType) {
4445
0
    if (!checkConst(SubobjType))
4446
0
      return false;
4447
4448
0
    if (!SubobjType->isVectorType()) {
4449
0
      Info.FFDiag(E);
4450
0
      return false;
4451
0
    }
4452
0
    return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4453
0
  }
4454
4455
0
  bool found(APSInt &Value, QualType SubobjType) {
4456
0
    if (!checkConst(SubobjType))
4457
0
      return false;
4458
4459
0
    if (!SubobjType->isIntegerType()) {
4460
      // We don't support compound assignment on integer-cast-to-pointer
4461
      // values.
4462
0
      Info.FFDiag(E);
4463
0
      return false;
4464
0
    }
4465
4466
0
    if (RHS.isInt()) {
4467
0
      APSInt LHS =
4468
0
          HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4469
0
      if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4470
0
        return false;
4471
0
      Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4472
0
      return true;
4473
0
    } else if (RHS.isFloat()) {
4474
0
      const FPOptions FPO = E->getFPFeaturesInEffect(
4475
0
                                    Info.Ctx.getLangOpts());
4476
0
      APFloat FValue(0.0);
4477
0
      return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4478
0
                                  PromotedLHSType, FValue) &&
4479
0
             handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4480
0
             HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4481
0
                                  Value);
4482
0
    }
4483
4484
0
    Info.FFDiag(E);
4485
0
    return false;
4486
0
  }
4487
0
  bool found(APFloat &Value, QualType SubobjType) {
4488
0
    return checkConst(SubobjType) &&
4489
0
           HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4490
0
                                  Value) &&
4491
0
           handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4492
0
           HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4493
0
  }
4494
0
  bool foundPointer(APValue &Subobj, QualType SubobjType) {
4495
0
    if (!checkConst(SubobjType))
4496
0
      return false;
4497
4498
0
    QualType PointeeType;
4499
0
    if (const PointerType *PT = SubobjType->getAs<PointerType>())
4500
0
      PointeeType = PT->getPointeeType();
4501
4502
0
    if (PointeeType.isNull() || !RHS.isInt() ||
4503
0
        (Opcode != BO_Add && Opcode != BO_Sub)) {
4504
0
      Info.FFDiag(E);
4505
0
      return false;
4506
0
    }
4507
4508
0
    APSInt Offset = RHS.getInt();
4509
0
    if (Opcode == BO_Sub)
4510
0
      negateAsSigned(Offset);
4511
4512
0
    LValue LVal;
4513
0
    LVal.setFrom(Info.Ctx, Subobj);
4514
0
    if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4515
0
      return false;
4516
0
    LVal.moveInto(Subobj);
4517
0
    return true;
4518
0
  }
4519
};
4520
} // end anonymous namespace
4521
4522
const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4523
4524
/// Perform a compound assignment of LVal <op>= RVal.
4525
static bool handleCompoundAssignment(EvalInfo &Info,
4526
                                     const CompoundAssignOperator *E,
4527
                                     const LValue &LVal, QualType LValType,
4528
                                     QualType PromotedLValType,
4529
                                     BinaryOperatorKind Opcode,
4530
0
                                     const APValue &RVal) {
4531
0
  if (LVal.Designator.Invalid)
4532
0
    return false;
4533
4534
0
  if (!Info.getLangOpts().CPlusPlus14) {
4535
0
    Info.FFDiag(E);
4536
0
    return false;
4537
0
  }
4538
4539
0
  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4540
0
  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4541
0
                                             RVal };
4542
0
  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4543
0
}
4544
4545
namespace {
4546
struct IncDecSubobjectHandler {
4547
  EvalInfo &Info;
4548
  const UnaryOperator *E;
4549
  AccessKinds AccessKind;
4550
  APValue *Old;
4551
4552
  typedef bool result_type;
4553
4554
0
  bool checkConst(QualType QT) {
4555
    // Assigning to a const object has undefined behavior.
4556
0
    if (QT.isConstQualified()) {
4557
0
      Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4558
0
      return false;
4559
0
    }
4560
0
    return true;
4561
0
  }
4562
4563
0
  bool failed() { return false; }
4564
0
  bool found(APValue &Subobj, QualType SubobjType) {
4565
    // Stash the old value. Also clear Old, so we don't clobber it later
4566
    // if we're post-incrementing a complex.
4567
0
    if (Old) {
4568
0
      *Old = Subobj;
4569
0
      Old = nullptr;
4570
0
    }
4571
4572
0
    switch (Subobj.getKind()) {
4573
0
    case APValue::Int:
4574
0
      return found(Subobj.getInt(), SubobjType);
4575
0
    case APValue::Float:
4576
0
      return found(Subobj.getFloat(), SubobjType);
4577
0
    case APValue::ComplexInt:
4578
0
      return found(Subobj.getComplexIntReal(),
4579
0
                   SubobjType->castAs<ComplexType>()->getElementType()
4580
0
                     .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4581
0
    case APValue::ComplexFloat:
4582
0
      return found(Subobj.getComplexFloatReal(),
4583
0
                   SubobjType->castAs<ComplexType>()->getElementType()
4584
0
                     .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4585
0
    case APValue::LValue:
4586
0
      return foundPointer(Subobj, SubobjType);
4587
0
    default:
4588
      // FIXME: can this happen?
4589
0
      Info.FFDiag(E);
4590
0
      return false;
4591
0
    }
4592
0
  }
4593
0
  bool found(APSInt &Value, QualType SubobjType) {
4594
0
    if (!checkConst(SubobjType))
4595
0
      return false;
4596
4597
0
    if (!SubobjType->isIntegerType()) {
4598
      // We don't support increment / decrement on integer-cast-to-pointer
4599
      // values.
4600
0
      Info.FFDiag(E);
4601
0
      return false;
4602
0
    }
4603
4604
0
    if (Old) *Old = APValue(Value);
4605
4606
    // bool arithmetic promotes to int, and the conversion back to bool
4607
    // doesn't reduce mod 2^n, so special-case it.
4608
0
    if (SubobjType->isBooleanType()) {
4609
0
      if (AccessKind == AK_Increment)
4610
0
        Value = 1;
4611
0
      else
4612
0
        Value = !Value;
4613
0
      return true;
4614
0
    }
4615
4616
0
    bool WasNegative = Value.isNegative();
4617
0
    if (AccessKind == AK_Increment) {
4618
0
      ++Value;
4619
4620
0
      if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4621
0
        APSInt ActualValue(Value, /*IsUnsigned*/true);
4622
0
        return HandleOverflow(Info, E, ActualValue, SubobjType);
4623
0
      }
4624
0
    } else {
4625
0
      --Value;
4626
4627
0
      if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4628
0
        unsigned BitWidth = Value.getBitWidth();
4629
0
        APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4630
0
        ActualValue.setBit(BitWidth);
4631
0
        return HandleOverflow(Info, E, ActualValue, SubobjType);
4632
0
      }
4633
0
    }
4634
0
    return true;
4635
0
  }
4636
0
  bool found(APFloat &Value, QualType SubobjType) {
4637
0
    if (!checkConst(SubobjType))
4638
0
      return false;
4639
4640
0
    if (Old) *Old = APValue(Value);
4641
4642
0
    APFloat One(Value.getSemantics(), 1);
4643
0
    llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4644
0
    APFloat::opStatus St;
4645
0
    if (AccessKind == AK_Increment)
4646
0
      St = Value.add(One, RM);
4647
0
    else
4648
0
      St = Value.subtract(One, RM);
4649
0
    return checkFloatingPointResult(Info, E, St);
4650
0
  }
4651
0
  bool foundPointer(APValue &Subobj, QualType SubobjType) {
4652
0
    if (!checkConst(SubobjType))
4653
0
      return false;
4654
4655
0
    QualType PointeeType;
4656
0
    if (const PointerType *PT = SubobjType->getAs<PointerType>())
4657
0
      PointeeType = PT->getPointeeType();
4658
0
    else {
4659
0
      Info.FFDiag(E);
4660
0
      return false;
4661
0
    }
4662
4663
0
    LValue LVal;
4664
0
    LVal.setFrom(Info.Ctx, Subobj);
4665
0
    if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4666
0
                                     AccessKind == AK_Increment ? 1 : -1))
4667
0
      return false;
4668
0
    LVal.moveInto(Subobj);
4669
0
    return true;
4670
0
  }
4671
};
4672
} // end anonymous namespace
4673
4674
/// Perform an increment or decrement on LVal.
4675
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4676
0
                         QualType LValType, bool IsIncrement, APValue *Old) {
4677
0
  if (LVal.Designator.Invalid)
4678
0
    return false;
4679
4680
0
  if (!Info.getLangOpts().CPlusPlus14) {
4681
0
    Info.FFDiag(E);
4682
0
    return false;
4683
0
  }
4684
4685
0
  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4686
0
  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4687
0
  IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4688
0
  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4689
0
}
4690
4691
/// Build an lvalue for the object argument of a member function call.
4692
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4693
0
                                   LValue &This) {
4694
0
  if (Object->getType()->isPointerType() && Object->isPRValue())
4695
0
    return EvaluatePointer(Object, This, Info);
4696
4697
0
  if (Object->isGLValue())
4698
0
    return EvaluateLValue(Object, This, Info);
4699
4700
0
  if (Object->getType()->isLiteralType(Info.Ctx))
4701
0
    return EvaluateTemporary(Object, This, Info);
4702
4703
0
  if (Object->getType()->isRecordType() && Object->isPRValue())
4704
0
    return EvaluateTemporary(Object, This, Info);
4705
4706
0
  Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4707
0
  return false;
4708
0
}
4709
4710
/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4711
/// lvalue referring to the result.
4712
///
4713
/// \param Info - Information about the ongoing evaluation.
4714
/// \param LV - An lvalue referring to the base of the member pointer.
4715
/// \param RHS - The member pointer expression.
4716
/// \param IncludeMember - Specifies whether the member itself is included in
4717
///        the resulting LValue subobject designator. This is not possible when
4718
///        creating a bound member function.
4719
/// \return The field or method declaration to which the member pointer refers,
4720
///         or 0 if evaluation fails.
4721
static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4722
                                                  QualType LVType,
4723
                                                  LValue &LV,
4724
                                                  const Expr *RHS,
4725
0
                                                  bool IncludeMember = true) {
4726
0
  MemberPtr MemPtr;
4727
0
  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4728
0
    return nullptr;
4729
4730
  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4731
  // member value, the behavior is undefined.
4732
0
  if (!MemPtr.getDecl()) {
4733
    // FIXME: Specific diagnostic.
4734
0
    Info.FFDiag(RHS);
4735
0
    return nullptr;
4736
0
  }
4737
4738
0
  if (MemPtr.isDerivedMember()) {
4739
    // This is a member of some derived class. Truncate LV appropriately.
4740
    // The end of the derived-to-base path for the base object must match the
4741
    // derived-to-base path for the member pointer.
4742
0
    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4743
0
        LV.Designator.Entries.size()) {
4744
0
      Info.FFDiag(RHS);
4745
0
      return nullptr;
4746
0
    }
4747
0
    unsigned PathLengthToMember =
4748
0
        LV.Designator.Entries.size() - MemPtr.Path.size();
4749
0
    for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4750
0
      const CXXRecordDecl *LVDecl = getAsBaseClass(
4751
0
          LV.Designator.Entries[PathLengthToMember + I]);
4752
0
      const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4753
0
      if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4754
0
        Info.FFDiag(RHS);
4755
0
        return nullptr;
4756
0
      }
4757
0
    }
4758
4759
    // Truncate the lvalue to the appropriate derived class.
4760
0
    if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4761
0
                            PathLengthToMember))
4762
0
      return nullptr;
4763
0
  } else if (!MemPtr.Path.empty()) {
4764
    // Extend the LValue path with the member pointer's path.
4765
0
    LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4766
0
                                  MemPtr.Path.size() + IncludeMember);
4767
4768
    // Walk down to the appropriate base class.
4769
0
    if (const PointerType *PT = LVType->getAs<PointerType>())
4770
0
      LVType = PT->getPointeeType();
4771
0
    const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4772
0
    assert(RD && "member pointer access on non-class-type expression");
4773
    // The first class in the path is that of the lvalue.
4774
0
    for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4775
0
      const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4776
0
      if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4777
0
        return nullptr;
4778
0
      RD = Base;
4779
0
    }
4780
    // Finally cast to the class containing the member.
4781
0
    if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4782
0
                                MemPtr.getContainingRecord()))
4783
0
      return nullptr;
4784
0
  }
4785
4786
  // Add the member. Note that we cannot build bound member functions here.
4787
0
  if (IncludeMember) {
4788
0
    if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4789
0
      if (!HandleLValueMember(Info, RHS, LV, FD))
4790
0
        return nullptr;
4791
0
    } else if (const IndirectFieldDecl *IFD =
4792
0
                 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4793
0
      if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4794
0
        return nullptr;
4795
0
    } else {
4796
0
      llvm_unreachable("can't construct reference to bound member function");
4797
0
    }
4798
0
  }
4799
4800
0
  return MemPtr.getDecl();
4801
0
}
4802
4803
static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4804
                                                  const BinaryOperator *BO,
4805
                                                  LValue &LV,
4806
0
                                                  bool IncludeMember = true) {
4807
0
  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4808
4809
0
  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4810
0
    if (Info.noteFailure()) {
4811
0
      MemberPtr MemPtr;
4812
0
      EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4813
0
    }
4814
0
    return nullptr;
4815
0
  }
4816
4817
0
  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4818
0
                                   BO->getRHS(), IncludeMember);
4819
0
}
4820
4821
/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4822
/// the provided lvalue, which currently refers to the base object.
4823
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4824
0
                                    LValue &Result) {
4825
0
  SubobjectDesignator &D = Result.Designator;
4826
0
  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4827
0
    return false;
4828
4829
0
  QualType TargetQT = E->getType();
4830
0
  if (const PointerType *PT = TargetQT->getAs<PointerType>())
4831
0
    TargetQT = PT->getPointeeType();
4832
4833
  // Check this cast lands within the final derived-to-base subobject path.
4834
0
  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4835
0
    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4836
0
      << D.MostDerivedType << TargetQT;
4837
0
    return false;
4838
0
  }
4839
4840
  // Check the type of the final cast. We don't need to check the path,
4841
  // since a cast can only be formed if the path is unique.
4842
0
  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4843
0
  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4844
0
  const CXXRecordDecl *FinalType;
4845
0
  if (NewEntriesSize == D.MostDerivedPathLength)
4846
0
    FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4847
0
  else
4848
0
    FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4849
0
  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4850
0
    Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4851
0
      << D.MostDerivedType << TargetQT;
4852
0
    return false;
4853
0
  }
4854
4855
  // Truncate the lvalue to the appropriate derived class.
4856
0
  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4857
0
}
4858
4859
/// Get the value to use for a default-initialized object of type T.
4860
/// Return false if it encounters something invalid.
4861
0
static bool handleDefaultInitValue(QualType T, APValue &Result) {
4862
0
  bool Success = true;
4863
4864
  // If there is already a value present don't overwrite it.
4865
0
  if (!Result.isAbsent())
4866
0
    return true;
4867
4868
0
  if (auto *RD = T->getAsCXXRecordDecl()) {
4869
0
    if (RD->isInvalidDecl()) {
4870
0
      Result = APValue();
4871
0
      return false;
4872
0
    }
4873
0
    if (RD->isUnion()) {
4874
0
      Result = APValue((const FieldDecl *)nullptr);
4875
0
      return true;
4876
0
    }
4877
0
    Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4878
0
                     std::distance(RD->field_begin(), RD->field_end()));
4879
4880
0
    unsigned Index = 0;
4881
0
    for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4882
0
                                                  End = RD->bases_end();
4883
0
         I != End; ++I, ++Index)
4884
0
      Success &=
4885
0
          handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4886
4887
0
    for (const auto *I : RD->fields()) {
4888
0
      if (I->isUnnamedBitfield())
4889
0
        continue;
4890
0
      Success &= handleDefaultInitValue(
4891
0
          I->getType(), Result.getStructField(I->getFieldIndex()));
4892
0
    }
4893
0
    return Success;
4894
0
  }
4895
4896
0
  if (auto *AT =
4897
0
          dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4898
0
    Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4899
0
    if (Result.hasArrayFiller())
4900
0
      Success &=
4901
0
          handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4902
4903
0
    return Success;
4904
0
  }
4905
4906
0
  Result = APValue::IndeterminateValue();
4907
0
  return true;
4908
0
}
4909
4910
namespace {
4911
enum EvalStmtResult {
4912
  /// Evaluation failed.
4913
  ESR_Failed,
4914
  /// Hit a 'return' statement.
4915
  ESR_Returned,
4916
  /// Evaluation succeeded.
4917
  ESR_Succeeded,
4918
  /// Hit a 'continue' statement.
4919
  ESR_Continue,
4920
  /// Hit a 'break' statement.
4921
  ESR_Break,
4922
  /// Still scanning for 'case' or 'default' statement.
4923
  ESR_CaseNotFound
4924
};
4925
}
4926
4927
0
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4928
0
  if (VD->isInvalidDecl())
4929
0
    return false;
4930
  // We don't need to evaluate the initializer for a static local.
4931
0
  if (!VD->hasLocalStorage())
4932
0
    return true;
4933
4934
0
  LValue Result;
4935
0
  APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4936
0
                                                   ScopeKind::Block, Result);
4937
4938
0
  const Expr *InitE = VD->getInit();
4939
0
  if (!InitE) {
4940
0
    if (VD->getType()->isDependentType())
4941
0
      return Info.noteSideEffect();
4942
0
    return handleDefaultInitValue(VD->getType(), Val);
4943
0
  }
4944
0
  if (InitE->isValueDependent())
4945
0
    return false;
4946
4947
0
  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4948
    // Wipe out any partially-computed value, to allow tracking that this
4949
    // evaluation failed.
4950
0
    Val = APValue();
4951
0
    return false;
4952
0
  }
4953
4954
0
  return true;
4955
0
}
4956
4957
0
static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4958
0
  bool OK = true;
4959
4960
0
  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4961
0
    OK &= EvaluateVarDecl(Info, VD);
4962
4963
0
  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4964
0
    for (auto *BD : DD->bindings())
4965
0
      if (auto *VD = BD->getHoldingVar())
4966
0
        OK &= EvaluateDecl(Info, VD);
4967
4968
0
  return OK;
4969
0
}
4970
4971
0
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4972
0
  assert(E->isValueDependent());
4973
0
  if (Info.noteSideEffect())
4974
0
    return true;
4975
0
  assert(E->containsErrors() && "valid value-dependent expression should never "
4976
0
                                "reach invalid code path.");
4977
0
  return false;
4978
0
}
4979
4980
/// Evaluate a condition (either a variable declaration or an expression).
4981
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4982
0
                         const Expr *Cond, bool &Result) {
4983
0
  if (Cond->isValueDependent())
4984
0
    return false;
4985
0
  FullExpressionRAII Scope(Info);
4986
0
  if (CondDecl && !EvaluateDecl(Info, CondDecl))
4987
0
    return false;
4988
0
  if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4989
0
    return false;
4990
0
  return Scope.destroy();
4991
0
}
4992
4993
namespace {
4994
/// A location where the result (returned value) of evaluating a
4995
/// statement should be stored.
4996
struct StmtResult {
4997
  /// The APValue that should be filled in with the returned value.
4998
  APValue &Value;
4999
  /// The location containing the result, if any (used to support RVO).
5000
  const LValue *Slot;
5001
};
5002
5003
struct TempVersionRAII {
5004
  CallStackFrame &Frame;
5005
5006
0
  TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5007
0
    Frame.pushTempVersion();
5008
0
  }
5009
5010
0
  ~TempVersionRAII() {
5011
0
    Frame.popTempVersion();
5012
0
  }
5013
};
5014
5015
}
5016
5017
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5018
                                   const Stmt *S,
5019
                                   const SwitchCase *SC = nullptr);
5020
5021
/// Evaluate the body of a loop, and translate the result as appropriate.
5022
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5023
                                       const Stmt *Body,
5024
0
                                       const SwitchCase *Case = nullptr) {
5025
0
  BlockScopeRAII Scope(Info);
5026
5027
0
  EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5028
0
  if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5029
0
    ESR = ESR_Failed;
5030
5031
0
  switch (ESR) {
5032
0
  case ESR_Break:
5033
0
    return ESR_Succeeded;
5034
0
  case ESR_Succeeded:
5035
0
  case ESR_Continue:
5036
0
    return ESR_Continue;
5037
0
  case ESR_Failed:
5038
0
  case ESR_Returned:
5039
0
  case ESR_CaseNotFound:
5040
0
    return ESR;
5041
0
  }
5042
0
  llvm_unreachable("Invalid EvalStmtResult!");
5043
0
}
5044
5045
/// Evaluate a switch statement.
5046
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5047
0
                                     const SwitchStmt *SS) {
5048
0
  BlockScopeRAII Scope(Info);
5049
5050
  // Evaluate the switch condition.
5051
0
  APSInt Value;
5052
0
  {
5053
0
    if (const Stmt *Init = SS->getInit()) {
5054
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5055
0
      if (ESR != ESR_Succeeded) {
5056
0
        if (ESR != ESR_Failed && !Scope.destroy())
5057
0
          ESR = ESR_Failed;
5058
0
        return ESR;
5059
0
      }
5060
0
    }
5061
5062
0
    FullExpressionRAII CondScope(Info);
5063
0
    if (SS->getConditionVariable() &&
5064
0
        !EvaluateDecl(Info, SS->getConditionVariable()))
5065
0
      return ESR_Failed;
5066
0
    if (SS->getCond()->isValueDependent()) {
5067
      // We don't know what the value is, and which branch should jump to.
5068
0
      EvaluateDependentExpr(SS->getCond(), Info);
5069
0
      return ESR_Failed;
5070
0
    }
5071
0
    if (!EvaluateInteger(SS->getCond(), Value, Info))
5072
0
      return ESR_Failed;
5073
5074
0
    if (!CondScope.destroy())
5075
0
      return ESR_Failed;
5076
0
  }
5077
5078
  // Find the switch case corresponding to the value of the condition.
5079
  // FIXME: Cache this lookup.
5080
0
  const SwitchCase *Found = nullptr;
5081
0
  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5082
0
       SC = SC->getNextSwitchCase()) {
5083
0
    if (isa<DefaultStmt>(SC)) {
5084
0
      Found = SC;
5085
0
      continue;
5086
0
    }
5087
5088
0
    const CaseStmt *CS = cast<CaseStmt>(SC);
5089
0
    APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5090
0
    APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5091
0
                              : LHS;
5092
0
    if (LHS <= Value && Value <= RHS) {
5093
0
      Found = SC;
5094
0
      break;
5095
0
    }
5096
0
  }
5097
5098
0
  if (!Found)
5099
0
    return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5100
5101
  // Search the switch body for the switch case and evaluate it from there.
5102
0
  EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5103
0
  if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5104
0
    return ESR_Failed;
5105
5106
0
  switch (ESR) {
5107
0
  case ESR_Break:
5108
0
    return ESR_Succeeded;
5109
0
  case ESR_Succeeded:
5110
0
  case ESR_Continue:
5111
0
  case ESR_Failed:
5112
0
  case ESR_Returned:
5113
0
    return ESR;
5114
0
  case ESR_CaseNotFound:
5115
    // This can only happen if the switch case is nested within a statement
5116
    // expression. We have no intention of supporting that.
5117
0
    Info.FFDiag(Found->getBeginLoc(),
5118
0
                diag::note_constexpr_stmt_expr_unsupported);
5119
0
    return ESR_Failed;
5120
0
  }
5121
0
  llvm_unreachable("Invalid EvalStmtResult!");
5122
0
}
5123
5124
0
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5125
  // An expression E is a core constant expression unless the evaluation of E
5126
  // would evaluate one of the following: [C++23] - a control flow that passes
5127
  // through a declaration of a variable with static or thread storage duration
5128
  // unless that variable is usable in constant expressions.
5129
0
  if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5130
0
      !VD->isUsableInConstantExpressions(Info.Ctx)) {
5131
0
    Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5132
0
        << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5133
0
    return false;
5134
0
  }
5135
0
  return true;
5136
0
}
5137
5138
// Evaluate a statement.
5139
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5140
0
                                   const Stmt *S, const SwitchCase *Case) {
5141
0
  if (!Info.nextStep(S))
5142
0
    return ESR_Failed;
5143
5144
  // If we're hunting down a 'case' or 'default' label, recurse through
5145
  // substatements until we hit the label.
5146
0
  if (Case) {
5147
0
    switch (S->getStmtClass()) {
5148
0
    case Stmt::CompoundStmtClass:
5149
      // FIXME: Precompute which substatement of a compound statement we
5150
      // would jump to, and go straight there rather than performing a
5151
      // linear scan each time.
5152
0
    case Stmt::LabelStmtClass:
5153
0
    case Stmt::AttributedStmtClass:
5154
0
    case Stmt::DoStmtClass:
5155
0
      break;
5156
5157
0
    case Stmt::CaseStmtClass:
5158
0
    case Stmt::DefaultStmtClass:
5159
0
      if (Case == S)
5160
0
        Case = nullptr;
5161
0
      break;
5162
5163
0
    case Stmt::IfStmtClass: {
5164
      // FIXME: Precompute which side of an 'if' we would jump to, and go
5165
      // straight there rather than scanning both sides.
5166
0
      const IfStmt *IS = cast<IfStmt>(S);
5167
5168
      // Wrap the evaluation in a block scope, in case it's a DeclStmt
5169
      // preceded by our switch label.
5170
0
      BlockScopeRAII Scope(Info);
5171
5172
      // Step into the init statement in case it brings an (uninitialized)
5173
      // variable into scope.
5174
0
      if (const Stmt *Init = IS->getInit()) {
5175
0
        EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5176
0
        if (ESR != ESR_CaseNotFound) {
5177
0
          assert(ESR != ESR_Succeeded);
5178
0
          return ESR;
5179
0
        }
5180
0
      }
5181
5182
      // Condition variable must be initialized if it exists.
5183
      // FIXME: We can skip evaluating the body if there's a condition
5184
      // variable, as there can't be any case labels within it.
5185
      // (The same is true for 'for' statements.)
5186
5187
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5188
0
      if (ESR == ESR_Failed)
5189
0
        return ESR;
5190
0
      if (ESR != ESR_CaseNotFound)
5191
0
        return Scope.destroy() ? ESR : ESR_Failed;
5192
0
      if (!IS->getElse())
5193
0
        return ESR_CaseNotFound;
5194
5195
0
      ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5196
0
      if (ESR == ESR_Failed)
5197
0
        return ESR;
5198
0
      if (ESR != ESR_CaseNotFound)
5199
0
        return Scope.destroy() ? ESR : ESR_Failed;
5200
0
      return ESR_CaseNotFound;
5201
0
    }
5202
5203
0
    case Stmt::WhileStmtClass: {
5204
0
      EvalStmtResult ESR =
5205
0
          EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5206
0
      if (ESR != ESR_Continue)
5207
0
        return ESR;
5208
0
      break;
5209
0
    }
5210
5211
0
    case Stmt::ForStmtClass: {
5212
0
      const ForStmt *FS = cast<ForStmt>(S);
5213
0
      BlockScopeRAII Scope(Info);
5214
5215
      // Step into the init statement in case it brings an (uninitialized)
5216
      // variable into scope.
5217
0
      if (const Stmt *Init = FS->getInit()) {
5218
0
        EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5219
0
        if (ESR != ESR_CaseNotFound) {
5220
0
          assert(ESR != ESR_Succeeded);
5221
0
          return ESR;
5222
0
        }
5223
0
      }
5224
5225
0
      EvalStmtResult ESR =
5226
0
          EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5227
0
      if (ESR != ESR_Continue)
5228
0
        return ESR;
5229
0
      if (const auto *Inc = FS->getInc()) {
5230
0
        if (Inc->isValueDependent()) {
5231
0
          if (!EvaluateDependentExpr(Inc, Info))
5232
0
            return ESR_Failed;
5233
0
        } else {
5234
0
          FullExpressionRAII IncScope(Info);
5235
0
          if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5236
0
            return ESR_Failed;
5237
0
        }
5238
0
      }
5239
0
      break;
5240
0
    }
5241
5242
0
    case Stmt::DeclStmtClass: {
5243
      // Start the lifetime of any uninitialized variables we encounter. They
5244
      // might be used by the selected branch of the switch.
5245
0
      const DeclStmt *DS = cast<DeclStmt>(S);
5246
0
      for (const auto *D : DS->decls()) {
5247
0
        if (const auto *VD = dyn_cast<VarDecl>(D)) {
5248
0
          if (!CheckLocalVariableDeclaration(Info, VD))
5249
0
            return ESR_Failed;
5250
0
          if (VD->hasLocalStorage() && !VD->getInit())
5251
0
            if (!EvaluateVarDecl(Info, VD))
5252
0
              return ESR_Failed;
5253
          // FIXME: If the variable has initialization that can't be jumped
5254
          // over, bail out of any immediately-surrounding compound-statement
5255
          // too. There can't be any case labels here.
5256
0
        }
5257
0
      }
5258
0
      return ESR_CaseNotFound;
5259
0
    }
5260
5261
0
    default:
5262
0
      return ESR_CaseNotFound;
5263
0
    }
5264
0
  }
5265
5266
0
  switch (S->getStmtClass()) {
5267
0
  default:
5268
0
    if (const Expr *E = dyn_cast<Expr>(S)) {
5269
0
      if (E->isValueDependent()) {
5270
0
        if (!EvaluateDependentExpr(E, Info))
5271
0
          return ESR_Failed;
5272
0
      } else {
5273
        // Don't bother evaluating beyond an expression-statement which couldn't
5274
        // be evaluated.
5275
        // FIXME: Do we need the FullExpressionRAII object here?
5276
        // VisitExprWithCleanups should create one when necessary.
5277
0
        FullExpressionRAII Scope(Info);
5278
0
        if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5279
0
          return ESR_Failed;
5280
0
      }
5281
0
      return ESR_Succeeded;
5282
0
    }
5283
5284
0
    Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5285
0
    return ESR_Failed;
5286
5287
0
  case Stmt::NullStmtClass:
5288
0
    return ESR_Succeeded;
5289
5290
0
  case Stmt::DeclStmtClass: {
5291
0
    const DeclStmt *DS = cast<DeclStmt>(S);
5292
0
    for (const auto *D : DS->decls()) {
5293
0
      const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5294
0
      if (VD && !CheckLocalVariableDeclaration(Info, VD))
5295
0
        return ESR_Failed;
5296
      // Each declaration initialization is its own full-expression.
5297
0
      FullExpressionRAII Scope(Info);
5298
0
      if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5299
0
        return ESR_Failed;
5300
0
      if (!Scope.destroy())
5301
0
        return ESR_Failed;
5302
0
    }
5303
0
    return ESR_Succeeded;
5304
0
  }
5305
5306
0
  case Stmt::ReturnStmtClass: {
5307
0
    const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5308
0
    FullExpressionRAII Scope(Info);
5309
0
    if (RetExpr && RetExpr->isValueDependent()) {
5310
0
      EvaluateDependentExpr(RetExpr, Info);
5311
      // We know we returned, but we don't know what the value is.
5312
0
      return ESR_Failed;
5313
0
    }
5314
0
    if (RetExpr &&
5315
0
        !(Result.Slot
5316
0
              ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5317
0
              : Evaluate(Result.Value, Info, RetExpr)))
5318
0
      return ESR_Failed;
5319
0
    return Scope.destroy() ? ESR_Returned : ESR_Failed;
5320
0
  }
5321
5322
0
  case Stmt::CompoundStmtClass: {
5323
0
    BlockScopeRAII Scope(Info);
5324
5325
0
    const CompoundStmt *CS = cast<CompoundStmt>(S);
5326
0
    for (const auto *BI : CS->body()) {
5327
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5328
0
      if (ESR == ESR_Succeeded)
5329
0
        Case = nullptr;
5330
0
      else if (ESR != ESR_CaseNotFound) {
5331
0
        if (ESR != ESR_Failed && !Scope.destroy())
5332
0
          return ESR_Failed;
5333
0
        return ESR;
5334
0
      }
5335
0
    }
5336
0
    if (Case)
5337
0
      return ESR_CaseNotFound;
5338
0
    return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5339
0
  }
5340
5341
0
  case Stmt::IfStmtClass: {
5342
0
    const IfStmt *IS = cast<IfStmt>(S);
5343
5344
    // Evaluate the condition, as either a var decl or as an expression.
5345
0
    BlockScopeRAII Scope(Info);
5346
0
    if (const Stmt *Init = IS->getInit()) {
5347
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5348
0
      if (ESR != ESR_Succeeded) {
5349
0
        if (ESR != ESR_Failed && !Scope.destroy())
5350
0
          return ESR_Failed;
5351
0
        return ESR;
5352
0
      }
5353
0
    }
5354
0
    bool Cond;
5355
0
    if (IS->isConsteval()) {
5356
0
      Cond = IS->isNonNegatedConsteval();
5357
      // If we are not in a constant context, if consteval should not evaluate
5358
      // to true.
5359
0
      if (!Info.InConstantContext)
5360
0
        Cond = !Cond;
5361
0
    } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5362
0
                             Cond))
5363
0
      return ESR_Failed;
5364
5365
0
    if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5366
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5367
0
      if (ESR != ESR_Succeeded) {
5368
0
        if (ESR != ESR_Failed && !Scope.destroy())
5369
0
          return ESR_Failed;
5370
0
        return ESR;
5371
0
      }
5372
0
    }
5373
0
    return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5374
0
  }
5375
5376
0
  case Stmt::WhileStmtClass: {
5377
0
    const WhileStmt *WS = cast<WhileStmt>(S);
5378
0
    while (true) {
5379
0
      BlockScopeRAII Scope(Info);
5380
0
      bool Continue;
5381
0
      if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5382
0
                        Continue))
5383
0
        return ESR_Failed;
5384
0
      if (!Continue)
5385
0
        break;
5386
5387
0
      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5388
0
      if (ESR != ESR_Continue) {
5389
0
        if (ESR != ESR_Failed && !Scope.destroy())
5390
0
          return ESR_Failed;
5391
0
        return ESR;
5392
0
      }
5393
0
      if (!Scope.destroy())
5394
0
        return ESR_Failed;
5395
0
    }
5396
0
    return ESR_Succeeded;
5397
0
  }
5398
5399
0
  case Stmt::DoStmtClass: {
5400
0
    const DoStmt *DS = cast<DoStmt>(S);
5401
0
    bool Continue;
5402
0
    do {
5403
0
      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5404
0
      if (ESR != ESR_Continue)
5405
0
        return ESR;
5406
0
      Case = nullptr;
5407
5408
0
      if (DS->getCond()->isValueDependent()) {
5409
0
        EvaluateDependentExpr(DS->getCond(), Info);
5410
        // Bailout as we don't know whether to keep going or terminate the loop.
5411
0
        return ESR_Failed;
5412
0
      }
5413
0
      FullExpressionRAII CondScope(Info);
5414
0
      if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5415
0
          !CondScope.destroy())
5416
0
        return ESR_Failed;
5417
0
    } while (Continue);
5418
0
    return ESR_Succeeded;
5419
0
  }
5420
5421
0
  case Stmt::ForStmtClass: {
5422
0
    const ForStmt *FS = cast<ForStmt>(S);
5423
0
    BlockScopeRAII ForScope(Info);
5424
0
    if (FS->getInit()) {
5425
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5426
0
      if (ESR != ESR_Succeeded) {
5427
0
        if (ESR != ESR_Failed && !ForScope.destroy())
5428
0
          return ESR_Failed;
5429
0
        return ESR;
5430
0
      }
5431
0
    }
5432
0
    while (true) {
5433
0
      BlockScopeRAII IterScope(Info);
5434
0
      bool Continue = true;
5435
0
      if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5436
0
                                         FS->getCond(), Continue))
5437
0
        return ESR_Failed;
5438
0
      if (!Continue)
5439
0
        break;
5440
5441
0
      EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5442
0
      if (ESR != ESR_Continue) {
5443
0
        if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5444
0
          return ESR_Failed;
5445
0
        return ESR;
5446
0
      }
5447
5448
0
      if (const auto *Inc = FS->getInc()) {
5449
0
        if (Inc->isValueDependent()) {
5450
0
          if (!EvaluateDependentExpr(Inc, Info))
5451
0
            return ESR_Failed;
5452
0
        } else {
5453
0
          FullExpressionRAII IncScope(Info);
5454
0
          if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5455
0
            return ESR_Failed;
5456
0
        }
5457
0
      }
5458
5459
0
      if (!IterScope.destroy())
5460
0
        return ESR_Failed;
5461
0
    }
5462
0
    return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5463
0
  }
5464
5465
0
  case Stmt::CXXForRangeStmtClass: {
5466
0
    const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5467
0
    BlockScopeRAII Scope(Info);
5468
5469
    // Evaluate the init-statement if present.
5470
0
    if (FS->getInit()) {
5471
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5472
0
      if (ESR != ESR_Succeeded) {
5473
0
        if (ESR != ESR_Failed && !Scope.destroy())
5474
0
          return ESR_Failed;
5475
0
        return ESR;
5476
0
      }
5477
0
    }
5478
5479
    // Initialize the __range variable.
5480
0
    EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5481
0
    if (ESR != ESR_Succeeded) {
5482
0
      if (ESR != ESR_Failed && !Scope.destroy())
5483
0
        return ESR_Failed;
5484
0
      return ESR;
5485
0
    }
5486
5487
    // In error-recovery cases it's possible to get here even if we failed to
5488
    // synthesize the __begin and __end variables.
5489
0
    if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5490
0
      return ESR_Failed;
5491
5492
    // Create the __begin and __end iterators.
5493
0
    ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5494
0
    if (ESR != ESR_Succeeded) {
5495
0
      if (ESR != ESR_Failed && !Scope.destroy())
5496
0
        return ESR_Failed;
5497
0
      return ESR;
5498
0
    }
5499
0
    ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5500
0
    if (ESR != ESR_Succeeded) {
5501
0
      if (ESR != ESR_Failed && !Scope.destroy())
5502
0
        return ESR_Failed;
5503
0
      return ESR;
5504
0
    }
5505
5506
0
    while (true) {
5507
      // Condition: __begin != __end.
5508
0
      {
5509
0
        if (FS->getCond()->isValueDependent()) {
5510
0
          EvaluateDependentExpr(FS->getCond(), Info);
5511
          // We don't know whether to keep going or terminate the loop.
5512
0
          return ESR_Failed;
5513
0
        }
5514
0
        bool Continue = true;
5515
0
        FullExpressionRAII CondExpr(Info);
5516
0
        if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5517
0
          return ESR_Failed;
5518
0
        if (!Continue)
5519
0
          break;
5520
0
      }
5521
5522
      // User's variable declaration, initialized by *__begin.
5523
0
      BlockScopeRAII InnerScope(Info);
5524
0
      ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5525
0
      if (ESR != ESR_Succeeded) {
5526
0
        if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5527
0
          return ESR_Failed;
5528
0
        return ESR;
5529
0
      }
5530
5531
      // Loop body.
5532
0
      ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5533
0
      if (ESR != ESR_Continue) {
5534
0
        if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5535
0
          return ESR_Failed;
5536
0
        return ESR;
5537
0
      }
5538
0
      if (FS->getInc()->isValueDependent()) {
5539
0
        if (!EvaluateDependentExpr(FS->getInc(), Info))
5540
0
          return ESR_Failed;
5541
0
      } else {
5542
        // Increment: ++__begin
5543
0
        if (!EvaluateIgnoredValue(Info, FS->getInc()))
5544
0
          return ESR_Failed;
5545
0
      }
5546
5547
0
      if (!InnerScope.destroy())
5548
0
        return ESR_Failed;
5549
0
    }
5550
5551
0
    return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5552
0
  }
5553
5554
0
  case Stmt::SwitchStmtClass:
5555
0
    return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5556
5557
0
  case Stmt::ContinueStmtClass:
5558
0
    return ESR_Continue;
5559
5560
0
  case Stmt::BreakStmtClass:
5561
0
    return ESR_Break;
5562
5563
0
  case Stmt::LabelStmtClass:
5564
0
    return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5565
5566
0
  case Stmt::AttributedStmtClass: {
5567
0
    const auto *AS = cast<AttributedStmt>(S);
5568
0
    const auto *SS = AS->getSubStmt();
5569
0
    MSConstexprContextRAII ConstexprContext(
5570
0
        *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5571
0
                               isa<ReturnStmt>(SS));
5572
0
    return EvaluateStmt(Result, Info, SS, Case);
5573
0
  }
5574
5575
0
  case Stmt::CaseStmtClass:
5576
0
  case Stmt::DefaultStmtClass:
5577
0
    return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5578
0
  case Stmt::CXXTryStmtClass:
5579
    // Evaluate try blocks by evaluating all sub statements.
5580
0
    return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5581
0
  }
5582
0
}
5583
5584
/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5585
/// default constructor. If so, we'll fold it whether or not it's marked as
5586
/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5587
/// so we need special handling.
5588
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5589
                                           const CXXConstructorDecl *CD,
5590
0
                                           bool IsValueInitialization) {
5591
0
  if (!CD->isTrivial() || !CD->isDefaultConstructor())
5592
0
    return false;
5593
5594
  // Value-initialization does not call a trivial default constructor, so such a
5595
  // call is a core constant expression whether or not the constructor is
5596
  // constexpr.
5597
0
  if (!CD->isConstexpr() && !IsValueInitialization) {
5598
0
    if (Info.getLangOpts().CPlusPlus11) {
5599
      // FIXME: If DiagDecl is an implicitly-declared special member function,
5600
      // we should be much more explicit about why it's not constexpr.
5601
0
      Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5602
0
        << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5603
0
      Info.Note(CD->getLocation(), diag::note_declared_at);
5604
0
    } else {
5605
0
      Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5606
0
    }
5607
0
  }
5608
0
  return true;
5609
0
}
5610
5611
/// CheckConstexprFunction - Check that a function can be called in a constant
5612
/// expression.
5613
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5614
                                   const FunctionDecl *Declaration,
5615
                                   const FunctionDecl *Definition,
5616
0
                                   const Stmt *Body) {
5617
  // Potential constant expressions can contain calls to declared, but not yet
5618
  // defined, constexpr functions.
5619
0
  if (Info.checkingPotentialConstantExpression() && !Definition &&
5620
0
      Declaration->isConstexpr())
5621
0
    return false;
5622
5623
  // Bail out if the function declaration itself is invalid.  We will
5624
  // have produced a relevant diagnostic while parsing it, so just
5625
  // note the problematic sub-expression.
5626
0
  if (Declaration->isInvalidDecl()) {
5627
0
    Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5628
0
    return false;
5629
0
  }
5630
5631
  // DR1872: An instantiated virtual constexpr function can't be called in a
5632
  // constant expression (prior to C++20). We can still constant-fold such a
5633
  // call.
5634
0
  if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5635
0
      cast<CXXMethodDecl>(Declaration)->isVirtual())
5636
0
    Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5637
5638
0
  if (Definition && Definition->isInvalidDecl()) {
5639
0
    Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5640
0
    return false;
5641
0
  }
5642
5643
  // Can we evaluate this function call?
5644
0
  if (Definition && Body &&
5645
0
      (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5646
0
                                        Definition->hasAttr<MSConstexprAttr>())))
5647
0
    return true;
5648
5649
0
  if (Info.getLangOpts().CPlusPlus11) {
5650
0
    const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5651
5652
    // If this function is not constexpr because it is an inherited
5653
    // non-constexpr constructor, diagnose that directly.
5654
0
    auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5655
0
    if (CD && CD->isInheritingConstructor()) {
5656
0
      auto *Inherited = CD->getInheritedConstructor().getConstructor();
5657
0
      if (!Inherited->isConstexpr())
5658
0
        DiagDecl = CD = Inherited;
5659
0
    }
5660
5661
    // FIXME: If DiagDecl is an implicitly-declared special member function
5662
    // or an inheriting constructor, we should be much more explicit about why
5663
    // it's not constexpr.
5664
0
    if (CD && CD->isInheritingConstructor())
5665
0
      Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5666
0
        << CD->getInheritedConstructor().getConstructor()->getParent();
5667
0
    else
5668
0
      Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5669
0
        << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5670
0
    Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5671
0
  } else {
5672
0
    Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5673
0
  }
5674
0
  return false;
5675
0
}
5676
5677
namespace {
5678
struct CheckDynamicTypeHandler {
5679
  AccessKinds AccessKind;
5680
  typedef bool result_type;
5681
0
  bool failed() { return false; }
5682
0
  bool found(APValue &Subobj, QualType SubobjType) { return true; }
5683
0
  bool found(APSInt &Value, QualType SubobjType) { return true; }
5684
0
  bool found(APFloat &Value, QualType SubobjType) { return true; }
5685
};
5686
} // end anonymous namespace
5687
5688
/// Check that we can access the notional vptr of an object / determine its
5689
/// dynamic type.
5690
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5691
0
                             AccessKinds AK, bool Polymorphic) {
5692
0
  if (This.Designator.Invalid)
5693
0
    return false;
5694
5695
0
  CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5696
5697
0
  if (!Obj)
5698
0
    return false;
5699
5700
0
  if (!Obj.Value) {
5701
    // The object is not usable in constant expressions, so we can't inspect
5702
    // its value to see if it's in-lifetime or what the active union members
5703
    // are. We can still check for a one-past-the-end lvalue.
5704
0
    if (This.Designator.isOnePastTheEnd() ||
5705
0
        This.Designator.isMostDerivedAnUnsizedArray()) {
5706
0
      Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5707
0
                         ? diag::note_constexpr_access_past_end
5708
0
                         : diag::note_constexpr_access_unsized_array)
5709
0
          << AK;
5710
0
      return false;
5711
0
    } else if (Polymorphic) {
5712
      // Conservatively refuse to perform a polymorphic operation if we would
5713
      // not be able to read a notional 'vptr' value.
5714
0
      APValue Val;
5715
0
      This.moveInto(Val);
5716
0
      QualType StarThisType =
5717
0
          Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5718
0
      Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5719
0
          << AK << Val.getAsString(Info.Ctx, StarThisType);
5720
0
      return false;
5721
0
    }
5722
0
    return true;
5723
0
  }
5724
5725
0
  CheckDynamicTypeHandler Handler{AK};
5726
0
  return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5727
0
}
5728
5729
/// Check that the pointee of the 'this' pointer in a member function call is
5730
/// either within its lifetime or in its period of construction or destruction.
5731
static bool
5732
checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5733
                                     const LValue &This,
5734
0
                                     const CXXMethodDecl *NamedMember) {
5735
0
  return checkDynamicType(
5736
0
      Info, E, This,
5737
0
      isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5738
0
}
5739
5740
struct DynamicType {
5741
  /// The dynamic class type of the object.
5742
  const CXXRecordDecl *Type;
5743
  /// The corresponding path length in the lvalue.
5744
  unsigned PathLength;
5745
};
5746
5747
static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5748
0
                                             unsigned PathLength) {
5749
0
  assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5750
0
      Designator.Entries.size() && "invalid path length");
5751
0
  return (PathLength == Designator.MostDerivedPathLength)
5752
0
             ? Designator.MostDerivedType->getAsCXXRecordDecl()
5753
0
             : getAsBaseClass(Designator.Entries[PathLength - 1]);
5754
0
}
5755
5756
/// Determine the dynamic type of an object.
5757
static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5758
                                                     const Expr *E,
5759
                                                     LValue &This,
5760
0
                                                     AccessKinds AK) {
5761
  // If we don't have an lvalue denoting an object of class type, there is no
5762
  // meaningful dynamic type. (We consider objects of non-class type to have no
5763
  // dynamic type.)
5764
0
  if (!checkDynamicType(Info, E, This, AK, true))
5765
0
    return std::nullopt;
5766
5767
  // Refuse to compute a dynamic type in the presence of virtual bases. This
5768
  // shouldn't happen other than in constant-folding situations, since literal
5769
  // types can't have virtual bases.
5770
  //
5771
  // Note that consumers of DynamicType assume that the type has no virtual
5772
  // bases, and will need modifications if this restriction is relaxed.
5773
0
  const CXXRecordDecl *Class =
5774
0
      This.Designator.MostDerivedType->getAsCXXRecordDecl();
5775
0
  if (!Class || Class->getNumVBases()) {
5776
0
    Info.FFDiag(E);
5777
0
    return std::nullopt;
5778
0
  }
5779
5780
  // FIXME: For very deep class hierarchies, it might be beneficial to use a
5781
  // binary search here instead. But the overwhelmingly common case is that
5782
  // we're not in the middle of a constructor, so it probably doesn't matter
5783
  // in practice.
5784
0
  ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5785
0
  for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5786
0
       PathLength <= Path.size(); ++PathLength) {
5787
0
    switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5788
0
                                      Path.slice(0, PathLength))) {
5789
0
    case ConstructionPhase::Bases:
5790
0
    case ConstructionPhase::DestroyingBases:
5791
      // We're constructing or destroying a base class. This is not the dynamic
5792
      // type.
5793
0
      break;
5794
5795
0
    case ConstructionPhase::None:
5796
0
    case ConstructionPhase::AfterBases:
5797
0
    case ConstructionPhase::AfterFields:
5798
0
    case ConstructionPhase::Destroying:
5799
      // We've finished constructing the base classes and not yet started
5800
      // destroying them again, so this is the dynamic type.
5801
0
      return DynamicType{getBaseClassType(This.Designator, PathLength),
5802
0
                         PathLength};
5803
0
    }
5804
0
  }
5805
5806
  // CWG issue 1517: we're constructing a base class of the object described by
5807
  // 'This', so that object has not yet begun its period of construction and
5808
  // any polymorphic operation on it results in undefined behavior.
5809
0
  Info.FFDiag(E);
5810
0
  return std::nullopt;
5811
0
}
5812
5813
/// Perform virtual dispatch.
5814
static const CXXMethodDecl *HandleVirtualDispatch(
5815
    EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5816
0
    llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5817
0
  std::optional<DynamicType> DynType = ComputeDynamicType(
5818
0
      Info, E, This,
5819
0
      isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5820
0
  if (!DynType)
5821
0
    return nullptr;
5822
5823
  // Find the final overrider. It must be declared in one of the classes on the
5824
  // path from the dynamic type to the static type.
5825
  // FIXME: If we ever allow literal types to have virtual base classes, that
5826
  // won't be true.
5827
0
  const CXXMethodDecl *Callee = Found;
5828
0
  unsigned PathLength = DynType->PathLength;
5829
0
  for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5830
0
    const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5831
0
    const CXXMethodDecl *Overrider =
5832
0
        Found->getCorrespondingMethodDeclaredInClass(Class, false);
5833
0
    if (Overrider) {
5834
0
      Callee = Overrider;
5835
0
      break;
5836
0
    }
5837
0
  }
5838
5839
  // C++2a [class.abstract]p6:
5840
  //   the effect of making a virtual call to a pure virtual function [...] is
5841
  //   undefined
5842
0
  if (Callee->isPure()) {
5843
0
    Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5844
0
    Info.Note(Callee->getLocation(), diag::note_declared_at);
5845
0
    return nullptr;
5846
0
  }
5847
5848
  // If necessary, walk the rest of the path to determine the sequence of
5849
  // covariant adjustment steps to apply.
5850
0
  if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5851
0
                                       Found->getReturnType())) {
5852
0
    CovariantAdjustmentPath.push_back(Callee->getReturnType());
5853
0
    for (unsigned CovariantPathLength = PathLength + 1;
5854
0
         CovariantPathLength != This.Designator.Entries.size();
5855
0
         ++CovariantPathLength) {
5856
0
      const CXXRecordDecl *NextClass =
5857
0
          getBaseClassType(This.Designator, CovariantPathLength);
5858
0
      const CXXMethodDecl *Next =
5859
0
          Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5860
0
      if (Next && !Info.Ctx.hasSameUnqualifiedType(
5861
0
                      Next->getReturnType(), CovariantAdjustmentPath.back()))
5862
0
        CovariantAdjustmentPath.push_back(Next->getReturnType());
5863
0
    }
5864
0
    if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5865
0
                                         CovariantAdjustmentPath.back()))
5866
0
      CovariantAdjustmentPath.push_back(Found->getReturnType());
5867
0
  }
5868
5869
  // Perform 'this' adjustment.
5870
0
  if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5871
0
    return nullptr;
5872
5873
0
  return Callee;
5874
0
}
5875
5876
/// Perform the adjustment from a value returned by a virtual function to
5877
/// a value of the statically expected type, which may be a pointer or
5878
/// reference to a base class of the returned type.
5879
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5880
                                            APValue &Result,
5881
0
                                            ArrayRef<QualType> Path) {
5882
0
  assert(Result.isLValue() &&
5883
0
         "unexpected kind of APValue for covariant return");
5884
0
  if (Result.isNullPointer())
5885
0
    return true;
5886
5887
0
  LValue LVal;
5888
0
  LVal.setFrom(Info.Ctx, Result);
5889
5890
0
  const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5891
0
  for (unsigned I = 1; I != Path.size(); ++I) {
5892
0
    const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5893
0
    assert(OldClass && NewClass && "unexpected kind of covariant return");
5894
0
    if (OldClass != NewClass &&
5895
0
        !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5896
0
      return false;
5897
0
    OldClass = NewClass;
5898
0
  }
5899
5900
0
  LVal.moveInto(Result);
5901
0
  return true;
5902
0
}
5903
5904
/// Determine whether \p Base, which is known to be a direct base class of
5905
/// \p Derived, is a public base class.
5906
static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5907
0
                              const CXXRecordDecl *Base) {
5908
0
  for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5909
0
    auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5910
0
    if (BaseClass && declaresSameEntity(BaseClass, Base))
5911
0
      return BaseSpec.getAccessSpecifier() == AS_public;
5912
0
  }
5913
0
  llvm_unreachable("Base is not a direct base of Derived");
5914
0
}
5915
5916
/// Apply the given dynamic cast operation on the provided lvalue.
5917
///
5918
/// This implements the hard case of dynamic_cast, requiring a "runtime check"
5919
/// to find a suitable target subobject.
5920
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5921
0
                              LValue &Ptr) {
5922
  // We can't do anything with a non-symbolic pointer value.
5923
0
  SubobjectDesignator &D = Ptr.Designator;
5924
0
  if (D.Invalid)
5925
0
    return false;
5926
5927
  // C++ [expr.dynamic.cast]p6:
5928
  //   If v is a null pointer value, the result is a null pointer value.
5929
0
  if (Ptr.isNullPointer() && !E->isGLValue())
5930
0
    return true;
5931
5932
  // For all the other cases, we need the pointer to point to an object within
5933
  // its lifetime / period of construction / destruction, and we need to know
5934
  // its dynamic type.
5935
0
  std::optional<DynamicType> DynType =
5936
0
      ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5937
0
  if (!DynType)
5938
0
    return false;
5939
5940
  // C++ [expr.dynamic.cast]p7:
5941
  //   If T is "pointer to cv void", then the result is a pointer to the most
5942
  //   derived object
5943
0
  if (E->getType()->isVoidPointerType())
5944
0
    return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5945
5946
0
  const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5947
0
  assert(C && "dynamic_cast target is not void pointer nor class");
5948
0
  CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5949
5950
0
  auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5951
    // C++ [expr.dynamic.cast]p9:
5952
0
    if (!E->isGLValue()) {
5953
      //   The value of a failed cast to pointer type is the null pointer value
5954
      //   of the required result type.
5955
0
      Ptr.setNull(Info.Ctx, E->getType());
5956
0
      return true;
5957
0
    }
5958
5959
    //   A failed cast to reference type throws [...] std::bad_cast.
5960
0
    unsigned DiagKind;
5961
0
    if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5962
0
                   DynType->Type->isDerivedFrom(C)))
5963
0
      DiagKind = 0;
5964
0
    else if (!Paths || Paths->begin() == Paths->end())
5965
0
      DiagKind = 1;
5966
0
    else if (Paths->isAmbiguous(CQT))
5967
0
      DiagKind = 2;
5968
0
    else {
5969
0
      assert(Paths->front().Access != AS_public && "why did the cast fail?");
5970
0
      DiagKind = 3;
5971
0
    }
5972
0
    Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5973
0
        << DiagKind << Ptr.Designator.getType(Info.Ctx)
5974
0
        << Info.Ctx.getRecordType(DynType->Type)
5975
0
        << E->getType().getUnqualifiedType();
5976
0
    return false;
5977
0
  };
5978
5979
  // Runtime check, phase 1:
5980
  //   Walk from the base subobject towards the derived object looking for the
5981
  //   target type.
5982
0
  for (int PathLength = Ptr.Designator.Entries.size();
5983
0
       PathLength >= (int)DynType->PathLength; --PathLength) {
5984
0
    const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5985
0
    if (declaresSameEntity(Class, C))
5986
0
      return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5987
    // We can only walk across public inheritance edges.
5988
0
    if (PathLength > (int)DynType->PathLength &&
5989
0
        !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5990
0
                           Class))
5991
0
      return RuntimeCheckFailed(nullptr);
5992
0
  }
5993
5994
  // Runtime check, phase 2:
5995
  //   Search the dynamic type for an unambiguous public base of type C.
5996
0
  CXXBasePaths Paths(/*FindAmbiguities=*/true,
5997
0
                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
5998
0
  if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5999
0
      Paths.front().Access == AS_public) {
6000
    // Downcast to the dynamic type...
6001
0
    if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6002
0
      return false;
6003
    // ... then upcast to the chosen base class subobject.
6004
0
    for (CXXBasePathElement &Elem : Paths.front())
6005
0
      if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6006
0
        return false;
6007
0
    return true;
6008
0
  }
6009
6010
  // Otherwise, the runtime check fails.
6011
0
  return RuntimeCheckFailed(&Paths);
6012
0
}
6013
6014
namespace {
6015
struct StartLifetimeOfUnionMemberHandler {
6016
  EvalInfo &Info;
6017
  const Expr *LHSExpr;
6018
  const FieldDecl *Field;
6019
  bool DuringInit;
6020
  bool Failed = false;
6021
  static const AccessKinds AccessKind = AK_Assign;
6022
6023
  typedef bool result_type;
6024
0
  bool failed() { return Failed; }
6025
0
  bool found(APValue &Subobj, QualType SubobjType) {
6026
    // We are supposed to perform no initialization but begin the lifetime of
6027
    // the object. We interpret that as meaning to do what default
6028
    // initialization of the object would do if all constructors involved were
6029
    // trivial:
6030
    //  * All base, non-variant member, and array element subobjects' lifetimes
6031
    //    begin
6032
    //  * No variant members' lifetimes begin
6033
    //  * All scalar subobjects whose lifetimes begin have indeterminate values
6034
0
    assert(SubobjType->isUnionType());
6035
0
    if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6036
      // This union member is already active. If it's also in-lifetime, there's
6037
      // nothing to do.
6038
0
      if (Subobj.getUnionValue().hasValue())
6039
0
        return true;
6040
0
    } else if (DuringInit) {
6041
      // We're currently in the process of initializing a different union
6042
      // member.  If we carried on, that initialization would attempt to
6043
      // store to an inactive union member, resulting in undefined behavior.
6044
0
      Info.FFDiag(LHSExpr,
6045
0
                  diag::note_constexpr_union_member_change_during_init);
6046
0
      return false;
6047
0
    }
6048
0
    APValue Result;
6049
0
    Failed = !handleDefaultInitValue(Field->getType(), Result);
6050
0
    Subobj.setUnion(Field, Result);
6051
0
    return true;
6052
0
  }
6053
0
  bool found(APSInt &Value, QualType SubobjType) {
6054
0
    llvm_unreachable("wrong value kind for union object");
6055
0
  }
6056
0
  bool found(APFloat &Value, QualType SubobjType) {
6057
0
    llvm_unreachable("wrong value kind for union object");
6058
0
  }
6059
};
6060
} // end anonymous namespace
6061
6062
const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6063
6064
/// Handle a builtin simple-assignment or a call to a trivial assignment
6065
/// operator whose left-hand side might involve a union member access. If it
6066
/// does, implicitly start the lifetime of any accessed union elements per
6067
/// C++20 [class.union]5.
6068
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6069
                                               const Expr *LHSExpr,
6070
0
                                               const LValue &LHS) {
6071
0
  if (LHS.InvalidBase || LHS.Designator.Invalid)
6072
0
    return false;
6073
6074
0
  llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
6075
  // C++ [class.union]p5:
6076
  //   define the set S(E) of subexpressions of E as follows:
6077
0
  unsigned PathLength = LHS.Designator.Entries.size();
6078
0
  for (const Expr *E = LHSExpr; E != nullptr;) {
6079
    //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
6080
0
    if (auto *ME = dyn_cast<MemberExpr>(E)) {
6081
0
      auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6082
      // Note that we can't implicitly start the lifetime of a reference,
6083
      // so we don't need to proceed any further if we reach one.
6084
0
      if (!FD || FD->getType()->isReferenceType())
6085
0
        break;
6086
6087
      //    ... and also contains A.B if B names a union member ...
6088
0
      if (FD->getParent()->isUnion()) {
6089
        //    ... of a non-class, non-array type, or of a class type with a
6090
        //    trivial default constructor that is not deleted, or an array of
6091
        //    such types.
6092
0
        auto *RD =
6093
0
            FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6094
0
        if (!RD || RD->hasTrivialDefaultConstructor())
6095
0
          UnionPathLengths.push_back({PathLength - 1, FD});
6096
0
      }
6097
6098
0
      E = ME->getBase();
6099
0
      --PathLength;
6100
0
      assert(declaresSameEntity(FD,
6101
0
                                LHS.Designator.Entries[PathLength]
6102
0
                                    .getAsBaseOrMember().getPointer()));
6103
6104
      //   -- If E is of the form A[B] and is interpreted as a built-in array
6105
      //      subscripting operator, S(E) is [S(the array operand, if any)].
6106
0
    } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6107
      // Step over an ArrayToPointerDecay implicit cast.
6108
0
      auto *Base = ASE->getBase()->IgnoreImplicit();
6109
0
      if (!Base->getType()->isArrayType())
6110
0
        break;
6111
6112
0
      E = Base;
6113
0
      --PathLength;
6114
6115
0
    } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6116
      // Step over a derived-to-base conversion.
6117
0
      E = ICE->getSubExpr();
6118
0
      if (ICE->getCastKind() == CK_NoOp)
6119
0
        continue;
6120
0
      if (ICE->getCastKind() != CK_DerivedToBase &&
6121
0
          ICE->getCastKind() != CK_UncheckedDerivedToBase)
6122
0
        break;
6123
      // Walk path backwards as we walk up from the base to the derived class.
6124
0
      for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6125
0
        if (Elt->isVirtual()) {
6126
          // A class with virtual base classes never has a trivial default
6127
          // constructor, so S(E) is empty in this case.
6128
0
          E = nullptr;
6129
0
          break;
6130
0
        }
6131
6132
0
        --PathLength;
6133
0
        assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6134
0
                                  LHS.Designator.Entries[PathLength]
6135
0
                                      .getAsBaseOrMember().getPointer()));
6136
0
      }
6137
6138
    //   -- Otherwise, S(E) is empty.
6139
0
    } else {
6140
0
      break;
6141
0
    }
6142
0
  }
6143
6144
  // Common case: no unions' lifetimes are started.
6145
0
  if (UnionPathLengths.empty())
6146
0
    return true;
6147
6148
  //   if modification of X [would access an inactive union member], an object
6149
  //   of the type of X is implicitly created
6150
0
  CompleteObject Obj =
6151
0
      findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6152
0
  if (!Obj)
6153
0
    return false;
6154
0
  for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6155
0
           llvm::reverse(UnionPathLengths)) {
6156
    // Form a designator for the union object.
6157
0
    SubobjectDesignator D = LHS.Designator;
6158
0
    D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6159
6160
0
    bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6161
0
                      ConstructionPhase::AfterBases;
6162
0
    StartLifetimeOfUnionMemberHandler StartLifetime{
6163
0
        Info, LHSExpr, LengthAndField.second, DuringInit};
6164
0
    if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6165
0
      return false;
6166
0
  }
6167
6168
0
  return true;
6169
0
}
6170
6171
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6172
                            CallRef Call, EvalInfo &Info,
6173
0
                            bool NonNull = false) {
6174
0
  LValue LV;
6175
  // Create the parameter slot and register its destruction. For a vararg
6176
  // argument, create a temporary.
6177
  // FIXME: For calling conventions that destroy parameters in the callee,
6178
  // should we consider performing destruction when the function returns
6179
  // instead?
6180
0
  APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6181
0
                   : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6182
0
                                                       ScopeKind::Call, LV);
6183
0
  if (!EvaluateInPlace(V, Info, LV, Arg))
6184
0
    return false;
6185
6186
  // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6187
  // undefined behavior, so is non-constant.
6188
0
  if (NonNull && V.isLValue() && V.isNullPointer()) {
6189
0
    Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6190
0
    return false;
6191
0
  }
6192
6193
0
  return true;
6194
0
}
6195
6196
/// Evaluate the arguments to a function call.
6197
static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6198
                         EvalInfo &Info, const FunctionDecl *Callee,
6199
0
                         bool RightToLeft = false) {
6200
0
  bool Success = true;
6201
0
  llvm::SmallBitVector ForbiddenNullArgs;
6202
0
  if (Callee->hasAttr<NonNullAttr>()) {
6203
0
    ForbiddenNullArgs.resize(Args.size());
6204
0
    for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6205
0
      if (!Attr->args_size()) {
6206
0
        ForbiddenNullArgs.set();
6207
0
        break;
6208
0
      } else
6209
0
        for (auto Idx : Attr->args()) {
6210
0
          unsigned ASTIdx = Idx.getASTIndex();
6211
0
          if (ASTIdx >= Args.size())
6212
0
            continue;
6213
0
          ForbiddenNullArgs[ASTIdx] = true;
6214
0
        }
6215
0
    }
6216
0
  }
6217
0
  for (unsigned I = 0; I < Args.size(); I++) {
6218
0
    unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6219
0
    const ParmVarDecl *PVD =
6220
0
        Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6221
0
    bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6222
0
    if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6223
      // If we're checking for a potential constant expression, evaluate all
6224
      // initializers even if some of them fail.
6225
0
      if (!Info.noteFailure())
6226
0
        return false;
6227
0
      Success = false;
6228
0
    }
6229
0
  }
6230
0
  return Success;
6231
0
}
6232
6233
/// Perform a trivial copy from Param, which is the parameter of a copy or move
6234
/// constructor or assignment operator.
6235
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6236
                              const Expr *E, APValue &Result,
6237
0
                              bool CopyObjectRepresentation) {
6238
  // Find the reference argument.
6239
0
  CallStackFrame *Frame = Info.CurrentCall;
6240
0
  APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6241
0
  if (!RefValue) {
6242
0
    Info.FFDiag(E);
6243
0
    return false;
6244
0
  }
6245
6246
  // Copy out the contents of the RHS object.
6247
0
  LValue RefLValue;
6248
0
  RefLValue.setFrom(Info.Ctx, *RefValue);
6249
0
  return handleLValueToRValueConversion(
6250
0
      Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6251
0
      CopyObjectRepresentation);
6252
0
}
6253
6254
/// Evaluate a function call.
6255
static bool HandleFunctionCall(SourceLocation CallLoc,
6256
                               const FunctionDecl *Callee, const LValue *This,
6257
                               const Expr *E, ArrayRef<const Expr *> Args,
6258
                               CallRef Call, const Stmt *Body, EvalInfo &Info,
6259
0
                               APValue &Result, const LValue *ResultSlot) {
6260
0
  if (!Info.CheckCallLimit(CallLoc))
6261
0
    return false;
6262
6263
0
  CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6264
6265
  // For a trivial copy or move assignment, perform an APValue copy. This is
6266
  // essential for unions, where the operations performed by the assignment
6267
  // operator cannot be represented as statements.
6268
  //
6269
  // Skip this for non-union classes with no fields; in that case, the defaulted
6270
  // copy/move does not actually read the object.
6271
0
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6272
0
  if (MD && MD->isDefaulted() &&
6273
0
      (MD->getParent()->isUnion() ||
6274
0
       (MD->isTrivial() &&
6275
0
        isReadByLvalueToRvalueConversion(MD->getParent())))) {
6276
0
    assert(This &&
6277
0
           (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6278
0
    APValue RHSValue;
6279
0
    if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6280
0
                           MD->getParent()->isUnion()))
6281
0
      return false;
6282
0
    if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6283
0
                          RHSValue))
6284
0
      return false;
6285
0
    This->moveInto(Result);
6286
0
    return true;
6287
0
  } else if (MD && isLambdaCallOperator(MD)) {
6288
    // We're in a lambda; determine the lambda capture field maps unless we're
6289
    // just constexpr checking a lambda's call operator. constexpr checking is
6290
    // done before the captures have been added to the closure object (unless
6291
    // we're inferring constexpr-ness), so we don't have access to them in this
6292
    // case. But since we don't need the captures to constexpr check, we can
6293
    // just ignore them.
6294
0
    if (!Info.checkingPotentialConstantExpression())
6295
0
      MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6296
0
                                        Frame.LambdaThisCaptureField);
6297
0
  }
6298
6299
0
  StmtResult Ret = {Result, ResultSlot};
6300
0
  EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6301
0
  if (ESR == ESR_Succeeded) {
6302
0
    if (Callee->getReturnType()->isVoidType())
6303
0
      return true;
6304
0
    Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6305
0
  }
6306
0
  return ESR == ESR_Returned;
6307
0
}
6308
6309
/// Evaluate a constructor call.
6310
static bool HandleConstructorCall(const Expr *E, const LValue &This,
6311
                                  CallRef Call,
6312
                                  const CXXConstructorDecl *Definition,
6313
0
                                  EvalInfo &Info, APValue &Result) {
6314
0
  SourceLocation CallLoc = E->getExprLoc();
6315
0
  if (!Info.CheckCallLimit(CallLoc))
6316
0
    return false;
6317
6318
0
  const CXXRecordDecl *RD = Definition->getParent();
6319
0
  if (RD->getNumVBases()) {
6320
0
    Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6321
0
    return false;
6322
0
  }
6323
6324
0
  EvalInfo::EvaluatingConstructorRAII EvalObj(
6325
0
      Info,
6326
0
      ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6327
0
      RD->getNumBases());
6328
0
  CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6329
6330
  // FIXME: Creating an APValue just to hold a nonexistent return value is
6331
  // wasteful.
6332
0
  APValue RetVal;
6333
0
  StmtResult Ret = {RetVal, nullptr};
6334
6335
  // If it's a delegating constructor, delegate.
6336
0
  if (Definition->isDelegatingConstructor()) {
6337
0
    CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6338
0
    if ((*I)->getInit()->isValueDependent()) {
6339
0
      if (!EvaluateDependentExpr((*I)->getInit(), Info))
6340
0
        return false;
6341
0
    } else {
6342
0
      FullExpressionRAII InitScope(Info);
6343
0
      if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6344
0
          !InitScope.destroy())
6345
0
        return false;
6346
0
    }
6347
0
    return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6348
0
  }
6349
6350
  // For a trivial copy or move constructor, perform an APValue copy. This is
6351
  // essential for unions (or classes with anonymous union members), where the
6352
  // operations performed by the constructor cannot be represented by
6353
  // ctor-initializers.
6354
  //
6355
  // Skip this for empty non-union classes; we should not perform an
6356
  // lvalue-to-rvalue conversion on them because their copy constructor does not
6357
  // actually read them.
6358
0
  if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6359
0
      (Definition->getParent()->isUnion() ||
6360
0
       (Definition->isTrivial() &&
6361
0
        isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6362
0
    return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6363
0
                             Definition->getParent()->isUnion());
6364
0
  }
6365
6366
  // Reserve space for the struct members.
6367
0
  if (!Result.hasValue()) {
6368
0
    if (!RD->isUnion())
6369
0
      Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6370
0
                       std::distance(RD->field_begin(), RD->field_end()));
6371
0
    else
6372
      // A union starts with no active member.
6373
0
      Result = APValue((const FieldDecl*)nullptr);
6374
0
  }
6375
6376
0
  if (RD->isInvalidDecl()) return false;
6377
0
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6378
6379
  // A scope for temporaries lifetime-extended by reference members.
6380
0
  BlockScopeRAII LifetimeExtendedScope(Info);
6381
6382
0
  bool Success = true;
6383
0
  unsigned BasesSeen = 0;
6384
0
#ifndef NDEBUG
6385
0
  CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6386
0
#endif
6387
0
  CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6388
0
  auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6389
    // We might be initializing the same field again if this is an indirect
6390
    // field initialization.
6391
0
    if (FieldIt == RD->field_end() ||
6392
0
        FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6393
0
      assert(Indirect && "fields out of order?");
6394
0
      return;
6395
0
    }
6396
6397
    // Default-initialize any fields with no explicit initializer.
6398
0
    for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6399
0
      assert(FieldIt != RD->field_end() && "missing field?");
6400
0
      if (!FieldIt->isUnnamedBitfield())
6401
0
        Success &= handleDefaultInitValue(
6402
0
            FieldIt->getType(),
6403
0
            Result.getStructField(FieldIt->getFieldIndex()));
6404
0
    }
6405
0
    ++FieldIt;
6406
0
  };
6407
0
  for (const auto *I : Definition->inits()) {
6408
0
    LValue Subobject = This;
6409
0
    LValue SubobjectParent = This;
6410
0
    APValue *Value = &Result;
6411
6412
    // Determine the subobject to initialize.
6413
0
    FieldDecl *FD = nullptr;
6414
0
    if (I->isBaseInitializer()) {
6415
0
      QualType BaseType(I->getBaseClass(), 0);
6416
0
#ifndef NDEBUG
6417
      // Non-virtual base classes are initialized in the order in the class
6418
      // definition. We have already checked for virtual base classes.
6419
0
      assert(!BaseIt->isVirtual() && "virtual base for literal type");
6420
0
      assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6421
0
             "base class initializers not in expected order");
6422
0
      ++BaseIt;
6423
0
#endif
6424
0
      if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6425
0
                                  BaseType->getAsCXXRecordDecl(), &Layout))
6426
0
        return false;
6427
0
      Value = &Result.getStructBase(BasesSeen++);
6428
0
    } else if ((FD = I->getMember())) {
6429
0
      if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6430
0
        return false;
6431
0
      if (RD->isUnion()) {
6432
0
        Result = APValue(FD);
6433
0
        Value = &Result.getUnionValue();
6434
0
      } else {
6435
0
        SkipToField(FD, false);
6436
0
        Value = &Result.getStructField(FD->getFieldIndex());
6437
0
      }
6438
0
    } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6439
      // Walk the indirect field decl's chain to find the object to initialize,
6440
      // and make sure we've initialized every step along it.
6441
0
      auto IndirectFieldChain = IFD->chain();
6442
0
      for (auto *C : IndirectFieldChain) {
6443
0
        FD = cast<FieldDecl>(C);
6444
0
        CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6445
        // Switch the union field if it differs. This happens if we had
6446
        // preceding zero-initialization, and we're now initializing a union
6447
        // subobject other than the first.
6448
        // FIXME: In this case, the values of the other subobjects are
6449
        // specified, since zero-initialization sets all padding bits to zero.
6450
0
        if (!Value->hasValue() ||
6451
0
            (Value->isUnion() && Value->getUnionField() != FD)) {
6452
0
          if (CD->isUnion())
6453
0
            *Value = APValue(FD);
6454
0
          else
6455
            // FIXME: This immediately starts the lifetime of all members of
6456
            // an anonymous struct. It would be preferable to strictly start
6457
            // member lifetime in initialization order.
6458
0
            Success &=
6459
0
                handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6460
0
        }
6461
        // Store Subobject as its parent before updating it for the last element
6462
        // in the chain.
6463
0
        if (C == IndirectFieldChain.back())
6464
0
          SubobjectParent = Subobject;
6465
0
        if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6466
0
          return false;
6467
0
        if (CD->isUnion())
6468
0
          Value = &Value->getUnionValue();
6469
0
        else {
6470
0
          if (C == IndirectFieldChain.front() && !RD->isUnion())
6471
0
            SkipToField(FD, true);
6472
0
          Value = &Value->getStructField(FD->getFieldIndex());
6473
0
        }
6474
0
      }
6475
0
    } else {
6476
0
      llvm_unreachable("unknown base initializer kind");
6477
0
    }
6478
6479
    // Need to override This for implicit field initializers as in this case
6480
    // This refers to innermost anonymous struct/union containing initializer,
6481
    // not to currently constructed class.
6482
0
    const Expr *Init = I->getInit();
6483
0
    if (Init->isValueDependent()) {
6484
0
      if (!EvaluateDependentExpr(Init, Info))
6485
0
        return false;
6486
0
    } else {
6487
0
      ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6488
0
                                    isa<CXXDefaultInitExpr>(Init));
6489
0
      FullExpressionRAII InitScope(Info);
6490
0
      if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6491
0
          (FD && FD->isBitField() &&
6492
0
           !truncateBitfieldValue(Info, Init, *Value, FD))) {
6493
        // If we're checking for a potential constant expression, evaluate all
6494
        // initializers even if some of them fail.
6495
0
        if (!Info.noteFailure())
6496
0
          return false;
6497
0
        Success = false;
6498
0
      }
6499
0
    }
6500
6501
    // This is the point at which the dynamic type of the object becomes this
6502
    // class type.
6503
0
    if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6504
0
      EvalObj.finishedConstructingBases();
6505
0
  }
6506
6507
  // Default-initialize any remaining fields.
6508
0
  if (!RD->isUnion()) {
6509
0
    for (; FieldIt != RD->field_end(); ++FieldIt) {
6510
0
      if (!FieldIt->isUnnamedBitfield())
6511
0
        Success &= handleDefaultInitValue(
6512
0
            FieldIt->getType(),
6513
0
            Result.getStructField(FieldIt->getFieldIndex()));
6514
0
    }
6515
0
  }
6516
6517
0
  EvalObj.finishedConstructingFields();
6518
6519
0
  return Success &&
6520
0
         EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6521
0
         LifetimeExtendedScope.destroy();
6522
0
}
6523
6524
static bool HandleConstructorCall(const Expr *E, const LValue &This,
6525
                                  ArrayRef<const Expr*> Args,
6526
                                  const CXXConstructorDecl *Definition,
6527
0
                                  EvalInfo &Info, APValue &Result) {
6528
0
  CallScopeRAII CallScope(Info);
6529
0
  CallRef Call = Info.CurrentCall->createCall(Definition);
6530
0
  if (!EvaluateArgs(Args, Call, Info, Definition))
6531
0
    return false;
6532
6533
0
  return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6534
0
         CallScope.destroy();
6535
0
}
6536
6537
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6538
                                  const LValue &This, APValue &Value,
6539
0
                                  QualType T) {
6540
  // Objects can only be destroyed while they're within their lifetimes.
6541
  // FIXME: We have no representation for whether an object of type nullptr_t
6542
  // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6543
  // as indeterminate instead?
6544
0
  if (Value.isAbsent() && !T->isNullPtrType()) {
6545
0
    APValue Printable;
6546
0
    This.moveInto(Printable);
6547
0
    Info.FFDiag(CallRange.getBegin(),
6548
0
                diag::note_constexpr_destroy_out_of_lifetime)
6549
0
        << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6550
0
    return false;
6551
0
  }
6552
6553
  // Invent an expression for location purposes.
6554
  // FIXME: We shouldn't need to do this.
6555
0
  OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6556
6557
  // For arrays, destroy elements right-to-left.
6558
0
  if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6559
0
    uint64_t Size = CAT->getSize().getZExtValue();
6560
0
    QualType ElemT = CAT->getElementType();
6561
6562
0
    if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6563
0
      return false;
6564
6565
0
    LValue ElemLV = This;
6566
0
    ElemLV.addArray(Info, &LocE, CAT);
6567
0
    if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6568
0
      return false;
6569
6570
    // Ensure that we have actual array elements available to destroy; the
6571
    // destructors might mutate the value, so we can't run them on the array
6572
    // filler.
6573
0
    if (Size && Size > Value.getArrayInitializedElts())
6574
0
      expandArray(Value, Value.getArraySize() - 1);
6575
6576
0
    for (; Size != 0; --Size) {
6577
0
      APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6578
0
      if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6579
0
          !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6580
0
        return false;
6581
0
    }
6582
6583
    // End the lifetime of this array now.
6584
0
    Value = APValue();
6585
0
    return true;
6586
0
  }
6587
6588
0
  const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6589
0
  if (!RD) {
6590
0
    if (T.isDestructedType()) {
6591
0
      Info.FFDiag(CallRange.getBegin(),
6592
0
                  diag::note_constexpr_unsupported_destruction)
6593
0
          << T;
6594
0
      return false;
6595
0
    }
6596
6597
0
    Value = APValue();
6598
0
    return true;
6599
0
  }
6600
6601
0
  if (RD->getNumVBases()) {
6602
0
    Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6603
0
    return false;
6604
0
  }
6605
6606
0
  const CXXDestructorDecl *DD = RD->getDestructor();
6607
0
  if (!DD && !RD->hasTrivialDestructor()) {
6608
0
    Info.FFDiag(CallRange.getBegin());
6609
0
    return false;
6610
0
  }
6611
6612
0
  if (!DD || DD->isTrivial() ||
6613
0
      (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6614
    // A trivial destructor just ends the lifetime of the object. Check for
6615
    // this case before checking for a body, because we might not bother
6616
    // building a body for a trivial destructor. Note that it doesn't matter
6617
    // whether the destructor is constexpr in this case; all trivial
6618
    // destructors are constexpr.
6619
    //
6620
    // If an anonymous union would be destroyed, some enclosing destructor must
6621
    // have been explicitly defined, and the anonymous union destruction should
6622
    // have no effect.
6623
0
    Value = APValue();
6624
0
    return true;
6625
0
  }
6626
6627
0
  if (!Info.CheckCallLimit(CallRange.getBegin()))
6628
0
    return false;
6629
6630
0
  const FunctionDecl *Definition = nullptr;
6631
0
  const Stmt *Body = DD->getBody(Definition);
6632
6633
0
  if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6634
0
    return false;
6635
6636
0
  CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6637
0
                       CallRef());
6638
6639
  // We're now in the period of destruction of this object.
6640
0
  unsigned BasesLeft = RD->getNumBases();
6641
0
  EvalInfo::EvaluatingDestructorRAII EvalObj(
6642
0
      Info,
6643
0
      ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6644
0
  if (!EvalObj.DidInsert) {
6645
    // C++2a [class.dtor]p19:
6646
    //   the behavior is undefined if the destructor is invoked for an object
6647
    //   whose lifetime has ended
6648
    // (Note that formally the lifetime ends when the period of destruction
6649
    // begins, even though certain uses of the object remain valid until the
6650
    // period of destruction ends.)
6651
0
    Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6652
0
    return false;
6653
0
  }
6654
6655
  // FIXME: Creating an APValue just to hold a nonexistent return value is
6656
  // wasteful.
6657
0
  APValue RetVal;
6658
0
  StmtResult Ret = {RetVal, nullptr};
6659
0
  if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6660
0
    return false;
6661
6662
  // A union destructor does not implicitly destroy its members.
6663
0
  if (RD->isUnion())
6664
0
    return true;
6665
6666
0
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6667
6668
  // We don't have a good way to iterate fields in reverse, so collect all the
6669
  // fields first and then walk them backwards.
6670
0
  SmallVector<FieldDecl*, 16> Fields(RD->fields());
6671
0
  for (const FieldDecl *FD : llvm::reverse(Fields)) {
6672
0
    if (FD->isUnnamedBitfield())
6673
0
      continue;
6674
6675
0
    LValue Subobject = This;
6676
0
    if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6677
0
      return false;
6678
6679
0
    APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6680
0
    if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6681
0
                               FD->getType()))
6682
0
      return false;
6683
0
  }
6684
6685
0
  if (BasesLeft != 0)
6686
0
    EvalObj.startedDestroyingBases();
6687
6688
  // Destroy base classes in reverse order.
6689
0
  for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6690
0
    --BasesLeft;
6691
6692
0
    QualType BaseType = Base.getType();
6693
0
    LValue Subobject = This;
6694
0
    if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6695
0
                                BaseType->getAsCXXRecordDecl(), &Layout))
6696
0
      return false;
6697
6698
0
    APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6699
0
    if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6700
0
                               BaseType))
6701
0
      return false;
6702
0
  }
6703
0
  assert(BasesLeft == 0 && "NumBases was wrong?");
6704
6705
  // The period of destruction ends now. The object is gone.
6706
0
  Value = APValue();
6707
0
  return true;
6708
0
}
6709
6710
namespace {
6711
struct DestroyObjectHandler {
6712
  EvalInfo &Info;
6713
  const Expr *E;
6714
  const LValue &This;
6715
  const AccessKinds AccessKind;
6716
6717
  typedef bool result_type;
6718
0
  bool failed() { return false; }
6719
0
  bool found(APValue &Subobj, QualType SubobjType) {
6720
0
    return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6721
0
                                 SubobjType);
6722
0
  }
6723
0
  bool found(APSInt &Value, QualType SubobjType) {
6724
0
    Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6725
0
    return false;
6726
0
  }
6727
0
  bool found(APFloat &Value, QualType SubobjType) {
6728
0
    Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6729
0
    return false;
6730
0
  }
6731
};
6732
}
6733
6734
/// Perform a destructor or pseudo-destructor call on the given object, which
6735
/// might in general not be a complete object.
6736
static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6737
0
                              const LValue &This, QualType ThisType) {
6738
0
  CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6739
0
  DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6740
0
  return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6741
0
}
6742
6743
/// Destroy and end the lifetime of the given complete object.
6744
static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6745
                              APValue::LValueBase LVBase, APValue &Value,
6746
0
                              QualType T) {
6747
  // If we've had an unmodeled side-effect, we can't rely on mutable state
6748
  // (such as the object we're about to destroy) being correct.
6749
0
  if (Info.EvalStatus.HasSideEffects)
6750
0
    return false;
6751
6752
0
  LValue LV;
6753
0
  LV.set({LVBase});
6754
0
  return HandleDestructionImpl(Info, Loc, LV, Value, T);
6755
0
}
6756
6757
/// Perform a call to 'operator new' or to `__builtin_operator_new'.
6758
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6759
0
                                  LValue &Result) {
6760
0
  if (Info.checkingPotentialConstantExpression() ||
6761
0
      Info.SpeculativeEvaluationDepth)
6762
0
    return false;
6763
6764
  // This is permitted only within a call to std::allocator<T>::allocate.
6765
0
  auto Caller = Info.getStdAllocatorCaller("allocate");
6766
0
  if (!Caller) {
6767
0
    Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6768
0
                                     ? diag::note_constexpr_new_untyped
6769
0
                                     : diag::note_constexpr_new);
6770
0
    return false;
6771
0
  }
6772
6773
0
  QualType ElemType = Caller.ElemType;
6774
0
  if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6775
0
    Info.FFDiag(E->getExprLoc(),
6776
0
                diag::note_constexpr_new_not_complete_object_type)
6777
0
        << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6778
0
    return false;
6779
0
  }
6780
6781
0
  APSInt ByteSize;
6782
0
  if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6783
0
    return false;
6784
0
  bool IsNothrow = false;
6785
0
  for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6786
0
    EvaluateIgnoredValue(Info, E->getArg(I));
6787
0
    IsNothrow |= E->getType()->isNothrowT();
6788
0
  }
6789
6790
0
  CharUnits ElemSize;
6791
0
  if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6792
0
    return false;
6793
0
  APInt Size, Remainder;
6794
0
  APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6795
0
  APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6796
0
  if (Remainder != 0) {
6797
    // This likely indicates a bug in the implementation of 'std::allocator'.
6798
0
    Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6799
0
        << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6800
0
    return false;
6801
0
  }
6802
6803
0
  if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6804
0
                           Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
6805
0
    if (IsNothrow) {
6806
0
      Result.setNull(Info.Ctx, E->getType());
6807
0
      return true;
6808
0
    }
6809
0
    return false;
6810
0
  }
6811
6812
0
  QualType AllocType = Info.Ctx.getConstantArrayType(
6813
0
      ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
6814
0
  APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6815
0
  *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6816
0
  Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6817
0
  return true;
6818
0
}
6819
6820
0
static bool hasVirtualDestructor(QualType T) {
6821
0
  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6822
0
    if (CXXDestructorDecl *DD = RD->getDestructor())
6823
0
      return DD->isVirtual();
6824
0
  return false;
6825
0
}
6826
6827
0
static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6828
0
  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6829
0
    if (CXXDestructorDecl *DD = RD->getDestructor())
6830
0
      return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6831
0
  return nullptr;
6832
0
}
6833
6834
/// Check that the given object is a suitable pointer to a heap allocation that
6835
/// still exists and is of the right kind for the purpose of a deletion.
6836
///
6837
/// On success, returns the heap allocation to deallocate. On failure, produces
6838
/// a diagnostic and returns std::nullopt.
6839
static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6840
                                                 const LValue &Pointer,
6841
0
                                                 DynAlloc::Kind DeallocKind) {
6842
0
  auto PointerAsString = [&] {
6843
0
    return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6844
0
  };
6845
6846
0
  DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6847
0
  if (!DA) {
6848
0
    Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6849
0
        << PointerAsString();
6850
0
    if (Pointer.Base)
6851
0
      NoteLValueLocation(Info, Pointer.Base);
6852
0
    return std::nullopt;
6853
0
  }
6854
6855
0
  std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6856
0
  if (!Alloc) {
6857
0
    Info.FFDiag(E, diag::note_constexpr_double_delete);
6858
0
    return std::nullopt;
6859
0
  }
6860
6861
0
  if (DeallocKind != (*Alloc)->getKind()) {
6862
0
    QualType AllocType = Pointer.Base.getDynamicAllocType();
6863
0
    Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6864
0
        << DeallocKind << (*Alloc)->getKind() << AllocType;
6865
0
    NoteLValueLocation(Info, Pointer.Base);
6866
0
    return std::nullopt;
6867
0
  }
6868
6869
0
  bool Subobject = false;
6870
0
  if (DeallocKind == DynAlloc::New) {
6871
0
    Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6872
0
                Pointer.Designator.isOnePastTheEnd();
6873
0
  } else {
6874
0
    Subobject = Pointer.Designator.Entries.size() != 1 ||
6875
0
                Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6876
0
  }
6877
0
  if (Subobject) {
6878
0
    Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6879
0
        << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6880
0
    return std::nullopt;
6881
0
  }
6882
6883
0
  return Alloc;
6884
0
}
6885
6886
// Perform a call to 'operator delete' or '__builtin_operator_delete'.
6887
0
bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6888
0
  if (Info.checkingPotentialConstantExpression() ||
6889
0
      Info.SpeculativeEvaluationDepth)
6890
0
    return false;
6891
6892
  // This is permitted only within a call to std::allocator<T>::deallocate.
6893
0
  if (!Info.getStdAllocatorCaller("deallocate")) {
6894
0
    Info.FFDiag(E->getExprLoc());
6895
0
    return true;
6896
0
  }
6897
6898
0
  LValue Pointer;
6899
0
  if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6900
0
    return false;
6901
0
  for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6902
0
    EvaluateIgnoredValue(Info, E->getArg(I));
6903
6904
0
  if (Pointer.Designator.Invalid)
6905
0
    return false;
6906
6907
  // Deleting a null pointer would have no effect, but it's not permitted by
6908
  // std::allocator<T>::deallocate's contract.
6909
0
  if (Pointer.isNullPointer()) {
6910
0
    Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6911
0
    return true;
6912
0
  }
6913
6914
0
  if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6915
0
    return false;
6916
6917
0
  Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6918
0
  return true;
6919
0
}
6920
6921
//===----------------------------------------------------------------------===//
6922
// Generic Evaluation
6923
//===----------------------------------------------------------------------===//
6924
namespace {
6925
6926
class BitCastBuffer {
6927
  // FIXME: We're going to need bit-level granularity when we support
6928
  // bit-fields.
6929
  // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6930
  // we don't support a host or target where that is the case. Still, we should
6931
  // use a more generic type in case we ever do.
6932
  SmallVector<std::optional<unsigned char>, 32> Bytes;
6933
6934
  static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6935
                "Need at least 8 bit unsigned char");
6936
6937
  bool TargetIsLittleEndian;
6938
6939
public:
6940
  BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6941
      : Bytes(Width.getQuantity()),
6942
0
        TargetIsLittleEndian(TargetIsLittleEndian) {}
6943
6944
  [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6945
0
                                SmallVectorImpl<unsigned char> &Output) const {
6946
0
    for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6947
      // If a byte of an integer is uninitialized, then the whole integer is
6948
      // uninitialized.
6949
0
      if (!Bytes[I.getQuantity()])
6950
0
        return false;
6951
0
      Output.push_back(*Bytes[I.getQuantity()]);
6952
0
    }
6953
0
    if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6954
0
      std::reverse(Output.begin(), Output.end());
6955
0
    return true;
6956
0
  }
6957
6958
0
  void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6959
0
    if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6960
0
      std::reverse(Input.begin(), Input.end());
6961
6962
0
    size_t Index = 0;
6963
0
    for (unsigned char Byte : Input) {
6964
0
      assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6965
0
      Bytes[Offset.getQuantity() + Index] = Byte;
6966
0
      ++Index;
6967
0
    }
6968
0
  }
6969
6970
0
  size_t size() { return Bytes.size(); }
6971
};
6972
6973
/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6974
/// target would represent the value at runtime.
6975
class APValueToBufferConverter {
6976
  EvalInfo &Info;
6977
  BitCastBuffer Buffer;
6978
  const CastExpr *BCE;
6979
6980
  APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6981
                           const CastExpr *BCE)
6982
      : Info(Info),
6983
        Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6984
0
        BCE(BCE) {}
6985
6986
0
  bool visit(const APValue &Val, QualType Ty) {
6987
0
    return visit(Val, Ty, CharUnits::fromQuantity(0));
6988
0
  }
6989
6990
  // Write out Val with type Ty into Buffer starting at Offset.
6991
0
  bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6992
0
    assert((size_t)Offset.getQuantity() <= Buffer.size());
6993
6994
    // As a special case, nullptr_t has an indeterminate value.
6995
0
    if (Ty->isNullPtrType())
6996
0
      return true;
6997
6998
    // Dig through Src to find the byte at SrcOffset.
6999
0
    switch (Val.getKind()) {
7000
0
    case APValue::Indeterminate:
7001
0
    case APValue::None:
7002
0
      return true;
7003
7004
0
    case APValue::Int:
7005
0
      return visitInt(Val.getInt(), Ty, Offset);
7006
0
    case APValue::Float:
7007
0
      return visitFloat(Val.getFloat(), Ty, Offset);
7008
0
    case APValue::Array:
7009
0
      return visitArray(Val, Ty, Offset);
7010
0
    case APValue::Struct:
7011
0
      return visitRecord(Val, Ty, Offset);
7012
0
    case APValue::Vector:
7013
0
      return visitVector(Val, Ty, Offset);
7014
7015
0
    case APValue::ComplexInt:
7016
0
    case APValue::ComplexFloat:
7017
0
    case APValue::FixedPoint:
7018
      // FIXME: We should support these.
7019
7020
0
    case APValue::Union:
7021
0
    case APValue::MemberPointer:
7022
0
    case APValue::AddrLabelDiff: {
7023
0
      Info.FFDiag(BCE->getBeginLoc(),
7024
0
                  diag::note_constexpr_bit_cast_unsupported_type)
7025
0
          << Ty;
7026
0
      return false;
7027
0
    }
7028
7029
0
    case APValue::LValue:
7030
0
      llvm_unreachable("LValue subobject in bit_cast?");
7031
0
    }
7032
0
    llvm_unreachable("Unhandled APValue::ValueKind");
7033
0
  }
7034
7035
0
  bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7036
0
    const RecordDecl *RD = Ty->getAsRecordDecl();
7037
0
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7038
7039
    // Visit the base classes.
7040
0
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7041
0
      for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7042
0
        const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7043
0
        CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7044
7045
0
        if (!visitRecord(Val.getStructBase(I), BS.getType(),
7046
0
                         Layout.getBaseClassOffset(BaseDecl) + Offset))
7047
0
          return false;
7048
0
      }
7049
0
    }
7050
7051
    // Visit the fields.
7052
0
    unsigned FieldIdx = 0;
7053
0
    for (FieldDecl *FD : RD->fields()) {
7054
0
      if (FD->isBitField()) {
7055
0
        Info.FFDiag(BCE->getBeginLoc(),
7056
0
                    diag::note_constexpr_bit_cast_unsupported_bitfield);
7057
0
        return false;
7058
0
      }
7059
7060
0
      uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7061
7062
0
      assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7063
0
             "only bit-fields can have sub-char alignment");
7064
0
      CharUnits FieldOffset =
7065
0
          Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7066
0
      QualType FieldTy = FD->getType();
7067
0
      if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7068
0
        return false;
7069
0
      ++FieldIdx;
7070
0
    }
7071
7072
0
    return true;
7073
0
  }
7074
7075
0
  bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7076
0
    const auto *CAT =
7077
0
        dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7078
0
    if (!CAT)
7079
0
      return false;
7080
7081
0
    CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7082
0
    unsigned NumInitializedElts = Val.getArrayInitializedElts();
7083
0
    unsigned ArraySize = Val.getArraySize();
7084
    // First, initialize the initialized elements.
7085
0
    for (unsigned I = 0; I != NumInitializedElts; ++I) {
7086
0
      const APValue &SubObj = Val.getArrayInitializedElt(I);
7087
0
      if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7088
0
        return false;
7089
0
    }
7090
7091
    // Next, initialize the rest of the array using the filler.
7092
0
    if (Val.hasArrayFiller()) {
7093
0
      const APValue &Filler = Val.getArrayFiller();
7094
0
      for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7095
0
        if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7096
0
          return false;
7097
0
      }
7098
0
    }
7099
7100
0
    return true;
7101
0
  }
7102
7103
0
  bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7104
0
    const VectorType *VTy = Ty->castAs<VectorType>();
7105
0
    QualType EltTy = VTy->getElementType();
7106
0
    unsigned NElts = VTy->getNumElements();
7107
0
    unsigned EltSize =
7108
0
        VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7109
7110
0
    if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7111
      // The vector's size in bits is not a multiple of the target's byte size,
7112
      // so its layout is unspecified. For now, we'll simply treat these cases
7113
      // as unsupported (this should only be possible with OpenCL bool vectors
7114
      // whose element count isn't a multiple of the byte size).
7115
0
      Info.FFDiag(BCE->getBeginLoc(),
7116
0
                  diag::note_constexpr_bit_cast_invalid_vector)
7117
0
          << Ty.getCanonicalType() << EltSize << NElts
7118
0
          << Info.Ctx.getCharWidth();
7119
0
      return false;
7120
0
    }
7121
7122
0
    if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7123
0
                                           &APFloat::x87DoubleExtended()) {
7124
      // The layout for x86_fp80 vectors seems to be handled very inconsistently
7125
      // by both clang and LLVM, so for now we won't allow bit_casts involving
7126
      // it in a constexpr context.
7127
0
      Info.FFDiag(BCE->getBeginLoc(),
7128
0
                  diag::note_constexpr_bit_cast_unsupported_type)
7129
0
          << EltTy;
7130
0
      return false;
7131
0
    }
7132
7133
0
    if (VTy->isExtVectorBoolType()) {
7134
      // Special handling for OpenCL bool vectors:
7135
      // Since these vectors are stored as packed bits, but we can't write
7136
      // individual bits to the BitCastBuffer, we'll buffer all of the elements
7137
      // together into an appropriately sized APInt and write them all out at
7138
      // once. Because we don't accept vectors where NElts * EltSize isn't a
7139
      // multiple of the char size, there will be no padding space, so we don't
7140
      // have to worry about writing data which should have been left
7141
      // uninitialized.
7142
0
      bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7143
7144
0
      llvm::APInt Res = llvm::APInt::getZero(NElts);
7145
0
      for (unsigned I = 0; I < NElts; ++I) {
7146
0
        const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7147
0
        assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7148
0
               "bool vector element must be 1-bit unsigned integer!");
7149
7150
0
        Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7151
0
      }
7152
7153
0
      SmallVector<uint8_t, 8> Bytes(NElts / 8);
7154
0
      llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7155
0
      Buffer.writeObject(Offset, Bytes);
7156
0
    } else {
7157
      // Iterate over each of the elements and write them out to the buffer at
7158
      // the appropriate offset.
7159
0
      CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7160
0
      for (unsigned I = 0; I < NElts; ++I) {
7161
0
        if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7162
0
          return false;
7163
0
      }
7164
0
    }
7165
7166
0
    return true;
7167
0
  }
7168
7169
0
  bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7170
0
    APSInt AdjustedVal = Val;
7171
0
    unsigned Width = AdjustedVal.getBitWidth();
7172
0
    if (Ty->isBooleanType()) {
7173
0
      Width = Info.Ctx.getTypeSize(Ty);
7174
0
      AdjustedVal = AdjustedVal.extend(Width);
7175
0
    }
7176
7177
0
    SmallVector<uint8_t, 8> Bytes(Width / 8);
7178
0
    llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7179
0
    Buffer.writeObject(Offset, Bytes);
7180
0
    return true;
7181
0
  }
7182
7183
0
  bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7184
0
    APSInt AsInt(Val.bitcastToAPInt());
7185
0
    return visitInt(AsInt, Ty, Offset);
7186
0
  }
7187
7188
public:
7189
  static std::optional<BitCastBuffer>
7190
0
  convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7191
0
    CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7192
0
    APValueToBufferConverter Converter(Info, DstSize, BCE);
7193
0
    if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7194
0
      return std::nullopt;
7195
0
    return Converter.Buffer;
7196
0
  }
7197
};
7198
7199
/// Write an BitCastBuffer into an APValue.
7200
class BufferToAPValueConverter {
7201
  EvalInfo &Info;
7202
  const BitCastBuffer &Buffer;
7203
  const CastExpr *BCE;
7204
7205
  BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7206
                           const CastExpr *BCE)
7207
0
      : Info(Info), Buffer(Buffer), BCE(BCE) {}
7208
7209
  // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7210
  // with an invalid type, so anything left is a deficiency on our part (FIXME).
7211
  // Ideally this will be unreachable.
7212
0
  std::nullopt_t unsupportedType(QualType Ty) {
7213
0
    Info.FFDiag(BCE->getBeginLoc(),
7214
0
                diag::note_constexpr_bit_cast_unsupported_type)
7215
0
        << Ty;
7216
0
    return std::nullopt;
7217
0
  }
7218
7219
0
  std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7220
0
    Info.FFDiag(BCE->getBeginLoc(),
7221
0
                diag::note_constexpr_bit_cast_unrepresentable_value)
7222
0
        << Ty << toString(Val, /*Radix=*/10);
7223
0
    return std::nullopt;
7224
0
  }
7225
7226
  std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7227
0
                               const EnumType *EnumSugar = nullptr) {
7228
0
    if (T->isNullPtrType()) {
7229
0
      uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7230
0
      return APValue((Expr *)nullptr,
7231
0
                     /*Offset=*/CharUnits::fromQuantity(NullValue),
7232
0
                     APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7233
0
    }
7234
7235
0
    CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7236
7237
    // Work around floating point types that contain unused padding bytes. This
7238
    // is really just `long double` on x86, which is the only fundamental type
7239
    // with padding bytes.
7240
0
    if (T->isRealFloatingType()) {
7241
0
      const llvm::fltSemantics &Semantics =
7242
0
          Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7243
0
      unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7244
0
      assert(NumBits % 8 == 0);
7245
0
      CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7246
0
      if (NumBytes != SizeOf)
7247
0
        SizeOf = NumBytes;
7248
0
    }
7249
7250
0
    SmallVector<uint8_t, 8> Bytes;
7251
0
    if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7252
      // If this is std::byte or unsigned char, then its okay to store an
7253
      // indeterminate value.
7254
0
      bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7255
0
      bool IsUChar =
7256
0
          !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7257
0
                         T->isSpecificBuiltinType(BuiltinType::Char_U));
7258
0
      if (!IsStdByte && !IsUChar) {
7259
0
        QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7260
0
        Info.FFDiag(BCE->getExprLoc(),
7261
0
                    diag::note_constexpr_bit_cast_indet_dest)
7262
0
            << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7263
0
        return std::nullopt;
7264
0
      }
7265
7266
0
      return APValue::IndeterminateValue();
7267
0
    }
7268
7269
0
    APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7270
0
    llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7271
7272
0
    if (T->isIntegralOrEnumerationType()) {
7273
0
      Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7274
7275
0
      unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7276
0
      if (IntWidth != Val.getBitWidth()) {
7277
0
        APSInt Truncated = Val.trunc(IntWidth);
7278
0
        if (Truncated.extend(Val.getBitWidth()) != Val)
7279
0
          return unrepresentableValue(QualType(T, 0), Val);
7280
0
        Val = Truncated;
7281
0
      }
7282
7283
0
      return APValue(Val);
7284
0
    }
7285
7286
0
    if (T->isRealFloatingType()) {
7287
0
      const llvm::fltSemantics &Semantics =
7288
0
          Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7289
0
      return APValue(APFloat(Semantics, Val));
7290
0
    }
7291
7292
0
    return unsupportedType(QualType(T, 0));
7293
0
  }
7294
7295
0
  std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7296
0
    const RecordDecl *RD = RTy->getAsRecordDecl();
7297
0
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7298
7299
0
    unsigned NumBases = 0;
7300
0
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7301
0
      NumBases = CXXRD->getNumBases();
7302
7303
0
    APValue ResultVal(APValue::UninitStruct(), NumBases,
7304
0
                      std::distance(RD->field_begin(), RD->field_end()));
7305
7306
    // Visit the base classes.
7307
0
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7308
0
      for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7309
0
        const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7310
0
        CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7311
0
        if (BaseDecl->isEmpty() ||
7312
0
            Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7313
0
          continue;
7314
7315
0
        std::optional<APValue> SubObj = visitType(
7316
0
            BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7317
0
        if (!SubObj)
7318
0
          return std::nullopt;
7319
0
        ResultVal.getStructBase(I) = *SubObj;
7320
0
      }
7321
0
    }
7322
7323
    // Visit the fields.
7324
0
    unsigned FieldIdx = 0;
7325
0
    for (FieldDecl *FD : RD->fields()) {
7326
      // FIXME: We don't currently support bit-fields. A lot of the logic for
7327
      // this is in CodeGen, so we need to factor it around.
7328
0
      if (FD->isBitField()) {
7329
0
        Info.FFDiag(BCE->getBeginLoc(),
7330
0
                    diag::note_constexpr_bit_cast_unsupported_bitfield);
7331
0
        return std::nullopt;
7332
0
      }
7333
7334
0
      uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7335
0
      assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7336
7337
0
      CharUnits FieldOffset =
7338
0
          CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7339
0
          Offset;
7340
0
      QualType FieldTy = FD->getType();
7341
0
      std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7342
0
      if (!SubObj)
7343
0
        return std::nullopt;
7344
0
      ResultVal.getStructField(FieldIdx) = *SubObj;
7345
0
      ++FieldIdx;
7346
0
    }
7347
7348
0
    return ResultVal;
7349
0
  }
7350
7351
0
  std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7352
0
    QualType RepresentationType = Ty->getDecl()->getIntegerType();
7353
0
    assert(!RepresentationType.isNull() &&
7354
0
           "enum forward decl should be caught by Sema");
7355
0
    const auto *AsBuiltin =
7356
0
        RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7357
    // Recurse into the underlying type. Treat std::byte transparently as
7358
    // unsigned char.
7359
0
    return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7360
0
  }
7361
7362
0
  std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7363
0
    size_t Size = Ty->getSize().getLimitedValue();
7364
0
    CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7365
7366
0
    APValue ArrayValue(APValue::UninitArray(), Size, Size);
7367
0
    for (size_t I = 0; I != Size; ++I) {
7368
0
      std::optional<APValue> ElementValue =
7369
0
          visitType(Ty->getElementType(), Offset + I * ElementWidth);
7370
0
      if (!ElementValue)
7371
0
        return std::nullopt;
7372
0
      ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7373
0
    }
7374
7375
0
    return ArrayValue;
7376
0
  }
7377
7378
0
  std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7379
0
    QualType EltTy = VTy->getElementType();
7380
0
    unsigned NElts = VTy->getNumElements();
7381
0
    unsigned EltSize =
7382
0
        VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7383
7384
0
    if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
7385
      // The vector's size in bits is not a multiple of the target's byte size,
7386
      // so its layout is unspecified. For now, we'll simply treat these cases
7387
      // as unsupported (this should only be possible with OpenCL bool vectors
7388
      // whose element count isn't a multiple of the byte size).
7389
0
      Info.FFDiag(BCE->getBeginLoc(),
7390
0
                  diag::note_constexpr_bit_cast_invalid_vector)
7391
0
          << QualType(VTy, 0) << EltSize << NElts << Info.Ctx.getCharWidth();
7392
0
      return std::nullopt;
7393
0
    }
7394
7395
0
    if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7396
0
                                           &APFloat::x87DoubleExtended()) {
7397
      // The layout for x86_fp80 vectors seems to be handled very inconsistently
7398
      // by both clang and LLVM, so for now we won't allow bit_casts involving
7399
      // it in a constexpr context.
7400
0
      Info.FFDiag(BCE->getBeginLoc(),
7401
0
                  diag::note_constexpr_bit_cast_unsupported_type)
7402
0
          << EltTy;
7403
0
      return std::nullopt;
7404
0
    }
7405
7406
0
    SmallVector<APValue, 4> Elts;
7407
0
    Elts.reserve(NElts);
7408
0
    if (VTy->isExtVectorBoolType()) {
7409
      // Special handling for OpenCL bool vectors:
7410
      // Since these vectors are stored as packed bits, but we can't read
7411
      // individual bits from the BitCastBuffer, we'll buffer all of the
7412
      // elements together into an appropriately sized APInt and write them all
7413
      // out at once. Because we don't accept vectors where NElts * EltSize
7414
      // isn't a multiple of the char size, there will be no padding space, so
7415
      // we don't have to worry about reading any padding data which didn't
7416
      // actually need to be accessed.
7417
0
      bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7418
7419
0
      SmallVector<uint8_t, 8> Bytes;
7420
0
      Bytes.reserve(NElts / 8);
7421
0
      if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7422
0
        return std::nullopt;
7423
7424
0
      APSInt SValInt(NElts, true);
7425
0
      llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7426
7427
0
      for (unsigned I = 0; I < NElts; ++I) {
7428
0
        llvm::APInt Elt =
7429
0
            SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7430
0
        Elts.emplace_back(
7431
0
            APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7432
0
      }
7433
0
    } else {
7434
      // Iterate over each of the elements and read them from the buffer at
7435
      // the appropriate offset.
7436
0
      CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7437
0
      for (unsigned I = 0; I < NElts; ++I) {
7438
0
        std::optional<APValue> EltValue =
7439
0
            visitType(EltTy, Offset + I * EltSizeChars);
7440
0
        if (!EltValue)
7441
0
          return std::nullopt;
7442
0
        Elts.push_back(std::move(*EltValue));
7443
0
      }
7444
0
    }
7445
7446
0
    return APValue(Elts.data(), Elts.size());
7447
0
  }
7448
7449
0
  std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7450
0
    return unsupportedType(QualType(Ty, 0));
7451
0
  }
7452
7453
0
  std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7454
0
    QualType Can = Ty.getCanonicalType();
7455
7456
0
    switch (Can->getTypeClass()) {
7457
0
#define TYPE(Class, Base)                                                      \
7458
0
  case Type::Class:                                                            \
7459
0
    return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7460
0
#define ABSTRACT_TYPE(Class, Base)
7461
0
#define NON_CANONICAL_TYPE(Class, Base)                                        \
7462
0
  case Type::Class:                                                            \
7463
0
    llvm_unreachable("non-canonical type should be impossible!");
7464
0
#define DEPENDENT_TYPE(Class, Base)                                            \
7465
0
  case Type::Class:                                                            \
7466
0
    llvm_unreachable(                                                          \
7467
0
        "dependent types aren't supported in the constant evaluator!");
7468
0
#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7469
0
  case Type::Class:                                                            \
7470
0
    llvm_unreachable("either dependent or not canonical!");
7471
0
#include "clang/AST/TypeNodes.inc"
7472
0
    }
7473
0
    llvm_unreachable("Unhandled Type::TypeClass");
7474
0
  }
7475
7476
public:
7477
  // Pull out a full value of type DstType.
7478
  static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7479
0
                                        const CastExpr *BCE) {
7480
0
    BufferToAPValueConverter Converter(Info, Buffer, BCE);
7481
0
    return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7482
0
  }
7483
};
7484
7485
static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7486
                                                 QualType Ty, EvalInfo *Info,
7487
                                                 const ASTContext &Ctx,
7488
0
                                                 bool CheckingDest) {
7489
0
  Ty = Ty.getCanonicalType();
7490
7491
0
  auto diag = [&](int Reason) {
7492
0
    if (Info)
7493
0
      Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7494
0
          << CheckingDest << (Reason == 4) << Reason;
7495
0
    return false;
7496
0
  };
7497
0
  auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7498
0
    if (Info)
7499
0
      Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7500
0
          << NoteTy << Construct << Ty;
7501
0
    return false;
7502
0
  };
7503
7504
0
  if (Ty->isUnionType())
7505
0
    return diag(0);
7506
0
  if (Ty->isPointerType())
7507
0
    return diag(1);
7508
0
  if (Ty->isMemberPointerType())
7509
0
    return diag(2);
7510
0
  if (Ty.isVolatileQualified())
7511
0
    return diag(3);
7512
7513
0
  if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7514
0
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7515
0
      for (CXXBaseSpecifier &BS : CXXRD->bases())
7516
0
        if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7517
0
                                                  CheckingDest))
7518
0
          return note(1, BS.getType(), BS.getBeginLoc());
7519
0
    }
7520
0
    for (FieldDecl *FD : Record->fields()) {
7521
0
      if (FD->getType()->isReferenceType())
7522
0
        return diag(4);
7523
0
      if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7524
0
                                                CheckingDest))
7525
0
        return note(0, FD->getType(), FD->getBeginLoc());
7526
0
    }
7527
0
  }
7528
7529
0
  if (Ty->isArrayType() &&
7530
0
      !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7531
0
                                            Info, Ctx, CheckingDest))
7532
0
    return false;
7533
7534
0
  return true;
7535
0
}
7536
7537
static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7538
                                             const ASTContext &Ctx,
7539
0
                                             const CastExpr *BCE) {
7540
0
  bool DestOK = checkBitCastConstexprEligibilityType(
7541
0
      BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7542
0
  bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7543
0
                                BCE->getBeginLoc(),
7544
0
                                BCE->getSubExpr()->getType(), Info, Ctx, false);
7545
0
  return SourceOK;
7546
0
}
7547
7548
static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7549
                                        const APValue &SourceRValue,
7550
0
                                        const CastExpr *BCE) {
7551
0
  assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7552
0
         "no host or target supports non 8-bit chars");
7553
7554
0
  if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7555
0
    return false;
7556
7557
  // Read out SourceValue into a char buffer.
7558
0
  std::optional<BitCastBuffer> Buffer =
7559
0
      APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7560
0
  if (!Buffer)
7561
0
    return false;
7562
7563
  // Write out the buffer into a new APValue.
7564
0
  std::optional<APValue> MaybeDestValue =
7565
0
      BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7566
0
  if (!MaybeDestValue)
7567
0
    return false;
7568
7569
0
  DestValue = std::move(*MaybeDestValue);
7570
0
  return true;
7571
0
}
7572
7573
static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7574
                                        APValue &SourceValue,
7575
0
                                        const CastExpr *BCE) {
7576
0
  assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7577
0
         "no host or target supports non 8-bit chars");
7578
0
  assert(SourceValue.isLValue() &&
7579
0
         "LValueToRValueBitcast requires an lvalue operand!");
7580
7581
0
  LValue SourceLValue;
7582
0
  APValue SourceRValue;
7583
0
  SourceLValue.setFrom(Info.Ctx, SourceValue);
7584
0
  if (!handleLValueToRValueConversion(
7585
0
          Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7586
0
          SourceRValue, /*WantObjectRepresentation=*/true))
7587
0
    return false;
7588
7589
0
  return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7590
0
}
7591
7592
template <class Derived>
7593
class ExprEvaluatorBase
7594
  : public ConstStmtVisitor<Derived, bool> {
7595
private:
7596
0
  Derived &getDerived() { return static_cast<Derived&>(*this); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::getDerived()
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::getDerived()
7597
0
  bool DerivedSuccess(const APValue &V, const Expr *E) {
7598
0
    return getDerived().Success(V, E);
7599
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::DerivedSuccess(clang::APValue const&, clang::Expr const*)
7600
0
  bool DerivedZeroInitialization(const Expr *E) {
7601
0
    return getDerived().ZeroInitialization(E);
7602
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::DerivedZeroInitialization(clang::Expr const*)
7603
7604
  // Check whether a conditional operator with a non-constant condition is a
7605
  // potential constant expression. If neither arm is a potential constant
7606
  // expression, then the conditional operator is not either.
7607
  template<typename ConditionalOperator>
7608
0
  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7609
0
    assert(Info.checkingPotentialConstantExpression());
7610
7611
    // Speculatively evaluate both arms.
7612
0
    SmallVector<PartialDiagnosticAt, 8> Diag;
7613
0
    {
7614
0
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7615
0
      StmtVisitorTy::Visit(E->getFalseExpr());
7616
0
      if (Diag.empty())
7617
0
        return;
7618
0
    }
7619
7620
0
    {
7621
0
      SpeculativeEvaluationRAII Speculate(Info, &Diag);
7622
0
      Diag.clear();
7623
0
      StmtVisitorTy::Visit(E->getTrueExpr());
7624
0
      if (Diag.empty())
7625
0
        return;
7626
0
    }
7627
7628
0
    Error(E, diag::note_constexpr_conditional_never_const);
7629
0
  }
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)::MemberPointerExprEvaluator>::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)::TemporaryExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::FixedPointExprEvaluator>::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)::FloatExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::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)::RecordExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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)::ArrayExprEvaluator>::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)::AtomicExprEvaluator>::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)::VectorExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::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)::VoidExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::CheckPotentialConstantConditional<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:void (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::CheckPotentialConstantConditional<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
7630
7631
7632
  template<typename ConditionalOperator>
7633
0
  bool HandleConditionalOperator(const ConditionalOperator *E) {
7634
0
    bool BoolResult;
7635
0
    if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7636
0
      if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7637
0
        CheckPotentialConstantConditional(E);
7638
0
        return false;
7639
0
      }
7640
0
      if (Info.noteFailure()) {
7641
0
        StmtVisitorTy::Visit(E->getTrueExpr());
7642
0
        StmtVisitorTy::Visit(E->getFalseExpr());
7643
0
      }
7644
0
      return false;
7645
0
    }
7646
7647
0
    Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7648
0
    return StmtVisitorTy::Visit(EvalExpr);
7649
0
  }
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::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)::TemporaryExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::FixedPointExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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)::ArrayExprEvaluator>::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)::AtomicExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::HandleConditionalOperator<clang::ConditionalOperator>(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:bool (anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::HandleConditionalOperator<clang::BinaryConditionalOperator>(clang::BinaryConditionalOperator const*)
7650
7651
protected:
7652
  EvalInfo &Info;
7653
  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7654
  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7655
7656
1
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7657
1
    return Info.CCEDiag(E, D);
7658
1
  }
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)::MemberPointerExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::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)::AtomicExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::CCEDiag(clang::Expr const*, unsigned int)
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
7656
1
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7657
1
    return Info.CCEDiag(E, D);
7658
1
  }
7659
7660
0
  bool ZeroInitialization(const Expr *E) { return Error(E); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::ZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::ZeroInitialization(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::ZeroInitialization(clang::Expr const*)
7661
7662
0
  bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7663
0
    unsigned BuiltinOp = E->getBuiltinCallee();
7664
0
    return BuiltinOp != 0 &&
7665
0
           Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7666
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::IsConstantEvaluatedBuiltinCall(clang::CallExpr const*)
7667
7668
public:
7669
20
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7669
9
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7669
10
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::ExprEvaluatorBase((anonymous namespace)::EvalInfo&)
Line
Count
Source
7669
1
  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7670
7671
0
  EvalInfo &getEvalInfo() { return Info; }
7672
7673
  /// Report an evaluation error. This should only be called when an error is
7674
  /// first discovered. When propagating an error, just return false.
7675
1
  bool Error(const Expr *E, diag::kind D) {
7676
1
    Info.FFDiag(E, D) << E->getSourceRange();
7677
1
    return false;
7678
1
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::Error(clang::Expr const*, unsigned int)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::Error(clang::Expr const*, unsigned int)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::Error(clang::Expr const*, unsigned int)
Line
Count
Source
7675
1
  bool Error(const Expr *E, diag::kind D) {
7676
1
    Info.FFDiag(E, D) << E->getSourceRange();
7677
1
    return false;
7678
1
  }
7679
1
  bool Error(const Expr *E) {
7680
1
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7681
1
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::Error(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::Error(clang::Expr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::Error(clang::Expr const*)
Line
Count
Source
7679
1
  bool Error(const Expr *E) {
7680
1
    return Error(E, diag::note_invalid_subexpr_in_const_expr);
7681
1
  }
7682
7683
0
  bool VisitStmt(const Stmt *) {
7684
0
    llvm_unreachable("Expression evaluator should not be called on stmts");
7685
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::MemberPointerExprEvaluator>::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*)
7686
0
  bool VisitExpr(const Expr *E) {
7687
0
    return Error(E);
7688
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitExpr(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitExpr(clang::Expr const*)
7689
7690
0
  bool VisitPredefinedExpr(const PredefinedExpr *E) {
7691
0
    return StmtVisitorTy::Visit(E->getFunctionName());
7692
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitPredefinedExpr(clang::PredefinedExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::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*)
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*)
7693
0
  bool VisitConstantExpr(const ConstantExpr *E) {
7694
0
    if (E->hasAPValueResult())
7695
0
      return DerivedSuccess(E->getAPValueResult(), E);
7696
7697
0
    return StmtVisitorTy::Visit(E->getSubExpr());
7698
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitConstantExpr(clang::ConstantExpr const*)
7699
7700
  bool VisitParenExpr(const ParenExpr *E)
7701
0
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitParenExpr(clang::ParenExpr const*)
7702
  bool VisitUnaryExtension(const UnaryOperator *E)
7703
0
    { return StmtVisitorTy::Visit(E->getSubExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::MemberPointerExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryExtension(clang::UnaryOperator const*)
7704
  bool VisitUnaryPlus(const UnaryOperator *E)
7705
0
    { 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)::TemporaryExprEvaluator>::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)::ArrayExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPlus(clang::UnaryOperator const*)
7706
  bool VisitChooseExpr(const ChooseExpr *E)
7707
0
    { 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)::MemberPointerExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::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)::AtomicExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitChooseExpr(clang::ChooseExpr const*)
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*)
7708
  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7709
0
    { return StmtVisitorTy::Visit(E->getResultExpr()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
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)::ArrayExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitGenericSelectionExpr(clang::GenericSelectionExpr const*)
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*)
7710
  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7711
0
    { return StmtVisitorTy::Visit(E->getReplacement()); }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::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)::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)::AtomicExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitSubstNonTypeTemplateParmExpr(clang::SubstNonTypeTemplateParmExpr const*)
7712
0
  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7713
0
    TempVersionRAII RAII(*Info.CurrentCall);
7714
0
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7715
0
    return StmtVisitorTy::Visit(E->getExpr());
7716
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXDefaultArgExpr(clang::CXXDefaultArgExpr const*)
7717
0
  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7718
0
    TempVersionRAII RAII(*Info.CurrentCall);
7719
    // The initializer may not have been parsed yet, or might be erroneous.
7720
0
    if (!E->getExpr())
7721
0
      return Error(E);
7722
0
    SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7723
0
    return StmtVisitorTy::Visit(E->getExpr());
7724
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXDefaultInitExpr(clang::CXXDefaultInitExpr const*)
7725
7726
0
  bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7727
0
    FullExpressionRAII Scope(Info);
7728
0
    return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7729
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitExprWithCleanups(clang::ExprWithCleanups const*)
7730
7731
  // Temporaries are registered when created, so we don't care about
7732
  // CXXBindTemporaryExpr.
7733
0
  bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7734
0
    return StmtVisitorTy::Visit(E->getSubExpr());
7735
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
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*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXBindTemporaryExpr(clang::CXXBindTemporaryExpr const*)
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*)
7736
7737
0
  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7738
0
    CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7739
0
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7740
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::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)::AtomicExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXReinterpretCastExpr(clang::CXXReinterpretCastExpr const*)
7741
0
  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7742
0
    if (!Info.Ctx.getLangOpts().CPlusPlus20)
7743
0
      CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7744
0
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7745
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::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)::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXDynamicCastExpr(clang::CXXDynamicCastExpr const*)
7746
0
  bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7747
0
    return static_cast<Derived*>(this)->VisitCastExpr(E);
7748
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
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)::ArrayExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitBuiltinBitCastExpr(clang::BuiltinBitCastExpr const*)
7749
7750
0
  bool VisitBinaryOperator(const BinaryOperator *E) {
7751
0
    switch (E->getOpcode()) {
7752
0
    default:
7753
0
      return Error(E);
7754
7755
0
    case BO_Comma:
7756
0
      VisitIgnoredValue(E->getLHS());
7757
0
      return StmtVisitorTy::Visit(E->getRHS());
7758
7759
0
    case BO_PtrMemD:
7760
0
    case BO_PtrMemI: {
7761
0
      LValue Obj;
7762
0
      if (!HandleMemberPointerAccess(Info, E, Obj))
7763
0
        return false;
7764
0
      APValue Result;
7765
0
      if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7766
0
        return false;
7767
0
      return DerivedSuccess(Result, E);
7768
0
    }
7769
0
    }
7770
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
7771
7772
0
  bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7773
0
    return StmtVisitorTy::Visit(E->getSemanticForm());
7774
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
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)::ArrayExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXRewrittenBinaryOperator(clang::CXXRewrittenBinaryOperator const*)
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*)
7775
7776
0
  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7777
    // Evaluate and cache the common expression. We treat it as a temporary,
7778
    // even though it's not quite the same thing.
7779
0
    LValue CommonLV;
7780
0
    if (!Evaluate(Info.CurrentCall->createTemporary(
7781
0
                      E->getOpaqueValue(),
7782
0
                      getStorageType(Info.Ctx, E->getOpaqueValue()),
7783
0
                      ScopeKind::FullExpression, CommonLV),
7784
0
                  Info, E->getCommon()))
7785
0
      return false;
7786
7787
0
    return HandleConditionalOperator(E);
7788
0
  }
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)::LValueExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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)::AtomicExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitBinaryConditionalOperator(clang::BinaryConditionalOperator const*)
7789
7790
0
  bool VisitConditionalOperator(const ConditionalOperator *E) {
7791
0
    bool IsBcpCall = false;
7792
    // If the condition (ignoring parens) is a __builtin_constant_p call,
7793
    // the result is a constant expression if it can be folded without
7794
    // side-effects. This is an important GNU extension. See GCC PR38377
7795
    // for discussion.
7796
0
    if (const CallExpr *CallCE =
7797
0
          dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7798
0
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7799
0
        IsBcpCall = true;
7800
7801
    // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7802
    // constant expression; we can't check whether it's potentially foldable.
7803
    // FIXME: We should instead treat __builtin_constant_p as non-constant if
7804
    // it would return 'false' in this mode.
7805
0
    if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7806
0
      return false;
7807
7808
0
    FoldConstant Fold(Info, IsBcpCall);
7809
0
    if (!HandleConditionalOperator(E)) {
7810
0
      Fold.keepDiagnostics();
7811
0
      return false;
7812
0
    }
7813
7814
0
    return true;
7815
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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)::AtomicExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitConditionalOperator(clang::ConditionalOperator const*)
7816
7817
0
  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7818
0
    if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7819
0
        Value && !Value->isAbsent())
7820
0
      return DerivedSuccess(*Value, E);
7821
7822
0
    const Expr *Source = E->getSourceExpr();
7823
0
    if (!Source)
7824
0
      return Error(E);
7825
0
    if (Source == E) {
7826
0
      assert(0 && "OpaqueValueExpr recursively refers to itself");
7827
0
      return Error(E);
7828
0
    }
7829
0
    return StmtVisitorTy::Visit(Source);
7830
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::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)::FixedPointExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitOpaqueValueExpr(clang::OpaqueValueExpr const*)
7831
7832
0
  bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7833
0
    for (const Expr *SemE : E->semantics()) {
7834
0
      if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7835
        // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7836
        // result expression: there could be two different LValues that would
7837
        // refer to the same object in that case, and we can't model that.
7838
0
        if (SemE == E->getResultExpr())
7839
0
          return Error(E);
7840
7841
        // Unique OVEs get evaluated if and when we encounter them when
7842
        // emitting the rest of the semantic form, rather than eagerly.
7843
0
        if (OVE->isUnique())
7844
0
          continue;
7845
7846
0
        LValue LV;
7847
0
        if (!Evaluate(Info.CurrentCall->createTemporary(
7848
0
                          OVE, getStorageType(Info.Ctx, OVE),
7849
0
                          ScopeKind::FullExpression, LV),
7850
0
                      Info, OVE->getSourceExpr()))
7851
0
          return false;
7852
0
      } else if (SemE == E->getResultExpr()) {
7853
0
        if (!StmtVisitorTy::Visit(SemE))
7854
0
          return false;
7855
0
      } else {
7856
0
        if (!EvaluateIgnoredValue(Info, SemE))
7857
0
          return false;
7858
0
      }
7859
0
    }
7860
0
    return true;
7861
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitPseudoObjectExpr(clang::PseudoObjectExpr const*)
7862
7863
0
  bool VisitCallExpr(const CallExpr *E) {
7864
0
    APValue Result;
7865
0
    if (!handleCallExpr(E, Result, nullptr))
7866
0
      return false;
7867
0
    return DerivedSuccess(Result, E);
7868
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCallExpr(clang::CallExpr const*)
7869
7870
  bool handleCallExpr(const CallExpr *E, APValue &Result,
7871
0
                     const LValue *ResultSlot) {
7872
0
    CallScopeRAII CallScope(Info);
7873
7874
0
    const Expr *Callee = E->getCallee()->IgnoreParens();
7875
0
    QualType CalleeType = Callee->getType();
7876
7877
0
    const FunctionDecl *FD = nullptr;
7878
0
    LValue *This = nullptr, ThisVal;
7879
0
    auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7880
0
    bool HasQualifier = false;
7881
7882
0
    CallRef Call;
7883
7884
    // Extract function decl and 'this' pointer from the callee.
7885
0
    if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7886
0
      const CXXMethodDecl *Member = nullptr;
7887
0
      if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7888
        // Explicit bound member calls, such as x.f() or p->g();
7889
0
        if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7890
0
          return false;
7891
0
        Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7892
0
        if (!Member)
7893
0
          return Error(Callee);
7894
0
        This = &ThisVal;
7895
0
        HasQualifier = ME->hasQualifier();
7896
0
      } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7897
        // Indirect bound member calls ('.*' or '->*').
7898
0
        const ValueDecl *D =
7899
0
            HandleMemberPointerAccess(Info, BE, ThisVal, false);
7900
0
        if (!D)
7901
0
          return false;
7902
0
        Member = dyn_cast<CXXMethodDecl>(D);
7903
0
        if (!Member)
7904
0
          return Error(Callee);
7905
0
        This = &ThisVal;
7906
0
      } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7907
0
        if (!Info.getLangOpts().CPlusPlus20)
7908
0
          Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7909
0
        return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7910
0
               HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7911
0
      } else
7912
0
        return Error(Callee);
7913
0
      FD = Member;
7914
0
    } else if (CalleeType->isFunctionPointerType()) {
7915
0
      LValue CalleeLV;
7916
0
      if (!EvaluatePointer(Callee, CalleeLV, Info))
7917
0
        return false;
7918
7919
0
      if (!CalleeLV.getLValueOffset().isZero())
7920
0
        return Error(Callee);
7921
0
      if (CalleeLV.isNullPointer()) {
7922
0
        Info.FFDiag(Callee, diag::note_constexpr_null_callee)
7923
0
            << const_cast<Expr *>(Callee);
7924
0
        return false;
7925
0
      }
7926
0
      FD = dyn_cast_or_null<FunctionDecl>(
7927
0
          CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7928
0
      if (!FD)
7929
0
        return Error(Callee);
7930
      // Don't call function pointers which have been cast to some other type.
7931
      // Per DR (no number yet), the caller and callee can differ in noexcept.
7932
0
      if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7933
0
        CalleeType->getPointeeType(), FD->getType())) {
7934
0
        return Error(E);
7935
0
      }
7936
7937
      // For an (overloaded) assignment expression, evaluate the RHS before the
7938
      // LHS.
7939
0
      auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7940
0
      if (OCE && OCE->isAssignmentOp()) {
7941
0
        assert(Args.size() == 2 && "wrong number of arguments in assignment");
7942
0
        Call = Info.CurrentCall->createCall(FD);
7943
0
        bool HasThis = false;
7944
0
        if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
7945
0
          HasThis = MD->isImplicitObjectMemberFunction();
7946
0
        if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
7947
0
                          /*RightToLeft=*/true))
7948
0
          return false;
7949
0
      }
7950
7951
      // Overloaded operator calls to member functions are represented as normal
7952
      // calls with '*this' as the first argument.
7953
0
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7954
0
      if (MD && MD->isImplicitObjectMemberFunction()) {
7955
        // FIXME: When selecting an implicit conversion for an overloaded
7956
        // operator delete, we sometimes try to evaluate calls to conversion
7957
        // operators without a 'this' parameter!
7958
0
        if (Args.empty())
7959
0
          return Error(E);
7960
7961
0
        if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7962
0
          return false;
7963
0
        This = &ThisVal;
7964
7965
        // If this is syntactically a simple assignment using a trivial
7966
        // assignment operator, start the lifetimes of union members as needed,
7967
        // per C++20 [class.union]5.
7968
0
        if (Info.getLangOpts().CPlusPlus20 && OCE &&
7969
0
            OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7970
0
            !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7971
0
          return false;
7972
7973
0
        Args = Args.slice(1);
7974
0
      } else if (MD && MD->isLambdaStaticInvoker()) {
7975
        // Map the static invoker for the lambda back to the call operator.
7976
        // Conveniently, we don't have to slice out the 'this' argument (as is
7977
        // being done for the non-static case), since a static member function
7978
        // doesn't have an implicit argument passed in.
7979
0
        const CXXRecordDecl *ClosureClass = MD->getParent();
7980
0
        assert(
7981
0
            ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7982
0
            "Number of captures must be zero for conversion to function-ptr");
7983
7984
0
        const CXXMethodDecl *LambdaCallOp =
7985
0
            ClosureClass->getLambdaCallOperator();
7986
7987
        // Set 'FD', the function that will be called below, to the call
7988
        // operator.  If the closure object represents a generic lambda, find
7989
        // the corresponding specialization of the call operator.
7990
7991
0
        if (ClosureClass->isGenericLambda()) {
7992
0
          assert(MD->isFunctionTemplateSpecialization() &&
7993
0
                 "A generic lambda's static-invoker function must be a "
7994
0
                 "template specialization");
7995
0
          const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7996
0
          FunctionTemplateDecl *CallOpTemplate =
7997
0
              LambdaCallOp->getDescribedFunctionTemplate();
7998
0
          void *InsertPos = nullptr;
7999
0
          FunctionDecl *CorrespondingCallOpSpecialization =
8000
0
              CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8001
0
          assert(CorrespondingCallOpSpecialization &&
8002
0
                 "We must always have a function call operator specialization "
8003
0
                 "that corresponds to our static invoker specialization");
8004
0
          FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
8005
0
        } else
8006
0
          FD = LambdaCallOp;
8007
0
      } else if (FD->isReplaceableGlobalAllocationFunction()) {
8008
0
        if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8009
0
            FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8010
0
          LValue Ptr;
8011
0
          if (!HandleOperatorNewCall(Info, E, Ptr))
8012
0
            return false;
8013
0
          Ptr.moveInto(Result);
8014
0
          return CallScope.destroy();
8015
0
        } else {
8016
0
          return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8017
0
        }
8018
0
      }
8019
0
    } else
8020
0
      return Error(E);
8021
8022
    // Evaluate the arguments now if we've not already done so.
8023
0
    if (!Call) {
8024
0
      Call = Info.CurrentCall->createCall(FD);
8025
0
      if (!EvaluateArgs(Args, Call, Info, FD))
8026
0
        return false;
8027
0
    }
8028
8029
0
    SmallVector<QualType, 4> CovariantAdjustmentPath;
8030
0
    if (This) {
8031
0
      auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8032
0
      if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8033
        // Perform virtual dispatch, if necessary.
8034
0
        FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8035
0
                                   CovariantAdjustmentPath);
8036
0
        if (!FD)
8037
0
          return false;
8038
0
      } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8039
        // Check that the 'this' pointer points to an object of the right type.
8040
        // FIXME: If this is an assignment operator call, we may need to change
8041
        // the active union member before we check this.
8042
0
        if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8043
0
          return false;
8044
0
      }
8045
0
    }
8046
8047
    // Destructor calls are different enough that they have their own codepath.
8048
0
    if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8049
0
      assert(This && "no 'this' pointer for destructor call");
8050
0
      return HandleDestruction(Info, E, *This,
8051
0
                               Info.Ctx.getRecordType(DD->getParent())) &&
8052
0
             CallScope.destroy();
8053
0
    }
8054
8055
0
    const FunctionDecl *Definition = nullptr;
8056
0
    Stmt *Body = FD->getBody(Definition);
8057
8058
0
    if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8059
0
        !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8060
0
                            Body, Info, Result, ResultSlot))
8061
0
      return false;
8062
8063
0
    if (!CovariantAdjustmentPath.empty() &&
8064
0
        !HandleCovariantReturnAdjustment(Info, E, Result,
8065
0
                                         CovariantAdjustmentPath))
8066
0
      return false;
8067
8068
0
    return CallScope.destroy();
8069
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
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)::FixedPointExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::handleCallExpr(clang::CallExpr const*, clang::APValue&, (anonymous namespace)::LValue const*)
8070
8071
0
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8072
0
    return StmtVisitorTy::Visit(E->getInitializer());
8073
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCompoundLiteralExpr(clang::CompoundLiteralExpr const*)
8074
0
  bool VisitInitListExpr(const InitListExpr *E) {
8075
0
    if (E->getNumInits() == 0)
8076
0
      return DerivedZeroInitialization(E);
8077
0
    if (E->getNumInits() == 1)
8078
0
      return StmtVisitorTy::Visit(E->getInit(0));
8079
0
    return Error(E);
8080
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitInitListExpr(clang::InitListExpr const*)
8081
0
  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8082
0
    return DerivedZeroInitialization(E);
8083
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitImplicitValueInitExpr(clang::ImplicitValueInitExpr const*)
8084
0
  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8085
0
    return DerivedZeroInitialization(E);
8086
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXScalarValueInitExpr(clang::CXXScalarValueInitExpr const*)
8087
0
  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8088
0
    return DerivedZeroInitialization(E);
8089
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
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)::ArrayExprEvaluator>::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)::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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCXXNullPtrLiteralExpr(clang::CXXNullPtrLiteralExpr const*)
8090
8091
  /// A member expression where the object is a prvalue is itself a prvalue.
8092
0
  bool VisitMemberExpr(const MemberExpr *E) {
8093
0
    assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8094
0
           "missing temporary materialization conversion");
8095
0
    assert(!E->isArrow() && "missing call to bound member function?");
8096
8097
0
    APValue Val;
8098
0
    if (!Evaluate(Val, Info, E->getBase()))
8099
0
      return false;
8100
8101
0
    QualType BaseTy = E->getBase()->getType();
8102
8103
0
    const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8104
0
    if (!FD) return Error(E);
8105
0
    assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8106
0
    assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8107
0
           FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8108
8109
    // Note: there is no lvalue base here. But this case should only ever
8110
    // happen in C or in C++98, where we cannot be evaluating a constexpr
8111
    // constructor, which is the only case the base matters.
8112
0
    CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8113
0
    SubobjectDesignator Designator(BaseTy);
8114
0
    Designator.addDeclUnchecked(FD);
8115
8116
0
    APValue Result;
8117
0
    return extractSubobject(Info, E, Obj, Designator, Result) &&
8118
0
           DerivedSuccess(Result, E);
8119
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
8120
8121
0
  bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8122
0
    APValue Val;
8123
0
    if (!Evaluate(Val, Info, E->getBase()))
8124
0
      return false;
8125
8126
0
    if (Val.isVector()) {
8127
0
      SmallVector<uint32_t, 4> Indices;
8128
0
      E->getEncodedElementAccess(Indices);
8129
0
      if (Indices.size() == 1) {
8130
        // Return scalar.
8131
0
        return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8132
0
      } else {
8133
        // Construct new APValue vector.
8134
0
        SmallVector<APValue, 4> Elts;
8135
0
        for (unsigned I = 0; I < Indices.size(); ++I) {
8136
0
          Elts.push_back(Val.getVectorElt(Indices[I]));
8137
0
        }
8138
0
        APValue VecResult(Elts.data(), Indices.size());
8139
0
        return DerivedSuccess(VecResult, E);
8140
0
      }
8141
0
    }
8142
8143
0
    return false;
8144
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::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)::AtomicExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitExtVectorElementExpr(clang::ExtVectorElementExpr const*)
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*)
8145
8146
6
  bool VisitCastExpr(const CastExpr *E) {
8147
6
    switch (E->getCastKind()) {
8148
1
    default:
8149
1
      break;
8150
8151
1
    case CK_AtomicToNonAtomic: {
8152
0
      APValue AtomicVal;
8153
      // This does not need to be done in place even for class/array types:
8154
      // atomic-to-non-atomic conversion implies copying the object
8155
      // representation.
8156
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8157
0
        return false;
8158
0
      return DerivedSuccess(AtomicVal, E);
8159
0
    }
8160
8161
0
    case CK_NoOp:
8162
0
    case CK_UserDefinedConversion:
8163
0
      return StmtVisitorTy::Visit(E->getSubExpr());
8164
8165
5
    case CK_LValueToRValue: {
8166
5
      LValue LVal;
8167
5
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8168
0
        return false;
8169
5
      APValue RVal;
8170
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8171
5
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8172
5
                                          LVal, RVal))
8173
5
        return false;
8174
0
      return DerivedSuccess(RVal, E);
8175
5
    }
8176
0
    case CK_LValueToRValueBitCast: {
8177
0
      APValue DestValue, SourceValue;
8178
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8179
0
        return false;
8180
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8181
0
        return false;
8182
0
      return DerivedSuccess(DestValue, E);
8183
0
    }
8184
8185
0
    case CK_AddressSpaceConversion: {
8186
0
      APValue Value;
8187
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8188
0
        return false;
8189
0
      return DerivedSuccess(Value, E);
8190
0
    }
8191
6
    }
8192
8193
1
    return Error(E);
8194
6
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8146
5
  bool VisitCastExpr(const CastExpr *E) {
8147
5
    switch (E->getCastKind()) {
8148
0
    default:
8149
0
      break;
8150
8151
0
    case CK_AtomicToNonAtomic: {
8152
0
      APValue AtomicVal;
8153
      // This does not need to be done in place even for class/array types:
8154
      // atomic-to-non-atomic conversion implies copying the object
8155
      // representation.
8156
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8157
0
        return false;
8158
0
      return DerivedSuccess(AtomicVal, E);
8159
0
    }
8160
8161
0
    case CK_NoOp:
8162
0
    case CK_UserDefinedConversion:
8163
0
      return StmtVisitorTy::Visit(E->getSubExpr());
8164
8165
5
    case CK_LValueToRValue: {
8166
5
      LValue LVal;
8167
5
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8168
0
        return false;
8169
5
      APValue RVal;
8170
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8171
5
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8172
5
                                          LVal, RVal))
8173
5
        return false;
8174
0
      return DerivedSuccess(RVal, E);
8175
5
    }
8176
0
    case CK_LValueToRValueBitCast: {
8177
0
      APValue DestValue, SourceValue;
8178
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8179
0
        return false;
8180
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8181
0
        return false;
8182
0
      return DerivedSuccess(DestValue, E);
8183
0
    }
8184
8185
0
    case CK_AddressSpaceConversion: {
8186
0
      APValue Value;
8187
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8188
0
        return false;
8189
0
      return DerivedSuccess(Value, E);
8190
0
    }
8191
5
    }
8192
8193
0
    return Error(E);
8194
5
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Line
Count
Source
8146
1
  bool VisitCastExpr(const CastExpr *E) {
8147
1
    switch (E->getCastKind()) {
8148
1
    default:
8149
1
      break;
8150
8151
1
    case CK_AtomicToNonAtomic: {
8152
0
      APValue AtomicVal;
8153
      // This does not need to be done in place even for class/array types:
8154
      // atomic-to-non-atomic conversion implies copying the object
8155
      // representation.
8156
0
      if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8157
0
        return false;
8158
0
      return DerivedSuccess(AtomicVal, E);
8159
0
    }
8160
8161
0
    case CK_NoOp:
8162
0
    case CK_UserDefinedConversion:
8163
0
      return StmtVisitorTy::Visit(E->getSubExpr());
8164
8165
0
    case CK_LValueToRValue: {
8166
0
      LValue LVal;
8167
0
      if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8168
0
        return false;
8169
0
      APValue RVal;
8170
      // Note, we use the subexpression's type in order to retain cv-qualifiers.
8171
0
      if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8172
0
                                          LVal, RVal))
8173
0
        return false;
8174
0
      return DerivedSuccess(RVal, E);
8175
0
    }
8176
0
    case CK_LValueToRValueBitCast: {
8177
0
      APValue DestValue, SourceValue;
8178
0
      if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8179
0
        return false;
8180
0
      if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8181
0
        return false;
8182
0
      return DerivedSuccess(DestValue, E);
8183
0
    }
8184
8185
0
    case CK_AddressSpaceConversion: {
8186
0
      APValue Value;
8187
0
      if (!Evaluate(Value, Info, E->getSubExpr()))
8188
0
        return false;
8189
0
      return DerivedSuccess(Value, E);
8190
0
    }
8191
1
    }
8192
8193
1
    return Error(E);
8194
1
  }
8195
8196
0
  bool VisitUnaryPostInc(const UnaryOperator *UO) {
8197
0
    return VisitUnaryPostIncDec(UO);
8198
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::MemberPointerExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPostInc(clang::UnaryOperator const*)
8199
0
  bool VisitUnaryPostDec(const UnaryOperator *UO) {
8200
0
    return VisitUnaryPostIncDec(UO);
8201
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::MemberPointerExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPostDec(clang::UnaryOperator const*)
8202
0
  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8203
0
    if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8204
0
      return Error(UO);
8205
8206
0
    LValue LVal;
8207
0
    if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8208
0
      return false;
8209
0
    APValue RVal;
8210
0
    if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8211
0
                      UO->isIncrementOp(), &RVal))
8212
0
      return false;
8213
0
    return DerivedSuccess(RVal, UO);
8214
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::MemberPointerExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
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*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitUnaryPostIncDec(clang::UnaryOperator const*)
8215
8216
0
  bool VisitStmtExpr(const StmtExpr *E) {
8217
    // We will have checked the full-expressions inside the statement expression
8218
    // when they were completed, and don't need to check them again now.
8219
0
    llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8220
0
                                          false);
8221
8222
0
    const CompoundStmt *CS = E->getSubStmt();
8223
0
    if (CS->body_empty())
8224
0
      return true;
8225
8226
0
    BlockScopeRAII Scope(Info);
8227
0
    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8228
0
                                           BE = CS->body_end();
8229
0
         /**/; ++BI) {
8230
0
      if (BI + 1 == BE) {
8231
0
        const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8232
0
        if (!FinalExpr) {
8233
0
          Info.FFDiag((*BI)->getBeginLoc(),
8234
0
                      diag::note_constexpr_stmt_expr_unsupported);
8235
0
          return false;
8236
0
        }
8237
0
        return this->Visit(FinalExpr) && Scope.destroy();
8238
0
      }
8239
8240
0
      APValue ReturnValue;
8241
0
      StmtResult Result = { ReturnValue, nullptr };
8242
0
      EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8243
0
      if (ESR != ESR_Succeeded) {
8244
        // FIXME: If the statement-expression terminated due to 'return',
8245
        // 'break', or 'continue', it would be nice to propagate that to
8246
        // the outer statement evaluation rather than bailing out.
8247
0
        if (ESR != ESR_Failed)
8248
0
          Info.FFDiag((*BI)->getBeginLoc(),
8249
0
                      diag::note_constexpr_stmt_expr_unsupported);
8250
0
        return false;
8251
0
      }
8252
0
    }
8253
8254
0
    llvm_unreachable("Return from function from the loop above.");
8255
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::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)::MemberPointerExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitStmtExpr(clang::StmtExpr const*)
8256
8257
  /// Visit a value which is evaluated, but whose value is ignored.
8258
0
  void VisitIgnoredValue(const Expr *E) {
8259
0
    EvaluateIgnoredValue(Info, E);
8260
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::MemberPointerExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FixedPointExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::FloatExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ComplexExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::RecordExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::ArrayExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::AtomicExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VectorExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::VoidExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::PointerExprEvaluator>::VisitIgnoredValue(clang::Expr const*)
8261
8262
  /// Potentially visit a MemberExpr's base expression.
8263
0
  void VisitIgnoredBaseExpression(const Expr *E) {
8264
    // While MSVC doesn't evaluate the base expression, it does diagnose the
8265
    // presence of side-effecting behavior.
8266
0
    if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8267
0
      return;
8268
0
    VisitIgnoredValue(E);
8269
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitIgnoredBaseExpression(clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::ExprEvaluatorBase<(anonymous namespace)::IntExprEvaluator>::VisitIgnoredBaseExpression(clang::Expr const*)
8270
};
8271
8272
} // namespace
8273
8274
//===----------------------------------------------------------------------===//
8275
// Common base class for lvalue and temporary evaluation.
8276
//===----------------------------------------------------------------------===//
8277
namespace {
8278
template<class Derived>
8279
class LValueExprEvaluatorBase
8280
  : public ExprEvaluatorBase<Derived> {
8281
protected:
8282
  LValue &Result;
8283
  bool InvalidBaseOK;
8284
  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8285
  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8286
8287
9
  bool Success(APValue::LValueBase B) {
8288
9
    Result.set(B);
8289
9
    return true;
8290
9
  }
8291
8292
0
  bool evaluatePointer(const Expr *E, LValue &Result) {
8293
0
    return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8294
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::evaluatePointer(clang::Expr const*, (anonymous namespace)::LValue&)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::evaluatePointer(clang::Expr const*, (anonymous namespace)::LValue&)
8295
8296
public:
8297
  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8298
      : ExprEvaluatorBaseTy(Info), Result(Result),
8299
9
        InvalidBaseOK(InvalidBaseOK) {}
ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::LValueExprEvaluatorBase((anonymous namespace)::EvalInfo&, (anonymous namespace)::LValue&, bool)
Line
Count
Source
8299
9
        InvalidBaseOK(InvalidBaseOK) {}
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::LValueExprEvaluatorBase((anonymous namespace)::EvalInfo&, (anonymous namespace)::LValue&, bool)
8300
8301
0
  bool Success(const APValue &V, const Expr *E) {
8302
0
    Result.setFrom(this->Info.Ctx, V);
8303
0
    return true;
8304
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::Success(clang::APValue const&, clang::Expr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::Success(clang::APValue const&, clang::Expr const*)
8305
8306
0
  bool VisitMemberExpr(const MemberExpr *E) {
8307
    // Handle non-static data members.
8308
0
    QualType BaseTy;
8309
0
    bool EvalOK;
8310
0
    if (E->isArrow()) {
8311
0
      EvalOK = evaluatePointer(E->getBase(), Result);
8312
0
      BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8313
0
    } else if (E->getBase()->isPRValue()) {
8314
0
      assert(E->getBase()->getType()->isRecordType());
8315
0
      EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8316
0
      BaseTy = E->getBase()->getType();
8317
0
    } else {
8318
0
      EvalOK = this->Visit(E->getBase());
8319
0
      BaseTy = E->getBase()->getType();
8320
0
    }
8321
0
    if (!EvalOK) {
8322
0
      if (!InvalidBaseOK)
8323
0
        return false;
8324
0
      Result.setInvalid(E);
8325
0
      return true;
8326
0
    }
8327
8328
0
    const ValueDecl *MD = E->getMemberDecl();
8329
0
    if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8330
0
      assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8331
0
             FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8332
0
      (void)BaseTy;
8333
0
      if (!HandleLValueMember(this->Info, E, Result, FD))
8334
0
        return false;
8335
0
    } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8336
0
      if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8337
0
        return false;
8338
0
    } else
8339
0
      return this->Error(E);
8340
8341
0
    if (MD->getType()->isReferenceType()) {
8342
0
      APValue RefValue;
8343
0
      if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8344
0
                                          RefValue))
8345
0
        return false;
8346
0
      return Success(RefValue, E);
8347
0
    }
8348
0
    return true;
8349
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitMemberExpr(clang::MemberExpr const*)
8350
8351
0
  bool VisitBinaryOperator(const BinaryOperator *E) {
8352
0
    switch (E->getOpcode()) {
8353
0
    default:
8354
0
      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8355
8356
0
    case BO_PtrMemD:
8357
0
    case BO_PtrMemI:
8358
0
      return HandleMemberPointerAccess(this->Info, E, Result);
8359
0
    }
8360
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitBinaryOperator(clang::BinaryOperator const*)
8361
8362
0
  bool VisitCastExpr(const CastExpr *E) {
8363
0
    switch (E->getCastKind()) {
8364
0
    default:
8365
0
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
8366
8367
0
    case CK_DerivedToBase:
8368
0
    case CK_UncheckedDerivedToBase:
8369
0
      if (!this->Visit(E->getSubExpr()))
8370
0
        return false;
8371
8372
      // Now figure out the necessary offset to add to the base LV to get from
8373
      // the derived class to the base class.
8374
0
      return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8375
0
                                  Result);
8376
0
    }
8377
0
  }
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::TemporaryExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
Unexecuted instantiation: ExprConstant.cpp:(anonymous namespace)::LValueExprEvaluatorBase<(anonymous namespace)::LValueExprEvaluator>::VisitCastExpr(clang::CastExpr const*)
8378
};
8379
}
8380
8381
//===----------------------------------------------------------------------===//
8382
// LValue Evaluation
8383
//
8384
// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8385
// function designators (in C), decl references to void objects (in C), and
8386
// temporaries (if building with -Wno-address-of-temporary).
8387
//
8388
// LValue evaluation produces values comprising a base expression of one of the
8389
// following types:
8390
// - Declarations
8391
//  * VarDecl
8392
//  * FunctionDecl
8393
// - Literals
8394
//  * CompoundLiteralExpr in C (and in global scope in C++)
8395
//  * StringLiteral
8396
//  * PredefinedExpr
8397
//  * ObjCStringLiteralExpr
8398
//  * ObjCEncodeExpr
8399
//  * AddrLabelExpr
8400
//  * BlockExpr
8401
//  * CallExpr for a MakeStringConstant builtin
8402
// - typeid(T) expressions, as TypeInfoLValues
8403
// - Locals and temporaries
8404
//  * MaterializeTemporaryExpr
8405
//  * Any Expr, with a CallIndex indicating the function in which the temporary
8406
//    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8407
//    from the AST (FIXME).
8408
//  * A MaterializeTemporaryExpr that has static storage duration, with no
8409
//    CallIndex, for a lifetime-extended temporary.
8410
//  * The ConstantExpr that is currently being evaluated during evaluation of an
8411
//    immediate invocation.
8412
// plus an offset in bytes.
8413
//===----------------------------------------------------------------------===//
8414
namespace {
8415
class LValueExprEvaluator
8416
  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8417
public:
8418
  LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8419
9
    LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8420
8421
  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8422
  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8423
8424
  bool VisitCallExpr(const CallExpr *E);
8425
  bool VisitDeclRefExpr(const DeclRefExpr *E);
8426
0
  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8427
  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8428
  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8429
  bool VisitMemberExpr(const MemberExpr *E);
8430
0
  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8431
0
  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8432
  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8433
  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8434
  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8435
  bool VisitUnaryDeref(const UnaryOperator *E);
8436
  bool VisitUnaryReal(const UnaryOperator *E);
8437
  bool VisitUnaryImag(const UnaryOperator *E);
8438
0
  bool VisitUnaryPreInc(const UnaryOperator *UO) {
8439
0
    return VisitUnaryPreIncDec(UO);
8440
0
  }
8441
0
  bool VisitUnaryPreDec(const UnaryOperator *UO) {
8442
0
    return VisitUnaryPreIncDec(UO);
8443
0
  }
8444
  bool VisitBinAssign(const BinaryOperator *BO);
8445
  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8446
8447
0
  bool VisitCastExpr(const CastExpr *E) {
8448
0
    switch (E->getCastKind()) {
8449
0
    default:
8450
0
      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8451
8452
0
    case CK_LValueBitCast:
8453
0
      this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8454
0
          << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8455
0
      if (!Visit(E->getSubExpr()))
8456
0
        return false;
8457
0
      Result.Designator.setInvalid();
8458
0
      return true;
8459
8460
0
    case CK_BaseToDerived:
8461
0
      if (!Visit(E->getSubExpr()))
8462
0
        return false;
8463
0
      return HandleBaseToDerivedCast(Info, E, Result);
8464
8465
0
    case CK_Dynamic:
8466
0
      if (!Visit(E->getSubExpr()))
8467
0
        return false;
8468
0
      return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8469
0
    }
8470
0
  }
8471
};
8472
} // end anonymous namespace
8473
8474
/// Evaluate an expression as an lvalue. This can be legitimately called on
8475
/// expressions which are not glvalues, in three cases:
8476
///  * function designators in C, and
8477
///  * "extern void" objects
8478
///  * @selector() expressions in Objective-C
8479
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8480
9
                           bool InvalidBaseOK) {
8481
9
  assert(!E->isValueDependent());
8482
0
  assert(E->isGLValue() || E->getType()->isFunctionType() ||
8483
9
         E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8484
0
  return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8485
9
}
8486
8487
9
bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8488
9
  const NamedDecl *D = E->getDecl();
8489
9
  if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8490
9
          UnnamedGlobalConstantDecl>(D))
8491
0
    return Success(cast<ValueDecl>(D));
8492
9
  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8493
9
    return VisitVarDecl(E, VD);
8494
0
  if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8495
0
    return Visit(BD->getBinding());
8496
0
  return Error(E);
8497
0
}
8498
8499
8500
9
bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8501
8502
  // If we are within a lambda's call operator, check whether the 'VD' referred
8503
  // to within 'E' actually represents a lambda-capture that maps to a
8504
  // data-member/field within the closure object, and if so, evaluate to the
8505
  // field or what the field refers to.
8506
9
  if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8507
9
      isa<DeclRefExpr>(E) &&
8508
9
      cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8509
    // We don't always have a complete capture-map when checking or inferring if
8510
    // the function call operator meets the requirements of a constexpr function
8511
    // - but we don't need to evaluate the captures to determine constexprness
8512
    // (dcl.constexpr C++17).
8513
0
    if (Info.checkingPotentialConstantExpression())
8514
0
      return false;
8515
8516
0
    if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8517
0
      const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8518
8519
      // Static lambda function call operators can't have captures. We already
8520
      // diagnosed this, so bail out here.
8521
0
      if (MD->isStatic()) {
8522
0
        assert(Info.CurrentCall->This == nullptr &&
8523
0
               "This should not be set for a static call operator");
8524
0
        return false;
8525
0
      }
8526
8527
      // Start with 'Result' referring to the complete closure object...
8528
0
      if (MD->isExplicitObjectMemberFunction()) {
8529
0
        APValue *RefValue =
8530
0
            Info.getParamSlot(Info.CurrentCall->Arguments, MD->getParamDecl(0));
8531
0
        Result.setFrom(Info.Ctx, *RefValue);
8532
0
      } else
8533
0
        Result = *Info.CurrentCall->This;
8534
8535
      // ... then update it to refer to the field of the closure object
8536
      // that represents the capture.
8537
0
      if (!HandleLValueMember(Info, E, Result, FD))
8538
0
        return false;
8539
      // And if the field is of reference type, update 'Result' to refer to what
8540
      // the field refers to.
8541
0
      if (FD->getType()->isReferenceType()) {
8542
0
        APValue RVal;
8543
0
        if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8544
0
                                            RVal))
8545
0
          return false;
8546
0
        Result.setFrom(Info.Ctx, RVal);
8547
0
      }
8548
0
      return true;
8549
0
    }
8550
0
  }
8551
8552
9
  CallStackFrame *Frame = nullptr;
8553
9
  unsigned Version = 0;
8554
9
  if (VD->hasLocalStorage()) {
8555
    // Only if a local variable was declared in the function currently being
8556
    // evaluated, do we expect to be able to find its value in the current
8557
    // frame. (Otherwise it was likely declared in an enclosing context and
8558
    // could either have a valid evaluatable value (for e.g. a constexpr
8559
    // variable) or be ill-formed (and trigger an appropriate evaluation
8560
    // diagnostic)).
8561
0
    CallStackFrame *CurrFrame = Info.CurrentCall;
8562
0
    if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8563
      // Function parameters are stored in some caller's frame. (Usually the
8564
      // immediate caller, but for an inherited constructor they may be more
8565
      // distant.)
8566
0
      if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8567
0
        if (CurrFrame->Arguments) {
8568
0
          VD = CurrFrame->Arguments.getOrigParam(PVD);
8569
0
          Frame =
8570
0
              Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8571
0
          Version = CurrFrame->Arguments.Version;
8572
0
        }
8573
0
      } else {
8574
0
        Frame = CurrFrame;
8575
0
        Version = CurrFrame->getCurrentTemporaryVersion(VD);
8576
0
      }
8577
0
    }
8578
0
  }
8579
8580
9
  if (!VD->getType()->isReferenceType()) {
8581
9
    if (Frame) {
8582
0
      Result.set({VD, Frame->Index, Version});
8583
0
      return true;
8584
0
    }
8585
9
    return Success(VD);
8586
9
  }
8587
8588
0
  if (!Info.getLangOpts().CPlusPlus11) {
8589
0
    Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8590
0
        << VD << VD->getType();
8591
0
    Info.Note(VD->getLocation(), diag::note_declared_at);
8592
0
  }
8593
8594
0
  APValue *V;
8595
0
  if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8596
0
    return false;
8597
0
  if (!V->hasValue()) {
8598
    // FIXME: Is it possible for V to be indeterminate here? If so, we should
8599
    // adjust the diagnostic to say that.
8600
0
    if (!Info.checkingPotentialConstantExpression())
8601
0
      Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8602
0
    return false;
8603
0
  }
8604
0
  return Success(*V, E);
8605
0
}
8606
8607
0
bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8608
0
  if (!IsConstantEvaluatedBuiltinCall(E))
8609
0
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
8610
8611
0
  switch (E->getBuiltinCallee()) {
8612
0
  default:
8613
0
    return false;
8614
0
  case Builtin::BIas_const:
8615
0
  case Builtin::BIforward:
8616
0
  case Builtin::BIforward_like:
8617
0
  case Builtin::BImove:
8618
0
  case Builtin::BImove_if_noexcept:
8619
0
    if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8620
0
      return Visit(E->getArg(0));
8621
0
    break;
8622
0
  }
8623
8624
0
  return ExprEvaluatorBaseTy::VisitCallExpr(E);
8625
0
}
8626
8627
bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8628
0
    const MaterializeTemporaryExpr *E) {
8629
  // Walk through the expression to find the materialized temporary itself.
8630
0
  SmallVector<const Expr *, 2> CommaLHSs;
8631
0
  SmallVector<SubobjectAdjustment, 2> Adjustments;
8632
0
  const Expr *Inner =
8633
0
      E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8634
8635
  // If we passed any comma operators, evaluate their LHSs.
8636
0
  for (const Expr *E : CommaLHSs)
8637
0
    if (!EvaluateIgnoredValue(Info, E))
8638
0
      return false;
8639
8640
  // A materialized temporary with static storage duration can appear within the
8641
  // result of a constant expression evaluation, so we need to preserve its
8642
  // value for use outside this evaluation.
8643
0
  APValue *Value;
8644
0
  if (E->getStorageDuration() == SD_Static) {
8645
0
    if (Info.EvalMode == EvalInfo::EM_ConstantFold)
8646
0
      return false;
8647
    // FIXME: What about SD_Thread?
8648
0
    Value = E->getOrCreateValue(true);
8649
0
    *Value = APValue();
8650
0
    Result.set(E);
8651
0
  } else {
8652
0
    Value = &Info.CurrentCall->createTemporary(
8653
0
        E, Inner->getType(),
8654
0
        E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8655
0
                                                     : ScopeKind::Block,
8656
0
        Result);
8657
0
  }
8658
8659
0
  QualType Type = Inner->getType();
8660
8661
  // Materialize the temporary itself.
8662
0
  if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8663
0
    *Value = APValue();
8664
0
    return false;
8665
0
  }
8666
8667
  // Adjust our lvalue to refer to the desired subobject.
8668
0
  for (unsigned I = Adjustments.size(); I != 0; /**/) {
8669
0
    --I;
8670
0
    switch (Adjustments[I].Kind) {
8671
0
    case SubobjectAdjustment::DerivedToBaseAdjustment:
8672
0
      if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8673
0
                                Type, Result))
8674
0
        return false;
8675
0
      Type = Adjustments[I].DerivedToBase.BasePath->getType();
8676
0
      break;
8677
8678
0
    case SubobjectAdjustment::FieldAdjustment:
8679
0
      if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8680
0
        return false;
8681
0
      Type = Adjustments[I].Field->getType();
8682
0
      break;
8683
8684
0
    case SubobjectAdjustment::MemberPointerAdjustment:
8685
0
      if (!HandleMemberPointerAccess(this->Info, Type, Result,
8686
0
                                     Adjustments[I].Ptr.RHS))
8687
0
        return false;
8688
0
      Type = Adjustments[I].Ptr.MPT->getPointeeType();
8689
0
      break;
8690
0
    }
8691
0
  }
8692
8693
0
  return true;
8694
0
}
8695
8696
bool
8697
0
LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8698
0
  assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8699
0
         "lvalue compound literal in c++?");
8700
  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8701
  // only see this when folding in C, so there's no standard to follow here.
8702
0
  return Success(E);
8703
0
}
8704
8705
0
bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8706
0
  TypeInfoLValue TypeInfo;
8707
8708
0
  if (!E->isPotentiallyEvaluated()) {
8709
0
    if (E->isTypeOperand())
8710
0
      TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8711
0
    else
8712
0
      TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8713
0
  } else {
8714
0
    if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8715
0
      Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8716
0
        << E->getExprOperand()->getType()
8717
0
        << E->getExprOperand()->getSourceRange();
8718
0
    }
8719
8720
0
    if (!Visit(E->getExprOperand()))
8721
0
      return false;
8722
8723
0
    std::optional<DynamicType> DynType =
8724
0
        ComputeDynamicType(Info, E, Result, AK_TypeId);
8725
0
    if (!DynType)
8726
0
      return false;
8727
8728
0
    TypeInfo =
8729
0
        TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8730
0
  }
8731
8732
0
  return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8733
0
}
8734
8735
0
bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8736
0
  return Success(E->getGuidDecl());
8737
0
}
8738
8739
0
bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8740
  // Handle static data members.
8741
0
  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8742
0
    VisitIgnoredBaseExpression(E->getBase());
8743
0
    return VisitVarDecl(E, VD);
8744
0
  }
8745
8746
  // Handle static member functions.
8747
0
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8748
0
    if (MD->isStatic()) {
8749
0
      VisitIgnoredBaseExpression(E->getBase());
8750
0
      return Success(MD);
8751
0
    }
8752
0
  }
8753
8754
  // Handle non-static data members.
8755
0
  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8756
0
}
8757
8758
0
bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8759
  // FIXME: Deal with vectors as array subscript bases.
8760
0
  if (E->getBase()->getType()->isVectorType() ||
8761
0
      E->getBase()->getType()->isSveVLSBuiltinType())
8762
0
    return Error(E);
8763
8764
0
  APSInt Index;
8765
0
  bool Success = true;
8766
8767
  // C++17's rules require us to evaluate the LHS first, regardless of which
8768
  // side is the base.
8769
0
  for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8770
0
    if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8771
0
                                : !EvaluateInteger(SubExpr, Index, Info)) {
8772
0
      if (!Info.noteFailure())
8773
0
        return false;
8774
0
      Success = false;
8775
0
    }
8776
0
  }
8777
8778
0
  return Success &&
8779
0
         HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8780
0
}
8781
8782
0
bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8783
0
  return evaluatePointer(E->getSubExpr(), Result);
8784
0
}
8785
8786
0
bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8787
0
  if (!Visit(E->getSubExpr()))
8788
0
    return false;
8789
  // __real is a no-op on scalar lvalues.
8790
0
  if (E->getSubExpr()->getType()->isAnyComplexType())
8791
0
    HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8792
0
  return true;
8793
0
}
8794
8795
0
bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8796
0
  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8797
0
         "lvalue __imag__ on scalar?");
8798
0
  if (!Visit(E->getSubExpr()))
8799
0
    return false;
8800
0
  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8801
0
  return true;
8802
0
}
8803
8804
0
bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8805
0
  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8806
0
    return Error(UO);
8807
8808
0
  if (!this->Visit(UO->getSubExpr()))
8809
0
    return false;
8810
8811
0
  return handleIncDec(
8812
0
      this->Info, UO, Result, UO->getSubExpr()->getType(),
8813
0
      UO->isIncrementOp(), nullptr);
8814
0
}
8815
8816
bool LValueExprEvaluator::VisitCompoundAssignOperator(
8817
0
    const CompoundAssignOperator *CAO) {
8818
0
  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8819
0
    return Error(CAO);
8820
8821
0
  bool Success = true;
8822
8823
  // C++17 onwards require that we evaluate the RHS first.
8824
0
  APValue RHS;
8825
0
  if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8826
0
    if (!Info.noteFailure())
8827
0
      return false;
8828
0
    Success = false;
8829
0
  }
8830
8831
  // The overall lvalue result is the result of evaluating the LHS.
8832
0
  if (!this->Visit(CAO->getLHS()) || !Success)
8833
0
    return false;
8834
8835
0
  return handleCompoundAssignment(
8836
0
      this->Info, CAO,
8837
0
      Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8838
0
      CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8839
0
}
8840
8841
0
bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8842
0
  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8843
0
    return Error(E);
8844
8845
0
  bool Success = true;
8846
8847
  // C++17 onwards require that we evaluate the RHS first.
8848
0
  APValue NewVal;
8849
0
  if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8850
0
    if (!Info.noteFailure())
8851
0
      return false;
8852
0
    Success = false;
8853
0
  }
8854
8855
0
  if (!this->Visit(E->getLHS()) || !Success)
8856
0
    return false;
8857
8858
0
  if (Info.getLangOpts().CPlusPlus20 &&
8859
0
      !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8860
0
    return false;
8861
8862
0
  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8863
0
                          NewVal);
8864
0
}
8865
8866
//===----------------------------------------------------------------------===//
8867
// Pointer Evaluation
8868
//===----------------------------------------------------------------------===//
8869
8870
/// Attempts to compute the number of bytes available at the pointer
8871
/// returned by a function with the alloc_size attribute. Returns true if we
8872
/// were successful. Places an unsigned number into `Result`.
8873
///
8874
/// This expects the given CallExpr to be a call to a function with an
8875
/// alloc_size attribute.
8876
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8877
                                            const CallExpr *Call,
8878
0
                                            llvm::APInt &Result) {
8879
0
  const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8880
8881
0
  assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8882
0
  unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8883
0
  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8884
0
  if (Call->getNumArgs() <= SizeArgNo)
8885
0
    return false;
8886
8887
0
  auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8888
0
    Expr::EvalResult ExprResult;
8889
0
    if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8890
0
      return false;
8891
0
    Into = ExprResult.Val.getInt();
8892
0
    if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8893
0
      return false;
8894
0
    Into = Into.zext(BitsInSizeT);
8895
0
    return true;
8896
0
  };
8897
8898
0
  APSInt SizeOfElem;
8899
0
  if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8900
0
    return false;
8901
8902
0
  if (!AllocSize->getNumElemsParam().isValid()) {
8903
0
    Result = std::move(SizeOfElem);
8904
0
    return true;
8905
0
  }
8906
8907
0
  APSInt NumberOfElems;
8908
0
  unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8909
0
  if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8910
0
    return false;
8911
8912
0
  bool Overflow;
8913
0
  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8914
0
  if (Overflow)
8915
0
    return false;
8916
8917
0
  Result = std::move(BytesAvailable);
8918
0
  return true;
8919
0
}
8920
8921
/// Convenience function. LVal's base must be a call to an alloc_size
8922
/// function.
8923
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8924
                                            const LValue &LVal,
8925
0
                                            llvm::APInt &Result) {
8926
0
  assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8927
0
         "Can't get the size of a non alloc_size function");
8928
0
  const auto *Base = LVal.getLValueBase().get<const Expr *>();
8929
0
  const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8930
0
  return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8931
0
}
8932
8933
/// Attempts to evaluate the given LValueBase as the result of a call to
8934
/// a function with the alloc_size attribute. If it was possible to do so, this
8935
/// function will return true, make Result's Base point to said function call,
8936
/// and mark Result's Base as invalid.
8937
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8938
0
                                      LValue &Result) {
8939
0
  if (Base.isNull())
8940
0
    return false;
8941
8942
  // Because we do no form of static analysis, we only support const variables.
8943
  //
8944
  // Additionally, we can't support parameters, nor can we support static
8945
  // variables (in the latter case, use-before-assign isn't UB; in the former,
8946
  // we have no clue what they'll be assigned to).
8947
0
  const auto *VD =
8948
0
      dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8949
0
  if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8950
0
    return false;
8951
8952
0
  const Expr *Init = VD->getAnyInitializer();
8953
0
  if (!Init || Init->getType().isNull())
8954
0
    return false;
8955
8956
0
  const Expr *E = Init->IgnoreParens();
8957
0
  if (!tryUnwrapAllocSizeCall(E))
8958
0
    return false;
8959
8960
  // Store E instead of E unwrapped so that the type of the LValue's base is
8961
  // what the user wanted.
8962
0
  Result.setInvalid(E);
8963
8964
0
  QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8965
0
  Result.addUnsizedArray(Info, E, Pointee);
8966
0
  return true;
8967
0
}
8968
8969
namespace {
8970
class PointerExprEvaluator
8971
  : public ExprEvaluatorBase<PointerExprEvaluator> {
8972
  LValue &Result;
8973
  bool InvalidBaseOK;
8974
8975
0
  bool Success(const Expr *E) {
8976
0
    Result.set(E);
8977
0
    return true;
8978
0
  }
8979
8980
0
  bool evaluateLValue(const Expr *E, LValue &Result) {
8981
0
    return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8982
0
  }
8983
8984
0
  bool evaluatePointer(const Expr *E, LValue &Result) {
8985
0
    return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8986
0
  }
8987
8988
  bool visitNonBuiltinCallExpr(const CallExpr *E);
8989
public:
8990
8991
  PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8992
      : ExprEvaluatorBaseTy(info), Result(Result),
8993
1
        InvalidBaseOK(InvalidBaseOK) {}
8994
8995
0
  bool Success(const APValue &V, const Expr *E) {
8996
0
    Result.setFrom(Info.Ctx, V);
8997
0
    return true;
8998
0
  }
8999
0
  bool ZeroInitialization(const Expr *E) {
9000
0
    Result.setNull(Info.Ctx, E->getType());
9001
0
    return true;
9002
0
  }
9003
9004
  bool VisitBinaryOperator(const BinaryOperator *E);
9005
  bool VisitCastExpr(const CastExpr* E);
9006
  bool VisitUnaryAddrOf(const UnaryOperator *E);
9007
  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9008
0
      { return Success(E); }
9009
0
  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9010
0
    if (E->isExpressibleAsConstantInitializer())
9011
0
      return Success(E);
9012
0
    if (Info.noteFailure())
9013
0
      EvaluateIgnoredValue(Info, E->getSubExpr());
9014
0
    return Error(E);
9015
0
  }
9016
  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9017
0
      { return Success(E); }
9018
  bool VisitCallExpr(const CallExpr *E);
9019
  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9020
0
  bool VisitBlockExpr(const BlockExpr *E) {
9021
0
    if (!E->getBlockDecl()->hasCaptures())
9022
0
      return Success(E);
9023
0
    return Error(E);
9024
0
  }
9025
0
  bool VisitCXXThisExpr(const CXXThisExpr *E) {
9026
    // Can't look at 'this' when checking a potential constant expression.
9027
0
    if (Info.checkingPotentialConstantExpression())
9028
0
      return false;
9029
0
    if (!Info.CurrentCall->This) {
9030
0
      if (Info.getLangOpts().CPlusPlus11)
9031
0
        Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9032
0
      else
9033
0
        Info.FFDiag(E);
9034
0
      return false;
9035
0
    }
9036
0
    Result = *Info.CurrentCall->This;
9037
9038
0
    if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9039
      // Ensure we actually have captured 'this'. If something was wrong with
9040
      // 'this' capture, the error would have been previously reported.
9041
      // Otherwise we can be inside of a default initialization of an object
9042
      // declared by lambda's body, so no need to return false.
9043
0
      if (!Info.CurrentCall->LambdaThisCaptureField)
9044
0
        return true;
9045
9046
      // If we have captured 'this',  the 'this' expression refers
9047
      // to the enclosing '*this' object (either by value or reference) which is
9048
      // either copied into the closure object's field that represents the
9049
      // '*this' or refers to '*this'.
9050
      // Update 'Result' to refer to the data member/field of the closure object
9051
      // that represents the '*this' capture.
9052
0
      if (!HandleLValueMember(Info, E, Result,
9053
0
                             Info.CurrentCall->LambdaThisCaptureField))
9054
0
        return false;
9055
      // If we captured '*this' by reference, replace the field with its referent.
9056
0
      if (Info.CurrentCall->LambdaThisCaptureField->getType()
9057
0
              ->isPointerType()) {
9058
0
        APValue RVal;
9059
0
        if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
9060
0
                                            RVal))
9061
0
          return false;
9062
9063
0
        Result.setFrom(Info.Ctx, RVal);
9064
0
      }
9065
0
    }
9066
0
    return true;
9067
0
  }
9068
9069
  bool VisitCXXNewExpr(const CXXNewExpr *E);
9070
9071
0
  bool VisitSourceLocExpr(const SourceLocExpr *E) {
9072
0
    assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9073
0
    APValue LValResult = E->EvaluateInContext(
9074
0
        Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9075
0
    Result.setFrom(Info.Ctx, LValResult);
9076
0
    return true;
9077
0
  }
9078
9079
0
  bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9080
0
    std::string ResultStr = E->ComputeName(Info.Ctx);
9081
9082
0
    QualType CharTy = Info.Ctx.CharTy.withConst();
9083
0
    APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9084
0
               ResultStr.size() + 1);
9085
0
    QualType ArrayTy = Info.Ctx.getConstantArrayType(
9086
0
        CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9087
9088
0
    StringLiteral *SL =
9089
0
        StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9090
0
                              /*Pascal*/ false, ArrayTy, E->getLocation());
9091
9092
0
    evaluateLValue(SL, Result);
9093
0
    Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9094
0
    return true;
9095
0
  }
9096
9097
  // FIXME: Missing: @protocol, @selector
9098
};
9099
} // end anonymous namespace
9100
9101
static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9102
1
                            bool InvalidBaseOK) {
9103
1
  assert(!E->isValueDependent());
9104
0
  assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9105
0
  return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9106
1
}
9107
9108
0
bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9109
0
  if (E->getOpcode() != BO_Add &&
9110
0
      E->getOpcode() != BO_Sub)
9111
0
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9112
9113
0
  const Expr *PExp = E->getLHS();
9114
0
  const Expr *IExp = E->getRHS();
9115
0
  if (IExp->getType()->isPointerType())
9116
0
    std::swap(PExp, IExp);
9117
9118
0
  bool EvalPtrOK = evaluatePointer(PExp, Result);
9119
0
  if (!EvalPtrOK && !Info.noteFailure())
9120
0
    return false;
9121
9122
0
  llvm::APSInt Offset;
9123
0
  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9124
0
    return false;
9125
9126
0
  if (E->getOpcode() == BO_Sub)
9127
0
    negateAsSigned(Offset);
9128
9129
0
  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9130
0
  return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9131
0
}
9132
9133
0
bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9134
0
  return evaluateLValue(E->getSubExpr(), Result);
9135
0
}
9136
9137
// Is the provided decl 'std::source_location::current'?
9138
0
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
9139
0
  if (!FD)
9140
0
    return false;
9141
0
  const IdentifierInfo *FnII = FD->getIdentifier();
9142
0
  if (!FnII || !FnII->isStr("current"))
9143
0
    return false;
9144
9145
0
  const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9146
0
  if (!RD)
9147
0
    return false;
9148
9149
0
  const IdentifierInfo *ClassII = RD->getIdentifier();
9150
0
  return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9151
0
}
9152
9153
1
bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9154
1
  const Expr *SubExpr = E->getSubExpr();
9155
9156
1
  switch (E->getCastKind()) {
9157
0
  default:
9158
0
    break;
9159
0
  case CK_BitCast:
9160
0
  case CK_CPointerToObjCPointerCast:
9161
0
  case CK_BlockPointerToObjCPointerCast:
9162
0
  case CK_AnyPointerToBlockPointerCast:
9163
0
  case CK_AddressSpaceConversion:
9164
0
    if (!Visit(SubExpr))
9165
0
      return false;
9166
    // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9167
    // permitted in constant expressions in C++11. Bitcasts from cv void* are
9168
    // also static_casts, but we disallow them as a resolution to DR1312.
9169
0
    if (!E->getType()->isVoidPointerType()) {
9170
      // In some circumstances, we permit casting from void* to cv1 T*, when the
9171
      // actual pointee object is actually a cv2 T.
9172
0
      bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9173
0
                            !Result.IsNullPtr;
9174
0
      bool VoidPtrCastMaybeOK =
9175
0
          HasValidResult &&
9176
0
          Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
9177
0
                                          E->getType()->getPointeeType());
9178
      // 1. We'll allow it in std::allocator::allocate, and anything which that
9179
      //    calls.
9180
      // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9181
      //    <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9182
      //    We'll allow it in the body of std::source_location::current.  GCC's
9183
      //    implementation had a parameter of type `void*`, and casts from
9184
      //    that back to `const __impl*` in its body.
9185
0
      if (VoidPtrCastMaybeOK &&
9186
0
          (Info.getStdAllocatorCaller("allocate") ||
9187
0
           IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9188
0
           Info.getLangOpts().CPlusPlus26)) {
9189
        // Permitted.
9190
0
      } else {
9191
0
        if (SubExpr->getType()->isVoidPointerType()) {
9192
0
          if (HasValidResult)
9193
0
            CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9194
0
                << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9195
0
                << Result.Designator.getType(Info.Ctx).getCanonicalType()
9196
0
                << E->getType()->getPointeeType();
9197
0
          else
9198
0
            CCEDiag(E, diag::note_constexpr_invalid_cast)
9199
0
                << 3 << SubExpr->getType();
9200
0
        } else
9201
0
          CCEDiag(E, diag::note_constexpr_invalid_cast)
9202
0
              << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9203
0
        Result.Designator.setInvalid();
9204
0
      }
9205
0
    }
9206
0
    if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9207
0
      ZeroInitialization(E);
9208
0
    return true;
9209
9210
0
  case CK_DerivedToBase:
9211
0
  case CK_UncheckedDerivedToBase:
9212
0
    if (!evaluatePointer(E->getSubExpr(), Result))
9213
0
      return false;
9214
0
    if (!Result.Base && Result.Offset.isZero())
9215
0
      return true;
9216
9217
    // Now figure out the necessary offset to add to the base LV to get from
9218
    // the derived class to the base class.
9219
0
    return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9220
0
                                  castAs<PointerType>()->getPointeeType(),
9221
0
                                Result);
9222
9223
0
  case CK_BaseToDerived:
9224
0
    if (!Visit(E->getSubExpr()))
9225
0
      return false;
9226
0
    if (!Result.Base && Result.Offset.isZero())
9227
0
      return true;
9228
0
    return HandleBaseToDerivedCast(Info, E, Result);
9229
9230
0
  case CK_Dynamic:
9231
0
    if (!Visit(E->getSubExpr()))
9232
0
      return false;
9233
0
    return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9234
9235
0
  case CK_NullToPointer:
9236
0
    VisitIgnoredValue(E->getSubExpr());
9237
0
    return ZeroInitialization(E);
9238
9239
1
  case CK_IntegralToPointer: {
9240
1
    CCEDiag(E, diag::note_constexpr_invalid_cast)
9241
1
        << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9242
9243
1
    APValue Value;
9244
1
    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9245
1
      break;
9246
9247
0
    if (Value.isInt()) {
9248
0
      unsigned Size = Info.Ctx.getTypeSize(E->getType());
9249
0
      uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9250
0
      Result.Base = (Expr*)nullptr;
9251
0
      Result.InvalidBase = false;
9252
0
      Result.Offset = CharUnits::fromQuantity(N);
9253
0
      Result.Designator.setInvalid();
9254
0
      Result.IsNullPtr = false;
9255
0
      return true;
9256
0
    } else {
9257
      // Cast is of an lvalue, no need to change value.
9258
0
      Result.setFrom(Info.Ctx, Value);
9259
0
      return true;
9260
0
    }
9261
0
  }
9262
9263
0
  case CK_ArrayToPointerDecay: {
9264
0
    if (SubExpr->isGLValue()) {
9265
0
      if (!evaluateLValue(SubExpr, Result))
9266
0
        return false;
9267
0
    } else {
9268
0
      APValue &Value = Info.CurrentCall->createTemporary(
9269
0
          SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9270
0
      if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9271
0
        return false;
9272
0
    }
9273
    // The result is a pointer to the first element of the array.
9274
0
    auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9275
0
    if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9276
0
      Result.addArray(Info, E, CAT);
9277
0
    else
9278
0
      Result.addUnsizedArray(Info, E, AT->getElementType());
9279
0
    return true;
9280
0
  }
9281
9282
0
  case CK_FunctionToPointerDecay:
9283
0
    return evaluateLValue(SubExpr, Result);
9284
9285
0
  case CK_LValueToRValue: {
9286
0
    LValue LVal;
9287
0
    if (!evaluateLValue(E->getSubExpr(), LVal))
9288
0
      return false;
9289
9290
0
    APValue RVal;
9291
    // Note, we use the subexpression's type in order to retain cv-qualifiers.
9292
0
    if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9293
0
                                        LVal, RVal))
9294
0
      return InvalidBaseOK &&
9295
0
             evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9296
0
    return Success(RVal, E);
9297
0
  }
9298
1
  }
9299
9300
1
  return ExprEvaluatorBaseTy::VisitCastExpr(E);
9301
1
}
9302
9303
static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9304
0
                                UnaryExprOrTypeTrait ExprKind) {
9305
  // C++ [expr.alignof]p3:
9306
  //     When alignof is applied to a reference type, the result is the
9307
  //     alignment of the referenced type.
9308
0
  T = T.getNonReferenceType();
9309
9310
0
  if (T.getQualifiers().hasUnaligned())
9311
0
    return CharUnits::One();
9312
9313
0
  const bool AlignOfReturnsPreferred =
9314
0
      Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9315
9316
  // __alignof is defined to return the preferred alignment.
9317
  // Before 8, clang returned the preferred alignment for alignof and _Alignof
9318
  // as well.
9319
0
  if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9320
0
    return Info.Ctx.toCharUnitsFromBits(
9321
0
      Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9322
  // alignof and _Alignof are defined to return the ABI alignment.
9323
0
  else if (ExprKind == UETT_AlignOf)
9324
0
    return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9325
0
  else
9326
0
    llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9327
0
}
9328
9329
static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9330
0
                                UnaryExprOrTypeTrait ExprKind) {
9331
0
  E = E->IgnoreParens();
9332
9333
  // The kinds of expressions that we have special-case logic here for
9334
  // should be kept up to date with the special checks for those
9335
  // expressions in Sema.
9336
9337
  // alignof decl is always accepted, even if it doesn't make sense: we default
9338
  // to 1 in those cases.
9339
0
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9340
0
    return Info.Ctx.getDeclAlign(DRE->getDecl(),
9341
0
                                 /*RefAsPointee*/true);
9342
9343
0
  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9344
0
    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9345
0
                                 /*RefAsPointee*/true);
9346
9347
0
  return GetAlignOfType(Info, E->getType(), ExprKind);
9348
0
}
9349
9350
0
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9351
0
  if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9352
0
    return Info.Ctx.getDeclAlign(VD);
9353
0
  if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9354
0
    return GetAlignOfExpr(Info, E, UETT_AlignOf);
9355
0
  return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9356
0
}
9357
9358
/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9359
/// __builtin_is_aligned and __builtin_assume_aligned.
9360
static bool getAlignmentArgument(const Expr *E, QualType ForType,
9361
0
                                 EvalInfo &Info, APSInt &Alignment) {
9362
0
  if (!EvaluateInteger(E, Alignment, Info))
9363
0
    return false;
9364
0
  if (Alignment < 0 || !Alignment.isPowerOf2()) {
9365
0
    Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9366
0
    return false;
9367
0
  }
9368
0
  unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9369
0
  APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9370
0
  if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9371
0
    Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9372
0
        << MaxValue << ForType << Alignment;
9373
0
    return false;
9374
0
  }
9375
  // Ensure both alignment and source value have the same bit width so that we
9376
  // don't assert when computing the resulting value.
9377
0
  APSInt ExtAlignment =
9378
0
      APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9379
0
  assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9380
0
         "Alignment should not be changed by ext/trunc");
9381
0
  Alignment = ExtAlignment;
9382
0
  assert(Alignment.getBitWidth() == SrcWidth);
9383
0
  return true;
9384
0
}
9385
9386
// To be clear: this happily visits unsupported builtins. Better name welcomed.
9387
0
bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9388
0
  if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9389
0
    return true;
9390
9391
0
  if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9392
0
    return false;
9393
9394
0
  Result.setInvalid(E);
9395
0
  QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9396
0
  Result.addUnsizedArray(Info, E, PointeeTy);
9397
0
  return true;
9398
0
}
9399
9400
0
bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9401
0
  if (!IsConstantEvaluatedBuiltinCall(E))
9402
0
    return visitNonBuiltinCallExpr(E);
9403
0
  return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9404
0
}
9405
9406
// Determine if T is a character type for which we guarantee that
9407
// sizeof(T) == 1.
9408
0
static bool isOneByteCharacterType(QualType T) {
9409
0
  return T->isCharType() || T->isChar8Type();
9410
0
}
9411
9412
bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9413
0
                                                unsigned BuiltinOp) {
9414
0
  if (IsNoOpCall(E))
9415
0
    return Success(E);
9416
9417
0
  switch (BuiltinOp) {
9418
0
  case Builtin::BIaddressof:
9419
0
  case Builtin::BI__addressof:
9420
0
  case Builtin::BI__builtin_addressof:
9421
0
    return evaluateLValue(E->getArg(0), Result);
9422
0
  case Builtin::BI__builtin_assume_aligned: {
9423
    // We need to be very careful here because: if the pointer does not have the
9424
    // asserted alignment, then the behavior is undefined, and undefined
9425
    // behavior is non-constant.
9426
0
    if (!evaluatePointer(E->getArg(0), Result))
9427
0
      return false;
9428
9429
0
    LValue OffsetResult(Result);
9430
0
    APSInt Alignment;
9431
0
    if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9432
0
                              Alignment))
9433
0
      return false;
9434
0
    CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9435
9436
0
    if (E->getNumArgs() > 2) {
9437
0
      APSInt Offset;
9438
0
      if (!EvaluateInteger(E->getArg(2), Offset, Info))
9439
0
        return false;
9440
9441
0
      int64_t AdditionalOffset = -Offset.getZExtValue();
9442
0
      OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9443
0
    }
9444
9445
    // If there is a base object, then it must have the correct alignment.
9446
0
    if (OffsetResult.Base) {
9447
0
      CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9448
9449
0
      if (BaseAlignment < Align) {
9450
0
        Result.Designator.setInvalid();
9451
        // FIXME: Add support to Diagnostic for long / long long.
9452
0
        CCEDiag(E->getArg(0),
9453
0
                diag::note_constexpr_baa_insufficient_alignment) << 0
9454
0
          << (unsigned)BaseAlignment.getQuantity()
9455
0
          << (unsigned)Align.getQuantity();
9456
0
        return false;
9457
0
      }
9458
0
    }
9459
9460
    // The offset must also have the correct alignment.
9461
0
    if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9462
0
      Result.Designator.setInvalid();
9463
9464
0
      (OffsetResult.Base
9465
0
           ? CCEDiag(E->getArg(0),
9466
0
                     diag::note_constexpr_baa_insufficient_alignment) << 1
9467
0
           : CCEDiag(E->getArg(0),
9468
0
                     diag::note_constexpr_baa_value_insufficient_alignment))
9469
0
        << (int)OffsetResult.Offset.getQuantity()
9470
0
        << (unsigned)Align.getQuantity();
9471
0
      return false;
9472
0
    }
9473
9474
0
    return true;
9475
0
  }
9476
0
  case Builtin::BI__builtin_align_up:
9477
0
  case Builtin::BI__builtin_align_down: {
9478
0
    if (!evaluatePointer(E->getArg(0), Result))
9479
0
      return false;
9480
0
    APSInt Alignment;
9481
0
    if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9482
0
                              Alignment))
9483
0
      return false;
9484
0
    CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9485
0
    CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9486
    // For align_up/align_down, we can return the same value if the alignment
9487
    // is known to be greater or equal to the requested value.
9488
0
    if (PtrAlign.getQuantity() >= Alignment)
9489
0
      return true;
9490
9491
    // The alignment could be greater than the minimum at run-time, so we cannot
9492
    // infer much about the resulting pointer value. One case is possible:
9493
    // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9494
    // can infer the correct index if the requested alignment is smaller than
9495
    // the base alignment so we can perform the computation on the offset.
9496
0
    if (BaseAlignment.getQuantity() >= Alignment) {
9497
0
      assert(Alignment.getBitWidth() <= 64 &&
9498
0
             "Cannot handle > 64-bit address-space");
9499
0
      uint64_t Alignment64 = Alignment.getZExtValue();
9500
0
      CharUnits NewOffset = CharUnits::fromQuantity(
9501
0
          BuiltinOp == Builtin::BI__builtin_align_down
9502
0
              ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9503
0
              : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9504
0
      Result.adjustOffset(NewOffset - Result.Offset);
9505
      // TODO: diagnose out-of-bounds values/only allow for arrays?
9506
0
      return true;
9507
0
    }
9508
    // Otherwise, we cannot constant-evaluate the result.
9509
0
    Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9510
0
        << Alignment;
9511
0
    return false;
9512
0
  }
9513
0
  case Builtin::BI__builtin_operator_new:
9514
0
    return HandleOperatorNewCall(Info, E, Result);
9515
0
  case Builtin::BI__builtin_launder:
9516
0
    return evaluatePointer(E->getArg(0), Result);
9517
0
  case Builtin::BIstrchr:
9518
0
  case Builtin::BIwcschr:
9519
0
  case Builtin::BImemchr:
9520
0
  case Builtin::BIwmemchr:
9521
0
    if (Info.getLangOpts().CPlusPlus11)
9522
0
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9523
0
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9524
0
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9525
0
    else
9526
0
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9527
0
    [[fallthrough]];
9528
0
  case Builtin::BI__builtin_strchr:
9529
0
  case Builtin::BI__builtin_wcschr:
9530
0
  case Builtin::BI__builtin_memchr:
9531
0
  case Builtin::BI__builtin_char_memchr:
9532
0
  case Builtin::BI__builtin_wmemchr: {
9533
0
    if (!Visit(E->getArg(0)))
9534
0
      return false;
9535
0
    APSInt Desired;
9536
0
    if (!EvaluateInteger(E->getArg(1), Desired, Info))
9537
0
      return false;
9538
0
    uint64_t MaxLength = uint64_t(-1);
9539
0
    if (BuiltinOp != Builtin::BIstrchr &&
9540
0
        BuiltinOp != Builtin::BIwcschr &&
9541
0
        BuiltinOp != Builtin::BI__builtin_strchr &&
9542
0
        BuiltinOp != Builtin::BI__builtin_wcschr) {
9543
0
      APSInt N;
9544
0
      if (!EvaluateInteger(E->getArg(2), N, Info))
9545
0
        return false;
9546
0
      MaxLength = N.getZExtValue();
9547
0
    }
9548
    // We cannot find the value if there are no candidates to match against.
9549
0
    if (MaxLength == 0u)
9550
0
      return ZeroInitialization(E);
9551
0
    if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9552
0
        Result.Designator.Invalid)
9553
0
      return false;
9554
0
    QualType CharTy = Result.Designator.getType(Info.Ctx);
9555
0
    bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9556
0
                     BuiltinOp == Builtin::BI__builtin_memchr;
9557
0
    assert(IsRawByte ||
9558
0
           Info.Ctx.hasSameUnqualifiedType(
9559
0
               CharTy, E->getArg(0)->getType()->getPointeeType()));
9560
    // Pointers to const void may point to objects of incomplete type.
9561
0
    if (IsRawByte && CharTy->isIncompleteType()) {
9562
0
      Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9563
0
      return false;
9564
0
    }
9565
    // Give up on byte-oriented matching against multibyte elements.
9566
    // FIXME: We can compare the bytes in the correct order.
9567
0
    if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9568
0
      Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9569
0
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9570
0
          << CharTy;
9571
0
      return false;
9572
0
    }
9573
    // Figure out what value we're actually looking for (after converting to
9574
    // the corresponding unsigned type if necessary).
9575
0
    uint64_t DesiredVal;
9576
0
    bool StopAtNull = false;
9577
0
    switch (BuiltinOp) {
9578
0
    case Builtin::BIstrchr:
9579
0
    case Builtin::BI__builtin_strchr:
9580
      // strchr compares directly to the passed integer, and therefore
9581
      // always fails if given an int that is not a char.
9582
0
      if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9583
0
                                                  E->getArg(1)->getType(),
9584
0
                                                  Desired),
9585
0
                               Desired))
9586
0
        return ZeroInitialization(E);
9587
0
      StopAtNull = true;
9588
0
      [[fallthrough]];
9589
0
    case Builtin::BImemchr:
9590
0
    case Builtin::BI__builtin_memchr:
9591
0
    case Builtin::BI__builtin_char_memchr:
9592
      // memchr compares by converting both sides to unsigned char. That's also
9593
      // correct for strchr if we get this far (to cope with plain char being
9594
      // unsigned in the strchr case).
9595
0
      DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9596
0
      break;
9597
9598
0
    case Builtin::BIwcschr:
9599
0
    case Builtin::BI__builtin_wcschr:
9600
0
      StopAtNull = true;
9601
0
      [[fallthrough]];
9602
0
    case Builtin::BIwmemchr:
9603
0
    case Builtin::BI__builtin_wmemchr:
9604
      // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9605
0
      DesiredVal = Desired.getZExtValue();
9606
0
      break;
9607
0
    }
9608
9609
0
    for (; MaxLength; --MaxLength) {
9610
0
      APValue Char;
9611
0
      if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9612
0
          !Char.isInt())
9613
0
        return false;
9614
0
      if (Char.getInt().getZExtValue() == DesiredVal)
9615
0
        return true;
9616
0
      if (StopAtNull && !Char.getInt())
9617
0
        break;
9618
0
      if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9619
0
        return false;
9620
0
    }
9621
    // Not found: return nullptr.
9622
0
    return ZeroInitialization(E);
9623
0
  }
9624
9625
0
  case Builtin::BImemcpy:
9626
0
  case Builtin::BImemmove:
9627
0
  case Builtin::BIwmemcpy:
9628
0
  case Builtin::BIwmemmove:
9629
0
    if (Info.getLangOpts().CPlusPlus11)
9630
0
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9631
0
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9632
0
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9633
0
    else
9634
0
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9635
0
    [[fallthrough]];
9636
0
  case Builtin::BI__builtin_memcpy:
9637
0
  case Builtin::BI__builtin_memmove:
9638
0
  case Builtin::BI__builtin_wmemcpy:
9639
0
  case Builtin::BI__builtin_wmemmove: {
9640
0
    bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9641
0
                 BuiltinOp == Builtin::BIwmemmove ||
9642
0
                 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9643
0
                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9644
0
    bool Move = BuiltinOp == Builtin::BImemmove ||
9645
0
                BuiltinOp == Builtin::BIwmemmove ||
9646
0
                BuiltinOp == Builtin::BI__builtin_memmove ||
9647
0
                BuiltinOp == Builtin::BI__builtin_wmemmove;
9648
9649
    // The result of mem* is the first argument.
9650
0
    if (!Visit(E->getArg(0)))
9651
0
      return false;
9652
0
    LValue Dest = Result;
9653
9654
0
    LValue Src;
9655
0
    if (!EvaluatePointer(E->getArg(1), Src, Info))
9656
0
      return false;
9657
9658
0
    APSInt N;
9659
0
    if (!EvaluateInteger(E->getArg(2), N, Info))
9660
0
      return false;
9661
0
    assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9662
9663
    // If the size is zero, we treat this as always being a valid no-op.
9664
    // (Even if one of the src and dest pointers is null.)
9665
0
    if (!N)
9666
0
      return true;
9667
9668
    // Otherwise, if either of the operands is null, we can't proceed. Don't
9669
    // try to determine the type of the copied objects, because there aren't
9670
    // any.
9671
0
    if (!Src.Base || !Dest.Base) {
9672
0
      APValue Val;
9673
0
      (!Src.Base ? Src : Dest).moveInto(Val);
9674
0
      Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9675
0
          << Move << WChar << !!Src.Base
9676
0
          << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9677
0
      return false;
9678
0
    }
9679
0
    if (Src.Designator.Invalid || Dest.Designator.Invalid)
9680
0
      return false;
9681
9682
    // We require that Src and Dest are both pointers to arrays of
9683
    // trivially-copyable type. (For the wide version, the designator will be
9684
    // invalid if the designated object is not a wchar_t.)
9685
0
    QualType T = Dest.Designator.getType(Info.Ctx);
9686
0
    QualType SrcT = Src.Designator.getType(Info.Ctx);
9687
0
    if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9688
      // FIXME: Consider using our bit_cast implementation to support this.
9689
0
      Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9690
0
      return false;
9691
0
    }
9692
0
    if (T->isIncompleteType()) {
9693
0
      Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9694
0
      return false;
9695
0
    }
9696
0
    if (!T.isTriviallyCopyableType(Info.Ctx)) {
9697
0
      Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9698
0
      return false;
9699
0
    }
9700
9701
    // Figure out how many T's we're copying.
9702
0
    uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9703
0
    if (TSize == 0)
9704
0
      return false;
9705
0
    if (!WChar) {
9706
0
      uint64_t Remainder;
9707
0
      llvm::APInt OrigN = N;
9708
0
      llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9709
0
      if (Remainder) {
9710
0
        Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9711
0
            << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9712
0
            << (unsigned)TSize;
9713
0
        return false;
9714
0
      }
9715
0
    }
9716
9717
    // Check that the copying will remain within the arrays, just so that we
9718
    // can give a more meaningful diagnostic. This implicitly also checks that
9719
    // N fits into 64 bits.
9720
0
    uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9721
0
    uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9722
0
    if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9723
0
      Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9724
0
          << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9725
0
          << toString(N, 10, /*Signed*/false);
9726
0
      return false;
9727
0
    }
9728
0
    uint64_t NElems = N.getZExtValue();
9729
0
    uint64_t NBytes = NElems * TSize;
9730
9731
    // Check for overlap.
9732
0
    int Direction = 1;
9733
0
    if (HasSameBase(Src, Dest)) {
9734
0
      uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9735
0
      uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9736
0
      if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9737
        // Dest is inside the source region.
9738
0
        if (!Move) {
9739
0
          Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9740
0
          return false;
9741
0
        }
9742
        // For memmove and friends, copy backwards.
9743
0
        if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9744
0
            !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9745
0
          return false;
9746
0
        Direction = -1;
9747
0
      } else if (!Move && SrcOffset >= DestOffset &&
9748
0
                 SrcOffset - DestOffset < NBytes) {
9749
        // Src is inside the destination region for memcpy: invalid.
9750
0
        Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9751
0
        return false;
9752
0
      }
9753
0
    }
9754
9755
0
    while (true) {
9756
0
      APValue Val;
9757
      // FIXME: Set WantObjectRepresentation to true if we're copying a
9758
      // char-like type?
9759
0
      if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9760
0
          !handleAssignment(Info, E, Dest, T, Val))
9761
0
        return false;
9762
      // Do not iterate past the last element; if we're copying backwards, that
9763
      // might take us off the start of the array.
9764
0
      if (--NElems == 0)
9765
0
        return true;
9766
0
      if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9767
0
          !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9768
0
        return false;
9769
0
    }
9770
0
  }
9771
9772
0
  default:
9773
0
    return false;
9774
0
  }
9775
0
}
9776
9777
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9778
                                     APValue &Result, const InitListExpr *ILE,
9779
                                     QualType AllocType);
9780
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9781
                                          APValue &Result,
9782
                                          const CXXConstructExpr *CCE,
9783
                                          QualType AllocType);
9784
9785
0
bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9786
0
  if (!Info.getLangOpts().CPlusPlus20)
9787
0
    Info.CCEDiag(E, diag::note_constexpr_new);
9788
9789
  // We cannot speculatively evaluate a delete expression.
9790
0
  if (Info.SpeculativeEvaluationDepth)
9791
0
    return false;
9792
9793
0
  FunctionDecl *OperatorNew = E->getOperatorNew();
9794
9795
0
  bool IsNothrow = false;
9796
0
  bool IsPlacement = false;
9797
0
  if (OperatorNew->isReservedGlobalPlacementOperator() &&
9798
0
      Info.CurrentCall->isStdFunction() && !E->isArray()) {
9799
    // FIXME Support array placement new.
9800
0
    assert(E->getNumPlacementArgs() == 1);
9801
0
    if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9802
0
      return false;
9803
0
    if (Result.Designator.Invalid)
9804
0
      return false;
9805
0
    IsPlacement = true;
9806
0
  } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9807
0
    Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9808
0
        << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9809
0
    return false;
9810
0
  } else if (E->getNumPlacementArgs()) {
9811
    // The only new-placement list we support is of the form (std::nothrow).
9812
    //
9813
    // FIXME: There is no restriction on this, but it's not clear that any
9814
    // other form makes any sense. We get here for cases such as:
9815
    //
9816
    //   new (std::align_val_t{N}) X(int)
9817
    //
9818
    // (which should presumably be valid only if N is a multiple of
9819
    // alignof(int), and in any case can't be deallocated unless N is
9820
    // alignof(X) and X has new-extended alignment).
9821
0
    if (E->getNumPlacementArgs() != 1 ||
9822
0
        !E->getPlacementArg(0)->getType()->isNothrowT())
9823
0
      return Error(E, diag::note_constexpr_new_placement);
9824
9825
0
    LValue Nothrow;
9826
0
    if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9827
0
      return false;
9828
0
    IsNothrow = true;
9829
0
  }
9830
9831
0
  const Expr *Init = E->getInitializer();
9832
0
  const InitListExpr *ResizedArrayILE = nullptr;
9833
0
  const CXXConstructExpr *ResizedArrayCCE = nullptr;
9834
0
  bool ValueInit = false;
9835
9836
0
  QualType AllocType = E->getAllocatedType();
9837
0
  if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9838
0
    const Expr *Stripped = *ArraySize;
9839
0
    for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9840
0
         Stripped = ICE->getSubExpr())
9841
0
      if (ICE->getCastKind() != CK_NoOp &&
9842
0
          ICE->getCastKind() != CK_IntegralCast)
9843
0
        break;
9844
9845
0
    llvm::APSInt ArrayBound;
9846
0
    if (!EvaluateInteger(Stripped, ArrayBound, Info))
9847
0
      return false;
9848
9849
    // C++ [expr.new]p9:
9850
    //   The expression is erroneous if:
9851
    //   -- [...] its value before converting to size_t [or] applying the
9852
    //      second standard conversion sequence is less than zero
9853
0
    if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9854
0
      if (IsNothrow)
9855
0
        return ZeroInitialization(E);
9856
9857
0
      Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9858
0
          << ArrayBound << (*ArraySize)->getSourceRange();
9859
0
      return false;
9860
0
    }
9861
9862
    //   -- its value is such that the size of the allocated object would
9863
    //      exceed the implementation-defined limit
9864
0
    if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
9865
0
                             ConstantArrayType::getNumAddressingBits(
9866
0
                                 Info.Ctx, AllocType, ArrayBound),
9867
0
                             ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
9868
0
      if (IsNothrow)
9869
0
        return ZeroInitialization(E);
9870
0
      return false;
9871
0
    }
9872
9873
    //   -- the new-initializer is a braced-init-list and the number of
9874
    //      array elements for which initializers are provided [...]
9875
    //      exceeds the number of elements to initialize
9876
0
    if (!Init) {
9877
      // No initialization is performed.
9878
0
    } else if (isa<CXXScalarValueInitExpr>(Init) ||
9879
0
               isa<ImplicitValueInitExpr>(Init)) {
9880
0
      ValueInit = true;
9881
0
    } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9882
0
      ResizedArrayCCE = CCE;
9883
0
    } else {
9884
0
      auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9885
0
      assert(CAT && "unexpected type for array initializer");
9886
9887
0
      unsigned Bits =
9888
0
          std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9889
0
      llvm::APInt InitBound = CAT->getSize().zext(Bits);
9890
0
      llvm::APInt AllocBound = ArrayBound.zext(Bits);
9891
0
      if (InitBound.ugt(AllocBound)) {
9892
0
        if (IsNothrow)
9893
0
          return ZeroInitialization(E);
9894
9895
0
        Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9896
0
            << toString(AllocBound, 10, /*Signed=*/false)
9897
0
            << toString(InitBound, 10, /*Signed=*/false)
9898
0
            << (*ArraySize)->getSourceRange();
9899
0
        return false;
9900
0
      }
9901
9902
      // If the sizes differ, we must have an initializer list, and we need
9903
      // special handling for this case when we initialize.
9904
0
      if (InitBound != AllocBound)
9905
0
        ResizedArrayILE = cast<InitListExpr>(Init);
9906
0
    }
9907
9908
0
    AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9909
0
                                              ArraySizeModifier::Normal, 0);
9910
0
  } else {
9911
0
    assert(!AllocType->isArrayType() &&
9912
0
           "array allocation with non-array new");
9913
0
  }
9914
9915
0
  APValue *Val;
9916
0
  if (IsPlacement) {
9917
0
    AccessKinds AK = AK_Construct;
9918
0
    struct FindObjectHandler {
9919
0
      EvalInfo &Info;
9920
0
      const Expr *E;
9921
0
      QualType AllocType;
9922
0
      const AccessKinds AccessKind;
9923
0
      APValue *Value;
9924
9925
0
      typedef bool result_type;
9926
0
      bool failed() { return false; }
9927
0
      bool found(APValue &Subobj, QualType SubobjType) {
9928
        // FIXME: Reject the cases where [basic.life]p8 would not permit the
9929
        // old name of the object to be used to name the new object.
9930
0
        if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9931
0
          Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9932
0
            SubobjType << AllocType;
9933
0
          return false;
9934
0
        }
9935
0
        Value = &Subobj;
9936
0
        return true;
9937
0
      }
9938
0
      bool found(APSInt &Value, QualType SubobjType) {
9939
0
        Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9940
0
        return false;
9941
0
      }
9942
0
      bool found(APFloat &Value, QualType SubobjType) {
9943
0
        Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9944
0
        return false;
9945
0
      }
9946
0
    } Handler = {Info, E, AllocType, AK, nullptr};
9947
9948
0
    CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9949
0
    if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9950
0
      return false;
9951
9952
0
    Val = Handler.Value;
9953
9954
    // [basic.life]p1:
9955
    //   The lifetime of an object o of type T ends when [...] the storage
9956
    //   which the object occupies is [...] reused by an object that is not
9957
    //   nested within o (6.6.2).
9958
0
    *Val = APValue();
9959
0
  } else {
9960
    // Perform the allocation and obtain a pointer to the resulting object.
9961
0
    Val = Info.createHeapAlloc(E, AllocType, Result);
9962
0
    if (!Val)
9963
0
      return false;
9964
0
  }
9965
9966
0
  if (ValueInit) {
9967
0
    ImplicitValueInitExpr VIE(AllocType);
9968
0
    if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9969
0
      return false;
9970
0
  } else if (ResizedArrayILE) {
9971
0
    if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9972
0
                                  AllocType))
9973
0
      return false;
9974
0
  } else if (ResizedArrayCCE) {
9975
0
    if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9976
0
                                       AllocType))
9977
0
      return false;
9978
0
  } else if (Init) {
9979
0
    if (!EvaluateInPlace(*Val, Info, Result, Init))
9980
0
      return false;
9981
0
  } else if (!handleDefaultInitValue(AllocType, *Val)) {
9982
0
    return false;
9983
0
  }
9984
9985
  // Array new returns a pointer to the first element, not a pointer to the
9986
  // array.
9987
0
  if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9988
0
    Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9989
9990
0
  return true;
9991
0
}
9992
//===----------------------------------------------------------------------===//
9993
// Member Pointer Evaluation
9994
//===----------------------------------------------------------------------===//
9995
9996
namespace {
9997
class MemberPointerExprEvaluator
9998
  : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9999
  MemberPtr &Result;
10000
10001
0
  bool Success(const ValueDecl *D) {
10002
0
    Result = MemberPtr(D);
10003
0
    return true;
10004
0
  }
10005
public:
10006
10007
  MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10008
0
    : ExprEvaluatorBaseTy(Info), Result(Result) {}
10009
10010
0
  bool Success(const APValue &V, const Expr *E) {
10011
0
    Result.setFrom(V);
10012
0
    return true;
10013
0
  }
10014
0
  bool ZeroInitialization(const Expr *E) {
10015
0
    return Success((const ValueDecl*)nullptr);
10016
0
  }
10017
10018
  bool VisitCastExpr(const CastExpr *E);
10019
  bool VisitUnaryAddrOf(const UnaryOperator *E);
10020
};
10021
} // end anonymous namespace
10022
10023
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10024
0
                                  EvalInfo &Info) {
10025
0
  assert(!E->isValueDependent());
10026
0
  assert(E->isPRValue() && E->getType()->isMemberPointerType());
10027
0
  return MemberPointerExprEvaluator(Info, Result).Visit(E);
10028
0
}
10029
10030
0
bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10031
0
  switch (E->getCastKind()) {
10032
0
  default:
10033
0
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
10034
10035
0
  case CK_NullToMemberPointer:
10036
0
    VisitIgnoredValue(E->getSubExpr());
10037
0
    return ZeroInitialization(E);
10038
10039
0
  case CK_BaseToDerivedMemberPointer: {
10040
0
    if (!Visit(E->getSubExpr()))
10041
0
      return false;
10042
0
    if (E->path_empty())
10043
0
      return true;
10044
    // Base-to-derived member pointer casts store the path in derived-to-base
10045
    // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10046
    // the wrong end of the derived->base arc, so stagger the path by one class.
10047
0
    typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10048
0
    for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10049
0
         PathI != PathE; ++PathI) {
10050
0
      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10051
0
      const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10052
0
      if (!Result.castToDerived(Derived))
10053
0
        return Error(E);
10054
0
    }
10055
0
    const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10056
0
    if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10057
0
      return Error(E);
10058
0
    return true;
10059
0
  }
10060
10061
0
  case CK_DerivedToBaseMemberPointer:
10062
0
    if (!Visit(E->getSubExpr()))
10063
0
      return false;
10064
0
    for (CastExpr::path_const_iterator PathI = E->path_begin(),
10065
0
         PathE = E->path_end(); PathI != PathE; ++PathI) {
10066
0
      assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10067
0
      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10068
0
      if (!Result.castToBase(Base))
10069
0
        return Error(E);
10070
0
    }
10071
0
    return true;
10072
0
  }
10073
0
}
10074
10075
0
bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10076
  // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10077
  // member can be formed.
10078
0
  return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10079
0
}
10080
10081
//===----------------------------------------------------------------------===//
10082
// Record Evaluation
10083
//===----------------------------------------------------------------------===//
10084
10085
namespace {
10086
  class RecordExprEvaluator
10087
  : public ExprEvaluatorBase<RecordExprEvaluator> {
10088
    const LValue &This;
10089
    APValue &Result;
10090
  public:
10091
10092
    RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10093
0
      : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10094
10095
0
    bool Success(const APValue &V, const Expr *E) {
10096
0
      Result = V;
10097
0
      return true;
10098
0
    }
10099
0
    bool ZeroInitialization(const Expr *E) {
10100
0
      return ZeroInitialization(E, E->getType());
10101
0
    }
10102
    bool ZeroInitialization(const Expr *E, QualType T);
10103
10104
0
    bool VisitCallExpr(const CallExpr *E) {
10105
0
      return handleCallExpr(E, Result, &This);
10106
0
    }
10107
    bool VisitCastExpr(const CastExpr *E);
10108
    bool VisitInitListExpr(const InitListExpr *E);
10109
0
    bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10110
0
      return VisitCXXConstructExpr(E, E->getType());
10111
0
    }
10112
    bool VisitLambdaExpr(const LambdaExpr *E);
10113
    bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10114
    bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10115
    bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10116
    bool VisitBinCmp(const BinaryOperator *E);
10117
    bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10118
    bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10119
                                         ArrayRef<Expr *> Args);
10120
  };
10121
}
10122
10123
/// Perform zero-initialization on an object of non-union class type.
10124
/// C++11 [dcl.init]p5:
10125
///  To zero-initialize an object or reference of type T means:
10126
///    [...]
10127
///    -- if T is a (possibly cv-qualified) non-union class type,
10128
///       each non-static data member and each base-class subobject is
10129
///       zero-initialized
10130
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10131
                                          const RecordDecl *RD,
10132
0
                                          const LValue &This, APValue &Result) {
10133
0
  assert(!RD->isUnion() && "Expected non-union class type");
10134
0
  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10135
0
  Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10136
0
                   std::distance(RD->field_begin(), RD->field_end()));
10137
10138
0
  if (RD->isInvalidDecl()) return false;
10139
0
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10140
10141
0
  if (CD) {
10142
0
    unsigned Index = 0;
10143
0
    for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10144
0
           End = CD->bases_end(); I != End; ++I, ++Index) {
10145
0
      const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10146
0
      LValue Subobject = This;
10147
0
      if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10148
0
        return false;
10149
0
      if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10150
0
                                         Result.getStructBase(Index)))
10151
0
        return false;
10152
0
    }
10153
0
  }
10154
10155
0
  for (const auto *I : RD->fields()) {
10156
    // -- if T is a reference type, no initialization is performed.
10157
0
    if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
10158
0
      continue;
10159
10160
0
    LValue Subobject = This;
10161
0
    if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10162
0
      return false;
10163
10164
0
    ImplicitValueInitExpr VIE(I->getType());
10165
0
    if (!EvaluateInPlace(
10166
0
          Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10167
0
      return false;
10168
0
  }
10169
10170
0
  return true;
10171
0
}
10172
10173
0
bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10174
0
  const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10175
0
  if (RD->isInvalidDecl()) return false;
10176
0
  if (RD->isUnion()) {
10177
    // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10178
    // object's first non-static named data member is zero-initialized
10179
0
    RecordDecl::field_iterator I = RD->field_begin();
10180
0
    while (I != RD->field_end() && (*I)->isUnnamedBitfield())
10181
0
      ++I;
10182
0
    if (I == RD->field_end()) {
10183
0
      Result = APValue((const FieldDecl*)nullptr);
10184
0
      return true;
10185
0
    }
10186
10187
0
    LValue Subobject = This;
10188
0
    if (!HandleLValueMember(Info, E, Subobject, *I))
10189
0
      return false;
10190
0
    Result = APValue(*I);
10191
0
    ImplicitValueInitExpr VIE(I->getType());
10192
0
    return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10193
0
  }
10194
10195
0
  if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10196
0
    Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10197
0
    return false;
10198
0
  }
10199
10200
0
  return HandleClassZeroInitialization(Info, E, RD, This, Result);
10201
0
}
10202
10203
0
bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10204
0
  switch (E->getCastKind()) {
10205
0
  default:
10206
0
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
10207
10208
0
  case CK_ConstructorConversion:
10209
0
    return Visit(E->getSubExpr());
10210
10211
0
  case CK_DerivedToBase:
10212
0
  case CK_UncheckedDerivedToBase: {
10213
0
    APValue DerivedObject;
10214
0
    if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10215
0
      return false;
10216
0
    if (!DerivedObject.isStruct())
10217
0
      return Error(E->getSubExpr());
10218
10219
    // Derived-to-base rvalue conversion: just slice off the derived part.
10220
0
    APValue *Value = &DerivedObject;
10221
0
    const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10222
0
    for (CastExpr::path_const_iterator PathI = E->path_begin(),
10223
0
         PathE = E->path_end(); PathI != PathE; ++PathI) {
10224
0
      assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10225
0
      const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10226
0
      Value = &Value->getStructBase(getBaseIndex(RD, Base));
10227
0
      RD = Base;
10228
0
    }
10229
0
    Result = *Value;
10230
0
    return true;
10231
0
  }
10232
0
  }
10233
0
}
10234
10235
0
bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10236
0
  if (E->isTransparent())
10237
0
    return Visit(E->getInit(0));
10238
0
  return VisitCXXParenListOrInitListExpr(E, E->inits());
10239
0
}
10240
10241
bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10242
0
    const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10243
0
  const RecordDecl *RD =
10244
0
      ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10245
0
  if (RD->isInvalidDecl()) return false;
10246
0
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10247
0
  auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10248
10249
0
  EvalInfo::EvaluatingConstructorRAII EvalObj(
10250
0
      Info,
10251
0
      ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10252
0
      CXXRD && CXXRD->getNumBases());
10253
10254
0
  if (RD->isUnion()) {
10255
0
    const FieldDecl *Field;
10256
0
    if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10257
0
      Field = ILE->getInitializedFieldInUnion();
10258
0
    } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10259
0
      Field = PLIE->getInitializedFieldInUnion();
10260
0
    } else {
10261
0
      llvm_unreachable(
10262
0
          "Expression is neither an init list nor a C++ paren list");
10263
0
    }
10264
10265
0
    Result = APValue(Field);
10266
0
    if (!Field)
10267
0
      return true;
10268
10269
    // If the initializer list for a union does not contain any elements, the
10270
    // first element of the union is value-initialized.
10271
    // FIXME: The element should be initialized from an initializer list.
10272
    //        Is this difference ever observable for initializer lists which
10273
    //        we don't build?
10274
0
    ImplicitValueInitExpr VIE(Field->getType());
10275
0
    const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10276
10277
0
    LValue Subobject = This;
10278
0
    if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10279
0
      return false;
10280
10281
    // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10282
0
    ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10283
0
                                  isa<CXXDefaultInitExpr>(InitExpr));
10284
10285
0
    if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10286
0
      if (Field->isBitField())
10287
0
        return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10288
0
                                     Field);
10289
0
      return true;
10290
0
    }
10291
10292
0
    return false;
10293
0
  }
10294
10295
0
  if (!Result.hasValue())
10296
0
    Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10297
0
                     std::distance(RD->field_begin(), RD->field_end()));
10298
0
  unsigned ElementNo = 0;
10299
0
  bool Success = true;
10300
10301
  // Initialize base classes.
10302
0
  if (CXXRD && CXXRD->getNumBases()) {
10303
0
    for (const auto &Base : CXXRD->bases()) {
10304
0
      assert(ElementNo < Args.size() && "missing init for base class");
10305
0
      const Expr *Init = Args[ElementNo];
10306
10307
0
      LValue Subobject = This;
10308
0
      if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10309
0
        return false;
10310
10311
0
      APValue &FieldVal = Result.getStructBase(ElementNo);
10312
0
      if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10313
0
        if (!Info.noteFailure())
10314
0
          return false;
10315
0
        Success = false;
10316
0
      }
10317
0
      ++ElementNo;
10318
0
    }
10319
10320
0
    EvalObj.finishedConstructingBases();
10321
0
  }
10322
10323
  // Initialize members.
10324
0
  for (const auto *Field : RD->fields()) {
10325
    // Anonymous bit-fields are not considered members of the class for
10326
    // purposes of aggregate initialization.
10327
0
    if (Field->isUnnamedBitfield())
10328
0
      continue;
10329
10330
0
    LValue Subobject = This;
10331
10332
0
    bool HaveInit = ElementNo < Args.size();
10333
10334
    // FIXME: Diagnostics here should point to the end of the initializer
10335
    // list, not the start.
10336
0
    if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10337
0
                            Subobject, Field, &Layout))
10338
0
      return false;
10339
10340
    // Perform an implicit value-initialization for members beyond the end of
10341
    // the initializer list.
10342
0
    ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10343
0
    const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10344
10345
0
    if (Field->getType()->isIncompleteArrayType()) {
10346
0
      if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10347
0
        if (!CAT->getSize().isZero()) {
10348
          // Bail out for now. This might sort of "work", but the rest of the
10349
          // code isn't really prepared to handle it.
10350
0
          Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10351
0
          return false;
10352
0
        }
10353
0
      }
10354
0
    }
10355
10356
    // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10357
0
    ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10358
0
                                  isa<CXXDefaultInitExpr>(Init));
10359
10360
0
    APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10361
0
    if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10362
0
        (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10363
0
                                                       FieldVal, Field))) {
10364
0
      if (!Info.noteFailure())
10365
0
        return false;
10366
0
      Success = false;
10367
0
    }
10368
0
  }
10369
10370
0
  EvalObj.finishedConstructingFields();
10371
10372
0
  return Success;
10373
0
}
10374
10375
bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10376
0
                                                QualType T) {
10377
  // Note that E's type is not necessarily the type of our class here; we might
10378
  // be initializing an array element instead.
10379
0
  const CXXConstructorDecl *FD = E->getConstructor();
10380
0
  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10381
10382
0
  bool ZeroInit = E->requiresZeroInitialization();
10383
0
  if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10384
    // If we've already performed zero-initialization, we're already done.
10385
0
    if (Result.hasValue())
10386
0
      return true;
10387
10388
0
    if (ZeroInit)
10389
0
      return ZeroInitialization(E, T);
10390
10391
0
    return handleDefaultInitValue(T, Result);
10392
0
  }
10393
10394
0
  const FunctionDecl *Definition = nullptr;
10395
0
  auto Body = FD->getBody(Definition);
10396
10397
0
  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10398
0
    return false;
10399
10400
  // Avoid materializing a temporary for an elidable copy/move constructor.
10401
0
  if (E->isElidable() && !ZeroInit) {
10402
    // FIXME: This only handles the simplest case, where the source object
10403
    //        is passed directly as the first argument to the constructor.
10404
    //        This should also handle stepping though implicit casts and
10405
    //        and conversion sequences which involve two steps, with a
10406
    //        conversion operator followed by a converting constructor.
10407
0
    const Expr *SrcObj = E->getArg(0);
10408
0
    assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10409
0
    assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10410
0
    if (const MaterializeTemporaryExpr *ME =
10411
0
            dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10412
0
      return Visit(ME->getSubExpr());
10413
0
  }
10414
10415
0
  if (ZeroInit && !ZeroInitialization(E, T))
10416
0
    return false;
10417
10418
0
  auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10419
0
  return HandleConstructorCall(E, This, Args,
10420
0
                               cast<CXXConstructorDecl>(Definition), Info,
10421
0
                               Result);
10422
0
}
10423
10424
bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10425
0
    const CXXInheritedCtorInitExpr *E) {
10426
0
  if (!Info.CurrentCall) {
10427
0
    assert(Info.checkingPotentialConstantExpression());
10428
0
    return false;
10429
0
  }
10430
10431
0
  const CXXConstructorDecl *FD = E->getConstructor();
10432
0
  if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10433
0
    return false;
10434
10435
0
  const FunctionDecl *Definition = nullptr;
10436
0
  auto Body = FD->getBody(Definition);
10437
10438
0
  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10439
0
    return false;
10440
10441
0
  return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10442
0
                               cast<CXXConstructorDecl>(Definition), Info,
10443
0
                               Result);
10444
0
}
10445
10446
bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10447
0
    const CXXStdInitializerListExpr *E) {
10448
0
  const ConstantArrayType *ArrayType =
10449
0
      Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10450
10451
0
  LValue Array;
10452
0
  if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10453
0
    return false;
10454
10455
0
  assert(ArrayType && "unexpected type for array initializer");
10456
10457
  // Get a pointer to the first element of the array.
10458
0
  Array.addArray(Info, E, ArrayType);
10459
10460
0
  auto InvalidType = [&] {
10461
0
    Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10462
0
      << E->getType();
10463
0
    return false;
10464
0
  };
10465
10466
  // FIXME: Perform the checks on the field types in SemaInit.
10467
0
  RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10468
0
  RecordDecl::field_iterator Field = Record->field_begin();
10469
0
  if (Field == Record->field_end())
10470
0
    return InvalidType();
10471
10472
  // Start pointer.
10473
0
  if (!Field->getType()->isPointerType() ||
10474
0
      !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10475
0
                            ArrayType->getElementType()))
10476
0
    return InvalidType();
10477
10478
  // FIXME: What if the initializer_list type has base classes, etc?
10479
0
  Result = APValue(APValue::UninitStruct(), 0, 2);
10480
0
  Array.moveInto(Result.getStructField(0));
10481
10482
0
  if (++Field == Record->field_end())
10483
0
    return InvalidType();
10484
10485
0
  if (Field->getType()->isPointerType() &&
10486
0
      Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10487
0
                           ArrayType->getElementType())) {
10488
    // End pointer.
10489
0
    if (!HandleLValueArrayAdjustment(Info, E, Array,
10490
0
                                     ArrayType->getElementType(),
10491
0
                                     ArrayType->getSize().getZExtValue()))
10492
0
      return false;
10493
0
    Array.moveInto(Result.getStructField(1));
10494
0
  } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10495
    // Length.
10496
0
    Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10497
0
  else
10498
0
    return InvalidType();
10499
10500
0
  if (++Field != Record->field_end())
10501
0
    return InvalidType();
10502
10503
0
  return true;
10504
0
}
10505
10506
0
bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10507
0
  const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10508
0
  if (ClosureClass->isInvalidDecl())
10509
0
    return false;
10510
10511
0
  const size_t NumFields =
10512
0
      std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10513
10514
0
  assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10515
0
                                            E->capture_init_end()) &&
10516
0
         "The number of lambda capture initializers should equal the number of "
10517
0
         "fields within the closure type");
10518
10519
0
  Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10520
  // Iterate through all the lambda's closure object's fields and initialize
10521
  // them.
10522
0
  auto *CaptureInitIt = E->capture_init_begin();
10523
0
  bool Success = true;
10524
0
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10525
0
  for (const auto *Field : ClosureClass->fields()) {
10526
0
    assert(CaptureInitIt != E->capture_init_end());
10527
    // Get the initializer for this field
10528
0
    Expr *const CurFieldInit = *CaptureInitIt++;
10529
10530
    // If there is no initializer, either this is a VLA or an error has
10531
    // occurred.
10532
0
    if (!CurFieldInit)
10533
0
      return Error(E);
10534
10535
0
    LValue Subobject = This;
10536
10537
0
    if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10538
0
      return false;
10539
10540
0
    APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10541
0
    if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10542
0
      if (!Info.keepEvaluatingAfterFailure())
10543
0
        return false;
10544
0
      Success = false;
10545
0
    }
10546
0
  }
10547
0
  return Success;
10548
0
}
10549
10550
static bool EvaluateRecord(const Expr *E, const LValue &This,
10551
0
                           APValue &Result, EvalInfo &Info) {
10552
0
  assert(!E->isValueDependent());
10553
0
  assert(E->isPRValue() && E->getType()->isRecordType() &&
10554
0
         "can't evaluate expression as a record rvalue");
10555
0
  return RecordExprEvaluator(Info, This, Result).Visit(E);
10556
0
}
10557
10558
//===----------------------------------------------------------------------===//
10559
// Temporary Evaluation
10560
//
10561
// Temporaries are represented in the AST as rvalues, but generally behave like
10562
// lvalues. The full-object of which the temporary is a subobject is implicitly
10563
// materialized so that a reference can bind to it.
10564
//===----------------------------------------------------------------------===//
10565
namespace {
10566
class TemporaryExprEvaluator
10567
  : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10568
public:
10569
  TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10570
0
    LValueExprEvaluatorBaseTy(Info, Result, false) {}
10571
10572
  /// Visit an expression which constructs the value of this temporary.
10573
0
  bool VisitConstructExpr(const Expr *E) {
10574
0
    APValue &Value = Info.CurrentCall->createTemporary(
10575
0
        E, E->getType(), ScopeKind::FullExpression, Result);
10576
0
    return EvaluateInPlace(Value, Info, Result, E);
10577
0
  }
10578
10579
0
  bool VisitCastExpr(const CastExpr *E) {
10580
0
    switch (E->getCastKind()) {
10581
0
    default:
10582
0
      return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10583
10584
0
    case CK_ConstructorConversion:
10585
0
      return VisitConstructExpr(E->getSubExpr());
10586
0
    }
10587
0
  }
10588
0
  bool VisitInitListExpr(const InitListExpr *E) {
10589
0
    return VisitConstructExpr(E);
10590
0
  }
10591
0
  bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10592
0
    return VisitConstructExpr(E);
10593
0
  }
10594
0
  bool VisitCallExpr(const CallExpr *E) {
10595
0
    return VisitConstructExpr(E);
10596
0
  }
10597
0
  bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10598
0
    return VisitConstructExpr(E);
10599
0
  }
10600
0
  bool VisitLambdaExpr(const LambdaExpr *E) {
10601
0
    return VisitConstructExpr(E);
10602
0
  }
10603
};
10604
} // end anonymous namespace
10605
10606
/// Evaluate an expression of record type as a temporary.
10607
0
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10608
0
  assert(!E->isValueDependent());
10609
0
  assert(E->isPRValue() && E->getType()->isRecordType());
10610
0
  return TemporaryExprEvaluator(Info, Result).Visit(E);
10611
0
}
10612
10613
//===----------------------------------------------------------------------===//
10614
// Vector Evaluation
10615
//===----------------------------------------------------------------------===//
10616
10617
namespace {
10618
  class VectorExprEvaluator
10619
  : public ExprEvaluatorBase<VectorExprEvaluator> {
10620
    APValue &Result;
10621
  public:
10622
10623
    VectorExprEvaluator(EvalInfo &info, APValue &Result)
10624
0
      : ExprEvaluatorBaseTy(info), Result(Result) {}
10625
10626
0
    bool Success(ArrayRef<APValue> V, const Expr *E) {
10627
0
      assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10628
      // FIXME: remove this APValue copy.
10629
0
      Result = APValue(V.data(), V.size());
10630
0
      return true;
10631
0
    }
10632
0
    bool Success(const APValue &V, const Expr *E) {
10633
0
      assert(V.isVector());
10634
0
      Result = V;
10635
0
      return true;
10636
0
    }
10637
    bool ZeroInitialization(const Expr *E);
10638
10639
    bool VisitUnaryReal(const UnaryOperator *E)
10640
0
      { return Visit(E->getSubExpr()); }
10641
    bool VisitCastExpr(const CastExpr* E);
10642
    bool VisitInitListExpr(const InitListExpr *E);
10643
    bool VisitUnaryImag(const UnaryOperator *E);
10644
    bool VisitBinaryOperator(const BinaryOperator *E);
10645
    bool VisitUnaryOperator(const UnaryOperator *E);
10646
    // FIXME: Missing: conditional operator (for GNU
10647
    //                 conditional select), shufflevector, ExtVectorElementExpr
10648
  };
10649
} // end anonymous namespace
10650
10651
0
static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10652
0
  assert(E->isPRValue() && E->getType()->isVectorType() &&
10653
0
         "not a vector prvalue");
10654
0
  return VectorExprEvaluator(Info, Result).Visit(E);
10655
0
}
10656
10657
0
bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10658
0
  const VectorType *VTy = E->getType()->castAs<VectorType>();
10659
0
  unsigned NElts = VTy->getNumElements();
10660
10661
0
  const Expr *SE = E->getSubExpr();
10662
0
  QualType SETy = SE->getType();
10663
10664
0
  switch (E->getCastKind()) {
10665
0
  case CK_VectorSplat: {
10666
0
    APValue Val = APValue();
10667
0
    if (SETy->isIntegerType()) {
10668
0
      APSInt IntResult;
10669
0
      if (!EvaluateInteger(SE, IntResult, Info))
10670
0
        return false;
10671
0
      Val = APValue(std::move(IntResult));
10672
0
    } else if (SETy->isRealFloatingType()) {
10673
0
      APFloat FloatResult(0.0);
10674
0
      if (!EvaluateFloat(SE, FloatResult, Info))
10675
0
        return false;
10676
0
      Val = APValue(std::move(FloatResult));
10677
0
    } else {
10678
0
      return Error(E);
10679
0
    }
10680
10681
    // Splat and create vector APValue.
10682
0
    SmallVector<APValue, 4> Elts(NElts, Val);
10683
0
    return Success(Elts, E);
10684
0
  }
10685
0
  case CK_BitCast: {
10686
0
    APValue SVal;
10687
0
    if (!Evaluate(SVal, Info, SE))
10688
0
      return false;
10689
10690
0
    if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
10691
      // Give up if the input isn't an int, float, or vector.  For example, we
10692
      // reject "(v4i16)(intptr_t)&a".
10693
0
      Info.FFDiag(E, diag::note_constexpr_invalid_cast)
10694
0
          << 2 << Info.Ctx.getLangOpts().CPlusPlus;
10695
0
      return false;
10696
0
    }
10697
10698
0
    if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
10699
0
      return false;
10700
10701
0
    return true;
10702
0
  }
10703
0
  default:
10704
0
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
10705
0
  }
10706
0
}
10707
10708
bool
10709
0
VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10710
0
  const VectorType *VT = E->getType()->castAs<VectorType>();
10711
0
  unsigned NumInits = E->getNumInits();
10712
0
  unsigned NumElements = VT->getNumElements();
10713
10714
0
  QualType EltTy = VT->getElementType();
10715
0
  SmallVector<APValue, 4> Elements;
10716
10717
  // The number of initializers can be less than the number of
10718
  // vector elements. For OpenCL, this can be due to nested vector
10719
  // initialization. For GCC compatibility, missing trailing elements
10720
  // should be initialized with zeroes.
10721
0
  unsigned CountInits = 0, CountElts = 0;
10722
0
  while (CountElts < NumElements) {
10723
    // Handle nested vector initialization.
10724
0
    if (CountInits < NumInits
10725
0
        && E->getInit(CountInits)->getType()->isVectorType()) {
10726
0
      APValue v;
10727
0
      if (!EvaluateVector(E->getInit(CountInits), v, Info))
10728
0
        return Error(E);
10729
0
      unsigned vlen = v.getVectorLength();
10730
0
      for (unsigned j = 0; j < vlen; j++)
10731
0
        Elements.push_back(v.getVectorElt(j));
10732
0
      CountElts += vlen;
10733
0
    } else if (EltTy->isIntegerType()) {
10734
0
      llvm::APSInt sInt(32);
10735
0
      if (CountInits < NumInits) {
10736
0
        if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10737
0
          return false;
10738
0
      } else // trailing integer zero.
10739
0
        sInt = Info.Ctx.MakeIntValue(0, EltTy);
10740
0
      Elements.push_back(APValue(sInt));
10741
0
      CountElts++;
10742
0
    } else {
10743
0
      llvm::APFloat f(0.0);
10744
0
      if (CountInits < NumInits) {
10745
0
        if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10746
0
          return false;
10747
0
      } else // trailing float zero.
10748
0
        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10749
0
      Elements.push_back(APValue(f));
10750
0
      CountElts++;
10751
0
    }
10752
0
    CountInits++;
10753
0
  }
10754
0
  return Success(Elements, E);
10755
0
}
10756
10757
bool
10758
0
VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10759
0
  const auto *VT = E->getType()->castAs<VectorType>();
10760
0
  QualType EltTy = VT->getElementType();
10761
0
  APValue ZeroElement;
10762
0
  if (EltTy->isIntegerType())
10763
0
    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10764
0
  else
10765
0
    ZeroElement =
10766
0
        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10767
10768
0
  SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10769
0
  return Success(Elements, E);
10770
0
}
10771
10772
0
bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10773
0
  VisitIgnoredValue(E->getSubExpr());
10774
0
  return ZeroInitialization(E);
10775
0
}
10776
10777
0
bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10778
0
  BinaryOperatorKind Op = E->getOpcode();
10779
0
  assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10780
0
         "Operation not supported on vector types");
10781
10782
0
  if (Op == BO_Comma)
10783
0
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10784
10785
0
  Expr *LHS = E->getLHS();
10786
0
  Expr *RHS = E->getRHS();
10787
10788
0
  assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10789
0
         "Must both be vector types");
10790
  // Checking JUST the types are the same would be fine, except shifts don't
10791
  // need to have their types be the same (since you always shift by an int).
10792
0
  assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10793
0
             E->getType()->castAs<VectorType>()->getNumElements() &&
10794
0
         RHS->getType()->castAs<VectorType>()->getNumElements() ==
10795
0
             E->getType()->castAs<VectorType>()->getNumElements() &&
10796
0
         "All operands must be the same size.");
10797
10798
0
  APValue LHSValue;
10799
0
  APValue RHSValue;
10800
0
  bool LHSOK = Evaluate(LHSValue, Info, LHS);
10801
0
  if (!LHSOK && !Info.noteFailure())
10802
0
    return false;
10803
0
  if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10804
0
    return false;
10805
10806
0
  if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10807
0
    return false;
10808
10809
0
  return Success(LHSValue, E);
10810
0
}
10811
10812
static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10813
                                                        QualType ResultTy,
10814
                                                        UnaryOperatorKind Op,
10815
0
                                                        APValue Elt) {
10816
0
  switch (Op) {
10817
0
  case UO_Plus:
10818
    // Nothing to do here.
10819
0
    return Elt;
10820
0
  case UO_Minus:
10821
0
    if (Elt.getKind() == APValue::Int) {
10822
0
      Elt.getInt().negate();
10823
0
    } else {
10824
0
      assert(Elt.getKind() == APValue::Float &&
10825
0
             "Vector can only be int or float type");
10826
0
      Elt.getFloat().changeSign();
10827
0
    }
10828
0
    return Elt;
10829
0
  case UO_Not:
10830
    // This is only valid for integral types anyway, so we don't have to handle
10831
    // float here.
10832
0
    assert(Elt.getKind() == APValue::Int &&
10833
0
           "Vector operator ~ can only be int");
10834
0
    Elt.getInt().flipAllBits();
10835
0
    return Elt;
10836
0
  case UO_LNot: {
10837
0
    if (Elt.getKind() == APValue::Int) {
10838
0
      Elt.getInt() = !Elt.getInt();
10839
      // operator ! on vectors returns -1 for 'truth', so negate it.
10840
0
      Elt.getInt().negate();
10841
0
      return Elt;
10842
0
    }
10843
0
    assert(Elt.getKind() == APValue::Float &&
10844
0
           "Vector can only be int or float type");
10845
    // Float types result in an int of the same size, but -1 for true, or 0 for
10846
    // false.
10847
0
    APSInt EltResult{Ctx.getIntWidth(ResultTy),
10848
0
                     ResultTy->isUnsignedIntegerType()};
10849
0
    if (Elt.getFloat().isZero())
10850
0
      EltResult.setAllBits();
10851
0
    else
10852
0
      EltResult.clearAllBits();
10853
10854
0
    return APValue{EltResult};
10855
0
  }
10856
0
  default:
10857
    // FIXME: Implement the rest of the unary operators.
10858
0
    return std::nullopt;
10859
0
  }
10860
0
}
10861
10862
0
bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10863
0
  Expr *SubExpr = E->getSubExpr();
10864
0
  const auto *VD = SubExpr->getType()->castAs<VectorType>();
10865
  // This result element type differs in the case of negating a floating point
10866
  // vector, since the result type is the a vector of the equivilant sized
10867
  // integer.
10868
0
  const QualType ResultEltTy = VD->getElementType();
10869
0
  UnaryOperatorKind Op = E->getOpcode();
10870
10871
0
  APValue SubExprValue;
10872
0
  if (!Evaluate(SubExprValue, Info, SubExpr))
10873
0
    return false;
10874
10875
  // FIXME: This vector evaluator someday needs to be changed to be LValue
10876
  // aware/keep LValue information around, rather than dealing with just vector
10877
  // types directly. Until then, we cannot handle cases where the operand to
10878
  // these unary operators is an LValue. The only case I've been able to see
10879
  // cause this is operator++ assigning to a member expression (only valid in
10880
  // altivec compilations) in C mode, so this shouldn't limit us too much.
10881
0
  if (SubExprValue.isLValue())
10882
0
    return false;
10883
10884
0
  assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10885
0
         "Vector length doesn't match type?");
10886
10887
0
  SmallVector<APValue, 4> ResultElements;
10888
0
  for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10889
0
    std::optional<APValue> Elt = handleVectorUnaryOperator(
10890
0
        Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10891
0
    if (!Elt)
10892
0
      return false;
10893
0
    ResultElements.push_back(*Elt);
10894
0
  }
10895
0
  return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10896
0
}
10897
10898
//===----------------------------------------------------------------------===//
10899
// Array Evaluation
10900
//===----------------------------------------------------------------------===//
10901
10902
namespace {
10903
  class ArrayExprEvaluator
10904
  : public ExprEvaluatorBase<ArrayExprEvaluator> {
10905
    const LValue &This;
10906
    APValue &Result;
10907
  public:
10908
10909
    ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10910
0
      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10911
10912
0
    bool Success(const APValue &V, const Expr *E) {
10913
0
      assert(V.isArray() && "expected array");
10914
0
      Result = V;
10915
0
      return true;
10916
0
    }
10917
10918
0
    bool ZeroInitialization(const Expr *E) {
10919
0
      const ConstantArrayType *CAT =
10920
0
          Info.Ctx.getAsConstantArrayType(E->getType());
10921
0
      if (!CAT) {
10922
0
        if (E->getType()->isIncompleteArrayType()) {
10923
          // We can be asked to zero-initialize a flexible array member; this
10924
          // is represented as an ImplicitValueInitExpr of incomplete array
10925
          // type. In this case, the array has zero elements.
10926
0
          Result = APValue(APValue::UninitArray(), 0, 0);
10927
0
          return true;
10928
0
        }
10929
        // FIXME: We could handle VLAs here.
10930
0
        return Error(E);
10931
0
      }
10932
10933
0
      Result = APValue(APValue::UninitArray(), 0,
10934
0
                       CAT->getSize().getZExtValue());
10935
0
      if (!Result.hasArrayFiller())
10936
0
        return true;
10937
10938
      // Zero-initialize all elements.
10939
0
      LValue Subobject = This;
10940
0
      Subobject.addArray(Info, E, CAT);
10941
0
      ImplicitValueInitExpr VIE(CAT->getElementType());
10942
0
      return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10943
0
    }
10944
10945
0
    bool VisitCallExpr(const CallExpr *E) {
10946
0
      return handleCallExpr(E, Result, &This);
10947
0
    }
10948
    bool VisitInitListExpr(const InitListExpr *E,
10949
                           QualType AllocType = QualType());
10950
    bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10951
    bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10952
    bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10953
                               const LValue &Subobject,
10954
                               APValue *Value, QualType Type);
10955
    bool VisitStringLiteral(const StringLiteral *E,
10956
0
                            QualType AllocType = QualType()) {
10957
0
      expandStringLiteral(Info, E, Result, AllocType);
10958
0
      return true;
10959
0
    }
10960
    bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10961
    bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10962
                                         ArrayRef<Expr *> Args,
10963
                                         const Expr *ArrayFiller,
10964
                                         QualType AllocType = QualType());
10965
  };
10966
} // end anonymous namespace
10967
10968
static bool EvaluateArray(const Expr *E, const LValue &This,
10969
0
                          APValue &Result, EvalInfo &Info) {
10970
0
  assert(!E->isValueDependent());
10971
0
  assert(E->isPRValue() && E->getType()->isArrayType() &&
10972
0
         "not an array prvalue");
10973
0
  return ArrayExprEvaluator(Info, This, Result).Visit(E);
10974
0
}
10975
10976
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10977
                                     APValue &Result, const InitListExpr *ILE,
10978
0
                                     QualType AllocType) {
10979
0
  assert(!ILE->isValueDependent());
10980
0
  assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10981
0
         "not an array prvalue");
10982
0
  return ArrayExprEvaluator(Info, This, Result)
10983
0
      .VisitInitListExpr(ILE, AllocType);
10984
0
}
10985
10986
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10987
                                          APValue &Result,
10988
                                          const CXXConstructExpr *CCE,
10989
0
                                          QualType AllocType) {
10990
0
  assert(!CCE->isValueDependent());
10991
0
  assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10992
0
         "not an array prvalue");
10993
0
  return ArrayExprEvaluator(Info, This, Result)
10994
0
      .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10995
0
}
10996
10997
// Return true iff the given array filler may depend on the element index.
10998
0
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10999
  // For now, just allow non-class value-initialization and initialization
11000
  // lists comprised of them.
11001
0
  if (isa<ImplicitValueInitExpr>(FillerExpr))
11002
0
    return false;
11003
0
  if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11004
0
    for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11005
0
      if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11006
0
        return true;
11007
0
    }
11008
11009
0
    if (ILE->hasArrayFiller() &&
11010
0
        MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11011
0
      return true;
11012
11013
0
    return false;
11014
0
  }
11015
0
  return true;
11016
0
}
11017
11018
bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11019
0
                                           QualType AllocType) {
11020
0
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11021
0
      AllocType.isNull() ? E->getType() : AllocType);
11022
0
  if (!CAT)
11023
0
    return Error(E);
11024
11025
  // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11026
  // an appropriately-typed string literal enclosed in braces.
11027
0
  if (E->isStringLiteralInit()) {
11028
0
    auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11029
    // FIXME: Support ObjCEncodeExpr here once we support it in
11030
    // ArrayExprEvaluator generally.
11031
0
    if (!SL)
11032
0
      return Error(E);
11033
0
    return VisitStringLiteral(SL, AllocType);
11034
0
  }
11035
  // Any other transparent list init will need proper handling of the
11036
  // AllocType; we can't just recurse to the inner initializer.
11037
0
  assert(!E->isTransparent() &&
11038
0
         "transparent array list initialization is not string literal init?");
11039
11040
0
  return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11041
0
                                         AllocType);
11042
0
}
11043
11044
bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11045
    const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11046
0
    QualType AllocType) {
11047
0
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11048
0
      AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11049
11050
0
  bool Success = true;
11051
11052
0
  assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11053
0
         "zero-initialized array shouldn't have any initialized elts");
11054
0
  APValue Filler;
11055
0
  if (Result.isArray() && Result.hasArrayFiller())
11056
0
    Filler = Result.getArrayFiller();
11057
11058
0
  unsigned NumEltsToInit = Args.size();
11059
0
  unsigned NumElts = CAT->getSize().getZExtValue();
11060
11061
  // If the initializer might depend on the array index, run it for each
11062
  // array element.
11063
0
  if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
11064
0
    NumEltsToInit = NumElts;
11065
11066
0
  LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11067
0
                          << NumEltsToInit << ".\n");
11068
11069
0
  Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11070
11071
  // If the array was previously zero-initialized, preserve the
11072
  // zero-initialized values.
11073
0
  if (Filler.hasValue()) {
11074
0
    for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11075
0
      Result.getArrayInitializedElt(I) = Filler;
11076
0
    if (Result.hasArrayFiller())
11077
0
      Result.getArrayFiller() = Filler;
11078
0
  }
11079
11080
0
  LValue Subobject = This;
11081
0
  Subobject.addArray(Info, ExprToVisit, CAT);
11082
0
  for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11083
0
    const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11084
0
    if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11085
0
                         Info, Subobject, Init) ||
11086
0
        !HandleLValueArrayAdjustment(Info, Init, Subobject,
11087
0
                                     CAT->getElementType(), 1)) {
11088
0
      if (!Info.noteFailure())
11089
0
        return false;
11090
0
      Success = false;
11091
0
    }
11092
0
  }
11093
11094
0
  if (!Result.hasArrayFiller())
11095
0
    return Success;
11096
11097
  // If we get here, we have a trivial filler, which we can just evaluate
11098
  // once and splat over the rest of the array elements.
11099
0
  assert(ArrayFiller && "no array filler for incomplete init list");
11100
0
  return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11101
0
                         ArrayFiller) &&
11102
0
         Success;
11103
0
}
11104
11105
0
bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11106
0
  LValue CommonLV;
11107
0
  if (E->getCommonExpr() &&
11108
0
      !Evaluate(Info.CurrentCall->createTemporary(
11109
0
                    E->getCommonExpr(),
11110
0
                    getStorageType(Info.Ctx, E->getCommonExpr()),
11111
0
                    ScopeKind::FullExpression, CommonLV),
11112
0
                Info, E->getCommonExpr()->getSourceExpr()))
11113
0
    return false;
11114
11115
0
  auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11116
11117
0
  uint64_t Elements = CAT->getSize().getZExtValue();
11118
0
  Result = APValue(APValue::UninitArray(), Elements, Elements);
11119
11120
0
  LValue Subobject = This;
11121
0
  Subobject.addArray(Info, E, CAT);
11122
11123
0
  bool Success = true;
11124
0
  for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11125
    // C++ [class.temporary]/5
11126
    // There are four contexts in which temporaries are destroyed at a different
11127
    // point than the end of the full-expression. [...] The second context is
11128
    // when a copy constructor is called to copy an element of an array while
11129
    // the entire array is copied [...]. In either case, if the constructor has
11130
    // one or more default arguments, the destruction of every temporary created
11131
    // in a default argument is sequenced before the construction of the next
11132
    // array element, if any.
11133
0
    FullExpressionRAII Scope(Info);
11134
11135
0
    if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11136
0
                         Info, Subobject, E->getSubExpr()) ||
11137
0
        !HandleLValueArrayAdjustment(Info, E, Subobject,
11138
0
                                     CAT->getElementType(), 1)) {
11139
0
      if (!Info.noteFailure())
11140
0
        return false;
11141
0
      Success = false;
11142
0
    }
11143
11144
    // Make sure we run the destructors too.
11145
0
    Scope.destroy();
11146
0
  }
11147
11148
0
  return Success;
11149
0
}
11150
11151
0
bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11152
0
  return VisitCXXConstructExpr(E, This, &Result, E->getType());
11153
0
}
11154
11155
bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11156
                                               const LValue &Subobject,
11157
                                               APValue *Value,
11158
0
                                               QualType Type) {
11159
0
  bool HadZeroInit = Value->hasValue();
11160
11161
0
  if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11162
0
    unsigned FinalSize = CAT->getSize().getZExtValue();
11163
11164
    // Preserve the array filler if we had prior zero-initialization.
11165
0
    APValue Filler =
11166
0
      HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11167
0
                                             : APValue();
11168
11169
0
    *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11170
0
    if (FinalSize == 0)
11171
0
      return true;
11172
11173
0
    bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11174
0
        Info, E->getExprLoc(), E->getConstructor(),
11175
0
        E->requiresZeroInitialization());
11176
0
    LValue ArrayElt = Subobject;
11177
0
    ArrayElt.addArray(Info, E, CAT);
11178
    // We do the whole initialization in two passes, first for just one element,
11179
    // then for the whole array. It's possible we may find out we can't do const
11180
    // init in the first pass, in which case we avoid allocating a potentially
11181
    // large array. We don't do more passes because expanding array requires
11182
    // copying the data, which is wasteful.
11183
0
    for (const unsigned N : {1u, FinalSize}) {
11184
0
      unsigned OldElts = Value->getArrayInitializedElts();
11185
0
      if (OldElts == N)
11186
0
        break;
11187
11188
      // Expand the array to appropriate size.
11189
0
      APValue NewValue(APValue::UninitArray(), N, FinalSize);
11190
0
      for (unsigned I = 0; I < OldElts; ++I)
11191
0
        NewValue.getArrayInitializedElt(I).swap(
11192
0
            Value->getArrayInitializedElt(I));
11193
0
      Value->swap(NewValue);
11194
11195
0
      if (HadZeroInit)
11196
0
        for (unsigned I = OldElts; I < N; ++I)
11197
0
          Value->getArrayInitializedElt(I) = Filler;
11198
11199
0
      if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11200
        // If we have a trivial constructor, only evaluate it once and copy
11201
        // the result into all the array elements.
11202
0
        APValue &FirstResult = Value->getArrayInitializedElt(0);
11203
0
        for (unsigned I = OldElts; I < FinalSize; ++I)
11204
0
          Value->getArrayInitializedElt(I) = FirstResult;
11205
0
      } else {
11206
0
        for (unsigned I = OldElts; I < N; ++I) {
11207
0
          if (!VisitCXXConstructExpr(E, ArrayElt,
11208
0
                                     &Value->getArrayInitializedElt(I),
11209
0
                                     CAT->getElementType()) ||
11210
0
              !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11211
0
                                           CAT->getElementType(), 1))
11212
0
            return false;
11213
          // When checking for const initilization any diagnostic is considered
11214
          // an error.
11215
0
          if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11216
0
              !Info.keepEvaluatingAfterFailure())
11217
0
            return false;
11218
0
        }
11219
0
      }
11220
0
    }
11221
11222
0
    return true;
11223
0
  }
11224
11225
0
  if (!Type->isRecordType())
11226
0
    return Error(E);
11227
11228
0
  return RecordExprEvaluator(Info, Subobject, *Value)
11229
0
             .VisitCXXConstructExpr(E, Type);
11230
0
}
11231
11232
bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11233
0
    const CXXParenListInitExpr *E) {
11234
0
  assert(dyn_cast<ConstantArrayType>(E->getType()) &&
11235
0
         "Expression result is not a constant array type");
11236
11237
0
  return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11238
0
                                         E->getArrayFiller());
11239
0
}
11240
11241
//===----------------------------------------------------------------------===//
11242
// Integer Evaluation
11243
//
11244
// As a GNU extension, we support casting pointers to sufficiently-wide integer
11245
// types and back in constant folding. Integer values are thus represented
11246
// either as an integer-valued APValue, or as an lvalue-valued APValue.
11247
//===----------------------------------------------------------------------===//
11248
11249
namespace {
11250
class IntExprEvaluator
11251
        : public ExprEvaluatorBase<IntExprEvaluator> {
11252
  APValue &Result;
11253
public:
11254
  IntExprEvaluator(EvalInfo &info, APValue &result)
11255
10
      : ExprEvaluatorBaseTy(info), Result(result) {}
11256
11257
1
  bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11258
1
    assert(E->getType()->isIntegralOrEnumerationType() &&
11259
1
           "Invalid evaluation result.");
11260
0
    assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11261
1
           "Invalid evaluation result.");
11262
0
    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11263
1
           "Invalid evaluation result.");
11264
0
    Result = APValue(SI);
11265
1
    return true;
11266
1
  }
11267
1
  bool Success(const llvm::APSInt &SI, const Expr *E) {
11268
1
    return Success(SI, E, Result);
11269
1
  }
11270
11271
5
  bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11272
5
    assert(E->getType()->isIntegralOrEnumerationType() &&
11273
5
           "Invalid evaluation result.");
11274
0
    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11275
5
           "Invalid evaluation result.");
11276
0
    Result = APValue(APSInt(I));
11277
5
    Result.getInt().setIsUnsigned(
11278
5
                            E->getType()->isUnsignedIntegerOrEnumerationType());
11279
5
    return true;
11280
5
  }
11281
5
  bool Success(const llvm::APInt &I, const Expr *E) {
11282
5
    return Success(I, E, Result);
11283
5
  }
11284
11285
0
  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11286
0
    assert(E->getType()->isIntegralOrEnumerationType() &&
11287
0
           "Invalid evaluation result.");
11288
0
    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11289
0
    return true;
11290
0
  }
11291
0
  bool Success(uint64_t Value, const Expr *E) {
11292
0
    return Success(Value, E, Result);
11293
0
  }
11294
11295
0
  bool Success(CharUnits Size, const Expr *E) {
11296
0
    return Success(Size.getQuantity(), E);
11297
0
  }
11298
11299
0
  bool Success(const APValue &V, const Expr *E) {
11300
0
    if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11301
0
      Result = V;
11302
0
      return true;
11303
0
    }
11304
0
    return Success(V.getInt(), E);
11305
0
  }
11306
11307
0
  bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11308
11309
  //===--------------------------------------------------------------------===//
11310
  //                            Visitor Methods
11311
  //===--------------------------------------------------------------------===//
11312
11313
5
  bool VisitIntegerLiteral(const IntegerLiteral *E) {
11314
5
    return Success(E->getValue(), E);
11315
5
  }
11316
0
  bool VisitCharacterLiteral(const CharacterLiteral *E) {
11317
0
    return Success(E->getValue(), E);
11318
0
  }
11319
11320
  bool CheckReferencedDecl(const Expr *E, const Decl *D);
11321
0
  bool VisitDeclRefExpr(const DeclRefExpr *E) {
11322
0
    if (CheckReferencedDecl(E, E->getDecl()))
11323
0
      return true;
11324
11325
0
    return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11326
0
  }
11327
0
  bool VisitMemberExpr(const MemberExpr *E) {
11328
0
    if (CheckReferencedDecl(E, E->getMemberDecl())) {
11329
0
      VisitIgnoredBaseExpression(E->getBase());
11330
0
      return true;
11331
0
    }
11332
11333
0
    return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11334
0
  }
11335
11336
  bool VisitCallExpr(const CallExpr *E);
11337
  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11338
  bool VisitBinaryOperator(const BinaryOperator *E);
11339
  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11340
  bool VisitUnaryOperator(const UnaryOperator *E);
11341
11342
  bool VisitCastExpr(const CastExpr* E);
11343
  bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11344
11345
0
  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11346
0
    return Success(E->getValue(), E);
11347
0
  }
11348
11349
0
  bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11350
0
    return Success(E->getValue(), E);
11351
0
  }
11352
11353
0
  bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11354
0
    if (Info.ArrayInitIndex == uint64_t(-1)) {
11355
      // We were asked to evaluate this subexpression independent of the
11356
      // enclosing ArrayInitLoopExpr. We can't do that.
11357
0
      Info.FFDiag(E);
11358
0
      return false;
11359
0
    }
11360
0
    return Success(Info.ArrayInitIndex, E);
11361
0
  }
11362
11363
  // Note, GNU defines __null as an integer, not a pointer.
11364
0
  bool VisitGNUNullExpr(const GNUNullExpr *E) {
11365
0
    return ZeroInitialization(E);
11366
0
  }
11367
11368
0
  bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11369
0
    return Success(E->getValue(), E);
11370
0
  }
11371
11372
0
  bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11373
0
    return Success(E->getValue(), E);
11374
0
  }
11375
11376
0
  bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11377
0
    return Success(E->getValue(), E);
11378
0
  }
11379
11380
  bool VisitUnaryReal(const UnaryOperator *E);
11381
  bool VisitUnaryImag(const UnaryOperator *E);
11382
11383
  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11384
  bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11385
  bool VisitSourceLocExpr(const SourceLocExpr *E);
11386
  bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11387
  bool VisitRequiresExpr(const RequiresExpr *E);
11388
  // FIXME: Missing: array subscript of vector, member of vector
11389
};
11390
11391
class FixedPointExprEvaluator
11392
    : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11393
  APValue &Result;
11394
11395
 public:
11396
  FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11397
0
      : ExprEvaluatorBaseTy(info), Result(result) {}
11398
11399
0
  bool Success(const llvm::APInt &I, const Expr *E) {
11400
0
    return Success(
11401
0
        APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11402
0
  }
11403
11404
0
  bool Success(uint64_t Value, const Expr *E) {
11405
0
    return Success(
11406
0
        APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11407
0
  }
11408
11409
0
  bool Success(const APValue &V, const Expr *E) {
11410
0
    return Success(V.getFixedPoint(), E);
11411
0
  }
11412
11413
0
  bool Success(const APFixedPoint &V, const Expr *E) {
11414
0
    assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11415
0
    assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11416
0
           "Invalid evaluation result.");
11417
0
    Result = APValue(V);
11418
0
    return true;
11419
0
  }
11420
11421
  //===--------------------------------------------------------------------===//
11422
  //                            Visitor Methods
11423
  //===--------------------------------------------------------------------===//
11424
11425
0
  bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11426
0
    return Success(E->getValue(), E);
11427
0
  }
11428
11429
  bool VisitCastExpr(const CastExpr *E);
11430
  bool VisitUnaryOperator(const UnaryOperator *E);
11431
  bool VisitBinaryOperator(const BinaryOperator *E);
11432
};
11433
} // end anonymous namespace
11434
11435
/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11436
/// produce either the integer value or a pointer.
11437
///
11438
/// GCC has a heinous extension which folds casts between pointer types and
11439
/// pointer-sized integral types. We support this by allowing the evaluation of
11440
/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11441
/// Some simple arithmetic on such values is supported (they are treated much
11442
/// like char*).
11443
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11444
1
                                    EvalInfo &Info) {
11445
1
  assert(!E->isValueDependent());
11446
0
  assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11447
0
  return IntExprEvaluator(Info, Result).Visit(E);
11448
1
}
11449
11450
0
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11451
0
  assert(!E->isValueDependent());
11452
0
  APValue Val;
11453
0
  if (!EvaluateIntegerOrLValue(E, Val, Info))
11454
0
    return false;
11455
0
  if (!Val.isInt()) {
11456
    // FIXME: It would be better to produce the diagnostic for casting
11457
    //        a pointer to an integer.
11458
0
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11459
0
    return false;
11460
0
  }
11461
0
  Result = Val.getInt();
11462
0
  return true;
11463
0
}
11464
11465
0
bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11466
0
  APValue Evaluated = E->EvaluateInContext(
11467
0
      Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11468
0
  return Success(Evaluated, E);
11469
0
}
11470
11471
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11472
0
                               EvalInfo &Info) {
11473
0
  assert(!E->isValueDependent());
11474
0
  if (E->getType()->isFixedPointType()) {
11475
0
    APValue Val;
11476
0
    if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11477
0
      return false;
11478
0
    if (!Val.isFixedPoint())
11479
0
      return false;
11480
11481
0
    Result = Val.getFixedPoint();
11482
0
    return true;
11483
0
  }
11484
0
  return false;
11485
0
}
11486
11487
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11488
0
                                        EvalInfo &Info) {
11489
0
  assert(!E->isValueDependent());
11490
0
  if (E->getType()->isIntegerType()) {
11491
0
    auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11492
0
    APSInt Val;
11493
0
    if (!EvaluateInteger(E, Val, Info))
11494
0
      return false;
11495
0
    Result = APFixedPoint(Val, FXSema);
11496
0
    return true;
11497
0
  } else if (E->getType()->isFixedPointType()) {
11498
0
    return EvaluateFixedPoint(E, Result, Info);
11499
0
  }
11500
0
  return false;
11501
0
}
11502
11503
/// Check whether the given declaration can be directly converted to an integral
11504
/// rvalue. If not, no diagnostic is produced; there are other things we can
11505
/// try.
11506
0
bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11507
  // Enums are integer constant exprs.
11508
0
  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11509
    // Check for signedness/width mismatches between E type and ECD value.
11510
0
    bool SameSign = (ECD->getInitVal().isSigned()
11511
0
                     == E->getType()->isSignedIntegerOrEnumerationType());
11512
0
    bool SameWidth = (ECD->getInitVal().getBitWidth()
11513
0
                      == Info.Ctx.getIntWidth(E->getType()));
11514
0
    if (SameSign && SameWidth)
11515
0
      return Success(ECD->getInitVal(), E);
11516
0
    else {
11517
      // Get rid of mismatch (otherwise Success assertions will fail)
11518
      // by computing a new value matching the type of E.
11519
0
      llvm::APSInt Val = ECD->getInitVal();
11520
0
      if (!SameSign)
11521
0
        Val.setIsSigned(!ECD->getInitVal().isSigned());
11522
0
      if (!SameWidth)
11523
0
        Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11524
0
      return Success(Val, E);
11525
0
    }
11526
0
  }
11527
0
  return false;
11528
0
}
11529
11530
/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11531
/// as GCC.
11532
GCCTypeClass EvaluateBuiltinClassifyType(QualType T,
11533
0
                                         const LangOptions &LangOpts) {
11534
0
  assert(!T->isDependentType() && "unexpected dependent type");
11535
11536
0
  QualType CanTy = T.getCanonicalType();
11537
11538
0
  switch (CanTy->getTypeClass()) {
11539
0
#define TYPE(ID, BASE)
11540
0
#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11541
0
#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11542
0
#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11543
0
#include "clang/AST/TypeNodes.inc"
11544
0
  case Type::Auto:
11545
0
  case Type::DeducedTemplateSpecialization:
11546
0
      llvm_unreachable("unexpected non-canonical or dependent type");
11547
11548
0
  case Type::Builtin:
11549
0
      switch (cast<BuiltinType>(CanTy)->getKind()) {
11550
0
#define BUILTIN_TYPE(ID, SINGLETON_ID)
11551
0
#define SIGNED_TYPE(ID, SINGLETON_ID) \
11552
0
    case BuiltinType::ID: return GCCTypeClass::Integer;
11553
0
#define FLOATING_TYPE(ID, SINGLETON_ID) \
11554
0
    case BuiltinType::ID: return GCCTypeClass::RealFloat;
11555
0
#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11556
0
    case BuiltinType::ID: break;
11557
0
#include "clang/AST/BuiltinTypes.def"
11558
0
    case BuiltinType::Void:
11559
0
      return GCCTypeClass::Void;
11560
11561
0
    case BuiltinType::Bool:
11562
0
      return GCCTypeClass::Bool;
11563
11564
0
    case BuiltinType::Char_U:
11565
0
    case BuiltinType::UChar:
11566
0
    case BuiltinType::WChar_U:
11567
0
    case BuiltinType::Char8:
11568
0
    case BuiltinType::Char16:
11569
0
    case BuiltinType::Char32:
11570
0
    case BuiltinType::UShort:
11571
0
    case BuiltinType::UInt:
11572
0
    case BuiltinType::ULong:
11573
0
    case BuiltinType::ULongLong:
11574
0
    case BuiltinType::UInt128:
11575
0
      return GCCTypeClass::Integer;
11576
11577
0
    case BuiltinType::UShortAccum:
11578
0
    case BuiltinType::UAccum:
11579
0
    case BuiltinType::ULongAccum:
11580
0
    case BuiltinType::UShortFract:
11581
0
    case BuiltinType::UFract:
11582
0
    case BuiltinType::ULongFract:
11583
0
    case BuiltinType::SatUShortAccum:
11584
0
    case BuiltinType::SatUAccum:
11585
0
    case BuiltinType::SatULongAccum:
11586
0
    case BuiltinType::SatUShortFract:
11587
0
    case BuiltinType::SatUFract:
11588
0
    case BuiltinType::SatULongFract:
11589
0
      return GCCTypeClass::None;
11590
11591
0
    case BuiltinType::NullPtr:
11592
11593
0
    case BuiltinType::ObjCId:
11594
0
    case BuiltinType::ObjCClass:
11595
0
    case BuiltinType::ObjCSel:
11596
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11597
0
    case BuiltinType::Id:
11598
0
#include "clang/Basic/OpenCLImageTypes.def"
11599
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11600
0
    case BuiltinType::Id:
11601
0
#include "clang/Basic/OpenCLExtensionTypes.def"
11602
0
    case BuiltinType::OCLSampler:
11603
0
    case BuiltinType::OCLEvent:
11604
0
    case BuiltinType::OCLClkEvent:
11605
0
    case BuiltinType::OCLQueue:
11606
0
    case BuiltinType::OCLReserveID:
11607
0
#define SVE_TYPE(Name, Id, SingletonId) \
11608
0
    case BuiltinType::Id:
11609
0
#include "clang/Basic/AArch64SVEACLETypes.def"
11610
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
11611
0
    case BuiltinType::Id:
11612
0
#include "clang/Basic/PPCTypes.def"
11613
0
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11614
0
#include "clang/Basic/RISCVVTypes.def"
11615
0
#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11616
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
11617
0
      return GCCTypeClass::None;
11618
11619
0
    case BuiltinType::Dependent:
11620
0
      llvm_unreachable("unexpected dependent type");
11621
0
    };
11622
0
    llvm_unreachable("unexpected placeholder type");
11623
11624
0
  case Type::Enum:
11625
0
    return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11626
11627
0
  case Type::Pointer:
11628
0
  case Type::ConstantArray:
11629
0
  case Type::VariableArray:
11630
0
  case Type::IncompleteArray:
11631
0
  case Type::FunctionNoProto:
11632
0
  case Type::FunctionProto:
11633
0
    return GCCTypeClass::Pointer;
11634
11635
0
  case Type::MemberPointer:
11636
0
    return CanTy->isMemberDataPointerType()
11637
0
               ? GCCTypeClass::PointerToDataMember
11638
0
               : GCCTypeClass::PointerToMemberFunction;
11639
11640
0
  case Type::Complex:
11641
0
    return GCCTypeClass::Complex;
11642
11643
0
  case Type::Record:
11644
0
    return CanTy->isUnionType() ? GCCTypeClass::Union
11645
0
                                : GCCTypeClass::ClassOrStruct;
11646
11647
0
  case Type::Atomic:
11648
    // GCC classifies _Atomic T the same as T.
11649
0
    return EvaluateBuiltinClassifyType(
11650
0
        CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11651
11652
0
  case Type::Vector:
11653
0
  case Type::ExtVector:
11654
0
    return GCCTypeClass::Vector;
11655
11656
0
  case Type::BlockPointer:
11657
0
  case Type::ConstantMatrix:
11658
0
  case Type::ObjCObject:
11659
0
  case Type::ObjCInterface:
11660
0
  case Type::ObjCObjectPointer:
11661
0
  case Type::Pipe:
11662
    // Classify all other types that don't fit into the regular
11663
    // classification the same way.
11664
0
    return GCCTypeClass::None;
11665
11666
0
  case Type::BitInt:
11667
0
    return GCCTypeClass::BitInt;
11668
11669
0
  case Type::LValueReference:
11670
0
  case Type::RValueReference:
11671
0
    llvm_unreachable("invalid type for expression");
11672
0
  }
11673
11674
0
  llvm_unreachable("unexpected type class");
11675
0
}
11676
11677
/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11678
/// as GCC.
11679
static GCCTypeClass
11680
0
EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11681
  // If no argument was supplied, default to None. This isn't
11682
  // ideal, however it is what gcc does.
11683
0
  if (E->getNumArgs() == 0)
11684
0
    return GCCTypeClass::None;
11685
11686
  // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11687
  // being an ICE, but still folds it to a constant using the type of the first
11688
  // argument.
11689
0
  return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11690
0
}
11691
11692
/// EvaluateBuiltinConstantPForLValue - Determine the result of
11693
/// __builtin_constant_p when applied to the given pointer.
11694
///
11695
/// A pointer is only "constant" if it is null (or a pointer cast to integer)
11696
/// or it points to the first character of a string literal.
11697
0
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11698
0
  APValue::LValueBase Base = LV.getLValueBase();
11699
0
  if (Base.isNull()) {
11700
    // A null base is acceptable.
11701
0
    return true;
11702
0
  } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11703
0
    if (!isa<StringLiteral>(E))
11704
0
      return false;
11705
0
    return LV.getLValueOffset().isZero();
11706
0
  } else if (Base.is<TypeInfoLValue>()) {
11707
    // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11708
    // evaluate to true.
11709
0
    return true;
11710
0
  } else {
11711
    // Any other base is not constant enough for GCC.
11712
0
    return false;
11713
0
  }
11714
0
}
11715
11716
/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11717
/// GCC as we can manage.
11718
0
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11719
  // This evaluation is not permitted to have side-effects, so evaluate it in
11720
  // a speculative evaluation context.
11721
0
  SpeculativeEvaluationRAII SpeculativeEval(Info);
11722
11723
  // Constant-folding is always enabled for the operand of __builtin_constant_p
11724
  // (even when the enclosing evaluation context otherwise requires a strict
11725
  // language-specific constant expression).
11726
0
  FoldConstant Fold(Info, true);
11727
11728
0
  QualType ArgType = Arg->getType();
11729
11730
  // __builtin_constant_p always has one operand. The rules which gcc follows
11731
  // are not precisely documented, but are as follows:
11732
  //
11733
  //  - If the operand is of integral, floating, complex or enumeration type,
11734
  //    and can be folded to a known value of that type, it returns 1.
11735
  //  - If the operand can be folded to a pointer to the first character
11736
  //    of a string literal (or such a pointer cast to an integral type)
11737
  //    or to a null pointer or an integer cast to a pointer, it returns 1.
11738
  //
11739
  // Otherwise, it returns 0.
11740
  //
11741
  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11742
  // its support for this did not work prior to GCC 9 and is not yet well
11743
  // understood.
11744
0
  if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11745
0
      ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11746
0
      ArgType->isNullPtrType()) {
11747
0
    APValue V;
11748
0
    if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11749
0
      Fold.keepDiagnostics();
11750
0
      return false;
11751
0
    }
11752
11753
    // For a pointer (possibly cast to integer), there are special rules.
11754
0
    if (V.getKind() == APValue::LValue)
11755
0
      return EvaluateBuiltinConstantPForLValue(V);
11756
11757
    // Otherwise, any constant value is good enough.
11758
0
    return V.hasValue();
11759
0
  }
11760
11761
  // Anything else isn't considered to be sufficiently constant.
11762
0
  return false;
11763
0
}
11764
11765
/// Retrieves the "underlying object type" of the given expression,
11766
/// as used by __builtin_object_size.
11767
0
static QualType getObjectType(APValue::LValueBase B) {
11768
0
  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11769
0
    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11770
0
      return VD->getType();
11771
0
  } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11772
0
    if (isa<CompoundLiteralExpr>(E))
11773
0
      return E->getType();
11774
0
  } else if (B.is<TypeInfoLValue>()) {
11775
0
    return B.getTypeInfoType();
11776
0
  } else if (B.is<DynamicAllocLValue>()) {
11777
0
    return B.getDynamicAllocType();
11778
0
  }
11779
11780
0
  return QualType();
11781
0
}
11782
11783
/// A more selective version of E->IgnoreParenCasts for
11784
/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11785
/// to change the type of E.
11786
/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11787
///
11788
/// Always returns an RValue with a pointer representation.
11789
0
static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11790
0
  assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11791
11792
0
  auto *NoParens = E->IgnoreParens();
11793
0
  auto *Cast = dyn_cast<CastExpr>(NoParens);
11794
0
  if (Cast == nullptr)
11795
0
    return NoParens;
11796
11797
  // We only conservatively allow a few kinds of casts, because this code is
11798
  // inherently a simple solution that seeks to support the common case.
11799
0
  auto CastKind = Cast->getCastKind();
11800
0
  if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11801
0
      CastKind != CK_AddressSpaceConversion)
11802
0
    return NoParens;
11803
11804
0
  auto *SubExpr = Cast->getSubExpr();
11805
0
  if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11806
0
    return NoParens;
11807
0
  return ignorePointerCastsAndParens(SubExpr);
11808
0
}
11809
11810
/// Checks to see if the given LValue's Designator is at the end of the LValue's
11811
/// record layout. e.g.
11812
///   struct { struct { int a, b; } fst, snd; } obj;
11813
///   obj.fst   // no
11814
///   obj.snd   // yes
11815
///   obj.fst.a // no
11816
///   obj.fst.b // no
11817
///   obj.snd.a // no
11818
///   obj.snd.b // yes
11819
///
11820
/// Please note: this function is specialized for how __builtin_object_size
11821
/// views "objects".
11822
///
11823
/// If this encounters an invalid RecordDecl or otherwise cannot determine the
11824
/// correct result, it will always return true.
11825
0
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11826
0
  assert(!LVal.Designator.Invalid);
11827
11828
0
  auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11829
0
    const RecordDecl *Parent = FD->getParent();
11830
0
    Invalid = Parent->isInvalidDecl();
11831
0
    if (Invalid || Parent->isUnion())
11832
0
      return true;
11833
0
    const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11834
0
    return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11835
0
  };
11836
11837
0
  auto &Base = LVal.getLValueBase();
11838
0
  if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11839
0
    if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11840
0
      bool Invalid;
11841
0
      if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11842
0
        return Invalid;
11843
0
    } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11844
0
      for (auto *FD : IFD->chain()) {
11845
0
        bool Invalid;
11846
0
        if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11847
0
          return Invalid;
11848
0
      }
11849
0
    }
11850
0
  }
11851
11852
0
  unsigned I = 0;
11853
0
  QualType BaseType = getType(Base);
11854
0
  if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11855
    // If we don't know the array bound, conservatively assume we're looking at
11856
    // the final array element.
11857
0
    ++I;
11858
0
    if (BaseType->isIncompleteArrayType())
11859
0
      BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11860
0
    else
11861
0
      BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11862
0
  }
11863
11864
0
  for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11865
0
    const auto &Entry = LVal.Designator.Entries[I];
11866
0
    if (BaseType->isArrayType()) {
11867
      // Because __builtin_object_size treats arrays as objects, we can ignore
11868
      // the index iff this is the last array in the Designator.
11869
0
      if (I + 1 == E)
11870
0
        return true;
11871
0
      const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11872
0
      uint64_t Index = Entry.getAsArrayIndex();
11873
0
      if (Index + 1 != CAT->getSize())
11874
0
        return false;
11875
0
      BaseType = CAT->getElementType();
11876
0
    } else if (BaseType->isAnyComplexType()) {
11877
0
      const auto *CT = BaseType->castAs<ComplexType>();
11878
0
      uint64_t Index = Entry.getAsArrayIndex();
11879
0
      if (Index != 1)
11880
0
        return false;
11881
0
      BaseType = CT->getElementType();
11882
0
    } else if (auto *FD = getAsField(Entry)) {
11883
0
      bool Invalid;
11884
0
      if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11885
0
        return Invalid;
11886
0
      BaseType = FD->getType();
11887
0
    } else {
11888
0
      assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11889
0
      return false;
11890
0
    }
11891
0
  }
11892
0
  return true;
11893
0
}
11894
11895
/// Tests to see if the LValue has a user-specified designator (that isn't
11896
/// necessarily valid). Note that this always returns 'true' if the LValue has
11897
/// an unsized array as its first designator entry, because there's currently no
11898
/// way to tell if the user typed *foo or foo[0].
11899
0
static bool refersToCompleteObject(const LValue &LVal) {
11900
0
  if (LVal.Designator.Invalid)
11901
0
    return false;
11902
11903
0
  if (!LVal.Designator.Entries.empty())
11904
0
    return LVal.Designator.isMostDerivedAnUnsizedArray();
11905
11906
0
  if (!LVal.InvalidBase)
11907
0
    return true;
11908
11909
  // If `E` is a MemberExpr, then the first part of the designator is hiding in
11910
  // the LValueBase.
11911
0
  const auto *E = LVal.Base.dyn_cast<const Expr *>();
11912
0
  return !E || !isa<MemberExpr>(E);
11913
0
}
11914
11915
/// Attempts to detect a user writing into a piece of memory that's impossible
11916
/// to figure out the size of by just using types.
11917
0
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11918
0
  const SubobjectDesignator &Designator = LVal.Designator;
11919
  // Notes:
11920
  // - Users can only write off of the end when we have an invalid base. Invalid
11921
  //   bases imply we don't know where the memory came from.
11922
  // - We used to be a bit more aggressive here; we'd only be conservative if
11923
  //   the array at the end was flexible, or if it had 0 or 1 elements. This
11924
  //   broke some common standard library extensions (PR30346), but was
11925
  //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11926
  //   with some sort of list. OTOH, it seems that GCC is always
11927
  //   conservative with the last element in structs (if it's an array), so our
11928
  //   current behavior is more compatible than an explicit list approach would
11929
  //   be.
11930
0
  auto isFlexibleArrayMember = [&] {
11931
0
    using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11932
0
    FAMKind StrictFlexArraysLevel =
11933
0
        Ctx.getLangOpts().getStrictFlexArraysLevel();
11934
11935
0
    if (Designator.isMostDerivedAnUnsizedArray())
11936
0
      return true;
11937
11938
0
    if (StrictFlexArraysLevel == FAMKind::Default)
11939
0
      return true;
11940
11941
0
    if (Designator.getMostDerivedArraySize() == 0 &&
11942
0
        StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11943
0
      return true;
11944
11945
0
    if (Designator.getMostDerivedArraySize() == 1 &&
11946
0
        StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11947
0
      return true;
11948
11949
0
    return false;
11950
0
  };
11951
11952
0
  return LVal.InvalidBase &&
11953
0
         Designator.Entries.size() == Designator.MostDerivedPathLength &&
11954
0
         Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11955
0
         isDesignatorAtObjectEnd(Ctx, LVal);
11956
0
}
11957
11958
/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11959
/// Fails if the conversion would cause loss of precision.
11960
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11961
0
                                            CharUnits &Result) {
11962
0
  auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11963
0
  if (Int.ugt(CharUnitsMax))
11964
0
    return false;
11965
0
  Result = CharUnits::fromQuantity(Int.getZExtValue());
11966
0
  return true;
11967
0
}
11968
11969
/// If we're evaluating the object size of an instance of a struct that
11970
/// contains a flexible array member, add the size of the initializer.
11971
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
11972
0
                                           const LValue &LV, CharUnits &Size) {
11973
0
  if (!T.isNull() && T->isStructureType() &&
11974
0
      T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
11975
0
    if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
11976
0
      if (const auto *VD = dyn_cast<VarDecl>(V))
11977
0
        if (VD->hasInit())
11978
0
          Size += VD->getFlexibleArrayInitChars(Info.Ctx);
11979
0
}
11980
11981
/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11982
/// determine how many bytes exist from the beginning of the object to either
11983
/// the end of the current subobject, or the end of the object itself, depending
11984
/// on what the LValue looks like + the value of Type.
11985
///
11986
/// If this returns false, the value of Result is undefined.
11987
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11988
                               unsigned Type, const LValue &LVal,
11989
0
                               CharUnits &EndOffset) {
11990
0
  bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11991
11992
0
  auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11993
0
    if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11994
0
      return false;
11995
0
    return HandleSizeof(Info, ExprLoc, Ty, Result);
11996
0
  };
11997
11998
  // We want to evaluate the size of the entire object. This is a valid fallback
11999
  // for when Type=1 and the designator is invalid, because we're asked for an
12000
  // upper-bound.
12001
0
  if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12002
    // Type=3 wants a lower bound, so we can't fall back to this.
12003
0
    if (Type == 3 && !DetermineForCompleteObject)
12004
0
      return false;
12005
12006
0
    llvm::APInt APEndOffset;
12007
0
    if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12008
0
        getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12009
0
      return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12010
12011
0
    if (LVal.InvalidBase)
12012
0
      return false;
12013
12014
0
    QualType BaseTy = getObjectType(LVal.getLValueBase());
12015
0
    const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12016
0
    addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12017
0
    return Ret;
12018
0
  }
12019
12020
  // We want to evaluate the size of a subobject.
12021
0
  const SubobjectDesignator &Designator = LVal.Designator;
12022
12023
  // The following is a moderately common idiom in C:
12024
  //
12025
  // struct Foo { int a; char c[1]; };
12026
  // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12027
  // strcpy(&F->c[0], Bar);
12028
  //
12029
  // In order to not break too much legacy code, we need to support it.
12030
0
  if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12031
    // If we can resolve this to an alloc_size call, we can hand that back,
12032
    // because we know for certain how many bytes there are to write to.
12033
0
    llvm::APInt APEndOffset;
12034
0
    if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12035
0
        getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12036
0
      return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12037
12038
    // If we cannot determine the size of the initial allocation, then we can't
12039
    // given an accurate upper-bound. However, we are still able to give
12040
    // conservative lower-bounds for Type=3.
12041
0
    if (Type == 1)
12042
0
      return false;
12043
0
  }
12044
12045
0
  CharUnits BytesPerElem;
12046
0
  if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12047
0
    return false;
12048
12049
  // According to the GCC documentation, we want the size of the subobject
12050
  // denoted by the pointer. But that's not quite right -- what we actually
12051
  // want is the size of the immediately-enclosing array, if there is one.
12052
0
  int64_t ElemsRemaining;
12053
0
  if (Designator.MostDerivedIsArrayElement &&
12054
0
      Designator.Entries.size() == Designator.MostDerivedPathLength) {
12055
0
    uint64_t ArraySize = Designator.getMostDerivedArraySize();
12056
0
    uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12057
0
    ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12058
0
  } else {
12059
0
    ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12060
0
  }
12061
12062
0
  EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12063
0
  return true;
12064
0
}
12065
12066
/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12067
/// returns true and stores the result in @p Size.
12068
///
12069
/// If @p WasError is non-null, this will report whether the failure to evaluate
12070
/// is to be treated as an Error in IntExprEvaluator.
12071
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12072
0
                                         EvalInfo &Info, uint64_t &Size) {
12073
  // Determine the denoted object.
12074
0
  LValue LVal;
12075
0
  {
12076
    // The operand of __builtin_object_size is never evaluated for side-effects.
12077
    // If there are any, but we can determine the pointed-to object anyway, then
12078
    // ignore the side-effects.
12079
0
    SpeculativeEvaluationRAII SpeculativeEval(Info);
12080
0
    IgnoreSideEffectsRAII Fold(Info);
12081
12082
0
    if (E->isGLValue()) {
12083
      // It's possible for us to be given GLValues if we're called via
12084
      // Expr::tryEvaluateObjectSize.
12085
0
      APValue RVal;
12086
0
      if (!EvaluateAsRValue(Info, E, RVal))
12087
0
        return false;
12088
0
      LVal.setFrom(Info.Ctx, RVal);
12089
0
    } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12090
0
                                /*InvalidBaseOK=*/true))
12091
0
      return false;
12092
0
  }
12093
12094
  // If we point to before the start of the object, there are no accessible
12095
  // bytes.
12096
0
  if (LVal.getLValueOffset().isNegative()) {
12097
0
    Size = 0;
12098
0
    return true;
12099
0
  }
12100
12101
0
  CharUnits EndOffset;
12102
0
  if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12103
0
    return false;
12104
12105
  // If we've fallen outside of the end offset, just pretend there's nothing to
12106
  // write to/read from.
12107
0
  if (EndOffset <= LVal.getLValueOffset())
12108
0
    Size = 0;
12109
0
  else
12110
0
    Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12111
0
  return true;
12112
0
}
12113
12114
0
bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12115
0
  if (!IsConstantEvaluatedBuiltinCall(E))
12116
0
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
12117
0
  return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12118
0
}
12119
12120
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12121
0
                                     APValue &Val, APSInt &Alignment) {
12122
0
  QualType SrcTy = E->getArg(0)->getType();
12123
0
  if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12124
0
    return false;
12125
  // Even though we are evaluating integer expressions we could get a pointer
12126
  // argument for the __builtin_is_aligned() case.
12127
0
  if (SrcTy->isPointerType()) {
12128
0
    LValue Ptr;
12129
0
    if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12130
0
      return false;
12131
0
    Ptr.moveInto(Val);
12132
0
  } else if (!SrcTy->isIntegralOrEnumerationType()) {
12133
0
    Info.FFDiag(E->getArg(0));
12134
0
    return false;
12135
0
  } else {
12136
0
    APSInt SrcInt;
12137
0
    if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12138
0
      return false;
12139
0
    assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12140
0
           "Bit widths must be the same");
12141
0
    Val = APValue(SrcInt);
12142
0
  }
12143
0
  assert(Val.hasValue());
12144
0
  return true;
12145
0
}
12146
12147
bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12148
0
                                            unsigned BuiltinOp) {
12149
0
  switch (BuiltinOp) {
12150
0
  default:
12151
0
    return false;
12152
12153
0
  case Builtin::BI__builtin_dynamic_object_size:
12154
0
  case Builtin::BI__builtin_object_size: {
12155
    // The type was checked when we built the expression.
12156
0
    unsigned Type =
12157
0
        E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12158
0
    assert(Type <= 3 && "unexpected type");
12159
12160
0
    uint64_t Size;
12161
0
    if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12162
0
      return Success(Size, E);
12163
12164
0
    if (E->getArg(0)->HasSideEffects(Info.Ctx))
12165
0
      return Success((Type & 2) ? 0 : -1, E);
12166
12167
    // Expression had no side effects, but we couldn't statically determine the
12168
    // size of the referenced object.
12169
0
    switch (Info.EvalMode) {
12170
0
    case EvalInfo::EM_ConstantExpression:
12171
0
    case EvalInfo::EM_ConstantFold:
12172
0
    case EvalInfo::EM_IgnoreSideEffects:
12173
      // Leave it to IR generation.
12174
0
      return Error(E);
12175
0
    case EvalInfo::EM_ConstantExpressionUnevaluated:
12176
      // Reduce it to a constant now.
12177
0
      return Success((Type & 2) ? 0 : -1, E);
12178
0
    }
12179
12180
0
    llvm_unreachable("unexpected EvalMode");
12181
0
  }
12182
12183
0
  case Builtin::BI__builtin_os_log_format_buffer_size: {
12184
0
    analyze_os_log::OSLogBufferLayout Layout;
12185
0
    analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
12186
0
    return Success(Layout.size().getQuantity(), E);
12187
0
  }
12188
12189
0
  case Builtin::BI__builtin_is_aligned: {
12190
0
    APValue Src;
12191
0
    APSInt Alignment;
12192
0
    if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12193
0
      return false;
12194
0
    if (Src.isLValue()) {
12195
      // If we evaluated a pointer, check the minimum known alignment.
12196
0
      LValue Ptr;
12197
0
      Ptr.setFrom(Info.Ctx, Src);
12198
0
      CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12199
0
      CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12200
      // We can return true if the known alignment at the computed offset is
12201
      // greater than the requested alignment.
12202
0
      assert(PtrAlign.isPowerOfTwo());
12203
0
      assert(Alignment.isPowerOf2());
12204
0
      if (PtrAlign.getQuantity() >= Alignment)
12205
0
        return Success(1, E);
12206
      // If the alignment is not known to be sufficient, some cases could still
12207
      // be aligned at run time. However, if the requested alignment is less or
12208
      // equal to the base alignment and the offset is not aligned, we know that
12209
      // the run-time value can never be aligned.
12210
0
      if (BaseAlignment.getQuantity() >= Alignment &&
12211
0
          PtrAlign.getQuantity() < Alignment)
12212
0
        return Success(0, E);
12213
      // Otherwise we can't infer whether the value is sufficiently aligned.
12214
      // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12215
      //  in cases where we can't fully evaluate the pointer.
12216
0
      Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12217
0
          << Alignment;
12218
0
      return false;
12219
0
    }
12220
0
    assert(Src.isInt());
12221
0
    return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12222
0
  }
12223
0
  case Builtin::BI__builtin_align_up: {
12224
0
    APValue Src;
12225
0
    APSInt Alignment;
12226
0
    if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12227
0
      return false;
12228
0
    if (!Src.isInt())
12229
0
      return Error(E);
12230
0
    APSInt AlignedVal =
12231
0
        APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12232
0
               Src.getInt().isUnsigned());
12233
0
    assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12234
0
    return Success(AlignedVal, E);
12235
0
  }
12236
0
  case Builtin::BI__builtin_align_down: {
12237
0
    APValue Src;
12238
0
    APSInt Alignment;
12239
0
    if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12240
0
      return false;
12241
0
    if (!Src.isInt())
12242
0
      return Error(E);
12243
0
    APSInt AlignedVal =
12244
0
        APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12245
0
    assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12246
0
    return Success(AlignedVal, E);
12247
0
  }
12248
12249
0
  case Builtin::BI__builtin_bitreverse8:
12250
0
  case Builtin::BI__builtin_bitreverse16:
12251
0
  case Builtin::BI__builtin_bitreverse32:
12252
0
  case Builtin::BI__builtin_bitreverse64: {
12253
0
    APSInt Val;
12254
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12255
0
      return false;
12256
12257
0
    return Success(Val.reverseBits(), E);
12258
0
  }
12259
12260
0
  case Builtin::BI__builtin_bswap16:
12261
0
  case Builtin::BI__builtin_bswap32:
12262
0
  case Builtin::BI__builtin_bswap64: {
12263
0
    APSInt Val;
12264
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12265
0
      return false;
12266
12267
0
    return Success(Val.byteSwap(), E);
12268
0
  }
12269
12270
0
  case Builtin::BI__builtin_classify_type:
12271
0
    return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12272
12273
0
  case Builtin::BI__builtin_clrsb:
12274
0
  case Builtin::BI__builtin_clrsbl:
12275
0
  case Builtin::BI__builtin_clrsbll: {
12276
0
    APSInt Val;
12277
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12278
0
      return false;
12279
12280
0
    return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12281
0
  }
12282
12283
0
  case Builtin::BI__builtin_clz:
12284
0
  case Builtin::BI__builtin_clzl:
12285
0
  case Builtin::BI__builtin_clzll:
12286
0
  case Builtin::BI__builtin_clzs:
12287
0
  case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12288
0
  case Builtin::BI__lzcnt:
12289
0
  case Builtin::BI__lzcnt64: {
12290
0
    APSInt Val;
12291
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12292
0
      return false;
12293
12294
    // When the argument is 0, the result of GCC builtins is undefined, whereas
12295
    // for Microsoft intrinsics, the result is the bit-width of the argument.
12296
0
    bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
12297
0
                           BuiltinOp != Builtin::BI__lzcnt &&
12298
0
                           BuiltinOp != Builtin::BI__lzcnt64;
12299
12300
0
    if (ZeroIsUndefined && !Val)
12301
0
      return Error(E);
12302
12303
0
    return Success(Val.countl_zero(), E);
12304
0
  }
12305
12306
0
  case Builtin::BI__builtin_constant_p: {
12307
0
    const Expr *Arg = E->getArg(0);
12308
0
    if (EvaluateBuiltinConstantP(Info, Arg))
12309
0
      return Success(true, E);
12310
0
    if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12311
      // Outside a constant context, eagerly evaluate to false in the presence
12312
      // of side-effects in order to avoid -Wunsequenced false-positives in
12313
      // a branch on __builtin_constant_p(expr).
12314
0
      return Success(false, E);
12315
0
    }
12316
0
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12317
0
    return false;
12318
0
  }
12319
12320
0
  case Builtin::BI__builtin_is_constant_evaluated: {
12321
0
    const auto *Callee = Info.CurrentCall->getCallee();
12322
0
    if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12323
0
        (Info.CallStackDepth == 1 ||
12324
0
         (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12325
0
          Callee->getIdentifier() &&
12326
0
          Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12327
      // FIXME: Find a better way to avoid duplicated diagnostics.
12328
0
      if (Info.EvalStatus.Diag)
12329
0
        Info.report((Info.CallStackDepth == 1)
12330
0
                        ? E->getExprLoc()
12331
0
                        : Info.CurrentCall->getCallRange().getBegin(),
12332
0
                    diag::warn_is_constant_evaluated_always_true_constexpr)
12333
0
            << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12334
0
                                         : "std::is_constant_evaluated");
12335
0
    }
12336
12337
0
    return Success(Info.InConstantContext, E);
12338
0
  }
12339
12340
0
  case Builtin::BI__builtin_ctz:
12341
0
  case Builtin::BI__builtin_ctzl:
12342
0
  case Builtin::BI__builtin_ctzll:
12343
0
  case Builtin::BI__builtin_ctzs: {
12344
0
    APSInt Val;
12345
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12346
0
      return false;
12347
0
    if (!Val)
12348
0
      return Error(E);
12349
12350
0
    return Success(Val.countr_zero(), E);
12351
0
  }
12352
12353
0
  case Builtin::BI__builtin_eh_return_data_regno: {
12354
0
    int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12355
0
    Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12356
0
    return Success(Operand, E);
12357
0
  }
12358
12359
0
  case Builtin::BI__builtin_expect:
12360
0
  case Builtin::BI__builtin_expect_with_probability:
12361
0
    return Visit(E->getArg(0));
12362
12363
0
  case Builtin::BI__builtin_ffs:
12364
0
  case Builtin::BI__builtin_ffsl:
12365
0
  case Builtin::BI__builtin_ffsll: {
12366
0
    APSInt Val;
12367
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12368
0
      return false;
12369
12370
0
    unsigned N = Val.countr_zero();
12371
0
    return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12372
0
  }
12373
12374
0
  case Builtin::BI__builtin_fpclassify: {
12375
0
    APFloat Val(0.0);
12376
0
    if (!EvaluateFloat(E->getArg(5), Val, Info))
12377
0
      return false;
12378
0
    unsigned Arg;
12379
0
    switch (Val.getCategory()) {
12380
0
    case APFloat::fcNaN: Arg = 0; break;
12381
0
    case APFloat::fcInfinity: Arg = 1; break;
12382
0
    case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12383
0
    case APFloat::fcZero: Arg = 4; break;
12384
0
    }
12385
0
    return Visit(E->getArg(Arg));
12386
0
  }
12387
12388
0
  case Builtin::BI__builtin_isinf_sign: {
12389
0
    APFloat Val(0.0);
12390
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12391
0
           Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12392
0
  }
12393
12394
0
  case Builtin::BI__builtin_isinf: {
12395
0
    APFloat Val(0.0);
12396
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12397
0
           Success(Val.isInfinity() ? 1 : 0, E);
12398
0
  }
12399
12400
0
  case Builtin::BI__builtin_isfinite: {
12401
0
    APFloat Val(0.0);
12402
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12403
0
           Success(Val.isFinite() ? 1 : 0, E);
12404
0
  }
12405
12406
0
  case Builtin::BI__builtin_isnan: {
12407
0
    APFloat Val(0.0);
12408
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12409
0
           Success(Val.isNaN() ? 1 : 0, E);
12410
0
  }
12411
12412
0
  case Builtin::BI__builtin_isnormal: {
12413
0
    APFloat Val(0.0);
12414
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12415
0
           Success(Val.isNormal() ? 1 : 0, E);
12416
0
  }
12417
12418
0
  case Builtin::BI__builtin_issubnormal: {
12419
0
    APFloat Val(0.0);
12420
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12421
0
           Success(Val.isDenormal() ? 1 : 0, E);
12422
0
  }
12423
12424
0
  case Builtin::BI__builtin_iszero: {
12425
0
    APFloat Val(0.0);
12426
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12427
0
           Success(Val.isZero() ? 1 : 0, E);
12428
0
  }
12429
12430
0
  case Builtin::BI__builtin_issignaling: {
12431
0
    APFloat Val(0.0);
12432
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12433
0
           Success(Val.isSignaling() ? 1 : 0, E);
12434
0
  }
12435
12436
0
  case Builtin::BI__builtin_isfpclass: {
12437
0
    APSInt MaskVal;
12438
0
    if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12439
0
      return false;
12440
0
    unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
12441
0
    APFloat Val(0.0);
12442
0
    return EvaluateFloat(E->getArg(0), Val, Info) &&
12443
0
           Success((Val.classify() & Test) ? 1 : 0, E);
12444
0
  }
12445
12446
0
  case Builtin::BI__builtin_parity:
12447
0
  case Builtin::BI__builtin_parityl:
12448
0
  case Builtin::BI__builtin_parityll: {
12449
0
    APSInt Val;
12450
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12451
0
      return false;
12452
12453
0
    return Success(Val.popcount() % 2, E);
12454
0
  }
12455
12456
0
  case Builtin::BI__builtin_popcount:
12457
0
  case Builtin::BI__builtin_popcountl:
12458
0
  case Builtin::BI__builtin_popcountll:
12459
0
  case Builtin::BI__popcnt16: // Microsoft variants of popcount
12460
0
  case Builtin::BI__popcnt:
12461
0
  case Builtin::BI__popcnt64: {
12462
0
    APSInt Val;
12463
0
    if (!EvaluateInteger(E->getArg(0), Val, Info))
12464
0
      return false;
12465
12466
0
    return Success(Val.popcount(), E);
12467
0
  }
12468
12469
0
  case Builtin::BI__builtin_rotateleft8:
12470
0
  case Builtin::BI__builtin_rotateleft16:
12471
0
  case Builtin::BI__builtin_rotateleft32:
12472
0
  case Builtin::BI__builtin_rotateleft64:
12473
0
  case Builtin::BI_rotl8: // Microsoft variants of rotate right
12474
0
  case Builtin::BI_rotl16:
12475
0
  case Builtin::BI_rotl:
12476
0
  case Builtin::BI_lrotl:
12477
0
  case Builtin::BI_rotl64: {
12478
0
    APSInt Val, Amt;
12479
0
    if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12480
0
        !EvaluateInteger(E->getArg(1), Amt, Info))
12481
0
      return false;
12482
12483
0
    return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12484
0
  }
12485
12486
0
  case Builtin::BI__builtin_rotateright8:
12487
0
  case Builtin::BI__builtin_rotateright16:
12488
0
  case Builtin::BI__builtin_rotateright32:
12489
0
  case Builtin::BI__builtin_rotateright64:
12490
0
  case Builtin::BI_rotr8: // Microsoft variants of rotate right
12491
0
  case Builtin::BI_rotr16:
12492
0
  case Builtin::BI_rotr:
12493
0
  case Builtin::BI_lrotr:
12494
0
  case Builtin::BI_rotr64: {
12495
0
    APSInt Val, Amt;
12496
0
    if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12497
0
        !EvaluateInteger(E->getArg(1), Amt, Info))
12498
0
      return false;
12499
12500
0
    return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12501
0
  }
12502
12503
0
  case Builtin::BIstrlen:
12504
0
  case Builtin::BIwcslen:
12505
    // A call to strlen is not a constant expression.
12506
0
    if (Info.getLangOpts().CPlusPlus11)
12507
0
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12508
0
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12509
0
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12510
0
    else
12511
0
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12512
0
    [[fallthrough]];
12513
0
  case Builtin::BI__builtin_strlen:
12514
0
  case Builtin::BI__builtin_wcslen: {
12515
    // As an extension, we support __builtin_strlen() as a constant expression,
12516
    // and support folding strlen() to a constant.
12517
0
    uint64_t StrLen;
12518
0
    if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12519
0
      return Success(StrLen, E);
12520
0
    return false;
12521
0
  }
12522
12523
0
  case Builtin::BIstrcmp:
12524
0
  case Builtin::BIwcscmp:
12525
0
  case Builtin::BIstrncmp:
12526
0
  case Builtin::BIwcsncmp:
12527
0
  case Builtin::BImemcmp:
12528
0
  case Builtin::BIbcmp:
12529
0
  case Builtin::BIwmemcmp:
12530
    // A call to strlen is not a constant expression.
12531
0
    if (Info.getLangOpts().CPlusPlus11)
12532
0
      Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12533
0
          << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12534
0
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12535
0
    else
12536
0
      Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12537
0
    [[fallthrough]];
12538
0
  case Builtin::BI__builtin_strcmp:
12539
0
  case Builtin::BI__builtin_wcscmp:
12540
0
  case Builtin::BI__builtin_strncmp:
12541
0
  case Builtin::BI__builtin_wcsncmp:
12542
0
  case Builtin::BI__builtin_memcmp:
12543
0
  case Builtin::BI__builtin_bcmp:
12544
0
  case Builtin::BI__builtin_wmemcmp: {
12545
0
    LValue String1, String2;
12546
0
    if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12547
0
        !EvaluatePointer(E->getArg(1), String2, Info))
12548
0
      return false;
12549
12550
0
    uint64_t MaxLength = uint64_t(-1);
12551
0
    if (BuiltinOp != Builtin::BIstrcmp &&
12552
0
        BuiltinOp != Builtin::BIwcscmp &&
12553
0
        BuiltinOp != Builtin::BI__builtin_strcmp &&
12554
0
        BuiltinOp != Builtin::BI__builtin_wcscmp) {
12555
0
      APSInt N;
12556
0
      if (!EvaluateInteger(E->getArg(2), N, Info))
12557
0
        return false;
12558
0
      MaxLength = N.getZExtValue();
12559
0
    }
12560
12561
    // Empty substrings compare equal by definition.
12562
0
    if (MaxLength == 0u)
12563
0
      return Success(0, E);
12564
12565
0
    if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12566
0
        !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12567
0
        String1.Designator.Invalid || String2.Designator.Invalid)
12568
0
      return false;
12569
12570
0
    QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12571
0
    QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12572
12573
0
    bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12574
0
                     BuiltinOp == Builtin::BIbcmp ||
12575
0
                     BuiltinOp == Builtin::BI__builtin_memcmp ||
12576
0
                     BuiltinOp == Builtin::BI__builtin_bcmp;
12577
12578
0
    assert(IsRawByte ||
12579
0
           (Info.Ctx.hasSameUnqualifiedType(
12580
0
                CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12581
0
            Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12582
12583
    // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12584
    // 'char8_t', but no other types.
12585
0
    if (IsRawByte &&
12586
0
        !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12587
      // FIXME: Consider using our bit_cast implementation to support this.
12588
0
      Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12589
0
          << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12590
0
          << CharTy1 << CharTy2;
12591
0
      return false;
12592
0
    }
12593
12594
0
    const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12595
0
      return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12596
0
             handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12597
0
             Char1.isInt() && Char2.isInt();
12598
0
    };
12599
0
    const auto &AdvanceElems = [&] {
12600
0
      return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12601
0
             HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12602
0
    };
12603
12604
0
    bool StopAtNull =
12605
0
        (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12606
0
         BuiltinOp != Builtin::BIwmemcmp &&
12607
0
         BuiltinOp != Builtin::BI__builtin_memcmp &&
12608
0
         BuiltinOp != Builtin::BI__builtin_bcmp &&
12609
0
         BuiltinOp != Builtin::BI__builtin_wmemcmp);
12610
0
    bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12611
0
                  BuiltinOp == Builtin::BIwcsncmp ||
12612
0
                  BuiltinOp == Builtin::BIwmemcmp ||
12613
0
                  BuiltinOp == Builtin::BI__builtin_wcscmp ||
12614
0
                  BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12615
0
                  BuiltinOp == Builtin::BI__builtin_wmemcmp;
12616
12617
0
    for (; MaxLength; --MaxLength) {
12618
0
      APValue Char1, Char2;
12619
0
      if (!ReadCurElems(Char1, Char2))
12620
0
        return false;
12621
0
      if (Char1.getInt().ne(Char2.getInt())) {
12622
0
        if (IsWide) // wmemcmp compares with wchar_t signedness.
12623
0
          return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12624
        // memcmp always compares unsigned chars.
12625
0
        return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12626
0
      }
12627
0
      if (StopAtNull && !Char1.getInt())
12628
0
        return Success(0, E);
12629
0
      assert(!(StopAtNull && !Char2.getInt()));
12630
0
      if (!AdvanceElems())
12631
0
        return false;
12632
0
    }
12633
    // We hit the strncmp / memcmp limit.
12634
0
    return Success(0, E);
12635
0
  }
12636
12637
0
  case Builtin::BI__atomic_always_lock_free:
12638
0
  case Builtin::BI__atomic_is_lock_free:
12639
0
  case Builtin::BI__c11_atomic_is_lock_free: {
12640
0
    APSInt SizeVal;
12641
0
    if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12642
0
      return false;
12643
12644
    // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12645
    // of two less than or equal to the maximum inline atomic width, we know it
12646
    // is lock-free.  If the size isn't a power of two, or greater than the
12647
    // maximum alignment where we promote atomics, we know it is not lock-free
12648
    // (at least not in the sense of atomic_is_lock_free).  Otherwise,
12649
    // the answer can only be determined at runtime; for example, 16-byte
12650
    // atomics have lock-free implementations on some, but not all,
12651
    // x86-64 processors.
12652
12653
    // Check power-of-two.
12654
0
    CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12655
0
    if (Size.isPowerOfTwo()) {
12656
      // Check against inlining width.
12657
0
      unsigned InlineWidthBits =
12658
0
          Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12659
0
      if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12660
0
        if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12661
0
            Size == CharUnits::One() ||
12662
0
            E->getArg(1)->isNullPointerConstant(Info.Ctx,
12663
0
                                                Expr::NPC_NeverValueDependent))
12664
          // OK, we will inline appropriately-aligned operations of this size,
12665
          // and _Atomic(T) is appropriately-aligned.
12666
0
          return Success(1, E);
12667
12668
0
        QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12669
0
          castAs<PointerType>()->getPointeeType();
12670
0
        if (!PointeeType->isIncompleteType() &&
12671
0
            Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12672
          // OK, we will inline operations on this object.
12673
0
          return Success(1, E);
12674
0
        }
12675
0
      }
12676
0
    }
12677
12678
0
    return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12679
0
        Success(0, E) : Error(E);
12680
0
  }
12681
0
  case Builtin::BI__builtin_add_overflow:
12682
0
  case Builtin::BI__builtin_sub_overflow:
12683
0
  case Builtin::BI__builtin_mul_overflow:
12684
0
  case Builtin::BI__builtin_sadd_overflow:
12685
0
  case Builtin::BI__builtin_uadd_overflow:
12686
0
  case Builtin::BI__builtin_uaddl_overflow:
12687
0
  case Builtin::BI__builtin_uaddll_overflow:
12688
0
  case Builtin::BI__builtin_usub_overflow:
12689
0
  case Builtin::BI__builtin_usubl_overflow:
12690
0
  case Builtin::BI__builtin_usubll_overflow:
12691
0
  case Builtin::BI__builtin_umul_overflow:
12692
0
  case Builtin::BI__builtin_umull_overflow:
12693
0
  case Builtin::BI__builtin_umulll_overflow:
12694
0
  case Builtin::BI__builtin_saddl_overflow:
12695
0
  case Builtin::BI__builtin_saddll_overflow:
12696
0
  case Builtin::BI__builtin_ssub_overflow:
12697
0
  case Builtin::BI__builtin_ssubl_overflow:
12698
0
  case Builtin::BI__builtin_ssubll_overflow:
12699
0
  case Builtin::BI__builtin_smul_overflow:
12700
0
  case Builtin::BI__builtin_smull_overflow:
12701
0
  case Builtin::BI__builtin_smulll_overflow: {
12702
0
    LValue ResultLValue;
12703
0
    APSInt LHS, RHS;
12704
12705
0
    QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12706
0
    if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12707
0
        !EvaluateInteger(E->getArg(1), RHS, Info) ||
12708
0
        !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12709
0
      return false;
12710
12711
0
    APSInt Result;
12712
0
    bool DidOverflow = false;
12713
12714
    // If the types don't have to match, enlarge all 3 to the largest of them.
12715
0
    if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12716
0
        BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12717
0
        BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12718
0
      bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12719
0
                      ResultType->isSignedIntegerOrEnumerationType();
12720
0
      bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12721
0
                      ResultType->isSignedIntegerOrEnumerationType();
12722
0
      uint64_t LHSSize = LHS.getBitWidth();
12723
0
      uint64_t RHSSize = RHS.getBitWidth();
12724
0
      uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12725
0
      uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12726
12727
      // Add an additional bit if the signedness isn't uniformly agreed to. We
12728
      // could do this ONLY if there is a signed and an unsigned that both have
12729
      // MaxBits, but the code to check that is pretty nasty.  The issue will be
12730
      // caught in the shrink-to-result later anyway.
12731
0
      if (IsSigned && !AllSigned)
12732
0
        ++MaxBits;
12733
12734
0
      LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12735
0
      RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12736
0
      Result = APSInt(MaxBits, !IsSigned);
12737
0
    }
12738
12739
    // Find largest int.
12740
0
    switch (BuiltinOp) {
12741
0
    default:
12742
0
      llvm_unreachable("Invalid value for BuiltinOp");
12743
0
    case Builtin::BI__builtin_add_overflow:
12744
0
    case Builtin::BI__builtin_sadd_overflow:
12745
0
    case Builtin::BI__builtin_saddl_overflow:
12746
0
    case Builtin::BI__builtin_saddll_overflow:
12747
0
    case Builtin::BI__builtin_uadd_overflow:
12748
0
    case Builtin::BI__builtin_uaddl_overflow:
12749
0
    case Builtin::BI__builtin_uaddll_overflow:
12750
0
      Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12751
0
                              : LHS.uadd_ov(RHS, DidOverflow);
12752
0
      break;
12753
0
    case Builtin::BI__builtin_sub_overflow:
12754
0
    case Builtin::BI__builtin_ssub_overflow:
12755
0
    case Builtin::BI__builtin_ssubl_overflow:
12756
0
    case Builtin::BI__builtin_ssubll_overflow:
12757
0
    case Builtin::BI__builtin_usub_overflow:
12758
0
    case Builtin::BI__builtin_usubl_overflow:
12759
0
    case Builtin::BI__builtin_usubll_overflow:
12760
0
      Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12761
0
                              : LHS.usub_ov(RHS, DidOverflow);
12762
0
      break;
12763
0
    case Builtin::BI__builtin_mul_overflow:
12764
0
    case Builtin::BI__builtin_smul_overflow:
12765
0
    case Builtin::BI__builtin_smull_overflow:
12766
0
    case Builtin::BI__builtin_smulll_overflow:
12767
0
    case Builtin::BI__builtin_umul_overflow:
12768
0
    case Builtin::BI__builtin_umull_overflow:
12769
0
    case Builtin::BI__builtin_umulll_overflow:
12770
0
      Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12771
0
                              : LHS.umul_ov(RHS, DidOverflow);
12772
0
      break;
12773
0
    }
12774
12775
    // In the case where multiple sizes are allowed, truncate and see if
12776
    // the values are the same.
12777
0
    if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12778
0
        BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12779
0
        BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12780
      // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12781
      // since it will give us the behavior of a TruncOrSelf in the case where
12782
      // its parameter <= its size.  We previously set Result to be at least the
12783
      // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12784
      // will work exactly like TruncOrSelf.
12785
0
      APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12786
0
      Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12787
12788
0
      if (!APSInt::isSameValue(Temp, Result))
12789
0
        DidOverflow = true;
12790
0
      Result = Temp;
12791
0
    }
12792
12793
0
    APValue APV{Result};
12794
0
    if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12795
0
      return false;
12796
0
    return Success(DidOverflow, E);
12797
0
  }
12798
0
  }
12799
0
}
12800
12801
/// Determine whether this is a pointer past the end of the complete
12802
/// object referred to by the lvalue.
12803
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12804
0
                                            const LValue &LV) {
12805
  // A null pointer can be viewed as being "past the end" but we don't
12806
  // choose to look at it that way here.
12807
0
  if (!LV.getLValueBase())
12808
0
    return false;
12809
12810
  // If the designator is valid and refers to a subobject, we're not pointing
12811
  // past the end.
12812
0
  if (!LV.getLValueDesignator().Invalid &&
12813
0
      !LV.getLValueDesignator().isOnePastTheEnd())
12814
0
    return false;
12815
12816
  // A pointer to an incomplete type might be past-the-end if the type's size is
12817
  // zero.  We cannot tell because the type is incomplete.
12818
0
  QualType Ty = getType(LV.getLValueBase());
12819
0
  if (Ty->isIncompleteType())
12820
0
    return true;
12821
12822
  // We're a past-the-end pointer if we point to the byte after the object,
12823
  // no matter what our type or path is.
12824
0
  auto Size = Ctx.getTypeSizeInChars(Ty);
12825
0
  return LV.getLValueOffset() == Size;
12826
0
}
12827
12828
namespace {
12829
12830
/// Data recursive integer evaluator of certain binary operators.
12831
///
12832
/// We use a data recursive algorithm for binary operators so that we are able
12833
/// to handle extreme cases of chained binary operators without causing stack
12834
/// overflow.
12835
class DataRecursiveIntBinOpEvaluator {
12836
  struct EvalResult {
12837
    APValue Val;
12838
    bool Failed = false;
12839
12840
0
    EvalResult() = default;
12841
12842
0
    void swap(EvalResult &RHS) {
12843
0
      Val.swap(RHS.Val);
12844
0
      Failed = RHS.Failed;
12845
0
      RHS.Failed = false;
12846
0
    }
12847
  };
12848
12849
  struct Job {
12850
    const Expr *E;
12851
    EvalResult LHSResult; // meaningful only for binary operator expression.
12852
    enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12853
12854
0
    Job() = default;
12855
0
    Job(Job &&) = default;
12856
12857
0
    void startSpeculativeEval(EvalInfo &Info) {
12858
0
      SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12859
0
    }
12860
12861
  private:
12862
    SpeculativeEvaluationRAII SpecEvalRAII;
12863
  };
12864
12865
  SmallVector<Job, 16> Queue;
12866
12867
  IntExprEvaluator &IntEval;
12868
  EvalInfo &Info;
12869
  APValue &FinalResult;
12870
12871
public:
12872
  DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12873
0
    : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12874
12875
  /// True if \param E is a binary operator that we are going to handle
12876
  /// data recursively.
12877
  /// We handle binary operators that are comma, logical, or that have operands
12878
  /// with integral or enumeration type.
12879
0
  static bool shouldEnqueue(const BinaryOperator *E) {
12880
0
    return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12881
0
           (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12882
0
            E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12883
0
            E->getRHS()->getType()->isIntegralOrEnumerationType());
12884
0
  }
12885
12886
0
  bool Traverse(const BinaryOperator *E) {
12887
0
    enqueue(E);
12888
0
    EvalResult PrevResult;
12889
0
    while (!Queue.empty())
12890
0
      process(PrevResult);
12891
12892
0
    if (PrevResult.Failed) return false;
12893
12894
0
    FinalResult.swap(PrevResult.Val);
12895
0
    return true;
12896
0
  }
12897
12898
private:
12899
0
  bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12900
0
    return IntEval.Success(Value, E, Result);
12901
0
  }
12902
0
  bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12903
0
    return IntEval.Success(Value, E, Result);
12904
0
  }
12905
0
  bool Error(const Expr *E) {
12906
0
    return IntEval.Error(E);
12907
0
  }
12908
0
  bool Error(const Expr *E, diag::kind D) {
12909
0
    return IntEval.Error(E, D);
12910
0
  }
12911
12912
0
  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12913
0
    return Info.CCEDiag(E, D);
12914
0
  }
12915
12916
  // Returns true if visiting the RHS is necessary, false otherwise.
12917
  bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12918
                         bool &SuppressRHSDiags);
12919
12920
  bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12921
                  const BinaryOperator *E, APValue &Result);
12922
12923
0
  void EvaluateExpr(const Expr *E, EvalResult &Result) {
12924
0
    Result.Failed = !Evaluate(Result.Val, Info, E);
12925
0
    if (Result.Failed)
12926
0
      Result.Val = APValue();
12927
0
  }
12928
12929
  void process(EvalResult &Result);
12930
12931
0
  void enqueue(const Expr *E) {
12932
0
    E = E->IgnoreParens();
12933
0
    Queue.resize(Queue.size()+1);
12934
0
    Queue.back().E = E;
12935
0
    Queue.back().Kind = Job::AnyExprKind;
12936
0
  }
12937
};
12938
12939
}
12940
12941
bool DataRecursiveIntBinOpEvaluator::
12942
       VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12943
0
                         bool &SuppressRHSDiags) {
12944
0
  if (E->getOpcode() == BO_Comma) {
12945
    // Ignore LHS but note if we could not evaluate it.
12946
0
    if (LHSResult.Failed)
12947
0
      return Info.noteSideEffect();
12948
0
    return true;
12949
0
  }
12950
12951
0
  if (E->isLogicalOp()) {
12952
0
    bool LHSAsBool;
12953
0
    if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12954
      // We were able to evaluate the LHS, see if we can get away with not
12955
      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12956
0
      if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12957
0
        Success(LHSAsBool, E, LHSResult.Val);
12958
0
        return false; // Ignore RHS
12959
0
      }
12960
0
    } else {
12961
0
      LHSResult.Failed = true;
12962
12963
      // Since we weren't able to evaluate the left hand side, it
12964
      // might have had side effects.
12965
0
      if (!Info.noteSideEffect())
12966
0
        return false;
12967
12968
      // We can't evaluate the LHS; however, sometimes the result
12969
      // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12970
      // Don't ignore RHS and suppress diagnostics from this arm.
12971
0
      SuppressRHSDiags = true;
12972
0
    }
12973
12974
0
    return true;
12975
0
  }
12976
12977
0
  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12978
0
         E->getRHS()->getType()->isIntegralOrEnumerationType());
12979
12980
0
  if (LHSResult.Failed && !Info.noteFailure())
12981
0
    return false; // Ignore RHS;
12982
12983
0
  return true;
12984
0
}
12985
12986
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12987
0
                                    bool IsSub) {
12988
  // Compute the new offset in the appropriate width, wrapping at 64 bits.
12989
  // FIXME: When compiling for a 32-bit target, we should use 32-bit
12990
  // offsets.
12991
0
  assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12992
0
  CharUnits &Offset = LVal.getLValueOffset();
12993
0
  uint64_t Offset64 = Offset.getQuantity();
12994
0
  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12995
0
  Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12996
0
                                         : Offset64 + Index64);
12997
0
}
12998
12999
bool DataRecursiveIntBinOpEvaluator::
13000
       VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
13001
0
                  const BinaryOperator *E, APValue &Result) {
13002
0
  if (E->getOpcode() == BO_Comma) {
13003
0
    if (RHSResult.Failed)
13004
0
      return false;
13005
0
    Result = RHSResult.Val;
13006
0
    return true;
13007
0
  }
13008
13009
0
  if (E->isLogicalOp()) {
13010
0
    bool lhsResult, rhsResult;
13011
0
    bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
13012
0
    bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
13013
13014
0
    if (LHSIsOK) {
13015
0
      if (RHSIsOK) {
13016
0
        if (E->getOpcode() == BO_LOr)
13017
0
          return Success(lhsResult || rhsResult, E, Result);
13018
0
        else
13019
0
          return Success(lhsResult && rhsResult, E, Result);
13020
0
      }
13021
0
    } else {
13022
0
      if (RHSIsOK) {
13023
        // We can't evaluate the LHS; however, sometimes the result
13024
        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13025
0
        if (rhsResult == (E->getOpcode() == BO_LOr))
13026
0
          return Success(rhsResult, E, Result);
13027
0
      }
13028
0
    }
13029
13030
0
    return false;
13031
0
  }
13032
13033
0
  assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13034
0
         E->getRHS()->getType()->isIntegralOrEnumerationType());
13035
13036
0
  if (LHSResult.Failed || RHSResult.Failed)
13037
0
    return false;
13038
13039
0
  const APValue &LHSVal = LHSResult.Val;
13040
0
  const APValue &RHSVal = RHSResult.Val;
13041
13042
  // Handle cases like (unsigned long)&a + 4.
13043
0
  if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13044
0
    Result = LHSVal;
13045
0
    addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13046
0
    return true;
13047
0
  }
13048
13049
  // Handle cases like 4 + (unsigned long)&a
13050
0
  if (E->getOpcode() == BO_Add &&
13051
0
      RHSVal.isLValue() && LHSVal.isInt()) {
13052
0
    Result = RHSVal;
13053
0
    addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
13054
0
    return true;
13055
0
  }
13056
13057
0
  if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13058
    // Handle (intptr_t)&&A - (intptr_t)&&B.
13059
0
    if (!LHSVal.getLValueOffset().isZero() ||
13060
0
        !RHSVal.getLValueOffset().isZero())
13061
0
      return false;
13062
0
    const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
13063
0
    const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
13064
0
    if (!LHSExpr || !RHSExpr)
13065
0
      return false;
13066
0
    const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13067
0
    const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13068
0
    if (!LHSAddrExpr || !RHSAddrExpr)
13069
0
      return false;
13070
    // Make sure both labels come from the same function.
13071
0
    if (LHSAddrExpr->getLabel()->getDeclContext() !=
13072
0
        RHSAddrExpr->getLabel()->getDeclContext())
13073
0
      return false;
13074
0
    Result = APValue(LHSAddrExpr, RHSAddrExpr);
13075
0
    return true;
13076
0
  }
13077
13078
  // All the remaining cases expect both operands to be an integer
13079
0
  if (!LHSVal.isInt() || !RHSVal.isInt())
13080
0
    return Error(E);
13081
13082
  // Set up the width and signedness manually, in case it can't be deduced
13083
  // from the operation we're performing.
13084
  // FIXME: Don't do this in the cases where we can deduce it.
13085
0
  APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13086
0
               E->getType()->isUnsignedIntegerOrEnumerationType());
13087
0
  if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13088
0
                         RHSVal.getInt(), Value))
13089
0
    return false;
13090
0
  return Success(Value, E, Result);
13091
0
}
13092
13093
0
void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
13094
0
  Job &job = Queue.back();
13095
13096
0
  switch (job.Kind) {
13097
0
    case Job::AnyExprKind: {
13098
0
      if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
13099
0
        if (shouldEnqueue(Bop)) {
13100
0
          job.Kind = Job::BinOpKind;
13101
0
          enqueue(Bop->getLHS());
13102
0
          return;
13103
0
        }
13104
0
      }
13105
13106
0
      EvaluateExpr(job.E, Result);
13107
0
      Queue.pop_back();
13108
0
      return;
13109
0
    }
13110
13111
0
    case Job::BinOpKind: {
13112
0
      const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13113
0
      bool SuppressRHSDiags = false;
13114
0
      if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
13115
0
        Queue.pop_back();
13116
0
        return;
13117
0
      }
13118
0
      if (SuppressRHSDiags)
13119
0
        job.startSpeculativeEval(Info);
13120
0
      job.LHSResult.swap(Result);
13121
0
      job.Kind = Job::BinOpVisitedLHSKind;
13122
0
      enqueue(Bop->getRHS());
13123
0
      return;
13124
0
    }
13125
13126
0
    case Job::BinOpVisitedLHSKind: {
13127
0
      const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
13128
0
      EvalResult RHS;
13129
0
      RHS.swap(Result);
13130
0
      Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
13131
0
      Queue.pop_back();
13132
0
      return;
13133
0
    }
13134
0
  }
13135
13136
0
  llvm_unreachable("Invalid Job::Kind!");
13137
0
}
13138
13139
namespace {
13140
enum class CmpResult {
13141
  Unequal,
13142
  Less,
13143
  Equal,
13144
  Greater,
13145
  Unordered,
13146
};
13147
}
13148
13149
template <class SuccessCB, class AfterCB>
13150
static bool
13151
EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
13152
0
                                 SuccessCB &&Success, AfterCB &&DoAfter) {
13153
0
  assert(!E->isValueDependent());
13154
0
  assert(E->isComparisonOp() && "expected comparison operator");
13155
0
  assert((E->getOpcode() == BO_Cmp ||
13156
0
          E->getType()->isIntegralOrEnumerationType()) &&
13157
0
         "unsupported binary expression evaluation");
13158
0
  auto Error = [&](const Expr *E) {
13159
0
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13160
0
    return false;
13161
0
  };
Unexecuted instantiation: ExprConstant.cpp:EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4&&)::{lambda(clang::Expr const*)#1}::operator()(clang::Expr const*) const
Unexecuted instantiation: ExprConstant.cpp:EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6&&)::{lambda(clang::Expr const*)#1}::operator()(clang::Expr const*) const
13162
13163
0
  bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13164
0
  bool IsEquality = E->isEqualityOp();
13165
13166
0
  QualType LHSTy = E->getLHS()->getType();
13167
0
  QualType RHSTy = E->getRHS()->getType();
13168
13169
0
  if (LHSTy->isIntegralOrEnumerationType() &&
13170
0
      RHSTy->isIntegralOrEnumerationType()) {
13171
0
    APSInt LHS, RHS;
13172
0
    bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13173
0
    if (!LHSOK && !Info.noteFailure())
13174
0
      return false;
13175
0
    if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13176
0
      return false;
13177
0
    if (LHS < RHS)
13178
0
      return Success(CmpResult::Less, E);
13179
0
    if (LHS > RHS)
13180
0
      return Success(CmpResult::Greater, E);
13181
0
    return Success(CmpResult::Equal, E);
13182
0
  }
13183
13184
0
  if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13185
0
    APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
13186
0
    APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
13187
13188
0
    bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13189
0
    if (!LHSOK && !Info.noteFailure())
13190
0
      return false;
13191
0
    if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13192
0
      return false;
13193
0
    if (LHSFX < RHSFX)
13194
0
      return Success(CmpResult::Less, E);
13195
0
    if (LHSFX > RHSFX)
13196
0
      return Success(CmpResult::Greater, E);
13197
0
    return Success(CmpResult::Equal, E);
13198
0
  }
13199
13200
0
  if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13201
0
    ComplexValue LHS, RHS;
13202
0
    bool LHSOK;
13203
0
    if (E->isAssignmentOp()) {
13204
0
      LValue LV;
13205
0
      EvaluateLValue(E->getLHS(), LV, Info);
13206
0
      LHSOK = false;
13207
0
    } else if (LHSTy->isRealFloatingType()) {
13208
0
      LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13209
0
      if (LHSOK) {
13210
0
        LHS.makeComplexFloat();
13211
0
        LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
13212
0
      }
13213
0
    } else {
13214
0
      LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13215
0
    }
13216
0
    if (!LHSOK && !Info.noteFailure())
13217
0
      return false;
13218
13219
0
    if (E->getRHS()->getType()->isRealFloatingType()) {
13220
0
      if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13221
0
        return false;
13222
0
      RHS.makeComplexFloat();
13223
0
      RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
13224
0
    } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13225
0
      return false;
13226
13227
0
    if (LHS.isComplexFloat()) {
13228
0
      APFloat::cmpResult CR_r =
13229
0
        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
13230
0
      APFloat::cmpResult CR_i =
13231
0
        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
13232
0
      bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
13233
0
      return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13234
0
    } else {
13235
0
      assert(IsEquality && "invalid complex comparison");
13236
0
      bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
13237
0
                     LHS.getComplexIntImag() == RHS.getComplexIntImag();
13238
0
      return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
13239
0
    }
13240
0
  }
13241
13242
0
  if (LHSTy->isRealFloatingType() &&
13243
0
      RHSTy->isRealFloatingType()) {
13244
0
    APFloat RHS(0.0), LHS(0.0);
13245
13246
0
    bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13247
0
    if (!LHSOK && !Info.noteFailure())
13248
0
      return false;
13249
13250
0
    if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13251
0
      return false;
13252
13253
0
    assert(E->isComparisonOp() && "Invalid binary operator!");
13254
0
    llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
13255
0
    if (!Info.InConstantContext &&
13256
0
        APFloatCmpResult == APFloat::cmpUnordered &&
13257
0
        E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13258
      // Note: Compares may raise invalid in some cases involving NaN or sNaN.
13259
0
      Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
13260
0
      return false;
13261
0
    }
13262
0
    auto GetCmpRes = [&]() {
13263
0
      switch (APFloatCmpResult) {
13264
0
      case APFloat::cmpEqual:
13265
0
        return CmpResult::Equal;
13266
0
      case APFloat::cmpLessThan:
13267
0
        return CmpResult::Less;
13268
0
      case APFloat::cmpGreaterThan:
13269
0
        return CmpResult::Greater;
13270
0
      case APFloat::cmpUnordered:
13271
0
        return CmpResult::Unordered;
13272
0
      }
13273
0
      llvm_unreachable("Unrecognised APFloat::cmpResult enum");
13274
0
    };
Unexecuted instantiation: ExprConstant.cpp:EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4&&)::{lambda()#1}::operator()() const
Unexecuted instantiation: ExprConstant.cpp:EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6&&)::{lambda()#1}::operator()() const
13275
0
    return Success(GetCmpRes(), E);
13276
0
  }
13277
13278
0
  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13279
0
    LValue LHSValue, RHSValue;
13280
13281
0
    bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13282
0
    if (!LHSOK && !Info.noteFailure())
13283
0
      return false;
13284
13285
0
    if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13286
0
      return false;
13287
13288
    // Reject differing bases from the normal codepath; we special-case
13289
    // comparisons to null.
13290
0
    if (!HasSameBase(LHSValue, RHSValue)) {
13291
0
      auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
13292
0
        std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13293
0
        std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13294
0
        Info.FFDiag(E, DiagID)
13295
0
            << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
13296
0
        return false;
13297
0
      };
Unexecuted instantiation: ExprConstant.cpp:EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4&&)::{lambda(unsigned int, bool)#1}::operator()(unsigned int, bool) const
Unexecuted instantiation: ExprConstant.cpp:EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6&&)::{lambda(unsigned int, bool)#1}::operator()(unsigned int, bool) const
13298
      // Inequalities and subtractions between unrelated pointers have
13299
      // unspecified or undefined behavior.
13300
0
      if (!IsEquality)
13301
0
        return DiagComparison(
13302
0
            diag::note_constexpr_pointer_comparison_unspecified);
13303
      // A constant address may compare equal to the address of a symbol.
13304
      // The one exception is that address of an object cannot compare equal
13305
      // to a null pointer constant.
13306
      // TODO: Should we restrict this to actual null pointers, and exclude the
13307
      // case of zero cast to pointer type?
13308
0
      if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
13309
0
          (!RHSValue.Base && !RHSValue.Offset.isZero()))
13310
0
        return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
13311
0
                              !RHSValue.Base);
13312
      // It's implementation-defined whether distinct literals will have
13313
      // distinct addresses. In clang, the result of such a comparison is
13314
      // unspecified, so it is not a constant expression. However, we do know
13315
      // that the address of a literal will be non-null.
13316
0
      if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13317
0
          LHSValue.Base && RHSValue.Base)
13318
0
        return DiagComparison(diag::note_constexpr_literal_comparison);
13319
      // We can't tell whether weak symbols will end up pointing to the same
13320
      // object.
13321
0
      if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13322
0
        return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13323
0
                              !IsWeakLValue(LHSValue));
13324
      // We can't compare the address of the start of one object with the
13325
      // past-the-end address of another object, per C++ DR1652.
13326
0
      if (LHSValue.Base && LHSValue.Offset.isZero() &&
13327
0
          isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13328
0
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13329
0
                              true);
13330
0
      if (RHSValue.Base && RHSValue.Offset.isZero() &&
13331
0
           isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13332
0
        return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13333
0
                              false);
13334
      // We can't tell whether an object is at the same address as another
13335
      // zero sized object.
13336
0
      if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13337
0
          (LHSValue.Base && isZeroSized(RHSValue)))
13338
0
        return DiagComparison(
13339
0
            diag::note_constexpr_pointer_comparison_zero_sized);
13340
0
      return Success(CmpResult::Unequal, E);
13341
0
    }
13342
13343
0
    const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13344
0
    const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13345
13346
0
    SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13347
0
    SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13348
13349
    // C++11 [expr.rel]p3:
13350
    //   Pointers to void (after pointer conversions) can be compared, with a
13351
    //   result defined as follows: If both pointers represent the same
13352
    //   address or are both the null pointer value, the result is true if the
13353
    //   operator is <= or >= and false otherwise; otherwise the result is
13354
    //   unspecified.
13355
    // We interpret this as applying to pointers to *cv* void.
13356
0
    if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13357
0
      Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13358
13359
    // C++11 [expr.rel]p2:
13360
    // - If two pointers point to non-static data members of the same object,
13361
    //   or to subobjects or array elements fo such members, recursively, the
13362
    //   pointer to the later declared member compares greater provided the
13363
    //   two members have the same access control and provided their class is
13364
    //   not a union.
13365
    //   [...]
13366
    // - Otherwise pointer comparisons are unspecified.
13367
0
    if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13368
0
      bool WasArrayIndex;
13369
0
      unsigned Mismatch = FindDesignatorMismatch(
13370
0
          getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13371
      // At the point where the designators diverge, the comparison has a
13372
      // specified value if:
13373
      //  - we are comparing array indices
13374
      //  - we are comparing fields of a union, or fields with the same access
13375
      // Otherwise, the result is unspecified and thus the comparison is not a
13376
      // constant expression.
13377
0
      if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13378
0
          Mismatch < RHSDesignator.Entries.size()) {
13379
0
        const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13380
0
        const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13381
0
        if (!LF && !RF)
13382
0
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13383
0
        else if (!LF)
13384
0
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13385
0
              << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13386
0
              << RF->getParent() << RF;
13387
0
        else if (!RF)
13388
0
          Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13389
0
              << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13390
0
              << LF->getParent() << LF;
13391
0
        else if (!LF->getParent()->isUnion() &&
13392
0
                 LF->getAccess() != RF->getAccess())
13393
0
          Info.CCEDiag(E,
13394
0
                       diag::note_constexpr_pointer_comparison_differing_access)
13395
0
              << LF << LF->getAccess() << RF << RF->getAccess()
13396
0
              << LF->getParent();
13397
0
      }
13398
0
    }
13399
13400
    // The comparison here must be unsigned, and performed with the same
13401
    // width as the pointer.
13402
0
    unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13403
0
    uint64_t CompareLHS = LHSOffset.getQuantity();
13404
0
    uint64_t CompareRHS = RHSOffset.getQuantity();
13405
0
    assert(PtrSize <= 64 && "Unexpected pointer width");
13406
0
    uint64_t Mask = ~0ULL >> (64 - PtrSize);
13407
0
    CompareLHS &= Mask;
13408
0
    CompareRHS &= Mask;
13409
13410
    // If there is a base and this is a relational operator, we can only
13411
    // compare pointers within the object in question; otherwise, the result
13412
    // depends on where the object is located in memory.
13413
0
    if (!LHSValue.Base.isNull() && IsRelational) {
13414
0
      QualType BaseTy = getType(LHSValue.Base);
13415
0
      if (BaseTy->isIncompleteType())
13416
0
        return Error(E);
13417
0
      CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13418
0
      uint64_t OffsetLimit = Size.getQuantity();
13419
0
      if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13420
0
        return Error(E);
13421
0
    }
13422
13423
0
    if (CompareLHS < CompareRHS)
13424
0
      return Success(CmpResult::Less, E);
13425
0
    if (CompareLHS > CompareRHS)
13426
0
      return Success(CmpResult::Greater, E);
13427
0
    return Success(CmpResult::Equal, E);
13428
0
  }
13429
13430
0
  if (LHSTy->isMemberPointerType()) {
13431
0
    assert(IsEquality && "unexpected member pointer operation");
13432
0
    assert(RHSTy->isMemberPointerType() && "invalid comparison");
13433
13434
0
    MemberPtr LHSValue, RHSValue;
13435
13436
0
    bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13437
0
    if (!LHSOK && !Info.noteFailure())
13438
0
      return false;
13439
13440
0
    if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13441
0
      return false;
13442
13443
    // If either operand is a pointer to a weak function, the comparison is not
13444
    // constant.
13445
0
    if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13446
0
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13447
0
          << LHSValue.getDecl();
13448
0
      return false;
13449
0
    }
13450
0
    if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13451
0
      Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13452
0
          << RHSValue.getDecl();
13453
0
      return false;
13454
0
    }
13455
13456
    // C++11 [expr.eq]p2:
13457
    //   If both operands are null, they compare equal. Otherwise if only one is
13458
    //   null, they compare unequal.
13459
0
    if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13460
0
      bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13461
0
      return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13462
0
    }
13463
13464
    //   Otherwise if either is a pointer to a virtual member function, the
13465
    //   result is unspecified.
13466
0
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13467
0
      if (MD->isVirtual())
13468
0
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13469
0
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13470
0
      if (MD->isVirtual())
13471
0
        Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13472
13473
    //   Otherwise they compare equal if and only if they would refer to the
13474
    //   same member of the same most derived object or the same subobject if
13475
    //   they were dereferenced with a hypothetical object of the associated
13476
    //   class type.
13477
0
    bool Equal = LHSValue == RHSValue;
13478
0
    return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13479
0
  }
13480
13481
0
  if (LHSTy->isNullPtrType()) {
13482
0
    assert(E->isComparisonOp() && "unexpected nullptr operation");
13483
0
    assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13484
    // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13485
    // are compared, the result is true of the operator is <=, >= or ==, and
13486
    // false otherwise.
13487
0
    LValue Res;
13488
0
    if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13489
0
        !EvaluatePointer(E->getRHS(), Res, Info))
13490
0
      return false;
13491
0
    return Success(CmpResult::Equal, E);
13492
0
  }
13493
13494
0
  return DoAfter();
13495
0
}
Unexecuted instantiation: ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_3&, (anonymous namespace)::RecordExprEvaluator::VisitBinCmp(clang::BinaryOperator const*)::$_4&&)
Unexecuted instantiation: ExprConstant.cpp:bool EvaluateComparisonBinaryOperator<(anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6>((anonymous namespace)::EvalInfo&, clang::BinaryOperator const*, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_5&, (anonymous namespace)::IntExprEvaluator::VisitBinaryOperator(clang::BinaryOperator const*)::$_6&&)
13496
13497
0
bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13498
0
  if (!CheckLiteralType(Info, E))
13499
0
    return false;
13500
13501
0
  auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13502
0
    ComparisonCategoryResult CCR;
13503
0
    switch (CR) {
13504
0
    case CmpResult::Unequal:
13505
0
      llvm_unreachable("should never produce Unequal for three-way comparison");
13506
0
    case CmpResult::Less:
13507
0
      CCR = ComparisonCategoryResult::Less;
13508
0
      break;
13509
0
    case CmpResult::Equal:
13510
0
      CCR = ComparisonCategoryResult::Equal;
13511
0
      break;
13512
0
    case CmpResult::Greater:
13513
0
      CCR = ComparisonCategoryResult::Greater;
13514
0
      break;
13515
0
    case CmpResult::Unordered:
13516
0
      CCR = ComparisonCategoryResult::Unordered;
13517
0
      break;
13518
0
    }
13519
    // Evaluation succeeded. Lookup the information for the comparison category
13520
    // type and fetch the VarDecl for the result.
13521
0
    const ComparisonCategoryInfo &CmpInfo =
13522
0
        Info.Ctx.CompCategories.getInfoForType(E->getType());
13523
0
    const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13524
    // Check and evaluate the result as a constant expression.
13525
0
    LValue LV;
13526
0
    LV.set(VD);
13527
0
    if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13528
0
      return false;
13529
0
    return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13530
0
                                   ConstantExprKind::Normal);
13531
0
  };
13532
0
  return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13533
0
    return ExprEvaluatorBaseTy::VisitBinCmp(E);
13534
0
  });
13535
0
}
13536
13537
bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13538
0
    const CXXParenListInitExpr *E) {
13539
0
  return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13540
0
}
13541
13542
0
bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13543
  // We don't support assignment in C. C++ assignments don't get here because
13544
  // assignment is an lvalue in C++.
13545
0
  if (E->isAssignmentOp()) {
13546
0
    Error(E);
13547
0
    if (!Info.noteFailure())
13548
0
      return false;
13549
0
  }
13550
13551
0
  if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13552
0
    return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13553
13554
0
  assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13555
0
          !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13556
0
         "DataRecursiveIntBinOpEvaluator should have handled integral types");
13557
13558
0
  if (E->isComparisonOp()) {
13559
    // Evaluate builtin binary comparisons by evaluating them as three-way
13560
    // comparisons and then translating the result.
13561
0
    auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13562
0
      assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13563
0
             "should only produce Unequal for equality comparisons");
13564
0
      bool IsEqual   = CR == CmpResult::Equal,
13565
0
           IsLess    = CR == CmpResult::Less,
13566
0
           IsGreater = CR == CmpResult::Greater;
13567
0
      auto Op = E->getOpcode();
13568
0
      switch (Op) {
13569
0
      default:
13570
0
        llvm_unreachable("unsupported binary operator");
13571
0
      case BO_EQ:
13572
0
      case BO_NE:
13573
0
        return Success(IsEqual == (Op == BO_EQ), E);
13574
0
      case BO_LT:
13575
0
        return Success(IsLess, E);
13576
0
      case BO_GT:
13577
0
        return Success(IsGreater, E);
13578
0
      case BO_LE:
13579
0
        return Success(IsEqual || IsLess, E);
13580
0
      case BO_GE:
13581
0
        return Success(IsEqual || IsGreater, E);
13582
0
      }
13583
0
    };
13584
0
    return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13585
0
      return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13586
0
    });
13587
0
  }
13588
13589
0
  QualType LHSTy = E->getLHS()->getType();
13590
0
  QualType RHSTy = E->getRHS()->getType();
13591
13592
0
  if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13593
0
      E->getOpcode() == BO_Sub) {
13594
0
    LValue LHSValue, RHSValue;
13595
13596
0
    bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13597
0
    if (!LHSOK && !Info.noteFailure())
13598
0
      return false;
13599
13600
0
    if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13601
0
      return false;
13602
13603
    // Reject differing bases from the normal codepath; we special-case
13604
    // comparisons to null.
13605
0
    if (!HasSameBase(LHSValue, RHSValue)) {
13606
      // Handle &&A - &&B.
13607
0
      if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13608
0
        return Error(E);
13609
0
      const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13610
0
      const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13611
0
      if (!LHSExpr || !RHSExpr)
13612
0
        return Error(E);
13613
0
      const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13614
0
      const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13615
0
      if (!LHSAddrExpr || !RHSAddrExpr)
13616
0
        return Error(E);
13617
      // Make sure both labels come from the same function.
13618
0
      if (LHSAddrExpr->getLabel()->getDeclContext() !=
13619
0
          RHSAddrExpr->getLabel()->getDeclContext())
13620
0
        return Error(E);
13621
0
      return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13622
0
    }
13623
0
    const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13624
0
    const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13625
13626
0
    SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13627
0
    SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13628
13629
    // C++11 [expr.add]p6:
13630
    //   Unless both pointers point to elements of the same array object, or
13631
    //   one past the last element of the array object, the behavior is
13632
    //   undefined.
13633
0
    if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13634
0
        !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13635
0
                                RHSDesignator))
13636
0
      Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13637
13638
0
    QualType Type = E->getLHS()->getType();
13639
0
    QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13640
13641
0
    CharUnits ElementSize;
13642
0
    if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13643
0
      return false;
13644
13645
    // As an extension, a type may have zero size (empty struct or union in
13646
    // C, array of zero length). Pointer subtraction in such cases has
13647
    // undefined behavior, so is not constant.
13648
0
    if (ElementSize.isZero()) {
13649
0
      Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13650
0
          << ElementType;
13651
0
      return false;
13652
0
    }
13653
13654
    // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13655
    // and produce incorrect results when it overflows. Such behavior
13656
    // appears to be non-conforming, but is common, so perhaps we should
13657
    // assume the standard intended for such cases to be undefined behavior
13658
    // and check for them.
13659
13660
    // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13661
    // overflow in the final conversion to ptrdiff_t.
13662
0
    APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13663
0
    APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13664
0
    APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13665
0
                    false);
13666
0
    APSInt TrueResult = (LHS - RHS) / ElemSize;
13667
0
    APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13668
13669
0
    if (Result.extend(65) != TrueResult &&
13670
0
        !HandleOverflow(Info, E, TrueResult, E->getType()))
13671
0
      return false;
13672
0
    return Success(Result, E);
13673
0
  }
13674
13675
0
  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13676
0
}
13677
13678
/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13679
/// a result as the expression's type.
13680
bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13681
0
                                    const UnaryExprOrTypeTraitExpr *E) {
13682
0
  switch(E->getKind()) {
13683
0
  case UETT_PreferredAlignOf:
13684
0
  case UETT_AlignOf: {
13685
0
    if (E->isArgumentType())
13686
0
      return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13687
0
                     E);
13688
0
    else
13689
0
      return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13690
0
                     E);
13691
0
  }
13692
13693
0
  case UETT_VecStep: {
13694
0
    QualType Ty = E->getTypeOfArgument();
13695
13696
0
    if (Ty->isVectorType()) {
13697
0
      unsigned n = Ty->castAs<VectorType>()->getNumElements();
13698
13699
      // The vec_step built-in functions that take a 3-component
13700
      // vector return 4. (OpenCL 1.1 spec 6.11.12)
13701
0
      if (n == 3)
13702
0
        n = 4;
13703
13704
0
      return Success(n, E);
13705
0
    } else
13706
0
      return Success(1, E);
13707
0
  }
13708
13709
0
  case UETT_DataSizeOf:
13710
0
  case UETT_SizeOf: {
13711
0
    QualType SrcTy = E->getTypeOfArgument();
13712
    // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13713
    //   the result is the size of the referenced type."
13714
0
    if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13715
0
      SrcTy = Ref->getPointeeType();
13716
13717
0
    CharUnits Sizeof;
13718
0
    if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
13719
0
                      E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
13720
0
                                                      : SizeOfType::SizeOf)) {
13721
0
      return false;
13722
0
    }
13723
0
    return Success(Sizeof, E);
13724
0
  }
13725
0
  case UETT_OpenMPRequiredSimdAlign:
13726
0
    assert(E->isArgumentType());
13727
0
    return Success(
13728
0
        Info.Ctx.toCharUnitsFromBits(
13729
0
                    Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13730
0
            .getQuantity(),
13731
0
        E);
13732
0
  case UETT_VectorElements: {
13733
0
    QualType Ty = E->getTypeOfArgument();
13734
    // If the vector has a fixed size, we can determine the number of elements
13735
    // at compile time.
13736
0
    if (Ty->isVectorType())
13737
0
      return Success(Ty->castAs<VectorType>()->getNumElements(), E);
13738
13739
0
    assert(Ty->isSizelessVectorType());
13740
0
    if (Info.InConstantContext)
13741
0
      Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
13742
0
          << E->getSourceRange();
13743
13744
0
    return false;
13745
0
  }
13746
0
  }
13747
13748
0
  llvm_unreachable("unknown expr/type trait");
13749
0
}
13750
13751
0
bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13752
0
  CharUnits Result;
13753
0
  unsigned n = OOE->getNumComponents();
13754
0
  if (n == 0)
13755
0
    return Error(OOE);
13756
0
  QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13757
0
  for (unsigned i = 0; i != n; ++i) {
13758
0
    OffsetOfNode ON = OOE->getComponent(i);
13759
0
    switch (ON.getKind()) {
13760
0
    case OffsetOfNode::Array: {
13761
0
      const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13762
0
      APSInt IdxResult;
13763
0
      if (!EvaluateInteger(Idx, IdxResult, Info))
13764
0
        return false;
13765
0
      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13766
0
      if (!AT)
13767
0
        return Error(OOE);
13768
0
      CurrentType = AT->getElementType();
13769
0
      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13770
0
      Result += IdxResult.getSExtValue() * ElementSize;
13771
0
      break;
13772
0
    }
13773
13774
0
    case OffsetOfNode::Field: {
13775
0
      FieldDecl *MemberDecl = ON.getField();
13776
0
      const RecordType *RT = CurrentType->getAs<RecordType>();
13777
0
      if (!RT)
13778
0
        return Error(OOE);
13779
0
      RecordDecl *RD = RT->getDecl();
13780
0
      if (RD->isInvalidDecl()) return false;
13781
0
      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13782
0
      unsigned i = MemberDecl->getFieldIndex();
13783
0
      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13784
0
      Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13785
0
      CurrentType = MemberDecl->getType().getNonReferenceType();
13786
0
      break;
13787
0
    }
13788
13789
0
    case OffsetOfNode::Identifier:
13790
0
      llvm_unreachable("dependent __builtin_offsetof");
13791
13792
0
    case OffsetOfNode::Base: {
13793
0
      CXXBaseSpecifier *BaseSpec = ON.getBase();
13794
0
      if (BaseSpec->isVirtual())
13795
0
        return Error(OOE);
13796
13797
      // Find the layout of the class whose base we are looking into.
13798
0
      const RecordType *RT = CurrentType->getAs<RecordType>();
13799
0
      if (!RT)
13800
0
        return Error(OOE);
13801
0
      RecordDecl *RD = RT->getDecl();
13802
0
      if (RD->isInvalidDecl()) return false;
13803
0
      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13804
13805
      // Find the base class itself.
13806
0
      CurrentType = BaseSpec->getType();
13807
0
      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13808
0
      if (!BaseRT)
13809
0
        return Error(OOE);
13810
13811
      // Add the offset to the base.
13812
0
      Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13813
0
      break;
13814
0
    }
13815
0
    }
13816
0
  }
13817
0
  return Success(Result, OOE);
13818
0
}
13819
13820
3
bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13821
3
  switch (E->getOpcode()) {
13822
0
  default:
13823
    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13824
    // See C99 6.6p3.
13825
0
    return Error(E);
13826
0
  case UO_Extension:
13827
    // FIXME: Should extension allow i-c-e extension expressions in its scope?
13828
    // If so, we could clear the diagnostic ID.
13829
0
    return Visit(E->getSubExpr());
13830
0
  case UO_Plus:
13831
    // The result is just the value.
13832
0
    return Visit(E->getSubExpr());
13833
3
  case UO_Minus: {
13834
3
    if (!Visit(E->getSubExpr()))
13835
2
      return false;
13836
1
    if (!Result.isInt()) return Error(E);
13837
1
    const APSInt &Value = Result.getInt();
13838
1
    if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
13839
0
      if (Info.checkingForUndefinedBehavior())
13840
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13841
0
                                         diag::warn_integer_constant_overflow)
13842
0
            << toString(Value, 10) << E->getType() << E->getSourceRange();
13843
13844
0
      if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13845
0
                          E->getType()))
13846
0
        return false;
13847
0
    }
13848
1
    return Success(-Value, E);
13849
1
  }
13850
0
  case UO_Not: {
13851
0
    if (!Visit(E->getSubExpr()))
13852
0
      return false;
13853
0
    if (!Result.isInt()) return Error(E);
13854
0
    return Success(~Result.getInt(), E);
13855
0
  }
13856
0
  case UO_LNot: {
13857
0
    bool bres;
13858
0
    if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13859
0
      return false;
13860
0
    return Success(!bres, E);
13861
0
  }
13862
3
  }
13863
3
}
13864
13865
/// HandleCast - This is used to evaluate implicit or explicit casts where the
13866
/// result type is integer.
13867
5
bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13868
5
  const Expr *SubExpr = E->getSubExpr();
13869
5
  QualType DestType = E->getType();
13870
5
  QualType SrcType = SubExpr->getType();
13871
13872
5
  switch (E->getCastKind()) {
13873
0
  case CK_BaseToDerived:
13874
0
  case CK_DerivedToBase:
13875
0
  case CK_UncheckedDerivedToBase:
13876
0
  case CK_Dynamic:
13877
0
  case CK_ToUnion:
13878
0
  case CK_ArrayToPointerDecay:
13879
0
  case CK_FunctionToPointerDecay:
13880
0
  case CK_NullToPointer:
13881
0
  case CK_NullToMemberPointer:
13882
0
  case CK_BaseToDerivedMemberPointer:
13883
0
  case CK_DerivedToBaseMemberPointer:
13884
0
  case CK_ReinterpretMemberPointer:
13885
0
  case CK_ConstructorConversion:
13886
0
  case CK_IntegralToPointer:
13887
0
  case CK_ToVoid:
13888
0
  case CK_VectorSplat:
13889
0
  case CK_IntegralToFloating:
13890
0
  case CK_FloatingCast:
13891
0
  case CK_CPointerToObjCPointerCast:
13892
0
  case CK_BlockPointerToObjCPointerCast:
13893
0
  case CK_AnyPointerToBlockPointerCast:
13894
0
  case CK_ObjCObjectLValueCast:
13895
0
  case CK_FloatingRealToComplex:
13896
0
  case CK_FloatingComplexToReal:
13897
0
  case CK_FloatingComplexCast:
13898
0
  case CK_FloatingComplexToIntegralComplex:
13899
0
  case CK_IntegralRealToComplex:
13900
0
  case CK_IntegralComplexCast:
13901
0
  case CK_IntegralComplexToFloatingComplex:
13902
0
  case CK_BuiltinFnToFnPtr:
13903
0
  case CK_ZeroToOCLOpaqueType:
13904
0
  case CK_NonAtomicToAtomic:
13905
0
  case CK_AddressSpaceConversion:
13906
0
  case CK_IntToOCLSampler:
13907
0
  case CK_FloatingToFixedPoint:
13908
0
  case CK_FixedPointToFloating:
13909
0
  case CK_FixedPointCast:
13910
0
  case CK_IntegralToFixedPoint:
13911
0
  case CK_MatrixCast:
13912
0
    llvm_unreachable("invalid cast kind for integral value");
13913
13914
0
  case CK_BitCast:
13915
0
  case CK_Dependent:
13916
0
  case CK_LValueBitCast:
13917
0
  case CK_ARCProduceObject:
13918
0
  case CK_ARCConsumeObject:
13919
0
  case CK_ARCReclaimReturnedObject:
13920
0
  case CK_ARCExtendBlockObject:
13921
0
  case CK_CopyAndAutoreleaseBlockObject:
13922
0
    return Error(E);
13923
13924
0
  case CK_UserDefinedConversion:
13925
5
  case CK_LValueToRValue:
13926
5
  case CK_AtomicToNonAtomic:
13927
5
  case CK_NoOp:
13928
5
  case CK_LValueToRValueBitCast:
13929
5
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
13930
13931
0
  case CK_MemberPointerToBoolean:
13932
0
  case CK_PointerToBoolean:
13933
0
  case CK_IntegralToBoolean:
13934
0
  case CK_FloatingToBoolean:
13935
0
  case CK_BooleanToSignedIntegral:
13936
0
  case CK_FloatingComplexToBoolean:
13937
0
  case CK_IntegralComplexToBoolean: {
13938
0
    bool BoolResult;
13939
0
    if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13940
0
      return false;
13941
0
    uint64_t IntResult = BoolResult;
13942
0
    if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13943
0
      IntResult = (uint64_t)-1;
13944
0
    return Success(IntResult, E);
13945
0
  }
13946
13947
0
  case CK_FixedPointToIntegral: {
13948
0
    APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13949
0
    if (!EvaluateFixedPoint(SubExpr, Src, Info))
13950
0
      return false;
13951
0
    bool Overflowed;
13952
0
    llvm::APSInt Result = Src.convertToInt(
13953
0
        Info.Ctx.getIntWidth(DestType),
13954
0
        DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13955
0
    if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13956
0
      return false;
13957
0
    return Success(Result, E);
13958
0
  }
13959
13960
0
  case CK_FixedPointToBoolean: {
13961
    // Unsigned padding does not affect this.
13962
0
    APValue Val;
13963
0
    if (!Evaluate(Val, Info, SubExpr))
13964
0
      return false;
13965
0
    return Success(Val.getFixedPoint().getBoolValue(), E);
13966
0
  }
13967
13968
0
  case CK_IntegralCast: {
13969
0
    if (!Visit(SubExpr))
13970
0
      return false;
13971
13972
0
    if (!Result.isInt()) {
13973
      // Allow casts of address-of-label differences if they are no-ops
13974
      // or narrowing.  (The narrowing case isn't actually guaranteed to
13975
      // be constant-evaluatable except in some narrow cases which are hard
13976
      // to detect here.  We let it through on the assumption the user knows
13977
      // what they are doing.)
13978
0
      if (Result.isAddrLabelDiff())
13979
0
        return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13980
      // Only allow casts of lvalues if they are lossless.
13981
0
      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13982
0
    }
13983
13984
0
    if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13985
0
        Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13986
0
        DestType->isEnumeralType()) {
13987
13988
0
      bool ConstexprVar = true;
13989
13990
      // We know if we are here that we are in a context that we might require
13991
      // a constant expression or a context that requires a constant
13992
      // value. But if we are initializing a value we don't know if it is a
13993
      // constexpr variable or not. We can check the EvaluatingDecl to determine
13994
      // if it constexpr or not. If not then we don't want to emit a diagnostic.
13995
0
      if (const auto *VD = dyn_cast_or_null<VarDecl>(
13996
0
              Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13997
0
        ConstexprVar = VD->isConstexpr();
13998
13999
0
      const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
14000
0
      const EnumDecl *ED = ET->getDecl();
14001
      // Check that the value is within the range of the enumeration values.
14002
      //
14003
      // This corressponds to [expr.static.cast]p10 which says:
14004
      // A value of integral or enumeration type can be explicitly converted
14005
      // to a complete enumeration type ... If the enumeration type does not
14006
      // have a fixed underlying type, the value is unchanged if the original
14007
      // value is within the range of the enumeration values ([dcl.enum]), and
14008
      // otherwise, the behavior is undefined.
14009
      //
14010
      // This was resolved as part of DR2338 which has CD5 status.
14011
0
      if (!ED->isFixed()) {
14012
0
        llvm::APInt Min;
14013
0
        llvm::APInt Max;
14014
14015
0
        ED->getValueRange(Max, Min);
14016
0
        --Max;
14017
14018
0
        if (ED->getNumNegativeBits() && ConstexprVar &&
14019
0
            (Max.slt(Result.getInt().getSExtValue()) ||
14020
0
             Min.sgt(Result.getInt().getSExtValue())))
14021
0
          Info.Ctx.getDiagnostics().Report(
14022
0
              E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14023
0
              << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
14024
0
              << Max.getSExtValue() << ED;
14025
0
        else if (!ED->getNumNegativeBits() && ConstexprVar &&
14026
0
                 Max.ult(Result.getInt().getZExtValue()))
14027
0
          Info.Ctx.getDiagnostics().Report(
14028
0
              E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14029
0
              << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
14030
0
              << Max.getZExtValue() << ED;
14031
0
      }
14032
0
    }
14033
14034
0
    return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
14035
0
                                      Result.getInt()), E);
14036
0
  }
14037
14038
0
  case CK_PointerToIntegral: {
14039
0
    CCEDiag(E, diag::note_constexpr_invalid_cast)
14040
0
        << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14041
14042
0
    LValue LV;
14043
0
    if (!EvaluatePointer(SubExpr, LV, Info))
14044
0
      return false;
14045
14046
0
    if (LV.getLValueBase()) {
14047
      // Only allow based lvalue casts if they are lossless.
14048
      // FIXME: Allow a larger integer size than the pointer size, and allow
14049
      // narrowing back down to pointer width in subsequent integral casts.
14050
      // FIXME: Check integer type's active bits, not its type size.
14051
0
      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
14052
0
        return Error(E);
14053
14054
0
      LV.Designator.setInvalid();
14055
0
      LV.moveInto(Result);
14056
0
      return true;
14057
0
    }
14058
14059
0
    APSInt AsInt;
14060
0
    APValue V;
14061
0
    LV.moveInto(V);
14062
0
    if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
14063
0
      llvm_unreachable("Can't cast this!");
14064
14065
0
    return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
14066
0
  }
14067
14068
0
  case CK_IntegralComplexToReal: {
14069
0
    ComplexValue C;
14070
0
    if (!EvaluateComplex(SubExpr, C, Info))
14071
0
      return false;
14072
0
    return Success(C.getComplexIntReal(), E);
14073
0
  }
14074
14075
0
  case CK_FloatingToIntegral: {
14076
0
    APFloat F(0.0);
14077
0
    if (!EvaluateFloat(SubExpr, F, Info))
14078
0
      return false;
14079
14080
0
    APSInt Value;
14081
0
    if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
14082
0
      return false;
14083
0
    return Success(Value, E);
14084
0
  }
14085
5
  }
14086
14087
0
  llvm_unreachable("unknown cast resulting in integral value");
14088
0
}
14089
14090
0
bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14091
0
  if (E->getSubExpr()->getType()->isAnyComplexType()) {
14092
0
    ComplexValue LV;
14093
0
    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14094
0
      return false;
14095
0
    if (!LV.isComplexInt())
14096
0
      return Error(E);
14097
0
    return Success(LV.getComplexIntReal(), E);
14098
0
  }
14099
14100
0
  return Visit(E->getSubExpr());
14101
0
}
14102
14103
0
bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14104
0
  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14105
0
    ComplexValue LV;
14106
0
    if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14107
0
      return false;
14108
0
    if (!LV.isComplexInt())
14109
0
      return Error(E);
14110
0
    return Success(LV.getComplexIntImag(), E);
14111
0
  }
14112
14113
0
  VisitIgnoredValue(E->getSubExpr());
14114
0
  return Success(0, E);
14115
0
}
14116
14117
0
bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
14118
0
  return Success(E->getPackLength(), E);
14119
0
}
14120
14121
0
bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
14122
0
  return Success(E->getValue(), E);
14123
0
}
14124
14125
bool IntExprEvaluator::VisitConceptSpecializationExpr(
14126
0
       const ConceptSpecializationExpr *E) {
14127
0
  return Success(E->isSatisfied(), E);
14128
0
}
14129
14130
0
bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
14131
0
  return Success(E->isSatisfied(), E);
14132
0
}
14133
14134
0
bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14135
0
  switch (E->getOpcode()) {
14136
0
    default:
14137
      // Invalid unary operators
14138
0
      return Error(E);
14139
0
    case UO_Plus:
14140
      // The result is just the value.
14141
0
      return Visit(E->getSubExpr());
14142
0
    case UO_Minus: {
14143
0
      if (!Visit(E->getSubExpr())) return false;
14144
0
      if (!Result.isFixedPoint())
14145
0
        return Error(E);
14146
0
      bool Overflowed;
14147
0
      APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
14148
0
      if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
14149
0
        return false;
14150
0
      return Success(Negated, E);
14151
0
    }
14152
0
    case UO_LNot: {
14153
0
      bool bres;
14154
0
      if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14155
0
        return false;
14156
0
      return Success(!bres, E);
14157
0
    }
14158
0
  }
14159
0
}
14160
14161
0
bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
14162
0
  const Expr *SubExpr = E->getSubExpr();
14163
0
  QualType DestType = E->getType();
14164
0
  assert(DestType->isFixedPointType() &&
14165
0
         "Expected destination type to be a fixed point type");
14166
0
  auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
14167
14168
0
  switch (E->getCastKind()) {
14169
0
  case CK_FixedPointCast: {
14170
0
    APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14171
0
    if (!EvaluateFixedPoint(SubExpr, Src, Info))
14172
0
      return false;
14173
0
    bool Overflowed;
14174
0
    APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
14175
0
    if (Overflowed) {
14176
0
      if (Info.checkingForUndefinedBehavior())
14177
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14178
0
                                         diag::warn_fixedpoint_constant_overflow)
14179
0
          << Result.toString() << E->getType();
14180
0
      if (!HandleOverflow(Info, E, Result, E->getType()))
14181
0
        return false;
14182
0
    }
14183
0
    return Success(Result, E);
14184
0
  }
14185
0
  case CK_IntegralToFixedPoint: {
14186
0
    APSInt Src;
14187
0
    if (!EvaluateInteger(SubExpr, Src, Info))
14188
0
      return false;
14189
14190
0
    bool Overflowed;
14191
0
    APFixedPoint IntResult = APFixedPoint::getFromIntValue(
14192
0
        Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14193
14194
0
    if (Overflowed) {
14195
0
      if (Info.checkingForUndefinedBehavior())
14196
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14197
0
                                         diag::warn_fixedpoint_constant_overflow)
14198
0
          << IntResult.toString() << E->getType();
14199
0
      if (!HandleOverflow(Info, E, IntResult, E->getType()))
14200
0
        return false;
14201
0
    }
14202
14203
0
    return Success(IntResult, E);
14204
0
  }
14205
0
  case CK_FloatingToFixedPoint: {
14206
0
    APFloat Src(0.0);
14207
0
    if (!EvaluateFloat(SubExpr, Src, Info))
14208
0
      return false;
14209
14210
0
    bool Overflowed;
14211
0
    APFixedPoint Result = APFixedPoint::getFromFloatValue(
14212
0
        Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
14213
14214
0
    if (Overflowed) {
14215
0
      if (Info.checkingForUndefinedBehavior())
14216
0
        Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14217
0
                                         diag::warn_fixedpoint_constant_overflow)
14218
0
          << Result.toString() << E->getType();
14219
0
      if (!HandleOverflow(Info, E, Result, E->getType()))
14220
0
        return false;
14221
0
    }
14222
14223
0
    return Success(Result, E);
14224
0
  }
14225
0
  case CK_NoOp:
14226
0
  case CK_LValueToRValue:
14227
0
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
14228
0
  default:
14229
0
    return Error(E);
14230
0
  }
14231
0
}
14232
14233
0
bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14234
0
  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14235
0
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14236
14237
0
  const Expr *LHS = E->getLHS();
14238
0
  const Expr *RHS = E->getRHS();
14239
0
  FixedPointSemantics ResultFXSema =
14240
0
      Info.Ctx.getFixedPointSemantics(E->getType());
14241
14242
0
  APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14243
0
  if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
14244
0
    return false;
14245
0
  APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14246
0
  if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
14247
0
    return false;
14248
14249
0
  bool OpOverflow = false, ConversionOverflow = false;
14250
0
  APFixedPoint Result(LHSFX.getSemantics());
14251
0
  switch (E->getOpcode()) {
14252
0
  case BO_Add: {
14253
0
    Result = LHSFX.add(RHSFX, &OpOverflow)
14254
0
                  .convert(ResultFXSema, &ConversionOverflow);
14255
0
    break;
14256
0
  }
14257
0
  case BO_Sub: {
14258
0
    Result = LHSFX.sub(RHSFX, &OpOverflow)
14259
0
                  .convert(ResultFXSema, &ConversionOverflow);
14260
0
    break;
14261
0
  }
14262
0
  case BO_Mul: {
14263
0
    Result = LHSFX.mul(RHSFX, &OpOverflow)
14264
0
                  .convert(ResultFXSema, &ConversionOverflow);
14265
0
    break;
14266
0
  }
14267
0
  case BO_Div: {
14268
0
    if (RHSFX.getValue() == 0) {
14269
0
      Info.FFDiag(E, diag::note_expr_divide_by_zero);
14270
0
      return false;
14271
0
    }
14272
0
    Result = LHSFX.div(RHSFX, &OpOverflow)
14273
0
                  .convert(ResultFXSema, &ConversionOverflow);
14274
0
    break;
14275
0
  }
14276
0
  case BO_Shl:
14277
0
  case BO_Shr: {
14278
0
    FixedPointSemantics LHSSema = LHSFX.getSemantics();
14279
0
    llvm::APSInt RHSVal = RHSFX.getValue();
14280
14281
0
    unsigned ShiftBW =
14282
0
        LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14283
0
    unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14284
    // Embedded-C 4.1.6.2.2:
14285
    //   The right operand must be nonnegative and less than the total number
14286
    //   of (nonpadding) bits of the fixed-point operand ...
14287
0
    if (RHSVal.isNegative())
14288
0
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
14289
0
    else if (Amt != RHSVal)
14290
0
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
14291
0
          << RHSVal << E->getType() << ShiftBW;
14292
14293
0
    if (E->getOpcode() == BO_Shl)
14294
0
      Result = LHSFX.shl(Amt, &OpOverflow);
14295
0
    else
14296
0
      Result = LHSFX.shr(Amt, &OpOverflow);
14297
0
    break;
14298
0
  }
14299
0
  default:
14300
0
    return false;
14301
0
  }
14302
0
  if (OpOverflow || ConversionOverflow) {
14303
0
    if (Info.checkingForUndefinedBehavior())
14304
0
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14305
0
                                       diag::warn_fixedpoint_constant_overflow)
14306
0
        << Result.toString() << E->getType();
14307
0
    if (!HandleOverflow(Info, E, Result, E->getType()))
14308
0
      return false;
14309
0
  }
14310
0
  return Success(Result, E);
14311
0
}
14312
14313
//===----------------------------------------------------------------------===//
14314
// Float Evaluation
14315
//===----------------------------------------------------------------------===//
14316
14317
namespace {
14318
class FloatExprEvaluator
14319
  : public ExprEvaluatorBase<FloatExprEvaluator> {
14320
  APFloat &Result;
14321
public:
14322
  FloatExprEvaluator(EvalInfo &info, APFloat &result)
14323
0
    : ExprEvaluatorBaseTy(info), Result(result) {}
14324
14325
0
  bool Success(const APValue &V, const Expr *e) {
14326
0
    Result = V.getFloat();
14327
0
    return true;
14328
0
  }
14329
14330
0
  bool ZeroInitialization(const Expr *E) {
14331
0
    Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14332
0
    return true;
14333
0
  }
14334
14335
  bool VisitCallExpr(const CallExpr *E);
14336
14337
  bool VisitUnaryOperator(const UnaryOperator *E);
14338
  bool VisitBinaryOperator(const BinaryOperator *E);
14339
  bool VisitFloatingLiteral(const FloatingLiteral *E);
14340
  bool VisitCastExpr(const CastExpr *E);
14341
14342
  bool VisitUnaryReal(const UnaryOperator *E);
14343
  bool VisitUnaryImag(const UnaryOperator *E);
14344
14345
  // FIXME: Missing: array subscript of vector, member of vector
14346
};
14347
} // end anonymous namespace
14348
14349
0
static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14350
0
  assert(!E->isValueDependent());
14351
0
  assert(E->isPRValue() && E->getType()->isRealFloatingType());
14352
0
  return FloatExprEvaluator(Info, Result).Visit(E);
14353
0
}
14354
14355
static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14356
                                  QualType ResultTy,
14357
                                  const Expr *Arg,
14358
                                  bool SNaN,
14359
0
                                  llvm::APFloat &Result) {
14360
0
  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14361
0
  if (!S) return false;
14362
14363
0
  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14364
14365
0
  llvm::APInt fill;
14366
14367
  // Treat empty strings as if they were zero.
14368
0
  if (S->getString().empty())
14369
0
    fill = llvm::APInt(32, 0);
14370
0
  else if (S->getString().getAsInteger(0, fill))
14371
0
    return false;
14372
14373
0
  if (Context.getTargetInfo().isNan2008()) {
14374
0
    if (SNaN)
14375
0
      Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14376
0
    else
14377
0
      Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14378
0
  } else {
14379
    // Prior to IEEE 754-2008, architectures were allowed to choose whether
14380
    // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14381
    // a different encoding to what became a standard in 2008, and for pre-
14382
    // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14383
    // sNaN. This is now known as "legacy NaN" encoding.
14384
0
    if (SNaN)
14385
0
      Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14386
0
    else
14387
0
      Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14388
0
  }
14389
14390
0
  return true;
14391
0
}
14392
14393
0
bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14394
0
  if (!IsConstantEvaluatedBuiltinCall(E))
14395
0
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
14396
14397
0
  switch (E->getBuiltinCallee()) {
14398
0
  default:
14399
0
    return false;
14400
14401
0
  case Builtin::BI__builtin_huge_val:
14402
0
  case Builtin::BI__builtin_huge_valf:
14403
0
  case Builtin::BI__builtin_huge_vall:
14404
0
  case Builtin::BI__builtin_huge_valf16:
14405
0
  case Builtin::BI__builtin_huge_valf128:
14406
0
  case Builtin::BI__builtin_inf:
14407
0
  case Builtin::BI__builtin_inff:
14408
0
  case Builtin::BI__builtin_infl:
14409
0
  case Builtin::BI__builtin_inff16:
14410
0
  case Builtin::BI__builtin_inff128: {
14411
0
    const llvm::fltSemantics &Sem =
14412
0
      Info.Ctx.getFloatTypeSemantics(E->getType());
14413
0
    Result = llvm::APFloat::getInf(Sem);
14414
0
    return true;
14415
0
  }
14416
14417
0
  case Builtin::BI__builtin_nans:
14418
0
  case Builtin::BI__builtin_nansf:
14419
0
  case Builtin::BI__builtin_nansl:
14420
0
  case Builtin::BI__builtin_nansf16:
14421
0
  case Builtin::BI__builtin_nansf128:
14422
0
    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14423
0
                               true, Result))
14424
0
      return Error(E);
14425
0
    return true;
14426
14427
0
  case Builtin::BI__builtin_nan:
14428
0
  case Builtin::BI__builtin_nanf:
14429
0
  case Builtin::BI__builtin_nanl:
14430
0
  case Builtin::BI__builtin_nanf16:
14431
0
  case Builtin::BI__builtin_nanf128:
14432
    // If this is __builtin_nan() turn this into a nan, otherwise we
14433
    // can't constant fold it.
14434
0
    if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14435
0
                               false, Result))
14436
0
      return Error(E);
14437
0
    return true;
14438
14439
0
  case Builtin::BI__builtin_fabs:
14440
0
  case Builtin::BI__builtin_fabsf:
14441
0
  case Builtin::BI__builtin_fabsl:
14442
0
  case Builtin::BI__builtin_fabsf128:
14443
    // The C standard says "fabs raises no floating-point exceptions,
14444
    // even if x is a signaling NaN. The returned value is independent of
14445
    // the current rounding direction mode."  Therefore constant folding can
14446
    // proceed without regard to the floating point settings.
14447
    // Reference, WG14 N2478 F.10.4.3
14448
0
    if (!EvaluateFloat(E->getArg(0), Result, Info))
14449
0
      return false;
14450
14451
0
    if (Result.isNegative())
14452
0
      Result.changeSign();
14453
0
    return true;
14454
14455
0
  case Builtin::BI__arithmetic_fence:
14456
0
    return EvaluateFloat(E->getArg(0), Result, Info);
14457
14458
  // FIXME: Builtin::BI__builtin_powi
14459
  // FIXME: Builtin::BI__builtin_powif
14460
  // FIXME: Builtin::BI__builtin_powil
14461
14462
0
  case Builtin::BI__builtin_copysign:
14463
0
  case Builtin::BI__builtin_copysignf:
14464
0
  case Builtin::BI__builtin_copysignl:
14465
0
  case Builtin::BI__builtin_copysignf128: {
14466
0
    APFloat RHS(0.);
14467
0
    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14468
0
        !EvaluateFloat(E->getArg(1), RHS, Info))
14469
0
      return false;
14470
0
    Result.copySign(RHS);
14471
0
    return true;
14472
0
  }
14473
14474
0
  case Builtin::BI__builtin_fmax:
14475
0
  case Builtin::BI__builtin_fmaxf:
14476
0
  case Builtin::BI__builtin_fmaxl:
14477
0
  case Builtin::BI__builtin_fmaxf16:
14478
0
  case Builtin::BI__builtin_fmaxf128: {
14479
    // TODO: Handle sNaN.
14480
0
    APFloat RHS(0.);
14481
0
    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14482
0
        !EvaluateFloat(E->getArg(1), RHS, Info))
14483
0
      return false;
14484
    // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14485
0
    if (Result.isZero() && RHS.isZero() && Result.isNegative())
14486
0
      Result = RHS;
14487
0
    else if (Result.isNaN() || RHS > Result)
14488
0
      Result = RHS;
14489
0
    return true;
14490
0
  }
14491
14492
0
  case Builtin::BI__builtin_fmin:
14493
0
  case Builtin::BI__builtin_fminf:
14494
0
  case Builtin::BI__builtin_fminl:
14495
0
  case Builtin::BI__builtin_fminf16:
14496
0
  case Builtin::BI__builtin_fminf128: {
14497
    // TODO: Handle sNaN.
14498
0
    APFloat RHS(0.);
14499
0
    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14500
0
        !EvaluateFloat(E->getArg(1), RHS, Info))
14501
0
      return false;
14502
    // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14503
0
    if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14504
0
      Result = RHS;
14505
0
    else if (Result.isNaN() || RHS < Result)
14506
0
      Result = RHS;
14507
0
    return true;
14508
0
  }
14509
0
  }
14510
0
}
14511
14512
0
bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14513
0
  if (E->getSubExpr()->getType()->isAnyComplexType()) {
14514
0
    ComplexValue CV;
14515
0
    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14516
0
      return false;
14517
0
    Result = CV.FloatReal;
14518
0
    return true;
14519
0
  }
14520
14521
0
  return Visit(E->getSubExpr());
14522
0
}
14523
14524
0
bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14525
0
  if (E->getSubExpr()->getType()->isAnyComplexType()) {
14526
0
    ComplexValue CV;
14527
0
    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14528
0
      return false;
14529
0
    Result = CV.FloatImag;
14530
0
    return true;
14531
0
  }
14532
14533
0
  VisitIgnoredValue(E->getSubExpr());
14534
0
  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14535
0
  Result = llvm::APFloat::getZero(Sem);
14536
0
  return true;
14537
0
}
14538
14539
0
bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14540
0
  switch (E->getOpcode()) {
14541
0
  default: return Error(E);
14542
0
  case UO_Plus:
14543
0
    return EvaluateFloat(E->getSubExpr(), Result, Info);
14544
0
  case UO_Minus:
14545
    // In C standard, WG14 N2478 F.3 p4
14546
    // "the unary - raises no floating point exceptions,
14547
    // even if the operand is signalling."
14548
0
    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14549
0
      return false;
14550
0
    Result.changeSign();
14551
0
    return true;
14552
0
  }
14553
0
}
14554
14555
0
bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14556
0
  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14557
0
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14558
14559
0
  APFloat RHS(0.0);
14560
0
  bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14561
0
  if (!LHSOK && !Info.noteFailure())
14562
0
    return false;
14563
0
  return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14564
0
         handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14565
0
}
14566
14567
0
bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14568
0
  Result = E->getValue();
14569
0
  return true;
14570
0
}
14571
14572
0
bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14573
0
  const Expr* SubExpr = E->getSubExpr();
14574
14575
0
  switch (E->getCastKind()) {
14576
0
  default:
14577
0
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
14578
14579
0
  case CK_IntegralToFloating: {
14580
0
    APSInt IntResult;
14581
0
    const FPOptions FPO = E->getFPFeaturesInEffect(
14582
0
                                  Info.Ctx.getLangOpts());
14583
0
    return EvaluateInteger(SubExpr, IntResult, Info) &&
14584
0
           HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14585
0
                                IntResult, E->getType(), Result);
14586
0
  }
14587
14588
0
  case CK_FixedPointToFloating: {
14589
0
    APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14590
0
    if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14591
0
      return false;
14592
0
    Result =
14593
0
        FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14594
0
    return true;
14595
0
  }
14596
14597
0
  case CK_FloatingCast: {
14598
0
    if (!Visit(SubExpr))
14599
0
      return false;
14600
0
    return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14601
0
                                  Result);
14602
0
  }
14603
14604
0
  case CK_FloatingComplexToReal: {
14605
0
    ComplexValue V;
14606
0
    if (!EvaluateComplex(SubExpr, V, Info))
14607
0
      return false;
14608
0
    Result = V.getComplexFloatReal();
14609
0
    return true;
14610
0
  }
14611
0
  }
14612
0
}
14613
14614
//===----------------------------------------------------------------------===//
14615
// Complex Evaluation (for float and integer)
14616
//===----------------------------------------------------------------------===//
14617
14618
namespace {
14619
class ComplexExprEvaluator
14620
  : public ExprEvaluatorBase<ComplexExprEvaluator> {
14621
  ComplexValue &Result;
14622
14623
public:
14624
  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14625
0
    : ExprEvaluatorBaseTy(info), Result(Result) {}
14626
14627
0
  bool Success(const APValue &V, const Expr *e) {
14628
0
    Result.setFrom(V);
14629
0
    return true;
14630
0
  }
14631
14632
  bool ZeroInitialization(const Expr *E);
14633
14634
  //===--------------------------------------------------------------------===//
14635
  //                            Visitor Methods
14636
  //===--------------------------------------------------------------------===//
14637
14638
  bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14639
  bool VisitCastExpr(const CastExpr *E);
14640
  bool VisitBinaryOperator(const BinaryOperator *E);
14641
  bool VisitUnaryOperator(const UnaryOperator *E);
14642
  bool VisitInitListExpr(const InitListExpr *E);
14643
  bool VisitCallExpr(const CallExpr *E);
14644
};
14645
} // end anonymous namespace
14646
14647
static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14648
0
                            EvalInfo &Info) {
14649
0
  assert(!E->isValueDependent());
14650
0
  assert(E->isPRValue() && E->getType()->isAnyComplexType());
14651
0
  return ComplexExprEvaluator(Info, Result).Visit(E);
14652
0
}
14653
14654
0
bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14655
0
  QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14656
0
  if (ElemTy->isRealFloatingType()) {
14657
0
    Result.makeComplexFloat();
14658
0
    APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14659
0
    Result.FloatReal = Zero;
14660
0
    Result.FloatImag = Zero;
14661
0
  } else {
14662
0
    Result.makeComplexInt();
14663
0
    APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14664
0
    Result.IntReal = Zero;
14665
0
    Result.IntImag = Zero;
14666
0
  }
14667
0
  return true;
14668
0
}
14669
14670
0
bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14671
0
  const Expr* SubExpr = E->getSubExpr();
14672
14673
0
  if (SubExpr->getType()->isRealFloatingType()) {
14674
0
    Result.makeComplexFloat();
14675
0
    APFloat &Imag = Result.FloatImag;
14676
0
    if (!EvaluateFloat(SubExpr, Imag, Info))
14677
0
      return false;
14678
14679
0
    Result.FloatReal = APFloat(Imag.getSemantics());
14680
0
    return true;
14681
0
  } else {
14682
0
    assert(SubExpr->getType()->isIntegerType() &&
14683
0
           "Unexpected imaginary literal.");
14684
14685
0
    Result.makeComplexInt();
14686
0
    APSInt &Imag = Result.IntImag;
14687
0
    if (!EvaluateInteger(SubExpr, Imag, Info))
14688
0
      return false;
14689
14690
0
    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14691
0
    return true;
14692
0
  }
14693
0
}
14694
14695
0
bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14696
14697
0
  switch (E->getCastKind()) {
14698
0
  case CK_BitCast:
14699
0
  case CK_BaseToDerived:
14700
0
  case CK_DerivedToBase:
14701
0
  case CK_UncheckedDerivedToBase:
14702
0
  case CK_Dynamic:
14703
0
  case CK_ToUnion:
14704
0
  case CK_ArrayToPointerDecay:
14705
0
  case CK_FunctionToPointerDecay:
14706
0
  case CK_NullToPointer:
14707
0
  case CK_NullToMemberPointer:
14708
0
  case CK_BaseToDerivedMemberPointer:
14709
0
  case CK_DerivedToBaseMemberPointer:
14710
0
  case CK_MemberPointerToBoolean:
14711
0
  case CK_ReinterpretMemberPointer:
14712
0
  case CK_ConstructorConversion:
14713
0
  case CK_IntegralToPointer:
14714
0
  case CK_PointerToIntegral:
14715
0
  case CK_PointerToBoolean:
14716
0
  case CK_ToVoid:
14717
0
  case CK_VectorSplat:
14718
0
  case CK_IntegralCast:
14719
0
  case CK_BooleanToSignedIntegral:
14720
0
  case CK_IntegralToBoolean:
14721
0
  case CK_IntegralToFloating:
14722
0
  case CK_FloatingToIntegral:
14723
0
  case CK_FloatingToBoolean:
14724
0
  case CK_FloatingCast:
14725
0
  case CK_CPointerToObjCPointerCast:
14726
0
  case CK_BlockPointerToObjCPointerCast:
14727
0
  case CK_AnyPointerToBlockPointerCast:
14728
0
  case CK_ObjCObjectLValueCast:
14729
0
  case CK_FloatingComplexToReal:
14730
0
  case CK_FloatingComplexToBoolean:
14731
0
  case CK_IntegralComplexToReal:
14732
0
  case CK_IntegralComplexToBoolean:
14733
0
  case CK_ARCProduceObject:
14734
0
  case CK_ARCConsumeObject:
14735
0
  case CK_ARCReclaimReturnedObject:
14736
0
  case CK_ARCExtendBlockObject:
14737
0
  case CK_CopyAndAutoreleaseBlockObject:
14738
0
  case CK_BuiltinFnToFnPtr:
14739
0
  case CK_ZeroToOCLOpaqueType:
14740
0
  case CK_NonAtomicToAtomic:
14741
0
  case CK_AddressSpaceConversion:
14742
0
  case CK_IntToOCLSampler:
14743
0
  case CK_FloatingToFixedPoint:
14744
0
  case CK_FixedPointToFloating:
14745
0
  case CK_FixedPointCast:
14746
0
  case CK_FixedPointToBoolean:
14747
0
  case CK_FixedPointToIntegral:
14748
0
  case CK_IntegralToFixedPoint:
14749
0
  case CK_MatrixCast:
14750
0
    llvm_unreachable("invalid cast kind for complex value");
14751
14752
0
  case CK_LValueToRValue:
14753
0
  case CK_AtomicToNonAtomic:
14754
0
  case CK_NoOp:
14755
0
  case CK_LValueToRValueBitCast:
14756
0
    return ExprEvaluatorBaseTy::VisitCastExpr(E);
14757
14758
0
  case CK_Dependent:
14759
0
  case CK_LValueBitCast:
14760
0
  case CK_UserDefinedConversion:
14761
0
    return Error(E);
14762
14763
0
  case CK_FloatingRealToComplex: {
14764
0
    APFloat &Real = Result.FloatReal;
14765
0
    if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14766
0
      return false;
14767
14768
0
    Result.makeComplexFloat();
14769
0
    Result.FloatImag = APFloat(Real.getSemantics());
14770
0
    return true;
14771
0
  }
14772
14773
0
  case CK_FloatingComplexCast: {
14774
0
    if (!Visit(E->getSubExpr()))
14775
0
      return false;
14776
14777
0
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14778
0
    QualType From
14779
0
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14780
14781
0
    return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14782
0
           HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14783
0
  }
14784
14785
0
  case CK_FloatingComplexToIntegralComplex: {
14786
0
    if (!Visit(E->getSubExpr()))
14787
0
      return false;
14788
14789
0
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14790
0
    QualType From
14791
0
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14792
0
    Result.makeComplexInt();
14793
0
    return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14794
0
                                To, Result.IntReal) &&
14795
0
           HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14796
0
                                To, Result.IntImag);
14797
0
  }
14798
14799
0
  case CK_IntegralRealToComplex: {
14800
0
    APSInt &Real = Result.IntReal;
14801
0
    if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14802
0
      return false;
14803
14804
0
    Result.makeComplexInt();
14805
0
    Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14806
0
    return true;
14807
0
  }
14808
14809
0
  case CK_IntegralComplexCast: {
14810
0
    if (!Visit(E->getSubExpr()))
14811
0
      return false;
14812
14813
0
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14814
0
    QualType From
14815
0
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14816
14817
0
    Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14818
0
    Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14819
0
    return true;
14820
0
  }
14821
14822
0
  case CK_IntegralComplexToFloatingComplex: {
14823
0
    if (!Visit(E->getSubExpr()))
14824
0
      return false;
14825
14826
0
    const FPOptions FPO = E->getFPFeaturesInEffect(
14827
0
                                  Info.Ctx.getLangOpts());
14828
0
    QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14829
0
    QualType From
14830
0
      = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14831
0
    Result.makeComplexFloat();
14832
0
    return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14833
0
                                To, Result.FloatReal) &&
14834
0
           HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14835
0
                                To, Result.FloatImag);
14836
0
  }
14837
0
  }
14838
14839
0
  llvm_unreachable("unknown cast resulting in complex value");
14840
0
}
14841
14842
0
bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14843
0
  if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14844
0
    return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14845
14846
  // Track whether the LHS or RHS is real at the type system level. When this is
14847
  // the case we can simplify our evaluation strategy.
14848
0
  bool LHSReal = false, RHSReal = false;
14849
14850
0
  bool LHSOK;
14851
0
  if (E->getLHS()->getType()->isRealFloatingType()) {
14852
0
    LHSReal = true;
14853
0
    APFloat &Real = Result.FloatReal;
14854
0
    LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14855
0
    if (LHSOK) {
14856
0
      Result.makeComplexFloat();
14857
0
      Result.FloatImag = APFloat(Real.getSemantics());
14858
0
    }
14859
0
  } else {
14860
0
    LHSOK = Visit(E->getLHS());
14861
0
  }
14862
0
  if (!LHSOK && !Info.noteFailure())
14863
0
    return false;
14864
14865
0
  ComplexValue RHS;
14866
0
  if (E->getRHS()->getType()->isRealFloatingType()) {
14867
0
    RHSReal = true;
14868
0
    APFloat &Real = RHS.FloatReal;
14869
0
    if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14870
0
      return false;
14871
0
    RHS.makeComplexFloat();
14872
0
    RHS.FloatImag = APFloat(Real.getSemantics());
14873
0
  } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14874
0
    return false;
14875
14876
0
  assert(!(LHSReal && RHSReal) &&
14877
0
         "Cannot have both operands of a complex operation be real.");
14878
0
  switch (E->getOpcode()) {
14879
0
  default: return Error(E);
14880
0
  case BO_Add:
14881
0
    if (Result.isComplexFloat()) {
14882
0
      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14883
0
                                       APFloat::rmNearestTiesToEven);
14884
0
      if (LHSReal)
14885
0
        Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14886
0
      else if (!RHSReal)
14887
0
        Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14888
0
                                         APFloat::rmNearestTiesToEven);
14889
0
    } else {
14890
0
      Result.getComplexIntReal() += RHS.getComplexIntReal();
14891
0
      Result.getComplexIntImag() += RHS.getComplexIntImag();
14892
0
    }
14893
0
    break;
14894
0
  case BO_Sub:
14895
0
    if (Result.isComplexFloat()) {
14896
0
      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14897
0
                                            APFloat::rmNearestTiesToEven);
14898
0
      if (LHSReal) {
14899
0
        Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14900
0
        Result.getComplexFloatImag().changeSign();
14901
0
      } else if (!RHSReal) {
14902
0
        Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14903
0
                                              APFloat::rmNearestTiesToEven);
14904
0
      }
14905
0
    } else {
14906
0
      Result.getComplexIntReal() -= RHS.getComplexIntReal();
14907
0
      Result.getComplexIntImag() -= RHS.getComplexIntImag();
14908
0
    }
14909
0
    break;
14910
0
  case BO_Mul:
14911
0
    if (Result.isComplexFloat()) {
14912
      // This is an implementation of complex multiplication according to the
14913
      // constraints laid out in C11 Annex G. The implementation uses the
14914
      // following naming scheme:
14915
      //   (a + ib) * (c + id)
14916
0
      ComplexValue LHS = Result;
14917
0
      APFloat &A = LHS.getComplexFloatReal();
14918
0
      APFloat &B = LHS.getComplexFloatImag();
14919
0
      APFloat &C = RHS.getComplexFloatReal();
14920
0
      APFloat &D = RHS.getComplexFloatImag();
14921
0
      APFloat &ResR = Result.getComplexFloatReal();
14922
0
      APFloat &ResI = Result.getComplexFloatImag();
14923
0
      if (LHSReal) {
14924
0
        assert(!RHSReal && "Cannot have two real operands for a complex op!");
14925
0
        ResR = A * C;
14926
0
        ResI = A * D;
14927
0
      } else if (RHSReal) {
14928
0
        ResR = C * A;
14929
0
        ResI = C * B;
14930
0
      } else {
14931
        // In the fully general case, we need to handle NaNs and infinities
14932
        // robustly.
14933
0
        APFloat AC = A * C;
14934
0
        APFloat BD = B * D;
14935
0
        APFloat AD = A * D;
14936
0
        APFloat BC = B * C;
14937
0
        ResR = AC - BD;
14938
0
        ResI = AD + BC;
14939
0
        if (ResR.isNaN() && ResI.isNaN()) {
14940
0
          bool Recalc = false;
14941
0
          if (A.isInfinity() || B.isInfinity()) {
14942
0
            A = APFloat::copySign(
14943
0
                APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14944
0
            B = APFloat::copySign(
14945
0
                APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14946
0
            if (C.isNaN())
14947
0
              C = APFloat::copySign(APFloat(C.getSemantics()), C);
14948
0
            if (D.isNaN())
14949
0
              D = APFloat::copySign(APFloat(D.getSemantics()), D);
14950
0
            Recalc = true;
14951
0
          }
14952
0
          if (C.isInfinity() || D.isInfinity()) {
14953
0
            C = APFloat::copySign(
14954
0
                APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14955
0
            D = APFloat::copySign(
14956
0
                APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14957
0
            if (A.isNaN())
14958
0
              A = APFloat::copySign(APFloat(A.getSemantics()), A);
14959
0
            if (B.isNaN())
14960
0
              B = APFloat::copySign(APFloat(B.getSemantics()), B);
14961
0
            Recalc = true;
14962
0
          }
14963
0
          if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14964
0
                          AD.isInfinity() || BC.isInfinity())) {
14965
0
            if (A.isNaN())
14966
0
              A = APFloat::copySign(APFloat(A.getSemantics()), A);
14967
0
            if (B.isNaN())
14968
0
              B = APFloat::copySign(APFloat(B.getSemantics()), B);
14969
0
            if (C.isNaN())
14970
0
              C = APFloat::copySign(APFloat(C.getSemantics()), C);
14971
0
            if (D.isNaN())
14972
0
              D = APFloat::copySign(APFloat(D.getSemantics()), D);
14973
0
            Recalc = true;
14974
0
          }
14975
0
          if (Recalc) {
14976
0
            ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14977
0
            ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14978
0
          }
14979
0
        }
14980
0
      }
14981
0
    } else {
14982
0
      ComplexValue LHS = Result;
14983
0
      Result.getComplexIntReal() =
14984
0
        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14985
0
         LHS.getComplexIntImag() * RHS.getComplexIntImag());
14986
0
      Result.getComplexIntImag() =
14987
0
        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14988
0
         LHS.getComplexIntImag() * RHS.getComplexIntReal());
14989
0
    }
14990
0
    break;
14991
0
  case BO_Div:
14992
0
    if (Result.isComplexFloat()) {
14993
      // This is an implementation of complex division according to the
14994
      // constraints laid out in C11 Annex G. The implementation uses the
14995
      // following naming scheme:
14996
      //   (a + ib) / (c + id)
14997
0
      ComplexValue LHS = Result;
14998
0
      APFloat &A = LHS.getComplexFloatReal();
14999
0
      APFloat &B = LHS.getComplexFloatImag();
15000
0
      APFloat &C = RHS.getComplexFloatReal();
15001
0
      APFloat &D = RHS.getComplexFloatImag();
15002
0
      APFloat &ResR = Result.getComplexFloatReal();
15003
0
      APFloat &ResI = Result.getComplexFloatImag();
15004
0
      if (RHSReal) {
15005
0
        ResR = A / C;
15006
0
        ResI = B / C;
15007
0
      } else {
15008
0
        if (LHSReal) {
15009
          // No real optimizations we can do here, stub out with zero.
15010
0
          B = APFloat::getZero(A.getSemantics());
15011
0
        }
15012
0
        int DenomLogB = 0;
15013
0
        APFloat MaxCD = maxnum(abs(C), abs(D));
15014
0
        if (MaxCD.isFinite()) {
15015
0
          DenomLogB = ilogb(MaxCD);
15016
0
          C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15017
0
          D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15018
0
        }
15019
0
        APFloat Denom = C * C + D * D;
15020
0
        ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
15021
0
                      APFloat::rmNearestTiesToEven);
15022
0
        ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
15023
0
                      APFloat::rmNearestTiesToEven);
15024
0
        if (ResR.isNaN() && ResI.isNaN()) {
15025
0
          if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
15026
0
            ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
15027
0
            ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
15028
0
          } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
15029
0
                     D.isFinite()) {
15030
0
            A = APFloat::copySign(
15031
0
                APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
15032
0
            B = APFloat::copySign(
15033
0
                APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
15034
0
            ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
15035
0
            ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15036
0
          } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
15037
0
            C = APFloat::copySign(
15038
0
                APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
15039
0
            D = APFloat::copySign(
15040
0
                APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
15041
0
            ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
15042
0
            ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15043
0
          }
15044
0
        }
15045
0
      }
15046
0
    } else {
15047
0
      if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
15048
0
        return Error(E, diag::note_expr_divide_by_zero);
15049
15050
0
      ComplexValue LHS = Result;
15051
0
      APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
15052
0
        RHS.getComplexIntImag() * RHS.getComplexIntImag();
15053
0
      Result.getComplexIntReal() =
15054
0
        (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
15055
0
         LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
15056
0
      Result.getComplexIntImag() =
15057
0
        (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15058
0
         LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
15059
0
    }
15060
0
    break;
15061
0
  }
15062
15063
0
  return true;
15064
0
}
15065
15066
0
bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15067
  // Get the operand value into 'Result'.
15068
0
  if (!Visit(E->getSubExpr()))
15069
0
    return false;
15070
15071
0
  switch (E->getOpcode()) {
15072
0
  default:
15073
0
    return Error(E);
15074
0
  case UO_Extension:
15075
0
    return true;
15076
0
  case UO_Plus:
15077
    // The result is always just the subexpr.
15078
0
    return true;
15079
0
  case UO_Minus:
15080
0
    if (Result.isComplexFloat()) {
15081
0
      Result.getComplexFloatReal().changeSign();
15082
0
      Result.getComplexFloatImag().changeSign();
15083
0
    }
15084
0
    else {
15085
0
      Result.getComplexIntReal() = -Result.getComplexIntReal();
15086
0
      Result.getComplexIntImag() = -Result.getComplexIntImag();
15087
0
    }
15088
0
    return true;
15089
0
  case UO_Not:
15090
0
    if (Result.isComplexFloat())
15091
0
      Result.getComplexFloatImag().changeSign();
15092
0
    else
15093
0
      Result.getComplexIntImag() = -Result.getComplexIntImag();
15094
0
    return true;
15095
0
  }
15096
0
}
15097
15098
0
bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
15099
0
  if (E->getNumInits() == 2) {
15100
0
    if (E->getType()->isComplexType()) {
15101
0
      Result.makeComplexFloat();
15102
0
      if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15103
0
        return false;
15104
0
      if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15105
0
        return false;
15106
0
    } else {
15107
0
      Result.makeComplexInt();
15108
0
      if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15109
0
        return false;
15110
0
      if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15111
0
        return false;
15112
0
    }
15113
0
    return true;
15114
0
  }
15115
0
  return ExprEvaluatorBaseTy::VisitInitListExpr(E);
15116
0
}
15117
15118
0
bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
15119
0
  if (!IsConstantEvaluatedBuiltinCall(E))
15120
0
    return ExprEvaluatorBaseTy::VisitCallExpr(E);
15121
15122
0
  switch (E->getBuiltinCallee()) {
15123
0
  case Builtin::BI__builtin_complex:
15124
0
    Result.makeComplexFloat();
15125
0
    if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15126
0
      return false;
15127
0
    if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15128
0
      return false;
15129
0
    return true;
15130
15131
0
  default:
15132
0
    return false;
15133
0
  }
15134
0
}
15135
15136
//===----------------------------------------------------------------------===//
15137
// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
15138
// implicit conversion.
15139
//===----------------------------------------------------------------------===//
15140
15141
namespace {
15142
class AtomicExprEvaluator :
15143
    public ExprEvaluatorBase<AtomicExprEvaluator> {
15144
  const LValue *This;
15145
  APValue &Result;
15146
public:
15147
  AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
15148
0
      : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
15149
15150
0
  bool Success(const APValue &V, const Expr *E) {
15151
0
    Result = V;
15152
0
    return true;
15153
0
  }
15154
15155
0
  bool ZeroInitialization(const Expr *E) {
15156
0
    ImplicitValueInitExpr VIE(
15157
0
        E->getType()->castAs<AtomicType>()->getValueType());
15158
    // For atomic-qualified class (and array) types in C++, initialize the
15159
    // _Atomic-wrapped subobject directly, in-place.
15160
0
    return This ? EvaluateInPlace(Result, Info, *This, &VIE)
15161
0
                : Evaluate(Result, Info, &VIE);
15162
0
  }
15163
15164
0
  bool VisitCastExpr(const CastExpr *E) {
15165
0
    switch (E->getCastKind()) {
15166
0
    default:
15167
0
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
15168
0
    case CK_NullToPointer:
15169
0
      VisitIgnoredValue(E->getSubExpr());
15170
0
      return ZeroInitialization(E);
15171
0
    case CK_NonAtomicToAtomic:
15172
0
      return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
15173
0
                  : Evaluate(Result, Info, E->getSubExpr());
15174
0
    }
15175
0
  }
15176
};
15177
} // end anonymous namespace
15178
15179
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
15180
0
                           EvalInfo &Info) {
15181
0
  assert(!E->isValueDependent());
15182
0
  assert(E->isPRValue() && E->getType()->isAtomicType());
15183
0
  return AtomicExprEvaluator(Info, This, Result).Visit(E);
15184
0
}
15185
15186
//===----------------------------------------------------------------------===//
15187
// Void expression evaluation, primarily for a cast to void on the LHS of a
15188
// comma operator
15189
//===----------------------------------------------------------------------===//
15190
15191
namespace {
15192
class VoidExprEvaluator
15193
  : public ExprEvaluatorBase<VoidExprEvaluator> {
15194
public:
15195
0
  VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
15196
15197
0
  bool Success(const APValue &V, const Expr *e) { return true; }
15198
15199
0
  bool ZeroInitialization(const Expr *E) { return true; }
15200
15201
0
  bool VisitCastExpr(const CastExpr *E) {
15202
0
    switch (E->getCastKind()) {
15203
0
    default:
15204
0
      return ExprEvaluatorBaseTy::VisitCastExpr(E);
15205
0
    case CK_ToVoid:
15206
0
      VisitIgnoredValue(E->getSubExpr());
15207
0
      return true;
15208
0
    }
15209
0
  }
15210
15211
0
  bool VisitCallExpr(const CallExpr *E) {
15212
0
    if (!IsConstantEvaluatedBuiltinCall(E))
15213
0
      return ExprEvaluatorBaseTy::VisitCallExpr(E);
15214
15215
0
    switch (E->getBuiltinCallee()) {
15216
0
    case Builtin::BI__assume:
15217
0
    case Builtin::BI__builtin_assume:
15218
      // The argument is not evaluated!
15219
0
      return true;
15220
15221
0
    case Builtin::BI__builtin_operator_delete:
15222
0
      return HandleOperatorDeleteCall(Info, E);
15223
15224
0
    default:
15225
0
      return false;
15226
0
    }
15227
0
  }
15228
15229
  bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
15230
};
15231
} // end anonymous namespace
15232
15233
0
bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
15234
  // We cannot speculatively evaluate a delete expression.
15235
0
  if (Info.SpeculativeEvaluationDepth)
15236
0
    return false;
15237
15238
0
  FunctionDecl *OperatorDelete = E->getOperatorDelete();
15239
0
  if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15240
0
    Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15241
0
        << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
15242
0
    return false;
15243
0
  }
15244
15245
0
  const Expr *Arg = E->getArgument();
15246
15247
0
  LValue Pointer;
15248
0
  if (!EvaluatePointer(Arg, Pointer, Info))
15249
0
    return false;
15250
0
  if (Pointer.Designator.Invalid)
15251
0
    return false;
15252
15253
  // Deleting a null pointer has no effect.
15254
0
  if (Pointer.isNullPointer()) {
15255
    // This is the only case where we need to produce an extension warning:
15256
    // the only other way we can succeed is if we find a dynamic allocation,
15257
    // and we will have warned when we allocated it in that case.
15258
0
    if (!Info.getLangOpts().CPlusPlus20)
15259
0
      Info.CCEDiag(E, diag::note_constexpr_new);
15260
0
    return true;
15261
0
  }
15262
15263
0
  std::optional<DynAlloc *> Alloc = CheckDeleteKind(
15264
0
      Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15265
0
  if (!Alloc)
15266
0
    return false;
15267
0
  QualType AllocType = Pointer.Base.getDynamicAllocType();
15268
15269
  // For the non-array case, the designator must be empty if the static type
15270
  // does not have a virtual destructor.
15271
0
  if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15272
0
      !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
15273
0
    Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
15274
0
        << Arg->getType()->getPointeeType() << AllocType;
15275
0
    return false;
15276
0
  }
15277
15278
  // For a class type with a virtual destructor, the selected operator delete
15279
  // is the one looked up when building the destructor.
15280
0
  if (!E->isArrayForm() && !E->isGlobalDelete()) {
15281
0
    const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
15282
0
    if (VirtualDelete &&
15283
0
        !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15284
0
      Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
15285
0
          << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
15286
0
      return false;
15287
0
    }
15288
0
  }
15289
15290
0
  if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15291
0
                         (*Alloc)->Value, AllocType))
15292
0
    return false;
15293
15294
0
  if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
15295
    // The element was already erased. This means the destructor call also
15296
    // deleted the object.
15297
    // FIXME: This probably results in undefined behavior before we get this
15298
    // far, and should be diagnosed elsewhere first.
15299
0
    Info.FFDiag(E, diag::note_constexpr_double_delete);
15300
0
    return false;
15301
0
  }
15302
15303
0
  return true;
15304
0
}
15305
15306
0
static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
15307
0
  assert(!E->isValueDependent());
15308
0
  assert(E->isPRValue() && E->getType()->isVoidType());
15309
0
  return VoidExprEvaluator(Info).Visit(E);
15310
0
}
15311
15312
//===----------------------------------------------------------------------===//
15313
// Top level Expr::EvaluateAsRValue method.
15314
//===----------------------------------------------------------------------===//
15315
15316
14
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
15317
14
  assert(!E->isValueDependent());
15318
  // In C, function designators are not lvalues, but we evaluate them as if they
15319
  // are.
15320
0
  QualType T = E->getType();
15321
14
  if (E->isGLValue() || T->isFunctionType()) {
15322
4
    LValue LV;
15323
4
    if (!EvaluateLValue(E, LV, Info))
15324
0
      return false;
15325
4
    LV.moveInto(Result);
15326
10
  } else if (T->isVectorType()) {
15327
0
    if (!EvaluateVector(E, Result, Info))
15328
0
      return false;
15329
10
  } else if (T->isIntegralOrEnumerationType()) {
15330
9
    if (!IntExprEvaluator(Info, Result).Visit(E))
15331
4
      return false;
15332
9
  } else if (T->hasPointerRepresentation()) {
15333
1
    LValue LV;
15334
1
    if (!EvaluatePointer(E, LV, Info))
15335
1
      return false;
15336
0
    LV.moveInto(Result);
15337
0
  } else if (T->isRealFloatingType()) {
15338
0
    llvm::APFloat F(0.0);
15339
0
    if (!EvaluateFloat(E, F, Info))
15340
0
      return false;
15341
0
    Result = APValue(F);
15342
0
  } else if (T->isAnyComplexType()) {
15343
0
    ComplexValue C;
15344
0
    if (!EvaluateComplex(E, C, Info))
15345
0
      return false;
15346
0
    C.moveInto(Result);
15347
0
  } else if (T->isFixedPointType()) {
15348
0
    if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15349
0
  } else if (T->isMemberPointerType()) {
15350
0
    MemberPtr P;
15351
0
    if (!EvaluateMemberPointer(E, P, Info))
15352
0
      return false;
15353
0
    P.moveInto(Result);
15354
0
    return true;
15355
0
  } else if (T->isArrayType()) {
15356
0
    LValue LV;
15357
0
    APValue &Value =
15358
0
        Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15359
0
    if (!EvaluateArray(E, LV, Value, Info))
15360
0
      return false;
15361
0
    Result = Value;
15362
0
  } else if (T->isRecordType()) {
15363
0
    LValue LV;
15364
0
    APValue &Value =
15365
0
        Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15366
0
    if (!EvaluateRecord(E, LV, Value, Info))
15367
0
      return false;
15368
0
    Result = Value;
15369
0
  } else if (T->isVoidType()) {
15370
0
    if (!Info.getLangOpts().CPlusPlus11)
15371
0
      Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15372
0
        << E->getType();
15373
0
    if (!EvaluateVoid(E, Info))
15374
0
      return false;
15375
0
  } else if (T->isAtomicType()) {
15376
0
    QualType Unqual = T.getAtomicUnqualifiedType();
15377
0
    if (Unqual->isArrayType() || Unqual->isRecordType()) {
15378
0
      LValue LV;
15379
0
      APValue &Value = Info.CurrentCall->createTemporary(
15380
0
          E, Unqual, ScopeKind::FullExpression, LV);
15381
0
      if (!EvaluateAtomic(E, &LV, Value, Info))
15382
0
        return false;
15383
0
      Result = Value;
15384
0
    } else {
15385
0
      if (!EvaluateAtomic(E, nullptr, Result, Info))
15386
0
        return false;
15387
0
    }
15388
0
  } else if (Info.getLangOpts().CPlusPlus11) {
15389
0
    Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15390
0
    return false;
15391
0
  } else {
15392
0
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15393
0
    return false;
15394
0
  }
15395
15396
9
  return true;
15397
14
}
15398
15399
/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15400
/// cases, the in-place evaluation is essential, since later initializers for
15401
/// an object can indirectly refer to subobjects which were initialized earlier.
15402
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15403
0
                            const Expr *E, bool AllowNonLiteralTypes) {
15404
0
  assert(!E->isValueDependent());
15405
15406
0
  if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15407
0
    return false;
15408
15409
0
  if (E->isPRValue()) {
15410
    // Evaluate arrays and record types in-place, so that later initializers can
15411
    // refer to earlier-initialized members of the object.
15412
0
    QualType T = E->getType();
15413
0
    if (T->isArrayType())
15414
0
      return EvaluateArray(E, This, Result, Info);
15415
0
    else if (T->isRecordType())
15416
0
      return EvaluateRecord(E, This, Result, Info);
15417
0
    else if (T->isAtomicType()) {
15418
0
      QualType Unqual = T.getAtomicUnqualifiedType();
15419
0
      if (Unqual->isArrayType() || Unqual->isRecordType())
15420
0
        return EvaluateAtomic(E, &This, Result, Info);
15421
0
    }
15422
0
  }
15423
15424
  // For any other type, in-place evaluation is unimportant.
15425
0
  return Evaluate(Result, Info, E);
15426
0
}
15427
15428
/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15429
/// lvalue-to-rvalue cast if it is an lvalue.
15430
14
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15431
14
  assert(!E->isValueDependent());
15432
15433
14
  if (E->getType().isNull())
15434
0
    return false;
15435
15436
14
  if (!CheckLiteralType(Info, E))
15437
0
    return false;
15438
15439
14
  if (Info.EnableNewConstInterp) {
15440
0
    if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15441
0
      return false;
15442
14
  } else {
15443
14
    if (!::Evaluate(Result, Info, E))
15444
5
      return false;
15445
14
  }
15446
15447
  // Implicit lvalue-to-rvalue cast.
15448
9
  if (E->isGLValue()) {
15449
4
    LValue LV;
15450
4
    LV.setFrom(Info.Ctx, Result);
15451
4
    if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15452
4
      return false;
15453
4
  }
15454
15455
  // Check this core constant expression is a constant expression.
15456
5
  return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15457
5
                                 ConstantExprKind::Normal) &&
15458
5
         CheckMemoryLeaks(Info);
15459
9
}
15460
15461
static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15462
14
                                 const ASTContext &Ctx, bool &IsConst) {
15463
  // Fast-path evaluations of integer literals, since we sometimes see files
15464
  // containing vast quantities of these.
15465
14
  if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15466
4
    Result.Val = APValue(APSInt(L->getValue(),
15467
4
                                L->getType()->isUnsignedIntegerType()));
15468
4
    IsConst = true;
15469
4
    return true;
15470
4
  }
15471
15472
10
  if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15473
0
    Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15474
0
    IsConst = true;
15475
0
    return true;
15476
0
  }
15477
15478
10
  if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
15479
0
    if (CE->hasAPValueResult()) {
15480
0
      Result.Val = CE->getAPValueResult();
15481
0
      IsConst = true;
15482
0
      return true;
15483
0
    }
15484
15485
    // The SubExpr is usually just an IntegerLiteral.
15486
0
    return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
15487
0
  }
15488
15489
  // This case should be rare, but we need to check it before we check on
15490
  // the type below.
15491
10
  if (Exp->getType().isNull()) {
15492
0
    IsConst = false;
15493
0
    return true;
15494
0
  }
15495
15496
10
  return false;
15497
10
}
15498
15499
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15500
3
                                      Expr::SideEffectsKind SEK) {
15501
3
  return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15502
3
         (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15503
3
}
15504
15505
static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15506
14
                             const ASTContext &Ctx, EvalInfo &Info) {
15507
14
  assert(!E->isValueDependent());
15508
0
  bool IsConst;
15509
14
  if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15510
4
    return IsConst;
15511
15512
10
  return EvaluateAsRValue(Info, E, Result.Val);
15513
14
}
15514
15515
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15516
                          const ASTContext &Ctx,
15517
                          Expr::SideEffectsKind AllowSideEffects,
15518
2
                          EvalInfo &Info) {
15519
2
  assert(!E->isValueDependent());
15520
2
  if (!E->getType()->isIntegralOrEnumerationType())
15521
0
    return false;
15522
15523
2
  if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15524
2
      !ExprResult.Val.isInt() ||
15525
2
      hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15526
2
    return false;
15527
15528
0
  return true;
15529
2
}
15530
15531
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15532
                                 const ASTContext &Ctx,
15533
                                 Expr::SideEffectsKind AllowSideEffects,
15534
0
                                 EvalInfo &Info) {
15535
0
  assert(!E->isValueDependent());
15536
0
  if (!E->getType()->isFixedPointType())
15537
0
    return false;
15538
15539
0
  if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15540
0
    return false;
15541
15542
0
  if (!ExprResult.Val.isFixedPoint() ||
15543
0
      hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15544
0
    return false;
15545
15546
0
  return true;
15547
0
}
15548
15549
/// EvaluateAsRValue - Return true if this is a constant which we can fold using
15550
/// any crazy technique (that has nothing to do with language standards) that
15551
/// we want to.  If this function returns true, it returns the folded constant
15552
/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15553
/// will be applied to the result.
15554
bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15555
12
                            bool InConstantContext) const {
15556
12
  assert(!isValueDependent() &&
15557
12
         "Expression evaluator can't be called on a dependent expression.");
15558
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15559
12
  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15560
12
  Info.InConstantContext = InConstantContext;
15561
12
  return ::EvaluateAsRValue(this, Result, Ctx, Info);
15562
12
}
15563
15564
bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15565
0
                                      bool InConstantContext) const {
15566
0
  assert(!isValueDependent() &&
15567
0
         "Expression evaluator can't be called on a dependent expression.");
15568
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15569
0
  EvalResult Scratch;
15570
0
  return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15571
0
         HandleConversionToBool(Scratch.Val, Result);
15572
0
}
15573
15574
bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15575
                         SideEffectsKind AllowSideEffects,
15576
2
                         bool InConstantContext) const {
15577
2
  assert(!isValueDependent() &&
15578
2
         "Expression evaluator can't be called on a dependent expression.");
15579
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15580
2
  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15581
2
  Info.InConstantContext = InConstantContext;
15582
2
  return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15583
2
}
15584
15585
bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15586
                                SideEffectsKind AllowSideEffects,
15587
0
                                bool InConstantContext) const {
15588
0
  assert(!isValueDependent() &&
15589
0
         "Expression evaluator can't be called on a dependent expression.");
15590
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15591
0
  EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15592
0
  Info.InConstantContext = InConstantContext;
15593
0
  return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15594
0
}
15595
15596
bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15597
                           SideEffectsKind AllowSideEffects,
15598
0
                           bool InConstantContext) const {
15599
0
  assert(!isValueDependent() &&
15600
0
         "Expression evaluator can't be called on a dependent expression.");
15601
15602
0
  if (!getType()->isRealFloatingType())
15603
0
    return false;
15604
15605
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15606
0
  EvalResult ExprResult;
15607
0
  if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15608
0
      !ExprResult.Val.isFloat() ||
15609
0
      hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15610
0
    return false;
15611
15612
0
  Result = ExprResult.Val.getFloat();
15613
0
  return true;
15614
0
}
15615
15616
bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15617
0
                            bool InConstantContext) const {
15618
0
  assert(!isValueDependent() &&
15619
0
         "Expression evaluator can't be called on a dependent expression.");
15620
15621
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15622
0
  EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15623
0
  Info.InConstantContext = InConstantContext;
15624
0
  LValue LV;
15625
0
  CheckedTemporaries CheckedTemps;
15626
0
  if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15627
0
      Result.HasSideEffects ||
15628
0
      !CheckLValueConstantExpression(Info, getExprLoc(),
15629
0
                                     Ctx.getLValueReferenceType(getType()), LV,
15630
0
                                     ConstantExprKind::Normal, CheckedTemps))
15631
0
    return false;
15632
15633
0
  LV.moveInto(Result.Val);
15634
0
  return true;
15635
0
}
15636
15637
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15638
                                APValue DestroyedValue, QualType Type,
15639
                                SourceLocation Loc, Expr::EvalStatus &EStatus,
15640
0
                                bool IsConstantDestruction) {
15641
0
  EvalInfo Info(Ctx, EStatus,
15642
0
                IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15643
0
                                      : EvalInfo::EM_ConstantFold);
15644
0
  Info.setEvaluatingDecl(Base, DestroyedValue,
15645
0
                         EvalInfo::EvaluatingDeclKind::Dtor);
15646
0
  Info.InConstantContext = IsConstantDestruction;
15647
15648
0
  LValue LVal;
15649
0
  LVal.set(Base);
15650
15651
0
  if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15652
0
      EStatus.HasSideEffects)
15653
0
    return false;
15654
15655
0
  if (!Info.discardCleanups())
15656
0
    llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15657
15658
0
  return true;
15659
0
}
15660
15661
bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15662
0
                                  ConstantExprKind Kind) const {
15663
0
  assert(!isValueDependent() &&
15664
0
         "Expression evaluator can't be called on a dependent expression.");
15665
0
  bool IsConst;
15666
0
  if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15667
0
    return true;
15668
15669
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15670
0
  EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15671
0
  EvalInfo Info(Ctx, Result, EM);
15672
0
  Info.InConstantContext = true;
15673
15674
  // The type of the object we're initializing is 'const T' for a class NTTP.
15675
0
  QualType T = getType();
15676
0
  if (Kind == ConstantExprKind::ClassTemplateArgument)
15677
0
    T.addConst();
15678
15679
  // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15680
  // represent the result of the evaluation. CheckConstantExpression ensures
15681
  // this doesn't escape.
15682
0
  MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15683
0
  APValue::LValueBase Base(&BaseMTE);
15684
0
  Info.setEvaluatingDecl(Base, Result.Val);
15685
15686
0
  if (Info.EnableNewConstInterp) {
15687
0
    if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
15688
0
      return false;
15689
0
  } else {
15690
0
    LValue LVal;
15691
0
    LVal.set(Base);
15692
    // C++23 [intro.execution]/p5
15693
    // A full-expression is [...] a constant-expression
15694
    // So we need to make sure temporary objects are destroyed after having
15695
    // evaluating the expression (per C++23 [class.temporary]/p4).
15696
0
    FullExpressionRAII Scope(Info);
15697
0
    if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
15698
0
        Result.HasSideEffects || !Scope.destroy())
15699
0
      return false;
15700
15701
0
    if (!Info.discardCleanups())
15702
0
      llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15703
0
  }
15704
15705
0
  if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15706
0
                               Result.Val, Kind))
15707
0
    return false;
15708
0
  if (!CheckMemoryLeaks(Info))
15709
0
    return false;
15710
15711
  // If this is a class template argument, it's required to have constant
15712
  // destruction too.
15713
0
  if (Kind == ConstantExprKind::ClassTemplateArgument &&
15714
0
      (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15715
0
                            true) ||
15716
0
       Result.HasSideEffects)) {
15717
    // FIXME: Prefix a note to indicate that the problem is lack of constant
15718
    // destruction.
15719
0
    return false;
15720
0
  }
15721
15722
0
  return true;
15723
0
}
15724
15725
bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15726
                                 const VarDecl *VD,
15727
                                 SmallVectorImpl<PartialDiagnosticAt> &Notes,
15728
0
                                 bool IsConstantInitialization) const {
15729
0
  assert(!isValueDependent() &&
15730
0
         "Expression evaluator can't be called on a dependent expression.");
15731
15732
0
  llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15733
0
    std::string Name;
15734
0
    llvm::raw_string_ostream OS(Name);
15735
0
    VD->printQualifiedName(OS);
15736
0
    return Name;
15737
0
  });
15738
15739
0
  Expr::EvalStatus EStatus;
15740
0
  EStatus.Diag = &Notes;
15741
15742
0
  EvalInfo Info(Ctx, EStatus,
15743
0
                (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus)
15744
0
                    ? EvalInfo::EM_ConstantExpression
15745
0
                    : EvalInfo::EM_ConstantFold);
15746
0
  Info.setEvaluatingDecl(VD, Value);
15747
0
  Info.InConstantContext = IsConstantInitialization;
15748
15749
0
  if (Info.EnableNewConstInterp) {
15750
0
    auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15751
0
    if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15752
0
      return false;
15753
0
  } else {
15754
0
    LValue LVal;
15755
0
    LVal.set(VD);
15756
15757
0
    {
15758
      // C++23 [intro.execution]/p5
15759
      // A full-expression is ... an init-declarator ([dcl.decl]) or a
15760
      // mem-initializer.
15761
      // So we need to make sure temporary objects are destroyed after having
15762
      // evaluated the expression (per C++23 [class.temporary]/p4).
15763
      //
15764
      // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
15765
      // serialization code calls ParmVarDecl::getDefaultArg() which strips the
15766
      // outermost FullExpr, such as ExprWithCleanups.
15767
0
      FullExpressionRAII Scope(Info);
15768
0
      if (!EvaluateInPlace(Value, Info, LVal, this,
15769
0
                           /*AllowNonLiteralTypes=*/true) ||
15770
0
          EStatus.HasSideEffects)
15771
0
        return false;
15772
0
    }
15773
15774
    // At this point, any lifetime-extended temporaries are completely
15775
    // initialized.
15776
0
    Info.performLifetimeExtension();
15777
15778
0
    if (!Info.discardCleanups())
15779
0
      llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15780
0
  }
15781
15782
0
  SourceLocation DeclLoc = VD->getLocation();
15783
0
  QualType DeclTy = VD->getType();
15784
0
  return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15785
0
                                 ConstantExprKind::Normal) &&
15786
0
         CheckMemoryLeaks(Info);
15787
0
}
15788
15789
bool VarDecl::evaluateDestruction(
15790
0
    SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15791
0
  Expr::EvalStatus EStatus;
15792
0
  EStatus.Diag = &Notes;
15793
15794
  // Only treat the destruction as constant destruction if we formally have
15795
  // constant initialization (or are usable in a constant expression).
15796
0
  bool IsConstantDestruction = hasConstantInitialization();
15797
15798
  // Make a copy of the value for the destructor to mutate, if we know it.
15799
  // Otherwise, treat the value as default-initialized; if the destructor works
15800
  // anyway, then the destruction is constant (and must be essentially empty).
15801
0
  APValue DestroyedValue;
15802
0
  if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15803
0
    DestroyedValue = *getEvaluatedValue();
15804
0
  else if (!handleDefaultInitValue(getType(), DestroyedValue))
15805
0
    return false;
15806
15807
0
  if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15808
0
                           getType(), getLocation(), EStatus,
15809
0
                           IsConstantDestruction) ||
15810
0
      EStatus.HasSideEffects)
15811
0
    return false;
15812
15813
0
  ensureEvaluatedStmt()->HasConstantDestruction = true;
15814
0
  return true;
15815
0
}
15816
15817
/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15818
/// constant folded, but discard the result.
15819
8
bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15820
8
  assert(!isValueDependent() &&
15821
8
         "Expression evaluator can't be called on a dependent expression.");
15822
15823
0
  EvalResult Result;
15824
8
  return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15825
8
         !hasUnacceptableSideEffect(Result, SEK);
15826
8
}
15827
15828
APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15829
0
                    SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15830
0
  assert(!isValueDependent() &&
15831
0
         "Expression evaluator can't be called on a dependent expression.");
15832
15833
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15834
0
  EvalResult EVResult;
15835
0
  EVResult.Diag = Diag;
15836
0
  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15837
0
  Info.InConstantContext = true;
15838
15839
0
  bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15840
0
  (void)Result;
15841
0
  assert(Result && "Could not evaluate expression");
15842
0
  assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15843
15844
0
  return EVResult.Val.getInt();
15845
0
}
15846
15847
APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15848
4
    const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15849
4
  assert(!isValueDependent() &&
15850
4
         "Expression evaluator can't be called on a dependent expression.");
15851
15852
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15853
4
  EvalResult EVResult;
15854
4
  EVResult.Diag = Diag;
15855
4
  EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15856
4
  Info.InConstantContext = true;
15857
4
  Info.CheckingForUndefinedBehavior = true;
15858
15859
4
  bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15860
4
  (void)Result;
15861
4
  assert(Result && "Could not evaluate expression");
15862
0
  assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15863
15864
0
  return EVResult.Val.getInt();
15865
4
}
15866
15867
0
void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15868
0
  assert(!isValueDependent() &&
15869
0
         "Expression evaluator can't be called on a dependent expression.");
15870
15871
0
  ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15872
0
  bool IsConst;
15873
0
  EvalResult EVResult;
15874
0
  if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15875
0
    EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15876
0
    Info.CheckingForUndefinedBehavior = true;
15877
0
    (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15878
0
  }
15879
0
}
15880
15881
0
bool Expr::EvalResult::isGlobalLValue() const {
15882
0
  assert(Val.isLValue());
15883
0
  return IsGlobalLValue(Val.getLValueBase());
15884
0
}
15885
15886
/// isIntegerConstantExpr - this recursive routine will test if an expression is
15887
/// an integer constant expression.
15888
15889
/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15890
/// comma, etc
15891
15892
// CheckICE - This function does the fundamental ICE checking: the returned
15893
// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15894
// and a (possibly null) SourceLocation indicating the location of the problem.
15895
//
15896
// Note that to reduce code duplication, this helper does no evaluation
15897
// itself; the caller checks whether the expression is evaluatable, and
15898
// in the rare cases where CheckICE actually cares about the evaluated
15899
// value, it calls into Evaluate.
15900
15901
namespace {
15902
15903
enum ICEKind {
15904
  /// This expression is an ICE.
15905
  IK_ICE,
15906
  /// This expression is not an ICE, but if it isn't evaluated, it's
15907
  /// a legal subexpression for an ICE. This return value is used to handle
15908
  /// the comma operator in C99 mode, and non-constant subexpressions.
15909
  IK_ICEIfUnevaluated,
15910
  /// This expression is not an ICE, and is not a legal subexpression for one.
15911
  IK_NotICE
15912
};
15913
15914
struct ICEDiag {
15915
  ICEKind Kind;
15916
  SourceLocation Loc;
15917
15918
7
  ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15919
};
15920
15921
}
15922
15923
4
static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15924
15925
0
static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15926
15927
0
static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15928
0
  Expr::EvalResult EVResult;
15929
0
  Expr::EvalStatus Status;
15930
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15931
15932
0
  Info.InConstantContext = true;
15933
0
  if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15934
0
      !EVResult.Val.isInt())
15935
0
    return ICEDiag(IK_NotICE, E->getBeginLoc());
15936
15937
0
  return NoDiag();
15938
0
}
15939
15940
10
static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15941
10
  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15942
10
  if (!E->getType()->isIntegralOrEnumerationType())
15943
0
    return ICEDiag(IK_NotICE, E->getBeginLoc());
15944
15945
10
  switch (E->getStmtClass()) {
15946
0
#define ABSTRACT_STMT(Node)
15947
0
#define STMT(Node, Base) case Expr::Node##Class:
15948
0
#define EXPR(Node, Base)
15949
0
#include "clang/AST/StmtNodes.inc"
15950
0
  case Expr::PredefinedExprClass:
15951
0
  case Expr::FloatingLiteralClass:
15952
0
  case Expr::ImaginaryLiteralClass:
15953
0
  case Expr::StringLiteralClass:
15954
0
  case Expr::ArraySubscriptExprClass:
15955
0
  case Expr::MatrixSubscriptExprClass:
15956
0
  case Expr::OMPArraySectionExprClass:
15957
0
  case Expr::OMPArrayShapingExprClass:
15958
0
  case Expr::OMPIteratorExprClass:
15959
0
  case Expr::MemberExprClass:
15960
0
  case Expr::CompoundAssignOperatorClass:
15961
0
  case Expr::CompoundLiteralExprClass:
15962
0
  case Expr::ExtVectorElementExprClass:
15963
0
  case Expr::DesignatedInitExprClass:
15964
0
  case Expr::ArrayInitLoopExprClass:
15965
0
  case Expr::ArrayInitIndexExprClass:
15966
0
  case Expr::NoInitExprClass:
15967
0
  case Expr::DesignatedInitUpdateExprClass:
15968
0
  case Expr::ImplicitValueInitExprClass:
15969
0
  case Expr::ParenListExprClass:
15970
0
  case Expr::VAArgExprClass:
15971
0
  case Expr::AddrLabelExprClass:
15972
0
  case Expr::StmtExprClass:
15973
0
  case Expr::CXXMemberCallExprClass:
15974
0
  case Expr::CUDAKernelCallExprClass:
15975
0
  case Expr::CXXAddrspaceCastExprClass:
15976
0
  case Expr::CXXDynamicCastExprClass:
15977
0
  case Expr::CXXTypeidExprClass:
15978
0
  case Expr::CXXUuidofExprClass:
15979
0
  case Expr::MSPropertyRefExprClass:
15980
0
  case Expr::MSPropertySubscriptExprClass:
15981
0
  case Expr::CXXNullPtrLiteralExprClass:
15982
0
  case Expr::UserDefinedLiteralClass:
15983
0
  case Expr::CXXThisExprClass:
15984
0
  case Expr::CXXThrowExprClass:
15985
0
  case Expr::CXXNewExprClass:
15986
0
  case Expr::CXXDeleteExprClass:
15987
0
  case Expr::CXXPseudoDestructorExprClass:
15988
0
  case Expr::UnresolvedLookupExprClass:
15989
0
  case Expr::TypoExprClass:
15990
0
  case Expr::RecoveryExprClass:
15991
0
  case Expr::DependentScopeDeclRefExprClass:
15992
0
  case Expr::CXXConstructExprClass:
15993
0
  case Expr::CXXInheritedCtorInitExprClass:
15994
0
  case Expr::CXXStdInitializerListExprClass:
15995
0
  case Expr::CXXBindTemporaryExprClass:
15996
0
  case Expr::ExprWithCleanupsClass:
15997
0
  case Expr::CXXTemporaryObjectExprClass:
15998
0
  case Expr::CXXUnresolvedConstructExprClass:
15999
0
  case Expr::CXXDependentScopeMemberExprClass:
16000
0
  case Expr::UnresolvedMemberExprClass:
16001
0
  case Expr::ObjCStringLiteralClass:
16002
0
  case Expr::ObjCBoxedExprClass:
16003
0
  case Expr::ObjCArrayLiteralClass:
16004
0
  case Expr::ObjCDictionaryLiteralClass:
16005
0
  case Expr::ObjCEncodeExprClass:
16006
0
  case Expr::ObjCMessageExprClass:
16007
0
  case Expr::ObjCSelectorExprClass:
16008
0
  case Expr::ObjCProtocolExprClass:
16009
0
  case Expr::ObjCIvarRefExprClass:
16010
0
  case Expr::ObjCPropertyRefExprClass:
16011
0
  case Expr::ObjCSubscriptRefExprClass:
16012
0
  case Expr::ObjCIsaExprClass:
16013
0
  case Expr::ObjCAvailabilityCheckExprClass:
16014
0
  case Expr::ShuffleVectorExprClass:
16015
0
  case Expr::ConvertVectorExprClass:
16016
0
  case Expr::BlockExprClass:
16017
0
  case Expr::NoStmtClass:
16018
0
  case Expr::OpaqueValueExprClass:
16019
0
  case Expr::PackExpansionExprClass:
16020
0
  case Expr::SubstNonTypeTemplateParmPackExprClass:
16021
0
  case Expr::FunctionParmPackExprClass:
16022
0
  case Expr::AsTypeExprClass:
16023
0
  case Expr::ObjCIndirectCopyRestoreExprClass:
16024
0
  case Expr::MaterializeTemporaryExprClass:
16025
0
  case Expr::PseudoObjectExprClass:
16026
0
  case Expr::AtomicExprClass:
16027
0
  case Expr::LambdaExprClass:
16028
0
  case Expr::CXXFoldExprClass:
16029
0
  case Expr::CoawaitExprClass:
16030
0
  case Expr::DependentCoawaitExprClass:
16031
0
  case Expr::CoyieldExprClass:
16032
0
  case Expr::SYCLUniqueStableNameExprClass:
16033
0
  case Expr::CXXParenListInitExprClass:
16034
0
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16035
16036
0
  case Expr::InitListExprClass: {
16037
    // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
16038
    // form "T x = { a };" is equivalent to "T x = a;".
16039
    // Unless we're initializing a reference, T is a scalar as it is known to be
16040
    // of integral or enumeration type.
16041
0
    if (E->isPRValue())
16042
0
      if (cast<InitListExpr>(E)->getNumInits() == 1)
16043
0
        return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16044
0
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16045
0
  }
16046
16047
0
  case Expr::SizeOfPackExprClass:
16048
0
  case Expr::GNUNullExprClass:
16049
0
  case Expr::SourceLocExprClass:
16050
0
    return NoDiag();
16051
16052
0
  case Expr::SubstNonTypeTemplateParmExprClass:
16053
0
    return
16054
0
      CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16055
16056
0
  case Expr::ConstantExprClass:
16057
0
    return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16058
16059
0
  case Expr::ParenExprClass:
16060
0
    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16061
0
  case Expr::GenericSelectionExprClass:
16062
0
    return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16063
4
  case Expr::IntegerLiteralClass:
16064
4
  case Expr::FixedPointLiteralClass:
16065
4
  case Expr::CharacterLiteralClass:
16066
4
  case Expr::ObjCBoolLiteralExprClass:
16067
4
  case Expr::CXXBoolLiteralExprClass:
16068
4
  case Expr::CXXScalarValueInitExprClass:
16069
4
  case Expr::TypeTraitExprClass:
16070
4
  case Expr::ConceptSpecializationExprClass:
16071
4
  case Expr::RequiresExprClass:
16072
4
  case Expr::ArrayTypeTraitExprClass:
16073
4
  case Expr::ExpressionTraitExprClass:
16074
4
  case Expr::CXXNoexceptExprClass:
16075
4
    return NoDiag();
16076
0
  case Expr::CallExprClass:
16077
0
  case Expr::CXXOperatorCallExprClass: {
16078
    // C99 6.6/3 allows function calls within unevaluated subexpressions of
16079
    // constant expressions, but they can never be ICEs because an ICE cannot
16080
    // contain an operand of (pointer to) function type.
16081
0
    const CallExpr *CE = cast<CallExpr>(E);
16082
0
    if (CE->getBuiltinCallee())
16083
0
      return CheckEvalInICE(E, Ctx);
16084
0
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16085
0
  }
16086
0
  case Expr::CXXRewrittenBinaryOperatorClass:
16087
0
    return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16088
0
                    Ctx);
16089
3
  case Expr::DeclRefExprClass: {
16090
3
    const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16091
3
    if (isa<EnumConstantDecl>(D))
16092
0
      return NoDiag();
16093
16094
    // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16095
    // integer variables in constant expressions:
16096
    //
16097
    // C++ 7.1.5.1p2
16098
    //   A variable of non-volatile const-qualified integral or enumeration
16099
    //   type initialized by an ICE can be used in ICEs.
16100
    //
16101
    // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
16102
    // that mode, use of reference variables should not be allowed.
16103
3
    const VarDecl *VD = dyn_cast<VarDecl>(D);
16104
3
    if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16105
3
        !VD->getType()->isReferenceType())
16106
0
      return NoDiag();
16107
16108
3
    return ICEDiag(IK_NotICE, E->getBeginLoc());
16109
3
  }
16110
1
  case Expr::UnaryOperatorClass: {
16111
1
    const UnaryOperator *Exp = cast<UnaryOperator>(E);
16112
1
    switch (Exp->getOpcode()) {
16113
0
    case UO_PostInc:
16114
0
    case UO_PostDec:
16115
0
    case UO_PreInc:
16116
0
    case UO_PreDec:
16117
0
    case UO_AddrOf:
16118
0
    case UO_Deref:
16119
0
    case UO_Coawait:
16120
      // C99 6.6/3 allows increment and decrement within unevaluated
16121
      // subexpressions of constant expressions, but they can never be ICEs
16122
      // because an ICE cannot contain an lvalue operand.
16123
0
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16124
0
    case UO_Extension:
16125
0
    case UO_LNot:
16126
0
    case UO_Plus:
16127
1
    case UO_Minus:
16128
1
    case UO_Not:
16129
1
    case UO_Real:
16130
1
    case UO_Imag:
16131
1
      return CheckICE(Exp->getSubExpr(), Ctx);
16132
1
    }
16133
0
    llvm_unreachable("invalid unary operator class");
16134
0
  }
16135
0
  case Expr::OffsetOfExprClass: {
16136
    // Note that per C99, offsetof must be an ICE. And AFAIK, using
16137
    // EvaluateAsRValue matches the proposed gcc behavior for cases like
16138
    // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
16139
    // compliance: we should warn earlier for offsetof expressions with
16140
    // array subscripts that aren't ICEs, and if the array subscripts
16141
    // are ICEs, the value of the offsetof must be an integer constant.
16142
0
    return CheckEvalInICE(E, Ctx);
16143
0
  }
16144
0
  case Expr::UnaryExprOrTypeTraitExprClass: {
16145
0
    const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
16146
0
    if ((Exp->getKind() ==  UETT_SizeOf) &&
16147
0
        Exp->getTypeOfArgument()->isVariableArrayType())
16148
0
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16149
0
    return NoDiag();
16150
0
  }
16151
0
  case Expr::BinaryOperatorClass: {
16152
0
    const BinaryOperator *Exp = cast<BinaryOperator>(E);
16153
0
    switch (Exp->getOpcode()) {
16154
0
    case BO_PtrMemD:
16155
0
    case BO_PtrMemI:
16156
0
    case BO_Assign:
16157
0
    case BO_MulAssign:
16158
0
    case BO_DivAssign:
16159
0
    case BO_RemAssign:
16160
0
    case BO_AddAssign:
16161
0
    case BO_SubAssign:
16162
0
    case BO_ShlAssign:
16163
0
    case BO_ShrAssign:
16164
0
    case BO_AndAssign:
16165
0
    case BO_XorAssign:
16166
0
    case BO_OrAssign:
16167
      // C99 6.6/3 allows assignments within unevaluated subexpressions of
16168
      // constant expressions, but they can never be ICEs because an ICE cannot
16169
      // contain an lvalue operand.
16170
0
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16171
16172
0
    case BO_Mul:
16173
0
    case BO_Div:
16174
0
    case BO_Rem:
16175
0
    case BO_Add:
16176
0
    case BO_Sub:
16177
0
    case BO_Shl:
16178
0
    case BO_Shr:
16179
0
    case BO_LT:
16180
0
    case BO_GT:
16181
0
    case BO_LE:
16182
0
    case BO_GE:
16183
0
    case BO_EQ:
16184
0
    case BO_NE:
16185
0
    case BO_And:
16186
0
    case BO_Xor:
16187
0
    case BO_Or:
16188
0
    case BO_Comma:
16189
0
    case BO_Cmp: {
16190
0
      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16191
0
      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16192
0
      if (Exp->getOpcode() == BO_Div ||
16193
0
          Exp->getOpcode() == BO_Rem) {
16194
        // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
16195
        // we don't evaluate one.
16196
0
        if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
16197
0
          llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16198
0
          if (REval == 0)
16199
0
            return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16200
0
          if (REval.isSigned() && REval.isAllOnes()) {
16201
0
            llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16202
0
            if (LEval.isMinSignedValue())
16203
0
              return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16204
0
          }
16205
0
        }
16206
0
      }
16207
0
      if (Exp->getOpcode() == BO_Comma) {
16208
0
        if (Ctx.getLangOpts().C99) {
16209
          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
16210
          // if it isn't evaluated.
16211
0
          if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
16212
0
            return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16213
0
        } else {
16214
          // In both C89 and C++, commas in ICEs are illegal.
16215
0
          return ICEDiag(IK_NotICE, E->getBeginLoc());
16216
0
        }
16217
0
      }
16218
0
      return Worst(LHSResult, RHSResult);
16219
0
    }
16220
0
    case BO_LAnd:
16221
0
    case BO_LOr: {
16222
0
      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16223
0
      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16224
0
      if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
16225
        // Rare case where the RHS has a comma "side-effect"; we need
16226
        // to actually check the condition to see whether the side
16227
        // with the comma is evaluated.
16228
0
        if ((Exp->getOpcode() == BO_LAnd) !=
16229
0
            (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16230
0
          return RHSResult;
16231
0
        return NoDiag();
16232
0
      }
16233
16234
0
      return Worst(LHSResult, RHSResult);
16235
0
    }
16236
0
    }
16237
0
    llvm_unreachable("invalid binary operator kind");
16238
0
  }
16239
2
  case Expr::ImplicitCastExprClass:
16240
2
  case Expr::CStyleCastExprClass:
16241
2
  case Expr::CXXFunctionalCastExprClass:
16242
2
  case Expr::CXXStaticCastExprClass:
16243
2
  case Expr::CXXReinterpretCastExprClass:
16244
2
  case Expr::CXXConstCastExprClass:
16245
2
  case Expr::ObjCBridgedCastExprClass: {
16246
2
    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16247
2
    if (isa<ExplicitCastExpr>(E)) {
16248
0
      if (const FloatingLiteral *FL
16249
0
            = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16250
0
        unsigned DestWidth = Ctx.getIntWidth(E->getType());
16251
0
        bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16252
0
        APSInt IgnoredVal(DestWidth, !DestSigned);
16253
0
        bool Ignored;
16254
        // If the value does not fit in the destination type, the behavior is
16255
        // undefined, so we are not required to treat it as a constant
16256
        // expression.
16257
0
        if (FL->getValue().convertToInteger(IgnoredVal,
16258
0
                                            llvm::APFloat::rmTowardZero,
16259
0
                                            &Ignored) & APFloat::opInvalidOp)
16260
0
          return ICEDiag(IK_NotICE, E->getBeginLoc());
16261
0
        return NoDiag();
16262
0
      }
16263
0
    }
16264
2
    switch (cast<CastExpr>(E)->getCastKind()) {
16265
2
    case CK_LValueToRValue:
16266
2
    case CK_AtomicToNonAtomic:
16267
2
    case CK_NonAtomicToAtomic:
16268
2
    case CK_NoOp:
16269
2
    case CK_IntegralToBoolean:
16270
2
    case CK_IntegralCast:
16271
2
      return CheckICE(SubExpr, Ctx);
16272
0
    default:
16273
0
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16274
2
    }
16275
2
  }
16276
0
  case Expr::BinaryConditionalOperatorClass: {
16277
0
    const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
16278
0
    ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16279
0
    if (CommonResult.Kind == IK_NotICE) return CommonResult;
16280
0
    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16281
0
    if (FalseResult.Kind == IK_NotICE) return FalseResult;
16282
0
    if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
16283
0
    if (FalseResult.Kind == IK_ICEIfUnevaluated &&
16284
0
        Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16285
0
    return FalseResult;
16286
0
  }
16287
0
  case Expr::ConditionalOperatorClass: {
16288
0
    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
16289
    // If the condition (ignoring parens) is a __builtin_constant_p call,
16290
    // then only the true side is actually considered in an integer constant
16291
    // expression, and it is fully evaluated.  This is an important GNU
16292
    // extension.  See GCC PR38377 for discussion.
16293
0
    if (const CallExpr *CallCE
16294
0
        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16295
0
      if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16296
0
        return CheckEvalInICE(E, Ctx);
16297
0
    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16298
0
    if (CondResult.Kind == IK_NotICE)
16299
0
      return CondResult;
16300
16301
0
    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16302
0
    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16303
16304
0
    if (TrueResult.Kind == IK_NotICE)
16305
0
      return TrueResult;
16306
0
    if (FalseResult.Kind == IK_NotICE)
16307
0
      return FalseResult;
16308
0
    if (CondResult.Kind == IK_ICEIfUnevaluated)
16309
0
      return CondResult;
16310
0
    if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
16311
0
      return NoDiag();
16312
    // Rare case where the diagnostics depend on which side is evaluated
16313
    // Note that if we get here, CondResult is 0, and at least one of
16314
    // TrueResult and FalseResult is non-zero.
16315
0
    if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16316
0
      return FalseResult;
16317
0
    return TrueResult;
16318
0
  }
16319
0
  case Expr::CXXDefaultArgExprClass:
16320
0
    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16321
0
  case Expr::CXXDefaultInitExprClass:
16322
0
    return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16323
0
  case Expr::ChooseExprClass: {
16324
0
    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16325
0
  }
16326
0
  case Expr::BuiltinBitCastExprClass: {
16327
0
    if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
16328
0
      return ICEDiag(IK_NotICE, E->getBeginLoc());
16329
0
    return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16330
0
  }
16331
10
  }
16332
16333
0
  llvm_unreachable("Invalid StmtClass!");
16334
0
}
16335
16336
/// Evaluate an expression as a C++11 integral constant expression.
16337
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
16338
                                                    const Expr *E,
16339
                                                    llvm::APSInt *Value,
16340
0
                                                    SourceLocation *Loc) {
16341
0
  if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16342
0
    if (Loc) *Loc = E->getExprLoc();
16343
0
    return false;
16344
0
  }
16345
16346
0
  APValue Result;
16347
0
  if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16348
0
    return false;
16349
16350
0
  if (!Result.isInt()) {
16351
0
    if (Loc) *Loc = E->getExprLoc();
16352
0
    return false;
16353
0
  }
16354
16355
0
  if (Value) *Value = Result.getInt();
16356
0
  return true;
16357
0
}
16358
16359
bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16360
7
                                 SourceLocation *Loc) const {
16361
7
  assert(!isValueDependent() &&
16362
7
         "Expression evaluator can't be called on a dependent expression.");
16363
16364
0
  ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16365
16366
7
  if (Ctx.getLangOpts().CPlusPlus11)
16367
0
    return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16368
16369
7
  ICEDiag D = CheckICE(this, Ctx);
16370
7
  if (D.Kind != IK_ICE) {
16371
3
    if (Loc) *Loc = D.Loc;
16372
3
    return false;
16373
3
  }
16374
4
  return true;
16375
7
}
16376
16377
std::optional<llvm::APSInt>
16378
0
Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc) const {
16379
0
  if (isValueDependent()) {
16380
    // Expression evaluator can't succeed on a dependent expression.
16381
0
    return std::nullopt;
16382
0
  }
16383
16384
0
  APSInt Value;
16385
16386
0
  if (Ctx.getLangOpts().CPlusPlus11) {
16387
0
    if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16388
0
      return Value;
16389
0
    return std::nullopt;
16390
0
  }
16391
16392
0
  if (!isIntegerConstantExpr(Ctx, Loc))
16393
0
    return std::nullopt;
16394
16395
  // The only possible side-effects here are due to UB discovered in the
16396
  // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16397
  // required to treat the expression as an ICE, so we produce the folded
16398
  // value.
16399
0
  EvalResult ExprResult;
16400
0
  Expr::EvalStatus Status;
16401
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16402
0
  Info.InConstantContext = true;
16403
16404
0
  if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16405
0
    llvm_unreachable("ICE cannot be evaluated!");
16406
16407
0
  return ExprResult.Val.getInt();
16408
0
}
16409
16410
0
bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16411
0
  assert(!isValueDependent() &&
16412
0
         "Expression evaluator can't be called on a dependent expression.");
16413
16414
0
  return CheckICE(this, Ctx).Kind == IK_ICE;
16415
0
}
16416
16417
bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16418
0
                               SourceLocation *Loc) const {
16419
0
  assert(!isValueDependent() &&
16420
0
         "Expression evaluator can't be called on a dependent expression.");
16421
16422
  // We support this checking in C++98 mode in order to diagnose compatibility
16423
  // issues.
16424
0
  assert(Ctx.getLangOpts().CPlusPlus);
16425
16426
  // Build evaluation settings.
16427
0
  Expr::EvalStatus Status;
16428
0
  SmallVector<PartialDiagnosticAt, 8> Diags;
16429
0
  Status.Diag = &Diags;
16430
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16431
16432
0
  APValue Scratch;
16433
0
  bool IsConstExpr =
16434
0
      ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16435
      // FIXME: We don't produce a diagnostic for this, but the callers that
16436
      // call us on arbitrary full-expressions should generally not care.
16437
0
      Info.discardCleanups() && !Status.HasSideEffects;
16438
16439
0
  if (!Diags.empty()) {
16440
0
    IsConstExpr = false;
16441
0
    if (Loc) *Loc = Diags[0].first;
16442
0
  } else if (!IsConstExpr) {
16443
    // FIXME: This shouldn't happen.
16444
0
    if (Loc) *Loc = getExprLoc();
16445
0
  }
16446
16447
0
  return IsConstExpr;
16448
0
}
16449
16450
bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16451
                                    const FunctionDecl *Callee,
16452
                                    ArrayRef<const Expr*> Args,
16453
0
                                    const Expr *This) const {
16454
0
  assert(!isValueDependent() &&
16455
0
         "Expression evaluator can't be called on a dependent expression.");
16456
16457
0
  llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16458
0
    std::string Name;
16459
0
    llvm::raw_string_ostream OS(Name);
16460
0
    Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16461
0
                                 /*Qualified=*/true);
16462
0
    return Name;
16463
0
  });
16464
16465
0
  Expr::EvalStatus Status;
16466
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16467
0
  Info.InConstantContext = true;
16468
16469
0
  LValue ThisVal;
16470
0
  const LValue *ThisPtr = nullptr;
16471
0
  if (This) {
16472
0
#ifndef NDEBUG
16473
0
    auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16474
0
    assert(MD && "Don't provide `this` for non-methods.");
16475
0
    assert(MD->isImplicitObjectMemberFunction() &&
16476
0
           "Don't provide `this` for methods without an implicit object.");
16477
0
#endif
16478
0
    if (!This->isValueDependent() &&
16479
0
        EvaluateObjectArgument(Info, This, ThisVal) &&
16480
0
        !Info.EvalStatus.HasSideEffects)
16481
0
      ThisPtr = &ThisVal;
16482
16483
    // Ignore any side-effects from a failed evaluation. This is safe because
16484
    // they can't interfere with any other argument evaluation.
16485
0
    Info.EvalStatus.HasSideEffects = false;
16486
0
  }
16487
16488
0
  CallRef Call = Info.CurrentCall->createCall(Callee);
16489
0
  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16490
0
       I != E; ++I) {
16491
0
    unsigned Idx = I - Args.begin();
16492
0
    if (Idx >= Callee->getNumParams())
16493
0
      break;
16494
0
    const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16495
0
    if ((*I)->isValueDependent() ||
16496
0
        !EvaluateCallArg(PVD, *I, Call, Info) ||
16497
0
        Info.EvalStatus.HasSideEffects) {
16498
      // If evaluation fails, throw away the argument entirely.
16499
0
      if (APValue *Slot = Info.getParamSlot(Call, PVD))
16500
0
        *Slot = APValue();
16501
0
    }
16502
16503
    // Ignore any side-effects from a failed evaluation. This is safe because
16504
    // they can't interfere with any other argument evaluation.
16505
0
    Info.EvalStatus.HasSideEffects = false;
16506
0
  }
16507
16508
  // Parameter cleanups happen in the caller and are not part of this
16509
  // evaluation.
16510
0
  Info.discardCleanups();
16511
0
  Info.EvalStatus.HasSideEffects = false;
16512
16513
  // Build fake call to Callee.
16514
0
  CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16515
0
                       Call);
16516
  // FIXME: Missing ExprWithCleanups in enable_if conditions?
16517
0
  FullExpressionRAII Scope(Info);
16518
0
  return Evaluate(Value, Info, this) && Scope.destroy() &&
16519
0
         !Info.EvalStatus.HasSideEffects;
16520
0
}
16521
16522
bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16523
                                   SmallVectorImpl<
16524
0
                                     PartialDiagnosticAt> &Diags) {
16525
  // FIXME: It would be useful to check constexpr function templates, but at the
16526
  // moment the constant expression evaluator cannot cope with the non-rigorous
16527
  // ASTs which we build for dependent expressions.
16528
0
  if (FD->isDependentContext())
16529
0
    return true;
16530
16531
0
  llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16532
0
    std::string Name;
16533
0
    llvm::raw_string_ostream OS(Name);
16534
0
    FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16535
0
                             /*Qualified=*/true);
16536
0
    return Name;
16537
0
  });
16538
16539
0
  Expr::EvalStatus Status;
16540
0
  Status.Diag = &Diags;
16541
16542
0
  EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16543
0
  Info.InConstantContext = true;
16544
0
  Info.CheckingPotentialConstantExpression = true;
16545
16546
  // The constexpr VM attempts to compile all methods to bytecode here.
16547
0
  if (Info.EnableNewConstInterp) {
16548
0
    Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16549
0
    return Diags.empty();
16550
0
  }
16551
16552
0
  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16553
0
  const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16554
16555
  // Fabricate an arbitrary expression on the stack and pretend that it
16556
  // is a temporary being used as the 'this' pointer.
16557
0
  LValue This;
16558
0
  ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16559
0
  This.set({&VIE, Info.CurrentCall->Index});
16560
16561
0
  ArrayRef<const Expr*> Args;
16562
16563
0
  APValue Scratch;
16564
0
  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16565
    // Evaluate the call as a constant initializer, to allow the construction
16566
    // of objects of non-literal types.
16567
0
    Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16568
0
    HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16569
0
  } else {
16570
0
    SourceLocation Loc = FD->getLocation();
16571
0
    HandleFunctionCall(
16572
0
        Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
16573
0
        &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
16574
0
        /*ResultSlot=*/nullptr);
16575
0
  }
16576
16577
0
  return Diags.empty();
16578
0
}
16579
16580
bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16581
                                              const FunctionDecl *FD,
16582
                                              SmallVectorImpl<
16583
0
                                                PartialDiagnosticAt> &Diags) {
16584
0
  assert(!E->isValueDependent() &&
16585
0
         "Expression evaluator can't be called on a dependent expression.");
16586
16587
0
  Expr::EvalStatus Status;
16588
0
  Status.Diag = &Diags;
16589
16590
0
  EvalInfo Info(FD->getASTContext(), Status,
16591
0
                EvalInfo::EM_ConstantExpressionUnevaluated);
16592
0
  Info.InConstantContext = true;
16593
0
  Info.CheckingPotentialConstantExpression = true;
16594
16595
  // Fabricate a call stack frame to give the arguments a plausible cover story.
16596
0
  CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
16597
0
                       /*CallExpr=*/nullptr, CallRef());
16598
16599
0
  APValue ResultScratch;
16600
0
  Evaluate(ResultScratch, Info, E);
16601
0
  return Diags.empty();
16602
0
}
16603
16604
bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16605
0
                                 unsigned Type) const {
16606
0
  if (!getType()->isPointerType())
16607
0
    return false;
16608
16609
0
  Expr::EvalStatus Status;
16610
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16611
0
  return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16612
0
}
16613
16614
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16615
0
                                  EvalInfo &Info) {
16616
0
  if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16617
0
    return false;
16618
16619
0
  LValue String;
16620
16621
0
  if (!EvaluatePointer(E, String, Info))
16622
0
    return false;
16623
16624
0
  QualType CharTy = E->getType()->getPointeeType();
16625
16626
  // Fast path: if it's a string literal, search the string value.
16627
0
  if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16628
0
          String.getLValueBase().dyn_cast<const Expr *>())) {
16629
0
    StringRef Str = S->getBytes();
16630
0
    int64_t Off = String.Offset.getQuantity();
16631
0
    if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16632
0
        S->getCharByteWidth() == 1 &&
16633
        // FIXME: Add fast-path for wchar_t too.
16634
0
        Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16635
0
      Str = Str.substr(Off);
16636
16637
0
      StringRef::size_type Pos = Str.find(0);
16638
0
      if (Pos != StringRef::npos)
16639
0
        Str = Str.substr(0, Pos);
16640
16641
0
      Result = Str.size();
16642
0
      return true;
16643
0
    }
16644
16645
    // Fall through to slow path.
16646
0
  }
16647
16648
  // Slow path: scan the bytes of the string looking for the terminating 0.
16649
0
  for (uint64_t Strlen = 0; /**/; ++Strlen) {
16650
0
    APValue Char;
16651
0
    if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16652
0
        !Char.isInt())
16653
0
      return false;
16654
0
    if (!Char.getInt()) {
16655
0
      Result = Strlen;
16656
0
      return true;
16657
0
    }
16658
0
    if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16659
0
      return false;
16660
0
  }
16661
0
}
16662
16663
bool Expr::EvaluateCharRangeAsString(std::string &Result,
16664
                                     const Expr *SizeExpression,
16665
                                     const Expr *PtrExpression, ASTContext &Ctx,
16666
0
                                     EvalResult &Status) const {
16667
0
  LValue String;
16668
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16669
0
  Info.InConstantContext = true;
16670
16671
0
  FullExpressionRAII Scope(Info);
16672
0
  APSInt SizeValue;
16673
0
  if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
16674
0
    return false;
16675
16676
0
  int64_t Size = SizeValue.getExtValue();
16677
16678
0
  if (!::EvaluatePointer(PtrExpression, String, Info))
16679
0
    return false;
16680
16681
0
  QualType CharTy = PtrExpression->getType()->getPointeeType();
16682
0
  for (int64_t I = 0; I < Size; ++I) {
16683
0
    APValue Char;
16684
0
    if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
16685
0
                                        Char))
16686
0
      return false;
16687
16688
0
    APSInt C = Char.getInt();
16689
0
    Result.push_back(static_cast<char>(C.getExtValue()));
16690
0
    if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
16691
0
      return false;
16692
0
  }
16693
0
  if (!Scope.destroy())
16694
0
    return false;
16695
16696
0
  if (!CheckMemoryLeaks(Info))
16697
0
    return false;
16698
16699
0
  return true;
16700
0
}
16701
16702
0
bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16703
0
  Expr::EvalStatus Status;
16704
0
  EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16705
0
  return EvaluateBuiltinStrLen(this, Result, Info);
16706
0
}