Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/ExprConstant.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the Expr constant evaluator.
10
//
11
// Constant expression evaluation produces four main results:
12
//
13
//  * A success/failure flag indicating whether constant folding was successful.
14
//    This is the 'bool' return value used by most of the code in this file. A
15
//    'false' return value indicates that constant folding has failed, and any
16
//    appropriate diagnostic has already been produced.
17
//
18
//  * An evaluated result, valid only if constant folding has not failed.
19
//
20
//  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21
//    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22
//    where it is possible to determine the evaluated result regardless.
23
//
24
//  * A set of notes indicating why the evaluation was not a constant expression
25
//    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26
//    too, why the expression could not be folded.
27
//
28
// If we are checking for a potential constant expression, failure to constant
29
// fold a potential constant sub-expression will be indicated by a 'false'
30
// return value (the expression could not be folded) and no diagnostic (the
31
// expression is not necessarily non-constant).
32
//
33
//===----------------------------------------------------------------------===//
34
35
#include "Interp/Context.h"
36
#include "Interp/Frame.h"
37
#include "Interp/State.h"
38
#include "clang/AST/APValue.h"
39
#include "clang/AST/ASTContext.h"
40
#include "clang/AST/ASTDiagnostic.h"
41
#include "clang/AST/ASTLambda.h"
42
#include "clang/AST/Attr.h"
43
#include "clang/AST/CXXInheritance.h"
44
#include "clang/AST/CharUnits.h"
45
#include "clang/AST/CurrentSourceLocExprScope.h"
46
#include "clang/AST/Expr.h"
47
#include "clang/AST/OSLog.h"
48
#include "clang/AST/OptionalDiagnostic.h"
49
#include "clang/AST/RecordLayout.h"
50
#include "clang/AST/StmtVisitor.h"
51
#include "clang/AST/TypeLoc.h"
52
#include "clang/Basic/Builtins.h"
53
#include "clang/Basic/TargetInfo.h"
54
#include "llvm/ADT/APFixedPoint.h"
55
#include "llvm/ADT/Optional.h"
56
#include "llvm/ADT/SmallBitVector.h"
57
#include "llvm/Support/Debug.h"
58
#include "llvm/Support/SaveAndRestore.h"
59
#include "llvm/Support/raw_ostream.h"
60
#include <cstring>
61
#include <functional>
62
63
#define DEBUG_TYPE "exprconstant"
64
65
using namespace clang;
66
using llvm::APFixedPoint;
67
using llvm::APInt;
68
using llvm::APSInt;
69
using llvm::APFloat;
70
using llvm::FixedPointSemantics;
71
using llvm::Optional;
72
73
namespace {
74
  struct LValue;
75
  class CallStackFrame;
76
  class EvalInfo;
77
78
  using SourceLocExprScopeGuard =
79
      CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80
81
18.6M
  static QualType getType(APValue::LValueBase B) {
82
18.6M
    return B.getType();
83
18.6M
  }
84
85
  /// Get an LValue path entry, which is known to not be an array index, as a
86
  /// field declaration.
87
43.4k
  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88
43.4k
    return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89
43.4k
  }
90
  /// Get an LValue path entry, which is known to not be an array index, as a
91
  /// base class declaration.
92
2.93k
  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93
2.93k
    return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94
2.93k
  }
95
  /// Determine whether this LValue path entry for a base class names a virtual
96
  /// base class.
97
807
  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98
807
    return E.getAsBaseOrMember().getInt();
99
807
  }
100
101
  /// Given an expression, determine the type used to store the result of
102
  /// evaluating that expression.
103
1.88M
  static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104
1.88M
    if (E->isPRValue())
105
1.84M
      return E->getType();
106
34.1k
    return Ctx.getLValueReferenceType(E->getType());
107
1.88M
  }
108
109
  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110
6.13k
  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111
6.13k
    if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112
4.55k
      return DirectCallee->getAttr<AllocSizeAttr>();
113
1.58k
    if (const Decl *IndirectCallee = CE->getCalleeDecl())
114
1.58k
      return IndirectCallee->getAttr<AllocSizeAttr>();
115
0
    return nullptr;
116
1.58k
  }
117
118
  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119
  /// This will look through a single cast.
120
  ///
121
  /// Returns null if we couldn't unwrap a function with alloc_size.
122
5.15k
  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123
5.15k
    if (!E->getType()->isPointerType())
124
0
      return nullptr;
125
126
5.15k
    E = E->IgnoreParens();
127
    // If we're doing a variable assignment from e.g. malloc(N), there will
128
    // probably be a cast of some kind. In exotic cases, we might also see a
129
    // top-level ExprWithCleanups. Ignore them either way.
130
5.15k
    if (const auto *FE = dyn_cast<FullExpr>(E))
131
15
      E = FE->getSubExpr()->IgnoreParens();
132
133
5.15k
    if (const auto *Cast = dyn_cast<CastExpr>(E))
134
1.79k
      E = Cast->getSubExpr()->IgnoreParens();
135
136
5.15k
    if (const auto *CE = dyn_cast<CallExpr>(E))
137
4.95k
      return getAllocSizeAttr(CE) ? 
CE4.35k
:
nullptr598
;
138
203
    return nullptr;
139
5.15k
  }
140
141
  /// Determines whether or not the given Base contains a call to a function
142
  /// with the alloc_size attribute.
143
701k
  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144
701k
    const auto *E = Base.dyn_cast<const Expr *>();
145
701k
    return E && 
E->getType()->isPointerType()44.9k
&&
tryUnwrapAllocSizeCall(E)2.62k
;
146
701k
  }
147
148
  /// Determines whether the given kind of constant expression is only ever
149
  /// used for name mangling. If so, it's permitted to reference things that we
150
  /// can't generate code for (in particular, dllimported functions).
151
28.8k
  static bool isForManglingOnly(ConstantExprKind Kind) {
152
28.8k
    switch (Kind) {
153
28.2k
    case ConstantExprKind::Normal:
154
28.2k
    case ConstantExprKind::ClassTemplateArgument:
155
28.2k
    case ConstantExprKind::ImmediateInvocation:
156
      // Note that non-type template arguments of class type are emitted as
157
      // template parameter objects.
158
28.2k
      return false;
159
160
548
    case ConstantExprKind::NonClassTemplateArgument:
161
548
      return true;
162
28.8k
    }
163
0
    llvm_unreachable("unknown ConstantExprKind");
164
0
  }
165
166
95.1k
  static bool isTemplateArgument(ConstantExprKind Kind) {
167
95.1k
    switch (Kind) {
168
94.3k
    case ConstantExprKind::Normal:
169
94.4k
    case ConstantExprKind::ImmediateInvocation:
170
94.4k
      return false;
171
172
46
    case ConstantExprKind::ClassTemplateArgument:
173
728
    case ConstantExprKind::NonClassTemplateArgument:
174
728
      return true;
175
95.1k
    }
176
0
    llvm_unreachable("unknown ConstantExprKind");
177
0
  }
178
179
  /// The bound to claim that an array of unknown bound has.
180
  /// The value in MostDerivedArraySize is undefined in this case. So, set it
181
  /// to an arbitrary value that's likely to loudly break things if it's used.
182
  static const uint64_t AssumedSizeForUnsizedArray =
183
      std::numeric_limits<uint64_t>::max() / 2;
184
185
  /// Determines if an LValue with the given LValueBase will have an unsized
186
  /// array in its designator.
187
  /// Find the path length and type of the most-derived subobject in the given
188
  /// path, and find the size of the containing array, if any.
189
  static unsigned
190
  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191
                           ArrayRef<APValue::LValuePathEntry> Path,
192
                           uint64_t &ArraySize, QualType &Type, bool &IsArray,
193
697k
                           bool &FirstEntryIsUnsizedArray) {
194
    // This only accepts LValueBases from APValues, and APValues don't support
195
    // arrays that lack size info.
196
697k
    assert(!isBaseAnAllocSizeCall(Base) &&
197
697k
           "Unsized arrays shouldn't appear here");
198
0
    unsigned MostDerivedLength = 0;
199
697k
    Type = getType(Base);
200
201
759k
    for (unsigned I = 0, N = Path.size(); I != N; 
++I62.0k
) {
202
62.0k
      if (Type->isArrayType()) {
203
42.4k
        const ArrayType *AT = Ctx.getAsArrayType(Type);
204
42.4k
        Type = AT->getElementType();
205
42.4k
        MostDerivedLength = I + 1;
206
42.4k
        IsArray = true;
207
208
42.4k
        if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209
42.3k
          ArraySize = CAT->getSize().getZExtValue();
210
42.3k
        } else {
211
136
          assert(I == 0 && "unexpected unsized array designator");
212
0
          FirstEntryIsUnsizedArray = true;
213
136
          ArraySize = AssumedSizeForUnsizedArray;
214
136
        }
215
42.4k
      } else 
if (19.5k
Type->isAnyComplexType()19.5k
) {
216
73
        const ComplexType *CT = Type->castAs<ComplexType>();
217
73
        Type = CT->getElementType();
218
73
        ArraySize = 2;
219
73
        MostDerivedLength = I + 1;
220
73
        IsArray = true;
221
19.4k
      } else if (const FieldDecl *FD = getAsField(Path[I])) {
222
16.0k
        Type = FD->getType();
223
16.0k
        ArraySize = 0;
224
16.0k
        MostDerivedLength = I + 1;
225
16.0k
        IsArray = false;
226
16.0k
      } else {
227
        // Path[I] describes a base class.
228
3.48k
        ArraySize = 0;
229
3.48k
        IsArray = false;
230
3.48k
      }
231
62.0k
    }
232
697k
    return MostDerivedLength;
233
697k
  }
234
235
  /// A path from a glvalue to a subobject of that glvalue.
236
  struct SubobjectDesignator {
237
    /// True if the subobject was named in a manner not supported by C++11. Such
238
    /// lvalues can still be folded, but they are not core constant expressions
239
    /// and we cannot perform lvalue-to-rvalue conversions on them.
240
    unsigned Invalid : 1;
241
242
    /// Is this a pointer one past the end of an object?
243
    unsigned IsOnePastTheEnd : 1;
244
245
    /// Indicator of whether the first entry is an unsized array.
246
    unsigned FirstEntryIsAnUnsizedArray : 1;
247
248
    /// Indicator of whether the most-derived object is an array element.
249
    unsigned MostDerivedIsArrayElement : 1;
250
251
    /// The length of the path to the most-derived object of which this is a
252
    /// subobject.
253
    unsigned MostDerivedPathLength : 28;
254
255
    /// The size of the array of which the most-derived object is an element.
256
    /// This will always be 0 if the most-derived object is not an array
257
    /// element. 0 is not an indicator of whether or not the most-derived object
258
    /// is an array, however, because 0-length arrays are allowed.
259
    ///
260
    /// If the current array is an unsized array, the value of this is
261
    /// undefined.
262
    uint64_t MostDerivedArraySize;
263
264
    /// The type of the most derived object referred to by this address.
265
    QualType MostDerivedType;
266
267
    typedef APValue::LValuePathEntry PathEntry;
268
269
    /// The entries on the path from the glvalue to the designated subobject.
270
    SmallVector<PathEntry, 8> Entries;
271
272
14.0M
    SubobjectDesignator() : Invalid(true) {}
273
274
    explicit SubobjectDesignator(QualType T)
275
        : Invalid(false), IsOnePastTheEnd(false),
276
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277
          MostDerivedPathLength(0), MostDerivedArraySize(0),
278
11.3M
          MostDerivedType(T) {}
279
280
    SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281
        : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282
          FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283
718k
          MostDerivedPathLength(0), MostDerivedArraySize(0) {
284
718k
      assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285
718k
      if (!Invalid) {
286
712k
        IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287
712k
        ArrayRef<PathEntry> VEntries = V.getLValuePath();
288
712k
        Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289
712k
        if (V.getLValueBase()) {
290
697k
          bool IsArray = false;
291
697k
          bool FirstIsUnsizedArray = false;
292
697k
          MostDerivedPathLength = findMostDerivedSubobject(
293
697k
              Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294
697k
              MostDerivedType, IsArray, FirstIsUnsizedArray);
295
697k
          MostDerivedIsArrayElement = IsArray;
296
697k
          FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297
697k
        }
298
712k
      }
299
718k
    }
300
301
    void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302
149
                  unsigned NewLength) {
303
149
      if (Invalid)
304
0
        return;
305
306
149
      assert(Base && "cannot truncate path for null pointer");
307
0
      assert(NewLength <= Entries.size() && "not a truncation");
308
309
149
      if (NewLength == Entries.size())
310
0
        return;
311
149
      Entries.resize(NewLength);
312
313
149
      bool IsArray = false;
314
149
      bool FirstIsUnsizedArray = false;
315
149
      MostDerivedPathLength = findMostDerivedSubobject(
316
149
          Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317
149
          FirstIsUnsizedArray);
318
149
      MostDerivedIsArrayElement = IsArray;
319
149
      FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320
149
    }
321
322
9.87k
    void setInvalid() {
323
9.87k
      Invalid = true;
324
9.87k
      Entries.clear();
325
9.87k
    }
326
327
    /// Determine whether the most derived subobject is an array without a
328
    /// known bound.
329
3.73M
    bool isMostDerivedAnUnsizedArray() const {
330
3.73M
      assert(!Invalid && "Calling this makes no sense on invalid designators");
331
3.73M
      return Entries.size() == 1 && 
FirstEntryIsAnUnsizedArray308k
;
332
3.73M
    }
333
334
    /// Determine what the most derived array's size is. Results in an assertion
335
    /// failure if the most derived array lacks a size.
336
101k
    uint64_t getMostDerivedArraySize() const {
337
101k
      assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338
0
      return MostDerivedArraySize;
339
101k
    }
340
341
    /// Determine whether this is a one-past-the-end pointer.
342
1.91M
    bool isOnePastTheEnd() const {
343
1.91M
      assert(!Invalid);
344
1.91M
      if (IsOnePastTheEnd)
345
105
        return true;
346
1.91M
      if (!isMostDerivedAnUnsizedArray() && 
MostDerivedIsArrayElement1.91M
&&
347
1.91M
          Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348
51.4k
              MostDerivedArraySize)
349
751
        return true;
350
1.91M
      return false;
351
1.91M
    }
352
353
    /// Get the range of valid index adjustments in the form
354
    ///   {maximum value that can be subtracted from this pointer,
355
    ///    maximum value that can be added to this pointer}
356
1.47k
    std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357
1.47k
      if (Invalid || isMostDerivedAnUnsizedArray())
358
64
        return {0, 0};
359
360
      // [expr.add]p4: For the purposes of these operators, a pointer to a
361
      // nonarray object behaves the same as a pointer to the first element of
362
      // an array of length one with the type of the object as its element type.
363
1.41k
      bool IsArray = MostDerivedPathLength == Entries.size() &&
364
1.41k
                     
MostDerivedIsArrayElement1.33k
;
365
1.41k
      uint64_t ArrayIndex = IsArray ? 
Entries.back().getAsArrayIndex()1.27k
366
1.41k
                                    : 
(uint64_t)IsOnePastTheEnd136
;
367
1.41k
      uint64_t ArraySize =
368
1.41k
          IsArray ? 
getMostDerivedArraySize()1.27k
:
(uint64_t)1136
;
369
1.41k
      return {ArrayIndex, ArraySize - ArrayIndex};
370
1.47k
    }
371
372
    /// Check that this refers to a valid subobject.
373
0
    bool isValidSubobject() const {
374
0
      if (Invalid)
375
0
        return false;
376
0
      return !isOnePastTheEnd();
377
0
    }
378
    /// Check that this refers to a valid subobject, and if not, produce a
379
    /// relevant diagnostic and set the designator as invalid.
380
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381
382
    /// Get the type of the designated object.
383
11.5k
    QualType getType(ASTContext &Ctx) const {
384
11.5k
      assert(!Invalid && "invalid designator has no subobject type");
385
11.5k
      return MostDerivedPathLength == Entries.size()
386
11.5k
                 ? 
MostDerivedType11.4k
387
11.5k
                 : 
Ctx.getRecordType(getAsBaseClass(Entries.back()))120
;
388
11.5k
    }
389
390
    /// Update this designator to refer to the first element within this array.
391
80.1k
    void addArrayUnchecked(const ConstantArrayType *CAT) {
392
80.1k
      Entries.push_back(PathEntry::ArrayIndex(0));
393
394
      // This is a most-derived object.
395
80.1k
      MostDerivedType = CAT->getElementType();
396
80.1k
      MostDerivedIsArrayElement = true;
397
80.1k
      MostDerivedArraySize = CAT->getSize().getZExtValue();
398
80.1k
      MostDerivedPathLength = Entries.size();
399
80.1k
    }
400
    /// Update this designator to refer to the first element within the array of
401
    /// elements of type T. This is an array of unknown size.
402
4.65k
    void addUnsizedArrayUnchecked(QualType ElemTy) {
403
4.65k
      Entries.push_back(PathEntry::ArrayIndex(0));
404
405
4.65k
      MostDerivedType = ElemTy;
406
4.65k
      MostDerivedIsArrayElement = true;
407
      // The value in MostDerivedArraySize is undefined in this case. So, set it
408
      // to an arbitrary value that's likely to loudly break things if it's
409
      // used.
410
4.65k
      MostDerivedArraySize = AssumedSizeForUnsizedArray;
411
4.65k
      MostDerivedPathLength = Entries.size();
412
4.65k
    }
413
    /// Update this designator to refer to the given base or member of this
414
    /// object.
415
174k
    void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416
174k
      Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417
418
      // If this isn't a base class, it's a new most-derived object.
419
174k
      if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420
162k
        MostDerivedType = FD->getType();
421
162k
        MostDerivedIsArrayElement = false;
422
162k
        MostDerivedArraySize = 0;
423
162k
        MostDerivedPathLength = Entries.size();
424
162k
      }
425
174k
    }
426
    /// Update this designator to refer to the given complex component.
427
221
    void addComplexUnchecked(QualType EltTy, bool Imag) {
428
221
      Entries.push_back(PathEntry::ArrayIndex(Imag));
429
430
      // This is technically a most-derived object, though in practice this
431
      // is unlikely to matter.
432
221
      MostDerivedType = EltTy;
433
221
      MostDerivedIsArrayElement = true;
434
221
      MostDerivedArraySize = 2;
435
221
      MostDerivedPathLength = Entries.size();
436
221
    }
437
    void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438
    void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439
                                   const APSInt &N);
440
    /// Add N to the address of this subobject.
441
100k
    void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442
100k
      if (Invalid || !N) 
return0
;
443
100k
      uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444
100k
      if (isMostDerivedAnUnsizedArray()) {
445
580
        diagnoseUnsizedArrayPointerArithmetic(Info, E);
446
        // Can't verify -- trust that the user is doing the right thing (or if
447
        // not, trust that the caller will catch the bad behavior).
448
        // FIXME: Should we reject if this overflows, at least?
449
580
        Entries.back() = PathEntry::ArrayIndex(
450
580
            Entries.back().getAsArrayIndex() + TruncatedN);
451
580
        return;
452
580
      }
453
454
      // [expr.add]p4: For the purposes of these operators, a pointer to a
455
      // nonarray object behaves the same as a pointer to the first element of
456
      // an array of length one with the type of the object as its element type.
457
99.5k
      bool IsArray = MostDerivedPathLength == Entries.size() &&
458
99.5k
                     
MostDerivedIsArrayElement99.5k
;
459
99.5k
      uint64_t ArrayIndex = IsArray ? 
Entries.back().getAsArrayIndex()99.2k
460
99.5k
                                    : 
(uint64_t)IsOnePastTheEnd354
;
461
99.5k
      uint64_t ArraySize =
462
99.5k
          IsArray ? 
getMostDerivedArraySize()99.2k
:
(uint64_t)1354
;
463
464
99.5k
      if (N < -(int64_t)ArrayIndex || 
N > ArraySize - ArrayIndex99.4k
) {
465
        // Calculate the actual index in a wide enough type, so we can include
466
        // it in the note.
467
426
        N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468
426
        (llvm::APInt&)N += ArrayIndex;
469
426
        assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470
0
        diagnosePointerArithmetic(Info, E, N);
471
426
        setInvalid();
472
426
        return;
473
426
      }
474
475
99.1k
      ArrayIndex += TruncatedN;
476
99.1k
      assert(ArrayIndex <= ArraySize &&
477
99.1k
             "bounds check succeeded for out-of-bounds index");
478
479
99.1k
      if (IsArray)
480
98.9k
        Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481
217
      else
482
217
        IsOnePastTheEnd = (ArrayIndex != 0);
483
99.1k
    }
484
  };
485
486
  /// A scope at the end of which an object can need to be destroyed.
487
  enum class ScopeKind {
488
    Block,
489
    FullExpression,
490
    Call
491
  };
492
493
  /// A reference to a particular call and its arguments.
494
  struct CallRef {
495
19.8M
    CallRef() : OrigCallee(), CallIndex(0), Version() {}
496
    CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497
378k
        : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498
499
597k
    explicit operator bool() const { return OrigCallee; }
500
501
    /// Get the parameter that the caller initialized, corresponding to the
502
    /// given parameter in the callee.
503
197k
    const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504
197k
      return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505
197k
                        : 
PVD0
;
506
197k
    }
507
508
    /// The callee at the point where the arguments were evaluated. This might
509
    /// be different from the actual callee (a different redeclaration, or a
510
    /// virtual override), but this function's parameters are the ones that
511
    /// appear in the parameter map.
512
    const FunctionDecl *OrigCallee;
513
    /// The call index of the frame that holds the argument values.
514
    unsigned CallIndex;
515
    /// The version of the parameters corresponding to this call.
516
    unsigned Version;
517
  };
518
519
  /// A stack frame in the constexpr call stack.
520
  class CallStackFrame : public interp::Frame {
521
  public:
522
    EvalInfo &Info;
523
524
    /// Parent - The caller of this stack frame.
525
    CallStackFrame *Caller;
526
527
    /// Callee - The function which was called.
528
    const FunctionDecl *Callee;
529
530
    /// This - The binding for the this pointer in this call, if any.
531
    const LValue *This;
532
533
    /// Information on how to find the arguments to this call. Our arguments
534
    /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535
    /// key and this value as the version.
536
    CallRef Arguments;
537
538
    /// Source location information about the default argument or default
539
    /// initializer expression we're evaluating, if any.
540
    CurrentSourceLocExprScope CurSourceLocExprScope;
541
542
    // Note that we intentionally use std::map here so that references to
543
    // values are stable.
544
    typedef std::pair<const void *, unsigned> MapKeyTy;
545
    typedef std::map<MapKeyTy, APValue> MapTy;
546
    /// Temporaries - Temporary lvalues materialized within this stack frame.
547
    MapTy Temporaries;
548
549
    /// CallLoc - The location of the call expression for this call.
550
    SourceLocation CallLoc;
551
552
    /// Index - The call index of this call.
553
    unsigned Index;
554
555
    /// The stack of integers for tracking version numbers for temporaries.
556
    SmallVector<unsigned, 2> TempVersionStack = {1};
557
    unsigned CurTempVersion = TempVersionStack.back();
558
559
47.8k
    unsigned getTempVersion() const { return TempVersionStack.back(); }
560
561
16.9M
    void pushTempVersion() {
562
16.9M
      TempVersionStack.push_back(++CurTempVersion);
563
16.9M
    }
564
565
16.9M
    void popTempVersion() {
566
16.9M
      TempVersionStack.pop_back();
567
16.9M
    }
568
569
378k
    CallRef createCall(const FunctionDecl *Callee) {
570
378k
      return {Callee, Index, ++CurTempVersion};
571
378k
    }
572
573
    // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574
    // on the overall stack usage of deeply-recursing constexpr evaluations.
575
    // (We should cache this map rather than recomputing it repeatedly.)
576
    // But let's try this and see how it goes; we can look into caching the map
577
    // as a later change.
578
579
    /// LambdaCaptureFields - Mapping from captured variables/this to
580
    /// corresponding data members in the closure class.
581
    llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582
    FieldDecl *LambdaThisCaptureField;
583
584
    CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585
                   const FunctionDecl *Callee, const LValue *This,
586
                   CallRef Arguments);
587
    ~CallStackFrame();
588
589
    // Return the temporary for Key whose version number is Version.
590
323k
    APValue *getTemporary(const void *Key, unsigned Version) {
591
323k
      MapKeyTy KV(Key, Version);
592
323k
      auto LB = Temporaries.lower_bound(KV);
593
323k
      if (LB != Temporaries.end() && 
LB->first == KV320k
)
594
320k
        return &LB->second;
595
      // Pair (Key,Version) wasn't found in the map. Check that no elements
596
      // in the map have 'Key' as their key.
597
3.68k
      assert((LB == Temporaries.end() || LB->first.first != Key) &&
598
3.68k
             (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599
3.68k
             "Element with key 'Key' found in map");
600
0
      return nullptr;
601
323k
    }
602
603
    // Return the current temporary for Key in the map.
604
3.79k
    APValue *getCurrentTemporary(const void *Key) {
605
3.79k
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606
3.79k
      if (UB != Temporaries.begin() && 
std::prev(UB)->first.first == Key2.71k
)
607
2.69k
        return &std::prev(UB)->second;
608
1.10k
      return nullptr;
609
3.79k
    }
610
611
    // Return the version number of the current temporary for Key.
612
89.2k
    unsigned getCurrentTemporaryVersion(const void *Key) const {
613
89.2k
      auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614
89.2k
      if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615
89.2k
        return std::prev(UB)->first.second;
616
0
      return 0;
617
89.2k
    }
618
619
    /// Allocate storage for an object of type T in this stack frame.
620
    /// Populates LV with a handle to the created object. Key identifies
621
    /// the temporary within the stack frame, and must not be reused without
622
    /// bumping the temporary version number.
623
    template<typename KeyT>
624
    APValue &createTemporary(const KeyT *Key, QualType T,
625
                             ScopeKind Scope, LValue &LV);
626
627
    /// Allocate storage for a parameter of a function call made in this frame.
628
    APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629
630
    void describe(llvm::raw_ostream &OS) override;
631
632
2.86k
    Frame *getCaller() const override { return Caller; }
633
2.86k
    SourceLocation getCallLocation() const override { return CallLoc; }
634
6.60k
    const FunctionDecl *getCallee() const override { return Callee; }
635
636
117
    bool isStdFunction() const {
637
176
      for (const DeclContext *DC = Callee; DC; 
DC = DC->getParent()59
)
638
112
        if (DC->isStdNamespace())
639
53
          return true;
640
64
      return false;
641
117
    }
642
643
  private:
644
    APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645
                         ScopeKind Scope);
646
  };
647
648
  /// Temporarily override 'this'.
649
  class ThisOverrideRAII {
650
  public:
651
    ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652
33.6k
        : Frame(Frame), OldThis(Frame.This) {
653
33.6k
      if (Enable)
654
2.81k
        Frame.This = NewThis;
655
33.6k
    }
656
33.6k
    ~ThisOverrideRAII() {
657
33.6k
      Frame.This = OldThis;
658
33.6k
    }
659
  private:
660
    CallStackFrame &Frame;
661
    const LValue *OldThis;
662
  };
663
}
664
665
static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666
                              const LValue &This, QualType ThisType);
667
static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668
                              APValue::LValueBase LVBase, APValue &Value,
669
                              QualType T);
670
671
namespace {
672
  /// A cleanup, and a flag indicating whether it is lifetime-extended.
673
  class Cleanup {
674
    llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675
    APValue::LValueBase Base;
676
    QualType T;
677
678
  public:
679
    Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680
            ScopeKind Scope)
681
477k
        : Value(Val, Scope), Base(Base), T(T) {}
682
683
    /// Determine whether this cleanup should be performed at the end of the
684
    /// given kind of scope.
685
998k
    bool isDestroyedAtEndOf(ScopeKind K) const {
686
998k
      return (int)Value.getInt() >= (int)K;
687
998k
    }
688
457k
    bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689
457k
      if (RunDestructors) {
690
84.3k
        SourceLocation Loc;
691
84.3k
        if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692
77.1k
          Loc = VD->getLocation();
693
7.17k
        else if (const Expr *E = Base.dyn_cast<const Expr*>())
694
7.17k
          Loc = E->getExprLoc();
695
84.3k
        return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696
84.3k
      }
697
372k
      *Value.getPointer() = APValue();
698
372k
      return true;
699
457k
    }
700
701
20.4k
    bool hasSideEffect() {
702
20.4k
      return T.isDestructedType();
703
20.4k
    }
704
  };
705
706
  /// A reference to an object whose construction we are currently evaluating.
707
  struct ObjectUnderConstruction {
708
    APValue::LValueBase Base;
709
    ArrayRef<APValue::LValuePathEntry> Path;
710
    friend bool operator==(const ObjectUnderConstruction &LHS,
711
1.93M
                           const ObjectUnderConstruction &RHS) {
712
1.93M
      return LHS.Base == RHS.Base && 
LHS.Path == RHS.Path1.50M
;
713
1.93M
    }
714
106k
    friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715
106k
      return llvm::hash_combine(Obj.Base, Obj.Path);
716
106k
    }
717
  };
718
  enum class ConstructionPhase {
719
    None,
720
    Bases,
721
    AfterBases,
722
    AfterFields,
723
    Destroying,
724
    DestroyingBases
725
  };
726
}
727
728
namespace llvm {
729
template<> struct DenseMapInfo<ObjectUnderConstruction> {
730
  using Base = DenseMapInfo<APValue::LValueBase>;
731
175k
  static ObjectUnderConstruction getEmptyKey() {
732
175k
    return {Base::getEmptyKey(), {}}; }
733
154k
  static ObjectUnderConstruction getTombstoneKey() {
734
154k
    return {Base::getTombstoneKey(), {}};
735
154k
  }
736
106k
  static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737
106k
    return hash_value(Object);
738
106k
  }
739
  static bool isEqual(const ObjectUnderConstruction &LHS,
740
1.93M
                      const ObjectUnderConstruction &RHS) {
741
1.93M
    return LHS == RHS;
742
1.93M
  }
743
};
744
}
745
746
namespace {
747
  /// A dynamically-allocated heap object.
748
  struct DynAlloc {
749
    /// The value of this heap-allocated object.
750
    APValue Value;
751
    /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752
    /// or a CallExpr (the latter is for direct calls to operator new inside
753
    /// std::allocator<T>::allocate).
754
    const Expr *AllocExpr = nullptr;
755
756
    enum Kind {
757
      New,
758
      ArrayNew,
759
      StdAllocator
760
    };
761
762
    /// Get the kind of the allocation. This must match between allocation
763
    /// and deallocation.
764
214
    Kind getKind() const {
765
214
      if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766
190
        return NE->isArray() ? 
ArrayNew71
:
New119
;
767
24
      assert(isa<CallExpr>(AllocExpr));
768
0
      return StdAllocator;
769
214
    }
770
  };
771
772
  struct DynAllocOrder {
773
9.67k
    bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774
9.67k
      return L.getIndex() < R.getIndex();
775
9.67k
    }
776
  };
777
778
  /// EvalInfo - This is a private struct used by the evaluator to capture
779
  /// information about a subexpression as it is folded.  It retains information
780
  /// about the AST context, but also maintains information about the folded
781
  /// expression.
782
  ///
783
  /// If an expression could be evaluated, it is still possible it is not a C
784
  /// "integer constant expression" or constant expression.  If not, this struct
785
  /// captures information about how and why not.
786
  ///
787
  /// One bit of information passed *into* the request for constant folding
788
  /// indicates whether the subexpression is "evaluated" or not according to C
789
  /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790
  /// evaluate the expression regardless of what the RHS is, but C only allows
791
  /// certain things in certain situations.
792
  class EvalInfo : public interp::State {
793
  public:
794
    ASTContext &Ctx;
795
796
    /// EvalStatus - Contains information about the evaluation.
797
    Expr::EvalStatus &EvalStatus;
798
799
    /// CurrentCall - The top of the constexpr call stack.
800
    CallStackFrame *CurrentCall;
801
802
    /// CallStackDepth - The number of calls in the call stack right now.
803
    unsigned CallStackDepth;
804
805
    /// NextCallIndex - The next call index to assign.
806
    unsigned NextCallIndex;
807
808
    /// StepsLeft - The remaining number of evaluation steps we're permitted
809
    /// to perform. This is essentially a limit for the number of statements
810
    /// we will evaluate.
811
    unsigned StepsLeft;
812
813
    /// Enable the experimental new constant interpreter. If an expression is
814
    /// not supported by the interpreter, an error is triggered.
815
    bool EnableNewConstInterp;
816
817
    /// BottomFrame - The frame in which evaluation started. This must be
818
    /// initialized after CurrentCall and CallStackDepth.
819
    CallStackFrame BottomFrame;
820
821
    /// A stack of values whose lifetimes end at the end of some surrounding
822
    /// evaluation frame.
823
    llvm::SmallVector<Cleanup, 16> CleanupStack;
824
825
    /// EvaluatingDecl - This is the declaration whose initializer is being
826
    /// evaluated, if any.
827
    APValue::LValueBase EvaluatingDecl;
828
829
    enum class EvaluatingDeclKind {
830
      None,
831
      /// We're evaluating the construction of EvaluatingDecl.
832
      Ctor,
833
      /// We're evaluating the destruction of EvaluatingDecl.
834
      Dtor,
835
    };
836
    EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837
838
    /// EvaluatingDeclValue - This is the value being constructed for the
839
    /// declaration whose initializer is being evaluated, if any.
840
    APValue *EvaluatingDeclValue;
841
842
    /// Set of objects that are currently being constructed.
843
    llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844
        ObjectsUnderConstruction;
845
846
    /// Current heap allocations, along with the location where each was
847
    /// allocated. We use std::map here because we need stable addresses
848
    /// for the stored APValues.
849
    std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850
851
    /// The number of heap allocations performed so far in this evaluation.
852
    unsigned NumHeapAllocs = 0;
853
854
    struct EvaluatingConstructorRAII {
855
      EvalInfo &EI;
856
      ObjectUnderConstruction Object;
857
      bool DidInsert;
858
      EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859
                                bool HasBases)
860
27.4k
          : EI(EI), Object(Object) {
861
27.4k
        DidInsert =
862
27.4k
            EI.ObjectsUnderConstruction
863
27.4k
                .insert({Object, HasBases ? 
ConstructionPhase::Bases1.33k
864
27.4k
                                          : 
ConstructionPhase::AfterBases26.1k
})
865
27.4k
                .second;
866
27.4k
      }
867
1.25k
      void finishedConstructingBases() {
868
1.25k
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869
1.25k
      }
870
24.2k
      void finishedConstructingFields() {
871
24.2k
        EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872
24.2k
      }
873
27.4k
      ~EvaluatingConstructorRAII() {
874
27.4k
        if (DidInsert) 
EI.ObjectsUnderConstruction.erase(Object)27.4k
;
875
27.4k
      }
876
    };
877
878
    struct EvaluatingDestructorRAII {
879
      EvalInfo &EI;
880
      ObjectUnderConstruction Object;
881
      bool DidInsert;
882
      EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883
335
          : EI(EI), Object(Object) {
884
335
        DidInsert = EI.ObjectsUnderConstruction
885
335
                        .insert({Object, ConstructionPhase::Destroying})
886
335
                        .second;
887
335
      }
888
47
      void startedDestroyingBases() {
889
47
        EI.ObjectsUnderConstruction[Object] =
890
47
            ConstructionPhase::DestroyingBases;
891
47
      }
892
335
      ~EvaluatingDestructorRAII() {
893
335
        if (DidInsert)
894
334
          EI.ObjectsUnderConstruction.erase(Object);
895
335
      }
896
    };
897
898
    ConstructionPhase
899
    isEvaluatingCtorDtor(APValue::LValueBase Base,
900
28.6k
                         ArrayRef<APValue::LValuePathEntry> Path) {
901
28.6k
      return ObjectsUnderConstruction.lookup({Base, Path});
902
28.6k
    }
903
904
    /// If we're currently speculatively evaluating, the outermost call stack
905
    /// depth at which we can mutate state, otherwise 0.
906
    unsigned SpeculativeEvaluationDepth = 0;
907
908
    /// The current array initialization index, if we're performing array
909
    /// initialization.
910
    uint64_t ArrayInitIndex = -1;
911
912
    /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913
    /// notes attached to it will also be stored, otherwise they will not be.
914
    bool HasActiveDiagnostic;
915
916
    /// Have we emitted a diagnostic explaining why we couldn't constant
917
    /// fold (not just why it's not strictly a constant expression)?
918
    bool HasFoldFailureDiagnostic;
919
920
    /// Whether or not we're in a context where the front end requires a
921
    /// constant value.
922
    bool InConstantContext;
923
924
    /// Whether we're checking that an expression is a potential constant
925
    /// expression. If so, do not fail on constructs that could become constant
926
    /// later on (such as a use of an undefined global).
927
    bool CheckingPotentialConstantExpression = false;
928
929
    /// Whether we're checking for an expression that has undefined behavior.
930
    /// If so, we will produce warnings if we encounter an operation that is
931
    /// always undefined.
932
    ///
933
    /// Note that we still need to evaluate the expression normally when this
934
    /// is set; this is used when evaluating ICEs in C.
935
    bool CheckingForUndefinedBehavior = false;
936
937
    enum EvaluationMode {
938
      /// Evaluate as a constant expression. Stop if we find that the expression
939
      /// is not a constant expression.
940
      EM_ConstantExpression,
941
942
      /// Evaluate as a constant expression. Stop if we find that the expression
943
      /// is not a constant expression. Some expressions can be retried in the
944
      /// optimizer if we don't constant fold them here, but in an unevaluated
945
      /// context we try to fold them immediately since the optimizer never
946
      /// gets a chance to look at it.
947
      EM_ConstantExpressionUnevaluated,
948
949
      /// Fold the expression to a constant. Stop if we hit a side-effect that
950
      /// we can't model.
951
      EM_ConstantFold,
952
953
      /// Evaluate in any way we know how. Don't worry about side-effects that
954
      /// can't be modeled.
955
      EM_IgnoreSideEffects,
956
    } EvalMode;
957
958
    /// Are we checking whether the expression is a potential constant
959
    /// expression?
960
10.1M
    bool checkingPotentialConstantExpression() const override  {
961
10.1M
      return CheckingPotentialConstantExpression;
962
10.1M
    }
963
964
    /// Are we checking an expression for overflow?
965
    // FIXME: We should check for any kind of undefined or suspicious behavior
966
    // in such constructs, not just overflow.
967
4.42M
    bool checkingForUndefinedBehavior() const override {
968
4.42M
      return CheckingForUndefinedBehavior;
969
4.42M
    }
970
971
    EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972
        : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973
          CallStackDepth(0), NextCallIndex(1),
974
          StepsLeft(C.getLangOpts().ConstexprStepLimit),
975
          EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976
          BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977
          EvaluatingDecl((const ValueDecl *)nullptr),
978
          EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979
          HasFoldFailureDiagnostic(false), InConstantContext(false),
980
19.1M
          EvalMode(Mode) {}
981
982
19.1M
    ~EvalInfo() {
983
19.1M
      discardCleanups();
984
19.1M
    }
985
986
    void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987
2.38M
                           EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988
2.38M
      EvaluatingDecl = Base;
989
2.38M
      IsEvaluatingDecl = EDK;
990
2.38M
      EvaluatingDeclValue = &Value;
991
2.38M
    }
992
993
149k
    bool CheckCallLimit(SourceLocation Loc) {
994
      // Don't perform any constexpr calls (other than the call we're checking)
995
      // when checking a potential constant expression.
996
149k
      if (checkingPotentialConstantExpression() && 
CallStackDepth > 151.0k
)
997
2.81k
        return false;
998
146k
      if (NextCallIndex == 0) {
999
        // NextCallIndex has wrapped around.
1000
0
        FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001
0
        return false;
1002
0
      }
1003
146k
      if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004
146k
        return true;
1005
12
      FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006
12
        << getLangOpts().ConstexprCallDepth;
1007
12
      return false;
1008
146k
    }
1009
1010
    std::pair<CallStackFrame *, unsigned>
1011
484k
    getCallFrameAndDepth(unsigned CallIndex) {
1012
484k
      assert(CallIndex && "no call index in getCallFrameAndDepth");
1013
      // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014
      // be null in this loop.
1015
0
      unsigned Depth = CallStackDepth;
1016
484k
      CallStackFrame *Frame = CurrentCall;
1017
1.03M
      while (Frame->Index > CallIndex) {
1018
546k
        Frame = Frame->Caller;
1019
546k
        --Depth;
1020
546k
      }
1021
484k
      if (Frame->Index == CallIndex)
1022
484k
        return {Frame, Depth};
1023
14
      return {nullptr, 0};
1024
484k
    }
1025
1026
6.62M
    bool nextStep(const Stmt *S) {
1027
6.62M
      if (!StepsLeft) {
1028
9
        FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029
9
        return false;
1030
9
      }
1031
6.62M
      --StepsLeft;
1032
6.62M
      return true;
1033
6.62M
    }
1034
1035
    APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036
1037
2.70k
    Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038
2.70k
      Optional<DynAlloc*> Result;
1039
2.70k
      auto It = HeapAllocs.find(DA);
1040
2.70k
      if (It != HeapAllocs.end())
1041
2.69k
        Result = &It->second;
1042
2.70k
      return Result;
1043
2.70k
    }
1044
1045
    /// Get the allocated storage for the given parameter of the given call.
1046
3.69k
    APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047
3.69k
      CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048
3.69k
      return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049
3.69k
                   : 
nullptr0
;
1050
3.69k
    }
1051
1052
    /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053
    struct StdAllocatorCaller {
1054
      unsigned FrameIndex;
1055
      QualType ElemType;
1056
894
      explicit operator bool() const { return FrameIndex != 0; };
1057
    };
1058
1059
894
    StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060
897
      for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061
894
           
Call = Call->Caller3
) {
1062
129
        const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063
129
        if (!MD)
1064
3
          continue;
1065
126
        const IdentifierInfo *FnII = MD->getIdentifier();
1066
126
        if (!FnII || !FnII->isStr(FnName))
1067
0
          continue;
1068
1069
126
        const auto *CTSD =
1070
126
            dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071
126
        if (!CTSD)
1072
0
          continue;
1073
1074
126
        const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075
126
        const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076
126
        if (CTSD->isInStdNamespace() && ClassII &&
1077
126
            ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078
126
            TAL[0].getKind() == TemplateArgument::Type)
1079
126
          return {Call->Index, TAL[0].getAsType()};
1080
126
      }
1081
1082
768
      return {};
1083
894
    }
1084
1085
363k
    void performLifetimeExtension() {
1086
      // Disable the cleanups for lifetime-extended temporaries.
1087
363k
      llvm::erase_if(CleanupStack, [](Cleanup &C) {
1088
339
        return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1089
339
      });
1090
363k
    }
1091
1092
    /// Throw away any remaining cleanups at the end of evaluation. If any
1093
    /// cleanups would have had a side-effect, note that as an unmodeled
1094
    /// side-effect and return false. Otherwise, return true.
1095
23.1M
    bool discardCleanups() {
1096
23.1M
      for (Cleanup &C : CleanupStack) {
1097
20.4k
        if (C.hasSideEffect() && 
!noteSideEffect()1.62k
) {
1098
464
          CleanupStack.clear();
1099
464
          return false;
1100
464
        }
1101
20.4k
      }
1102
23.1M
      CleanupStack.clear();
1103
23.1M
      return true;
1104
23.1M
    }
1105
1106
  private:
1107
758k
    interp::Frame *getCurrentFrame() override { return CurrentCall; }
1108
758k
    const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1109
1110
4.31M
    bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1111
6.01M
    void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1112
1113
758k
    void setFoldFailureDiagnostic(bool Flag) override {
1114
758k
      HasFoldFailureDiagnostic = Flag;
1115
758k
    }
1116
1117
9.67M
    Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1118
1119
25.3M
    ASTContext &getCtx() const override { return Ctx; }
1120
1121
    // If we have a prior diagnostic, it will be noting that the expression
1122
    // isn't a constant expression. This diagnostic is more important,
1123
    // unless we require this evaluation to produce a constant expression.
1124
    //
1125
    // FIXME: We might want to show both diagnostics to the user in
1126
    // EM_ConstantFold mode.
1127
762k
    bool hasPriorDiagnostic() override {
1128
762k
      if (!EvalStatus.Diag->empty()) {
1129
3.78k
        switch (EvalMode) {
1130
658
        case EM_ConstantFold:
1131
729
        case EM_IgnoreSideEffects:
1132
729
          if (!HasFoldFailureDiagnostic)
1133
652
            break;
1134
          // We've already failed to fold something. Keep that diagnostic.
1135
729
          
LLVM_FALLTHROUGH77
;77
1136
3.13k
        case EM_ConstantExpression:
1137
3.13k
        case EM_ConstantExpressionUnevaluated:
1138
3.13k
          setActiveDiagnostic(false);
1139
3.13k
          return true;
1140
3.78k
        }
1141
3.78k
      }
1142
758k
      return false;
1143
762k
    }
1144
1145
1.51M
    unsigned getCallStackDepth() override { return CallStackDepth; }
1146
1147
  public:
1148
    /// Should we continue evaluation after encountering a side-effect that we
1149
    /// couldn't model?
1150
1.47M
    bool keepEvaluatingAfterSideEffect() {
1151
1.47M
      switch (EvalMode) {
1152
61.1k
      case EM_IgnoreSideEffects:
1153
61.1k
        return true;
1154
1155
1.39M
      case EM_ConstantExpression:
1156
1.40M
      case EM_ConstantExpressionUnevaluated:
1157
1.40M
      case EM_ConstantFold:
1158
        // By default, assume any side effect might be valid in some other
1159
        // evaluation of this expression from a different context.
1160
1.40M
        return checkingPotentialConstantExpression() ||
1161
1.40M
               
checkingForUndefinedBehavior()1.10k
;
1162
1.47M
      }
1163
0
      llvm_unreachable("Missed EvalMode case");
1164
0
    }
1165
1166
    /// Note that we have had a side-effect, and determine whether we should
1167
    /// keep evaluating.
1168
1.47M
    bool noteSideEffect() {
1169
1.47M
      EvalStatus.HasSideEffects = true;
1170
1.47M
      return keepEvaluatingAfterSideEffect();
1171
1.47M
    }
1172
1173
    /// Should we continue evaluation after encountering undefined behavior?
1174
679
    bool keepEvaluatingAfterUndefinedBehavior() {
1175
679
      switch (EvalMode) {
1176
582
      case EM_IgnoreSideEffects:
1177
602
      case EM_ConstantFold:
1178
602
        return true;
1179
1180
77
      case EM_ConstantExpression:
1181
77
      case EM_ConstantExpressionUnevaluated:
1182
77
        return checkingForUndefinedBehavior();
1183
679
      }
1184
0
      llvm_unreachable("Missed EvalMode case");
1185
0
    }
1186
1187
    /// Note that we hit something that was technically undefined behavior, but
1188
    /// that we can evaluate past it (such as signed overflow or floating-point
1189
    /// division by zero.)
1190
679
    bool noteUndefinedBehavior() override {
1191
679
      EvalStatus.HasUndefinedBehavior = true;
1192
679
      return keepEvaluatingAfterUndefinedBehavior();
1193
679
    }
1194
1195
    /// Should we continue evaluation as much as possible after encountering a
1196
    /// construct which can't be reduced to a value?
1197
4.45M
    bool keepEvaluatingAfterFailure() const override {
1198
4.45M
      if (!StepsLeft)
1199
0
        return false;
1200
1201
4.45M
      switch (EvalMode) {
1202
168k
      case EM_ConstantExpression:
1203
185k
      case EM_ConstantExpressionUnevaluated:
1204
213k
      case EM_ConstantFold:
1205
4.45M
      case EM_IgnoreSideEffects:
1206
4.45M
        return checkingPotentialConstantExpression() ||
1207
4.45M
               
checkingForUndefinedBehavior()4.42M
;
1208
4.45M
      }
1209
0
      llvm_unreachable("Missed EvalMode case");
1210
0
    }
1211
1212
    /// Notes that we failed to evaluate an expression that other expressions
1213
    /// directly depend on, and determine if we should keep evaluating. This
1214
    /// should only be called if we actually intend to keep evaluating.
1215
    ///
1216
    /// Call noteSideEffect() instead if we may be able to ignore the value that
1217
    /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1218
    ///
1219
    /// (Foo(), 1)      // use noteSideEffect
1220
    /// (Foo() || true) // use noteSideEffect
1221
    /// Foo() + 1       // use noteFailure
1222
3.96M
    LLVM_NODISCARD bool noteFailure() {
1223
      // Failure when evaluating some expression often means there is some
1224
      // subexpression whose evaluation was skipped. Therefore, (because we
1225
      // don't track whether we skipped an expression when unwinding after an
1226
      // evaluation failure) every evaluation failure that bubbles up from a
1227
      // subexpression implies that a side-effect has potentially happened. We
1228
      // skip setting the HasSideEffects flag to true until we decide to
1229
      // continue evaluating after that point, which happens here.
1230
3.96M
      bool KeepGoing = keepEvaluatingAfterFailure();
1231
3.96M
      EvalStatus.HasSideEffects |= KeepGoing;
1232
3.96M
      return KeepGoing;
1233
3.96M
    }
1234
1235
    class ArrayInitLoopIndex {
1236
      EvalInfo &Info;
1237
      uint64_t OuterIndex;
1238
1239
    public:
1240
      ArrayInitLoopIndex(EvalInfo &Info)
1241
10
          : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1242
10
        Info.ArrayInitIndex = 0;
1243
10
      }
1244
10
      ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1245
1246
155
      operator uint64_t&() { return Info.ArrayInitIndex; }
1247
    };
1248
  };
1249
1250
  /// Object used to treat all foldable expressions as constant expressions.
1251
  struct FoldConstant {
1252
    EvalInfo &Info;
1253
    bool Enabled;
1254
    bool HadNoPriorDiags;
1255
    EvalInfo::EvaluationMode OldMode;
1256
1257
    explicit FoldConstant(EvalInfo &Info, bool Enabled)
1258
      : Info(Info),
1259
        Enabled(Enabled),
1260
        HadNoPriorDiags(Info.EvalStatus.Diag &&
1261
                        Info.EvalStatus.Diag->empty() &&
1262
                        !Info.EvalStatus.HasSideEffects),
1263
250k
        OldMode(Info.EvalMode) {
1264
250k
      if (Enabled)
1265
4.53k
        Info.EvalMode = EvalInfo::EM_ConstantFold;
1266
250k
    }
1267
156k
    void keepDiagnostics() { Enabled = false; }
1268
250k
    ~FoldConstant() {
1269
250k
      if (Enabled && 
HadNoPriorDiags1.81k
&&
!Info.EvalStatus.Diag->empty()67
&&
1270
250k
          
!Info.EvalStatus.HasSideEffects67
)
1271
67
        Info.EvalStatus.Diag->clear();
1272
250k
      Info.EvalMode = OldMode;
1273
250k
    }
1274
  };
1275
1276
  /// RAII object used to set the current evaluation mode to ignore
1277
  /// side-effects.
1278
  struct IgnoreSideEffectsRAII {
1279
    EvalInfo &Info;
1280
    EvalInfo::EvaluationMode OldMode;
1281
    explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1282
4.34k
        : Info(Info), OldMode(Info.EvalMode) {
1283
4.34k
      Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1284
4.34k
    }
1285
1286
4.34k
    ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1287
  };
1288
1289
  /// RAII object used to optionally suppress diagnostics and side-effects from
1290
  /// a speculative evaluation.
1291
  class SpeculativeEvaluationRAII {
1292
    EvalInfo *Info = nullptr;
1293
    Expr::EvalStatus OldStatus;
1294
    unsigned OldSpeculativeEvaluationDepth;
1295
1296
93.8k
    void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1297
93.8k
      Info = Other.Info;
1298
93.8k
      OldStatus = Other.OldStatus;
1299
93.8k
      OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1300
93.8k
      Other.Info = nullptr;
1301
93.8k
    }
1302
1303
14.9M
    void maybeRestoreState() {
1304
14.9M
      if (!Info)
1305
14.8M
        return;
1306
1307
71.1k
      Info->EvalStatus = OldStatus;
1308
71.1k
      Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1309
71.1k
    }
1310
1311
  public:
1312
14.7M
    SpeculativeEvaluationRAII() = default;
1313
1314
    SpeculativeEvaluationRAII(
1315
        EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1316
        : Info(&Info), OldStatus(Info.EvalStatus),
1317
71.1k
          OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1318
71.1k
      Info.EvalStatus.Diag = NewDiag;
1319
71.1k
      Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1320
71.1k
    }
1321
1322
    SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1323
33.8k
    SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1324
33.8k
      moveFromAndCancel(std::move(Other));
1325
33.8k
    }
1326
1327
60.0k
    SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1328
60.0k
      maybeRestoreState();
1329
60.0k
      moveFromAndCancel(std::move(Other));
1330
60.0k
      return *this;
1331
60.0k
    }
1332
1333
14.8M
    ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1334
  };
1335
1336
  /// RAII object wrapping a full-expression or block scope, and handling
1337
  /// the ending of the lifetime of temporaries created within it.
1338
  template<ScopeKind Kind>
1339
  class ScopeRAII {
1340
    EvalInfo &Info;
1341
    unsigned OldStackSize;
1342
  public:
1343
    ScopeRAII(EvalInfo &Info)
1344
16.9M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345
      // Push a new temporary version. This is needed to distinguish between
1346
      // temporaries created in different iterations of a loop.
1347
16.9M
      Info.CurrentCall->pushTempVersion();
1348
16.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1344
671k
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345
      // Push a new temporary version. This is needed to distinguish between
1346
      // temporaries created in different iterations of a loop.
1347
671k
      Info.CurrentCall->pushTempVersion();
1348
671k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1344
14.9M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345
      // Push a new temporary version. This is needed to distinguish between
1346
      // temporaries created in different iterations of a loop.
1347
14.9M
      Info.CurrentCall->pushTempVersion();
1348
14.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::ScopeRAII((anonymous namespace)::EvalInfo&)
Line
Count
Source
1344
1.31M
        : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1345
      // Push a new temporary version. This is needed to distinguish between
1346
      // temporaries created in different iterations of a loop.
1347
1.31M
      Info.CurrentCall->pushTempVersion();
1348
1.31M
    }
1349
16.9M
    bool destroy(bool RunDestructors = true) {
1350
16.9M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351
16.9M
      OldStackSize = -1U;
1352
16.9M
      return OK;
1353
16.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::destroy(bool)
Line
Count
Source
1349
14.9M
    bool destroy(bool RunDestructors = true) {
1350
14.9M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351
14.9M
      OldStackSize = -1U;
1352
14.9M
      return OK;
1353
14.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::destroy(bool)
Line
Count
Source
1349
671k
    bool destroy(bool RunDestructors = true) {
1350
671k
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351
671k
      OldStackSize = -1U;
1352
671k
      return OK;
1353
671k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::destroy(bool)
Line
Count
Source
1349
1.31M
    bool destroy(bool RunDestructors = true) {
1350
1.31M
      bool OK = cleanup(Info, RunDestructors, OldStackSize);
1351
1.31M
      OldStackSize = -1U;
1352
1.31M
      return OK;
1353
1.31M
    }
1354
16.9M
    ~ScopeRAII() {
1355
16.9M
      if (OldStackSize != -1U)
1356
729k
        destroy(false);
1357
      // Body moved to a static method to encourage the compiler to inline away
1358
      // instances of this class.
1359
16.9M
      Info.CurrentCall->popTempVersion();
1360
16.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::~ScopeRAII()
Line
Count
Source
1354
14.9M
    ~ScopeRAII() {
1355
14.9M
      if (OldStackSize != -1U)
1356
52.5k
        destroy(false);
1357
      // Body moved to a static method to encourage the compiler to inline away
1358
      // instances of this class.
1359
14.9M
      Info.CurrentCall->popTempVersion();
1360
14.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::~ScopeRAII()
Line
Count
Source
1354
671k
    ~ScopeRAII() {
1355
671k
      if (OldStackSize != -1U)
1356
593k
        destroy(false);
1357
      // Body moved to a static method to encourage the compiler to inline away
1358
      // instances of this class.
1359
671k
      Info.CurrentCall->popTempVersion();
1360
671k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::~ScopeRAII()
Line
Count
Source
1354
1.31M
    ~ScopeRAII() {
1355
1.31M
      if (OldStackSize != -1U)
1356
83.5k
        destroy(false);
1357
      // Body moved to a static method to encourage the compiler to inline away
1358
      // instances of this class.
1359
1.31M
      Info.CurrentCall->popTempVersion();
1360
1.31M
    }
1361
  private:
1362
    static bool cleanup(EvalInfo &Info, bool RunDestructors,
1363
16.9M
                        unsigned OldStackSize) {
1364
16.9M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1365
16.9M
             "running cleanups out of order?");
1366
1367
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368
      // for a full-expression scope.
1369
0
      bool Success = true;
1370
17.4M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I503k
) {
1371
503k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372
457k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373
272
            Success = false;
1374
272
            break;
1375
272
          }
1376
457k
        }
1377
503k
      }
1378
1379
      // Compact any retained cleanups.
1380
16.9M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381
16.9M
      if (Kind != ScopeKind::Block)
1382
1.98M
        NewEnd =
1383
1.98M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384
493k
              return C.isDestroyedAtEndOf(Kind);
1385
493k
            });
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::'lambda'((anonymous namespace)::Cleanup&)::operator()((anonymous namespace)::Cleanup&) const
Line
Count
Source
1383
466k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384
466k
              return C.isDestroyedAtEndOf(Kind);
1385
466k
            });
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)::'lambda'((anonymous namespace)::Cleanup&)::operator()((anonymous namespace)::Cleanup&) const
Line
Count
Source
1383
27.9k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384
27.9k
              return C.isDestroyedAtEndOf(Kind);
1385
27.9k
            });
1386
16.9M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387
16.9M
      return Success;
1388
16.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)0>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1363
14.9M
                        unsigned OldStackSize) {
1364
14.9M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1365
14.9M
             "running cleanups out of order?");
1366
1367
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368
      // for a full-expression scope.
1369
0
      bool Success = true;
1370
14.9M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I9.75k
) {
1371
9.89k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372
9.89k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373
140
            Success = false;
1374
140
            break;
1375
140
          }
1376
9.89k
        }
1377
9.89k
      }
1378
1379
      // Compact any retained cleanups.
1380
14.9M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381
14.9M
      if (Kind != ScopeKind::Block)
1382
0
        NewEnd =
1383
0
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384
0
              return C.isDestroyedAtEndOf(Kind);
1385
0
            });
1386
14.9M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387
14.9M
      return Success;
1388
14.9M
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)2>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1363
671k
                        unsigned OldStackSize) {
1364
671k
      assert(OldStackSize <= Info.CleanupStack.size() &&
1365
671k
             "running cleanups out of order?");
1366
1367
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368
      // for a full-expression scope.
1369
0
      bool Success = true;
1370
1.13M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I465k
) {
1371
465k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372
430k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373
108
            Success = false;
1374
108
            break;
1375
108
          }
1376
430k
        }
1377
465k
      }
1378
1379
      // Compact any retained cleanups.
1380
671k
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381
671k
      if (Kind != ScopeKind::Block)
1382
671k
        NewEnd =
1383
671k
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384
671k
              return C.isDestroyedAtEndOf(Kind);
1385
671k
            });
1386
671k
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387
671k
      return Success;
1388
671k
    }
ExprConstant.cpp:(anonymous namespace)::ScopeRAII<((anonymous namespace)::ScopeKind)1>::cleanup((anonymous namespace)::EvalInfo&, bool, unsigned int)
Line
Count
Source
1363
1.31M
                        unsigned OldStackSize) {
1364
1.31M
      assert(OldStackSize <= Info.CleanupStack.size() &&
1365
1.31M
             "running cleanups out of order?");
1366
1367
      // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1368
      // for a full-expression scope.
1369
0
      bool Success = true;
1370
1.34M
      for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; 
--I27.9k
) {
1371
27.9k
        if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1372
16.5k
          if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1373
24
            Success = false;
1374
24
            break;
1375
24
          }
1376
16.5k
        }
1377
27.9k
      }
1378
1379
      // Compact any retained cleanups.
1380
1.31M
      auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1381
1.31M
      if (Kind != ScopeKind::Block)
1382
1.31M
        NewEnd =
1383
1.31M
            std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1384
1.31M
              return C.isDestroyedAtEndOf(Kind);
1385
1.31M
            });
1386
1.31M
      Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1387
1.31M
      return Success;
1388
1.31M
    }
1389
  };
1390
  typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1391
  typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1392
  typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1393
}
1394
1395
bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1396
259k
                                         CheckSubobjectKind CSK) {
1397
259k
  if (Invalid)
1398
28
    return false;
1399
259k
  if (isOnePastTheEnd()) {
1400
32
    Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1401
32
      << CSK;
1402
32
    setInvalid();
1403
32
    return false;
1404
32
  }
1405
  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1406
  // must actually be at least one array element; even a VLA cannot have a
1407
  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1408
259k
  return true;
1409
259k
}
1410
1411
void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1412
580
                                                                const Expr *E) {
1413
580
  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1414
  // Do not set the designator as invalid: we can represent this situation,
1415
  // and correct handling of __builtin_object_size requires us to do so.
1416
580
}
1417
1418
void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1419
                                                    const Expr *E,
1420
426
                                                    const APSInt &N) {
1421
  // If we're complaining, we must be able to statically determine the size of
1422
  // the most derived array.
1423
426
  if (MostDerivedPathLength == Entries.size() && 
MostDerivedIsArrayElement414
)
1424
289
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1425
289
      << N << /*array*/ 0
1426
289
      << static_cast<unsigned>(getMostDerivedArraySize());
1427
137
  else
1428
137
    Info.CCEDiag(E, diag::note_constexpr_array_index)
1429
137
      << N << /*non-array*/ 1;
1430
426
  setInvalid();
1431
426
}
1432
1433
CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1434
                               const FunctionDecl *Callee, const LValue *This,
1435
                               CallRef Call)
1436
    : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1437
19.2M
      Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1438
19.2M
  Info.CurrentCall = this;
1439
19.2M
  ++Info.CallStackDepth;
1440
19.2M
}
1441
1442
19.2M
CallStackFrame::~CallStackFrame() {
1443
19.2M
  assert(Info.CurrentCall == this && "calls retired out of order");
1444
0
  --Info.CallStackDepth;
1445
19.2M
  Info.CurrentCall = Caller;
1446
19.2M
}
1447
1448
13.2M
static bool isRead(AccessKinds AK) {
1449
13.2M
  return AK == AK_Read || 
AK == AK_ReadObjectRepresentation274k
;
1450
13.2M
}
1451
1452
8.17M
static bool isModification(AccessKinds AK) {
1453
8.17M
  switch (AK) {
1454
7.71M
  case AK_Read:
1455
7.71M
  case AK_ReadObjectRepresentation:
1456
7.87M
  case AK_MemberCall:
1457
7.87M
  case AK_DynamicCast:
1458
7.87M
  case AK_TypeId:
1459
7.87M
    return false;
1460
158k
  case AK_Assign:
1461
297k
  case AK_Increment:
1462
298k
  case AK_Decrement:
1463
299k
  case AK_Construct:
1464
299k
  case AK_Destroy:
1465
299k
    return true;
1466
8.17M
  }
1467
0
  llvm_unreachable("unknown access kind");
1468
0
}
1469
1470
13.2M
static bool isAnyAccess(AccessKinds AK) {
1471
13.2M
  return isRead(AK) || 
isModification(AK)273k
;
1472
13.2M
}
1473
1474
/// Is this an access per the C++ definition?
1475
6.62M
static bool isFormalAccess(AccessKinds AK) {
1476
6.62M
  return isAnyAccess(AK) && 
AK != AK_Construct6.58M
&&
AK != AK_Destroy6.58M
;
1477
6.62M
}
1478
1479
/// Is this kind of axcess valid on an indeterminate object value?
1480
670
static bool isValidIndeterminateAccess(AccessKinds AK) {
1481
670
  switch (AK) {
1482
61
  case AK_Read:
1483
61
  case AK_Increment:
1484
61
  case AK_Decrement:
1485
    // These need the object's value.
1486
61
    return false;
1487
1488
0
  case AK_ReadObjectRepresentation:
1489
598
  case AK_Assign:
1490
607
  case AK_Construct:
1491
609
  case AK_Destroy:
1492
    // Construction and destruction don't need the value.
1493
609
    return true;
1494
1495
0
  case AK_MemberCall:
1496
0
  case AK_DynamicCast:
1497
0
  case AK_TypeId:
1498
    // These aren't really meaningful on scalars.
1499
0
    return true;
1500
670
  }
1501
0
  llvm_unreachable("unknown access kind");
1502
0
}
1503
1504
namespace {
1505
  struct ComplexValue {
1506
  private:
1507
    bool IsInt;
1508
1509
  public:
1510
    APSInt IntReal, IntImag;
1511
    APFloat FloatReal, FloatImag;
1512
1513
4.29k
    ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1514
1515
912
    void makeComplexFloat() { IsInt = false; }
1516
1.00k
    bool isComplexFloat() const { return !IsInt; }
1517
1.19k
    APFloat &getComplexFloatReal() { return FloatReal; }
1518
1.21k
    APFloat &getComplexFloatImag() { return FloatImag; }
1519
1520
293
    void makeComplexInt() { IsInt = true; }
1521
4
    bool isComplexInt() const { return IsInt; }
1522
327
    APSInt &getComplexIntReal() { return IntReal; }
1523
318
    APSInt &getComplexIntImag() { return IntImag; }
1524
1525
346
    void moveInto(APValue &v) const {
1526
346
      if (isComplexFloat())
1527
229
        v = APValue(FloatReal, FloatImag);
1528
117
      else
1529
117
        v = APValue(IntReal, IntImag);
1530
346
    }
1531
35
    void setFrom(const APValue &v) {
1532
35
      assert(v.isComplexFloat() || v.isComplexInt());
1533
35
      if (v.isComplexFloat()) {
1534
15
        makeComplexFloat();
1535
15
        FloatReal = v.getComplexFloatReal();
1536
15
        FloatImag = v.getComplexFloatImag();
1537
20
      } else {
1538
20
        makeComplexInt();
1539
20
        IntReal = v.getComplexIntReal();
1540
20
        IntImag = v.getComplexIntImag();
1541
20
      }
1542
35
    }
1543
  };
1544
1545
  struct LValue {
1546
    APValue::LValueBase Base;
1547
    CharUnits Offset;
1548
    SubobjectDesignator Designator;
1549
    bool IsNullPtr : 1;
1550
    bool InvalidBase : 1;
1551
1552
2.11M
    const APValue::LValueBase getLValueBase() const { return Base; }
1553
357k
    CharUnits &getLValueOffset() { return Offset; }
1554
338
    const CharUnits &getLValueOffset() const { return Offset; }
1555
8.35k
    SubobjectDesignator &getLValueDesignator() { return Designator; }
1556
95.6k
    const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1557
286
    bool isNullPointer() const { return IsNullPtr;}
1558
1559
7.03M
    unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1560
3.36M
    unsigned getLValueVersion() const { return Base.getVersion(); }
1561
1562
1.23M
    void moveInto(APValue &V) const {
1563
1.23M
      if (Designator.Invalid)
1564
6.63k
        V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1565
1.22M
      else {
1566
1.22M
        assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1567
0
        V = APValue(Base, Offset, Designator.Entries,
1568
1.22M
                    Designator.IsOnePastTheEnd, IsNullPtr);
1569
1.22M
      }
1570
1.23M
    }
1571
718k
    void setFrom(ASTContext &Ctx, const APValue &V) {
1572
718k
      assert(V.isLValue() && "Setting LValue from a non-LValue?");
1573
0
      Base = V.getLValueBase();
1574
718k
      Offset = V.getLValueOffset();
1575
718k
      InvalidBase = false;
1576
718k
      Designator = SubobjectDesignator(Ctx, V);
1577
718k
      IsNullPtr = V.isNullPointer();
1578
718k
    }
1579
1580
11.3M
    void set(APValue::LValueBase B, bool BInvalid = false) {
1581
11.3M
#ifndef NDEBUG
1582
      // We only allow a few types of invalid bases. Enforce that here.
1583
11.3M
      if (BInvalid) {
1584
1.50k
        const auto *E = B.get<const Expr *>();
1585
1.50k
        assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1586
1.50k
               "Unexpected type of invalid base");
1587
1.50k
      }
1588
0
#endif
1589
1590
0
      Base = B;
1591
11.3M
      Offset = CharUnits::fromQuantity(0);
1592
11.3M
      InvalidBase = BInvalid;
1593
11.3M
      Designator = SubobjectDesignator(getType(B));
1594
11.3M
      IsNullPtr = false;
1595
11.3M
    }
1596
1597
54.1k
    void setNull(ASTContext &Ctx, QualType PointerTy) {
1598
54.1k
      Base = (const ValueDecl *)nullptr;
1599
54.1k
      Offset =
1600
54.1k
          CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1601
54.1k
      InvalidBase = false;
1602
54.1k
      Designator = SubobjectDesignator(PointerTy->getPointeeType());
1603
54.1k
      IsNullPtr = true;
1604
54.1k
    }
1605
1606
1.50k
    void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1607
1.50k
      set(B, true);
1608
1.50k
    }
1609
1610
14
    std::string toString(ASTContext &Ctx, QualType T) const {
1611
14
      APValue Printable;
1612
14
      moveInto(Printable);
1613
14
      return Printable.getAsString(Ctx, T);
1614
14
    }
1615
1616
  private:
1617
    // Check that this LValue is not based on a null pointer. If it is, produce
1618
    // a diagnostic and mark the designator as invalid.
1619
    template <typename GenDiagType>
1620
282k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621
282k
      if (Designator.Invalid)
1622
290
        return false;
1623
281k
      if (IsNullPtr) {
1624
742
        GenDiag();
1625
742
        Designator.setInvalid();
1626
742
        return false;
1627
742
      }
1628
281k
      return true;
1629
281k
    }
ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::'lambda'()>((anonymous namespace)::LValue::checkNullPointer((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::CheckSubobjectKind)::'lambda'() const&)
Line
Count
Source
1620
275k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621
275k
      if (Designator.Invalid)
1622
290
        return false;
1623
275k
      if (IsNullPtr) {
1624
598
        GenDiag();
1625
598
        Designator.setInvalid();
1626
598
        return false;
1627
598
      }
1628
275k
      return true;
1629
275k
    }
ExprConstant.cpp:bool (anonymous namespace)::LValue::checkNullPointerDiagnosingWith<(anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::'lambda'()>((anonymous namespace)::LValue::checkNullPointerForFoldAccess((anonymous namespace)::EvalInfo&, clang::Expr const*, clang::AccessKinds)::'lambda'() const&)
Line
Count
Source
1620
6.20k
    bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1621
6.20k
      if (Designator.Invalid)
1622
0
        return false;
1623
6.20k
      if (IsNullPtr) {
1624
144
        GenDiag();
1625
144
        Designator.setInvalid();
1626
144
        return false;
1627
144
      }
1628
6.06k
      return true;
1629
6.20k
    }
1630
1631
  public:
1632
    bool checkNullPointer(EvalInfo &Info, const Expr *E,
1633
275k
                          CheckSubobjectKind CSK) {
1634
275k
      return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1635
598
        Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1636
598
      });
1637
275k
    }
1638
1639
    bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1640
6.20k
                                       AccessKinds AK) {
1641
6.20k
      return checkNullPointerDiagnosingWith([&Info, E, AK] {
1642
144
        Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1643
144
      });
1644
6.20k
    }
1645
1646
    // Check this LValue refers to an object. If not, set the designator to be
1647
    // invalid and emit a diagnostic.
1648
259k
    bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1649
259k
      return (CSK == CSK_ArrayToPointer || 
checkNullPointer(Info, E, CSK)175k
) &&
1650
259k
             
Designator.checkSubobject(Info, E, CSK)259k
;
1651
259k
    }
1652
1653
    void addDecl(EvalInfo &Info, const Expr *E,
1654
174k
                 const Decl *D, bool Virtual = false) {
1655
174k
      if (checkSubobject(Info, E, isa<FieldDecl>(D) ? 
CSK_Field162k
:
CSK_Base12.1k
))
1656
174k
        Designator.addDeclUnchecked(D, Virtual);
1657
174k
    }
1658
4.68k
    void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1659
4.68k
      if (!Designator.Entries.empty()) {
1660
24
        Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1661
24
        Designator.setInvalid();
1662
24
        return;
1663
24
      }
1664
4.65k
      if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1665
4.65k
        assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1666
0
        Designator.FirstEntryIsAnUnsizedArray = true;
1667
4.65k
        Designator.addUnsizedArrayUnchecked(ElemTy);
1668
4.65k
      }
1669
4.65k
    }
1670
80.1k
    void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1671
80.1k
      if (checkSubobject(Info, E, CSK_ArrayToPointer))
1672
80.1k
        Designator.addArrayUnchecked(CAT);
1673
80.1k
    }
1674
233
    void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1675
233
      if (checkSubobject(Info, E, Imag ? 
CSK_Imag111
:
CSK_Real122
))
1676
221
        Designator.addComplexUnchecked(EltTy, Imag);
1677
233
    }
1678
156k
    void clearIsNullPointer() {
1679
156k
      IsNullPtr = false;
1680
156k
    }
1681
    void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1682
110k
                              const APSInt &Index, CharUnits ElementSize) {
1683
      // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1684
      // but we're not required to diagnose it and it's valid in C++.)
1685
110k
      if (!Index)
1686
10.0k
        return;
1687
1688
      // Compute the new offset in the appropriate width, wrapping at 64 bits.
1689
      // FIXME: When compiling for a 32-bit target, we should use 32-bit
1690
      // offsets.
1691
100k
      uint64_t Offset64 = Offset.getQuantity();
1692
100k
      uint64_t ElemSize64 = ElementSize.getQuantity();
1693
100k
      uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1694
100k
      Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1695
1696
100k
      if (checkNullPointer(Info, E, CSK_ArrayIndex))
1697
100k
        Designator.adjustIndex(Info, E, Index);
1698
100k
      clearIsNullPointer();
1699
100k
    }
1700
162k
    void adjustOffset(CharUnits N) {
1701
162k
      Offset += N;
1702
162k
      if (N.getQuantity())
1703
55.9k
        clearIsNullPointer();
1704
162k
    }
1705
  };
1706
1707
  struct MemberPtr {
1708
2.99k
    MemberPtr() {}
1709
    explicit MemberPtr(const ValueDecl *Decl)
1710
1.93k
        : DeclAndIsDerivedMember(Decl, false) {}
1711
1712
    /// The member or (direct or indirect) field referred to by this member
1713
    /// pointer, or 0 if this is a null member pointer.
1714
3.79k
    const ValueDecl *getDecl() const {
1715
3.79k
      return DeclAndIsDerivedMember.getPointer();
1716
3.79k
    }
1717
    /// Is this actually a member of some type derived from the relevant class?
1718
2.78k
    bool isDerivedMember() const {
1719
2.78k
      return DeclAndIsDerivedMember.getInt();
1720
2.78k
    }
1721
    /// Get the class which the declaration actually lives in.
1722
116
    const CXXRecordDecl *getContainingRecord() const {
1723
116
      return cast<CXXRecordDecl>(
1724
116
          DeclAndIsDerivedMember.getPointer()->getDeclContext());
1725
116
    }
1726
1727
1.64k
    void moveInto(APValue &V) const {
1728
1.64k
      V = APValue(getDecl(), isDerivedMember(), Path);
1729
1.64k
    }
1730
234
    void setFrom(const APValue &V) {
1731
234
      assert(V.isMemberPointer());
1732
0
      DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1733
234
      DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1734
234
      Path.clear();
1735
234
      ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1736
234
      Path.insert(Path.end(), P.begin(), P.end());
1737
234
    }
1738
1739
    /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1740
    /// whether the member is a member of some class derived from the class type
1741
    /// of the member pointer.
1742
    llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1743
    /// Path - The path of base/derived classes from the member declaration's
1744
    /// class (exclusive) to the class type of the member pointer (inclusive).
1745
    SmallVector<const CXXRecordDecl*, 4> Path;
1746
1747
    /// Perform a cast towards the class of the Decl (either up or down the
1748
    /// hierarchy).
1749
144
    bool castBack(const CXXRecordDecl *Class) {
1750
144
      assert(!Path.empty());
1751
0
      const CXXRecordDecl *Expected;
1752
144
      if (Path.size() >= 2)
1753
141
        Expected = Path[Path.size() - 2];
1754
3
      else
1755
3
        Expected = getContainingRecord();
1756
144
      if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1757
        // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1758
        // if B does not contain the original member and is not a base or
1759
        // derived class of the class containing the original member, the result
1760
        // of the cast is undefined.
1761
        // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1762
        // (D::*). We consider that to be a language defect.
1763
0
        return false;
1764
0
      }
1765
144
      Path.pop_back();
1766
144
      return true;
1767
144
    }
1768
    /// Perform a base-to-derived member pointer cast.
1769
498
    bool castToDerived(const CXXRecordDecl *Derived) {
1770
498
      if (!getDecl())
1771
0
        return true;
1772
498
      if (!isDerivedMember()) {
1773
438
        Path.push_back(Derived);
1774
438
        return true;
1775
438
      }
1776
60
      if (!castBack(Derived))
1777
0
        return false;
1778
60
      if (Path.empty())
1779
3
        DeclAndIsDerivedMember.setInt(false);
1780
60
      return true;
1781
60
    }
1782
    /// Perform a derived-to-base member pointer cast.
1783
343
    bool castToBase(const CXXRecordDecl *Base) {
1784
343
      if (!getDecl())
1785
0
        return true;
1786
343
      if (Path.empty())
1787
82
        DeclAndIsDerivedMember.setInt(true);
1788
343
      if (isDerivedMember()) {
1789
259
        Path.push_back(Base);
1790
259
        return true;
1791
259
      }
1792
84
      return castBack(Base);
1793
343
    }
1794
  };
1795
1796
  /// Compare two member pointers, which are assumed to be of the same type.
1797
57
  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1798
57
    if (!LHS.getDecl() || !RHS.getDecl())
1799
0
      return !LHS.getDecl() && !RHS.getDecl();
1800
57
    if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1801
12
      return false;
1802
45
    return LHS.Path == RHS.Path;
1803
57
  }
1804
}
1805
1806
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1807
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1808
                            const LValue &This, const Expr *E,
1809
                            bool AllowNonLiteralTypes = false);
1810
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1811
                           bool InvalidBaseOK = false);
1812
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1813
                            bool InvalidBaseOK = false);
1814
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1815
                                  EvalInfo &Info);
1816
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1817
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1818
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1819
                                    EvalInfo &Info);
1820
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1821
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1822
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1823
                           EvalInfo &Info);
1824
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1825
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1826
                                  EvalInfo &Info);
1827
1828
/// Evaluate an integer or fixed point expression into an APResult.
1829
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1830
                                        EvalInfo &Info);
1831
1832
/// Evaluate only a fixed point expression into an APResult.
1833
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1834
                               EvalInfo &Info);
1835
1836
//===----------------------------------------------------------------------===//
1837
// Misc utilities
1838
//===----------------------------------------------------------------------===//
1839
1840
/// Negate an APSInt in place, converting it to a signed form if necessary, and
1841
/// preserving its value (by extending by up to one bit as needed).
1842
264
static void negateAsSigned(APSInt &Int) {
1843
264
  if (Int.isUnsigned() || 
Int.isMinSignedValue()254
) {
1844
10
    Int = Int.extend(Int.getBitWidth() + 1);
1845
10
    Int.setIsSigned(true);
1846
10
  }
1847
264
  Int = -Int;
1848
264
}
1849
1850
template<typename KeyT>
1851
APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1852
47.8k
                                         ScopeKind Scope, LValue &LV) {
1853
47.8k
  unsigned Version = getTempVersion();
1854
47.8k
  APValue::LValueBase Base(Key, Index, Version);
1855
47.8k
  LV.set(Base);
1856
47.8k
  return createLocal(Base, Key, T, Scope);
1857
47.8k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::OpaqueValueExpr>(clang::OpaqueValueExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1852
1.47k
                                         ScopeKind Scope, LValue &LV) {
1853
1.47k
  unsigned Version = getTempVersion();
1854
1.47k
  APValue::LValueBase Base(Key, Index, Version);
1855
1.47k
  LV.set(Base);
1856
1.47k
  return createLocal(Base, Key, T, Scope);
1857
1.47k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::VarDecl>(clang::VarDecl const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1852
9.85k
                                         ScopeKind Scope, LValue &LV) {
1853
9.85k
  unsigned Version = getTempVersion();
1854
9.85k
  APValue::LValueBase Base(Key, Index, Version);
1855
9.85k
  LV.set(Base);
1856
9.85k
  return createLocal(Base, Key, T, Scope);
1857
9.85k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::Expr>(clang::Expr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1852
4.96k
                                         ScopeKind Scope, LValue &LV) {
1853
4.96k
  unsigned Version = getTempVersion();
1854
4.96k
  APValue::LValueBase Base(Key, Index, Version);
1855
4.96k
  LV.set(Base);
1856
4.96k
  return createLocal(Base, Key, T, Scope);
1857
4.96k
}
ExprConstant.cpp:clang::APValue& (anonymous namespace)::CallStackFrame::createTemporary<clang::MaterializeTemporaryExpr>(clang::MaterializeTemporaryExpr const*, clang::QualType, (anonymous namespace)::ScopeKind, (anonymous namespace)::LValue&)
Line
Count
Source
1852
31.5k
                                         ScopeKind Scope, LValue &LV) {
1853
31.5k
  unsigned Version = getTempVersion();
1854
31.5k
  APValue::LValueBase Base(Key, Index, Version);
1855
31.5k
  LV.set(Base);
1856
31.5k
  return createLocal(Base, Key, T, Scope);
1857
31.5k
}
1858
1859
/// Allocate storage for a parameter of a function call made in this frame.
1860
APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1861
436k
                                     LValue &LV) {
1862
436k
  assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1863
0
  APValue::LValueBase Base(PVD, Index, Args.Version);
1864
436k
  LV.set(Base);
1865
  // We always destroy parameters at the end of the call, even if we'd allow
1866
  // them to live to the end of the full-expression at runtime, in order to
1867
  // give portable results and match other compilers.
1868
436k
  return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1869
436k
}
1870
1871
APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1872
484k
                                     QualType T, ScopeKind Scope) {
1873
484k
  assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1874
0
  unsigned Version = Base.getVersion();
1875
484k
  APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1876
484k
  assert(Result.isAbsent() && "local created multiple times");
1877
1878
  // If we're creating a local immediately in the operand of a speculative
1879
  // evaluation, don't register a cleanup to be run outside the speculative
1880
  // evaluation context, since we won't actually be able to initialize this
1881
  // object.
1882
484k
  if (Index <= Info.SpeculativeEvaluationDepth) {
1883
6.20k
    if (T.isDestructedType())
1884
493
      Info.noteSideEffect();
1885
477k
  } else {
1886
477k
    Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1887
477k
  }
1888
484k
  return Result;
1889
484k
}
1890
1891
838
APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1892
838
  if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1893
0
    FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1894
0
    return nullptr;
1895
0
  }
1896
1897
838
  DynamicAllocLValue DA(NumHeapAllocs++);
1898
838
  LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1899
838
  auto Result = HeapAllocs.emplace(std::piecewise_construct,
1900
838
                                   std::forward_as_tuple(DA), std::tuple<>());
1901
838
  assert(Result.second && "reused a heap alloc index?");
1902
0
  Result.first->second.AllocExpr = E;
1903
838
  return &Result.first->second.Value;
1904
838
}
1905
1906
/// Produce a string describing the given constexpr call.
1907
2.14k
void CallStackFrame::describe(raw_ostream &Out) {
1908
2.14k
  unsigned ArgIndex = 0;
1909
2.14k
  bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1910
2.14k
                      
!isa<CXXConstructorDecl>(Callee)1.28k
&&
1911
2.14k
                      
cast<CXXMethodDecl>(Callee)->isInstance()815
;
1912
1913
2.14k
  if (!IsMemberCall)
1914
1.33k
    Out << *Callee << '(';
1915
1916
2.14k
  if (This && 
IsMemberCall1.28k
) {
1917
815
    APValue Val;
1918
815
    This->moveInto(Val);
1919
815
    Val.printPretty(Out, Info.Ctx,
1920
815
                    This->Designator.MostDerivedType);
1921
    // FIXME: Add parens around Val if needed.
1922
815
    Out << "->" << *Callee << '(';
1923
815
    IsMemberCall = false;
1924
815
  }
1925
1926
2.14k
  for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1927
4.03k
       E = Callee->param_end(); I != E; 
++I, ++ArgIndex1.88k
) {
1928
1.88k
    if (ArgIndex > (unsigned)IsMemberCall)
1929
650
      Out << ", ";
1930
1931
1.88k
    const ParmVarDecl *Param = *I;
1932
1.88k
    APValue *V = Info.getParamSlot(Arguments, Param);
1933
1.88k
    if (V)
1934
1.88k
      V->printPretty(Out, Info.Ctx, Param->getType());
1935
0
    else
1936
0
      Out << "<...>";
1937
1938
1.88k
    if (ArgIndex == 0 && 
IsMemberCall1.23k
)
1939
0
      Out << "->" << *Callee << '(';
1940
1.88k
  }
1941
1942
2.14k
  Out << ')';
1943
2.14k
}
1944
1945
/// Evaluate an expression to see if it had side-effects, and discard its
1946
/// result.
1947
/// \return \c true if the caller should keep evaluating.
1948
87.0k
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1949
87.0k
  assert(!E->isValueDependent());
1950
0
  APValue Scratch;
1951
87.0k
  if (!Evaluate(Scratch, Info, E))
1952
    // We don't need the value, but we might have skipped a side effect here.
1953
8.72k
    return Info.noteSideEffect();
1954
78.3k
  return true;
1955
87.0k
}
1956
1957
/// Should this call expression be treated as a constant?
1958
31.2k
static bool IsConstantCall(const CallExpr *E) {
1959
31.2k
  unsigned Builtin = E->getBuiltinCallee();
1960
31.2k
  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1961
31.2k
          
Builtin == Builtin::BI__builtin___NSStringMakeConstantString29.8k
||
1962
31.2k
          
Builtin == Builtin::BI__builtin_function_start29.8k
);
1963
31.2k
}
1964
1965
95.0k
static bool IsGlobalLValue(APValue::LValueBase B) {
1966
  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1967
  // constant expression of pointer type that evaluates to...
1968
1969
  // ... a null pointer value, or a prvalue core constant expression of type
1970
  // std::nullptr_t.
1971
95.0k
  if (!B) 
return true14.9k
;
1972
1973
80.1k
  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1974
    // ... the address of an object with static storage duration,
1975
67.6k
    if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1976
54.4k
      return VD->hasGlobalStorage();
1977
13.2k
    if (isa<TemplateParamObjectDecl>(D))
1978
83
      return true;
1979
    // ... the address of a function,
1980
    // ... the address of a GUID [MS extension],
1981
13.1k
    return isa<FunctionDecl>(D) || 
isa<MSGuidDecl>(D)99
;
1982
13.2k
  }
1983
1984
12.4k
  if (B.is<TypeInfoLValue>() || 
B.is<DynamicAllocLValue>()11.3k
)
1985
1.28k
    return true;
1986
1987
11.1k
  const Expr *E = B.get<const Expr*>();
1988
11.1k
  switch (E->getStmtClass()) {
1989
0
  default:
1990
0
    return false;
1991
90
  case Expr::CompoundLiteralExprClass: {
1992
90
    const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1993
90
    return CLE->isFileScope() && 
CLE->isLValue()87
;
1994
0
  }
1995
1.08k
  case Expr::MaterializeTemporaryExprClass:
1996
    // A materialized temporary might have been lifetime-extended to static
1997
    // storage duration.
1998
1.08k
    return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1999
  // A string literal has static storage duration.
2000
5.11k
  case Expr::StringLiteralClass:
2001
5.14k
  case Expr::PredefinedExprClass:
2002
8.82k
  case Expr::ObjCStringLiteralClass:
2003
8.90k
  case Expr::ObjCEncodeExprClass:
2004
8.90k
    return true;
2005
9
  case Expr::ObjCBoxedExprClass:
2006
9
    return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2007
693
  case Expr::CallExprClass:
2008
693
    return IsConstantCall(cast<CallExpr>(E));
2009
  // For GCC compatibility, &&label has static storage duration.
2010
105
  case Expr::AddrLabelExprClass:
2011
105
    return true;
2012
  // A Block literal expression may be used as the initialization value for
2013
  // Block variables at global or local static scope.
2014
255
  case Expr::BlockExprClass:
2015
255
    return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2016
0
  case Expr::ImplicitValueInitExprClass:
2017
    // FIXME:
2018
    // We can never form an lvalue with an implicit value initialization as its
2019
    // base through expression evaluation, so these only appear in one case: the
2020
    // implicit variable declaration we invent when checking whether a constexpr
2021
    // constructor can produce a constant expression. We must assume that such
2022
    // an expression might be a global lvalue.
2023
0
    return true;
2024
11.1k
  }
2025
11.1k
}
2026
2027
1.58k
static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2028
1.58k
  return LVal.Base.dyn_cast<const ValueDecl*>();
2029
1.58k
}
2030
2031
1.10k
static bool IsLiteralLValue(const LValue &Value) {
2032
1.10k
  if (Value.getLValueCallIndex())
2033
15
    return false;
2034
1.08k
  const Expr *E = Value.Base.dyn_cast<const Expr*>();
2035
1.08k
  return E && 
!isa<MaterializeTemporaryExpr>(E)108
;
2036
1.10k
}
2037
2038
1.02k
static bool IsWeakLValue(const LValue &Value) {
2039
1.02k
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040
1.02k
  return Decl && 
Decl->isWeak()619
;
2041
1.02k
}
2042
2043
559
static bool isZeroSized(const LValue &Value) {
2044
559
  const ValueDecl *Decl = GetLValueBaseDecl(Value);
2045
559
  if (Decl && 
isa<VarDecl>(Decl)220
) {
2046
166
    QualType Ty = Decl->getType();
2047
166
    if (Ty->isArrayType())
2048
62
      return Ty->isIncompleteType() ||
2049
62
             
Decl->getASTContext().getTypeSize(Ty) == 042
;
2050
166
  }
2051
497
  return false;
2052
559
}
2053
2054
5.47k
static bool HasSameBase(const LValue &A, const LValue &B) {
2055
5.47k
  if (!A.getLValueBase())
2056
820
    return !B.getLValueBase();
2057
4.65k
  if (!B.getLValueBase())
2058
386
    return false;
2059
2060
4.26k
  if (A.getLValueBase().getOpaqueValue() !=
2061
4.26k
      B.getLValueBase().getOpaqueValue())
2062
349
    return false;
2063
2064
3.91k
  return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2065
3.91k
         A.getLValueVersion() == B.getLValueVersion();
2066
4.26k
}
2067
2068
1.26M
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2069
1.26M
  assert(Base && "no location for a null lvalue");
2070
0
  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2071
2072
  // For a parameter, find the corresponding call stack frame (if it still
2073
  // exists), and point at the parameter of the function definition we actually
2074
  // invoked.
2075
1.26M
  if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2076
1.00M
    unsigned Idx = PVD->getFunctionScopeIndex();
2077
2.02M
    for (CallStackFrame *F = Info.CurrentCall; F; 
F = F->Caller1.02M
) {
2078
1.02M
      if (F->Arguments.CallIndex == Base.getCallIndex() &&
2079
1.02M
          
F->Arguments.Version == Base.getVersion()1.00M
&&
F->Callee1.00M
&&
2080
1.02M
          
Idx < F->Callee->getNumParams()15
) {
2081
12
        VD = F->Callee->getParamDecl(Idx);
2082
12
        break;
2083
12
      }
2084
1.02M
    }
2085
1.00M
  }
2086
2087
1.26M
  if (VD)
2088
1.26M
    Info.Note(VD->getLocation(), diag::note_declared_at);
2089
646
  else if (const Expr *E = Base.dyn_cast<const Expr*>())
2090
383
    Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2091
263
  else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2092
    // FIXME: Produce a note for dangling pointers too.
2093
218
    if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2094
218
      Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2095
218
                diag::note_constexpr_dynamic_alloc_here);
2096
218
  }
2097
  // We have no information to show for a typeid(T) object.
2098
1.26M
}
2099
2100
enum class CheckEvaluationResultKind {
2101
  ConstantExpression,
2102
  FullyInitialized,
2103
};
2104
2105
/// Materialized temporaries that we've already checked to determine if they're
2106
/// initializsed by a constant expression.
2107
using CheckedTemporaries =
2108
    llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2109
2110
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2111
                                  EvalInfo &Info, SourceLocation DiagLoc,
2112
                                  QualType Type, const APValue &Value,
2113
                                  ConstantExprKind Kind,
2114
                                  SourceLocation SubobjectLoc,
2115
                                  CheckedTemporaries &CheckedTemps);
2116
2117
/// Check that this reference or pointer core constant expression is a valid
2118
/// value for an address or reference constant expression. Return true if we
2119
/// can fold this expression, whether or not it's a constant expression.
2120
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2121
                                          QualType Type, const LValue &LVal,
2122
                                          ConstantExprKind Kind,
2123
95.1k
                                          CheckedTemporaries &CheckedTemps) {
2124
95.1k
  bool IsReferenceType = Type->isReferenceType();
2125
2126
95.1k
  APValue::LValueBase Base = LVal.getLValueBase();
2127
95.1k
  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2128
2129
95.1k
  const Expr *BaseE = Base.dyn_cast<const Expr *>();
2130
95.1k
  const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2131
2132
  // Additional restrictions apply in a template argument. We only enforce the
2133
  // C++20 restrictions here; additional syntactic and semantic restrictions
2134
  // are applied elsewhere.
2135
95.1k
  if (isTemplateArgument(Kind)) {
2136
728
    int InvalidBaseKind = -1;
2137
728
    StringRef Ident;
2138
728
    if (Base.is<TypeInfoLValue>())
2139
6
      InvalidBaseKind = 0;
2140
722
    else if (isa_and_nonnull<StringLiteral>(BaseE))
2141
12
      InvalidBaseKind = 1;
2142
710
    else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2143
710
             
isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD)695
)
2144
15
      InvalidBaseKind = 2;
2145
695
    else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2146
8
      InvalidBaseKind = 3;
2147
8
      Ident = PE->getIdentKindName();
2148
8
    }
2149
2150
728
    if (InvalidBaseKind != -1) {
2151
41
      Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2152
41
          << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2153
41
          << Ident;
2154
41
      return false;
2155
41
    }
2156
728
  }
2157
2158
95.1k
  if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2159
13.1k
    if (FD->isConsteval()) {
2160
97
      Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2161
97
          << !Type->isAnyPointerType();
2162
97
      Info.Note(FD->getLocation(), diag::note_declared_at);
2163
97
      return false;
2164
97
    }
2165
13.1k
  }
2166
2167
  // Check that the object is a global. Note that the fake 'this' object we
2168
  // manufacture when checking potential constant expressions is conservatively
2169
  // assumed to be global here.
2170
95.0k
  if (!IsGlobalLValue(Base)) {
2171
37.3k
    if (Info.getLangOpts().CPlusPlus11) {
2172
34.8k
      const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2173
34.8k
      Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2174
34.8k
        << IsReferenceType << !Designator.Entries.empty()
2175
34.8k
        << !!VD << VD;
2176
2177
34.8k
      auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2178
34.8k
      if (VarD && 
VarD->isConstexpr()34.5k
) {
2179
        // Non-static local constexpr variables have unintuitive semantics:
2180
        //   constexpr int a = 1;
2181
        //   constexpr const int *p = &a;
2182
        // ... is invalid because the address of 'a' is not constant. Suggest
2183
        // adding a 'static' in this case.
2184
42
        Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2185
42
            << VarD
2186
42
            << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2187
34.8k
      } else {
2188
34.8k
        NoteLValueLocation(Info, Base);
2189
34.8k
      }
2190
34.8k
    } else {
2191
2.41k
      Info.FFDiag(Loc);
2192
2.41k
    }
2193
    // Don't allow references to temporaries to escape.
2194
37.3k
    return false;
2195
37.3k
  }
2196
57.6k
  assert((Info.checkingPotentialConstantExpression() ||
2197
57.6k
          LVal.getLValueCallIndex() == 0) &&
2198
57.6k
         "have call index for global lvalue");
2199
2200
57.6k
  if (Base.is<DynamicAllocLValue>()) {
2201
199
    Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2202
199
        << IsReferenceType << !Designator.Entries.empty();
2203
199
    NoteLValueLocation(Info, Base);
2204
199
    return false;
2205
199
  }
2206
2207
57.4k
  if (BaseVD) {
2208
30.7k
    if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2209
      // Check if this is a thread-local variable.
2210
17.4k
      if (Var->getTLSKind())
2211
        // FIXME: Diagnostic!
2212
118
        return false;
2213
2214
      // A dllimport variable never acts like a constant, unless we're
2215
      // evaluating a value for use only in name mangling.
2216
17.3k
      if (!isForManglingOnly(Kind) && 
Var->hasAttr<DLLImportAttr>()16.9k
)
2217
        // FIXME: Diagnostic!
2218
74
        return false;
2219
17.3k
    }
2220
30.5k
    if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2221
      // __declspec(dllimport) must be handled very carefully:
2222
      // We must never initialize an expression with the thunk in C++.
2223
      // Doing otherwise would allow the same id-expression to yield
2224
      // different addresses for the same function in different translation
2225
      // units.  However, this means that we must dynamically initialize the
2226
      // expression with the contents of the import address table at runtime.
2227
      //
2228
      // The C language has no notion of ODR; furthermore, it has no notion of
2229
      // dynamic initialization.  This means that we are permitted to
2230
      // perform initialization with the address of the thunk.
2231
13.0k
      if (Info.getLangOpts().CPlusPlus && 
!isForManglingOnly(Kind)10.5k
&&
2232
13.0k
          
FD->hasAttr<DLLImportAttr>()10.4k
)
2233
        // FIXME: Diagnostic!
2234
217
        return false;
2235
13.0k
    }
2236
30.5k
  } else 
if (const auto *26.7k
MTE26.7k
=
2237
26.7k
                 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2238
728
    if (CheckedTemps.insert(MTE).second) {
2239
716
      QualType TempType = getType(Base);
2240
716
      if (TempType.isDestructedType()) {
2241
4
        Info.FFDiag(MTE->getExprLoc(),
2242
4
                    diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2243
4
            << TempType;
2244
4
        return false;
2245
4
      }
2246
2247
712
      APValue *V = MTE->getOrCreateValue(false);
2248
712
      assert(V && "evasluation result refers to uninitialised temporary");
2249
712
      if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2250
712
                                 Info, MTE->getExprLoc(), TempType, *V,
2251
712
                                 Kind, SourceLocation(), CheckedTemps))
2252
11
        return false;
2253
712
    }
2254
728
  }
2255
2256
  // Allow address constant expressions to be past-the-end pointers. This is
2257
  // an extension: the standard requires them to point to an object.
2258
57.0k
  if (!IsReferenceType)
2259
38.7k
    return true;
2260
2261
  // A reference constant expression must refer to an object.
2262
18.2k
  if (!Base) {
2263
    // FIXME: diagnostic
2264
269
    Info.CCEDiag(Loc);
2265
269
    return true;
2266
269
  }
2267
2268
  // Does this refer one past the end of some object?
2269
18.0k
  if (!Designator.Invalid && 
Designator.isOnePastTheEnd()17.9k
) {
2270
59
    Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2271
59
      << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2272
59
    NoteLValueLocation(Info, Base);
2273
59
  }
2274
2275
18.0k
  return true;
2276
18.2k
}
2277
2278
/// Member pointers are constant expressions unless they point to a
2279
/// non-virtual dllimport member function.
2280
static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2281
                                                 SourceLocation Loc,
2282
                                                 QualType Type,
2283
                                                 const APValue &Value,
2284
1.32k
                                                 ConstantExprKind Kind) {
2285
1.32k
  const ValueDecl *Member = Value.getMemberPointerDecl();
2286
1.32k
  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2287
1.32k
  if (!FD)
2288
395
    return true;
2289
929
  if (FD->isConsteval()) {
2290
4
    Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2291
4
    Info.Note(FD->getLocation(), diag::note_declared_at);
2292
4
    return false;
2293
4
  }
2294
925
  return isForManglingOnly(Kind) || 
FD->isVirtual()911
||
2295
925
         
!FD->hasAttr<DLLImportAttr>()786
;
2296
929
}
2297
2298
/// Check that this core constant expression is of literal type, and if not,
2299
/// produce an appropriate diagnostic.
2300
static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2301
13.5M
                             const LValue *This = nullptr) {
2302
13.5M
  if (!E->isPRValue() || 
E->getType()->isLiteralType(Info.Ctx)11.7M
)
2303
13.4M
    return true;
2304
2305
  // C++1y: A constant initializer for an object o [...] may also invoke
2306
  // constexpr constructors for o and its subobjects even if those objects
2307
  // are of non-literal class types.
2308
  //
2309
  // C++11 missed this detail for aggregates, so classes like this:
2310
  //   struct foo_t { union { int i; volatile int j; } u; };
2311
  // are not (obviously) initializable like so:
2312
  //   __attribute__((__require_constant_initialization__))
2313
  //   static const foo_t x = {{0}};
2314
  // because "i" is a subobject with non-literal initialization (due to the
2315
  // volatile member of the union). See:
2316
  //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2317
  // Therefore, we use the C++1y behavior.
2318
92.6k
  if (This && 
Info.EvaluatingDecl == This->getLValueBase()21.7k
)
2319
2.65k
    return true;
2320
2321
  // Prvalue constant expressions must be of literal types.
2322
90.0k
  if (Info.getLangOpts().CPlusPlus11)
2323
52.8k
    Info.FFDiag(E, diag::note_constexpr_nonliteral)
2324
52.8k
      << E->getType();
2325
37.1k
  else
2326
37.1k
    Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2327
90.0k
  return false;
2328
92.6k
}
2329
2330
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2331
                                  EvalInfo &Info, SourceLocation DiagLoc,
2332
                                  QualType Type, const APValue &Value,
2333
                                  ConstantExprKind Kind,
2334
                                  SourceLocation SubobjectLoc,
2335
10.4M
                                  CheckedTemporaries &CheckedTemps) {
2336
10.4M
  if (!Value.hasValue()) {
2337
1.25k
    Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2338
1.25k
      << true << Type;
2339
1.25k
    if (SubobjectLoc.isValid())
2340
1.25k
      Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2341
1.25k
    return false;
2342
1.25k
  }
2343
2344
  // We allow _Atomic(T) to be initialized from anything that T can be
2345
  // initialized from.
2346
10.4M
  if (const AtomicType *AT = Type->getAs<AtomicType>())
2347
137
    Type = AT->getValueType();
2348
2349
  // Core issue 1454: For a literal constant expression of array or class type,
2350
  // each subobject of its value shall have been initialized by a constant
2351
  // expression.
2352
10.4M
  if (Value.isArray()) {
2353
6.02k
    QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2354
84.7k
    for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; 
++I78.7k
) {
2355
78.7k
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2356
78.7k
                                 Value.getArrayInitializedElt(I), Kind,
2357
78.7k
                                 SubobjectLoc, CheckedTemps))
2358
29
        return false;
2359
78.7k
    }
2360
5.99k
    if (!Value.hasArrayFiller())
2361
3.76k
      return true;
2362
2.23k
    return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2363
2.23k
                                 Value.getArrayFiller(), Kind, SubobjectLoc,
2364
2.23k
                                 CheckedTemps);
2365
5.99k
  }
2366
10.4M
  if (Value.isUnion() && 
Value.getUnionField()1.04k
) {
2367
808
    return CheckEvaluationResult(
2368
808
        CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2369
808
        Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2370
808
        CheckedTemps);
2371
808
  }
2372
10.4M
  if (Value.isStruct()) {
2373
25.5k
    RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2374
25.5k
    if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2375
25.5k
      unsigned BaseIndex = 0;
2376
25.5k
      for (const CXXBaseSpecifier &BS : CD->bases()) {
2377
2.80k
        if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2378
2.80k
                                   Value.getStructBase(BaseIndex), Kind,
2379
2.80k
                                   BS.getBeginLoc(), CheckedTemps))
2380
618
          return false;
2381
2.18k
        ++BaseIndex;
2382
2.18k
      }
2383
25.5k
    }
2384
24.9k
    for (const auto *I : RD->fields()) {
2385
20.0k
      if (I->isUnnamedBitfield())
2386
93
        continue;
2387
2388
19.9k
      if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2389
19.9k
                                 Value.getStructField(I->getFieldIndex()),
2390
19.9k
                                 Kind, I->getLocation(), CheckedTemps))
2391
1.57k
        return false;
2392
19.9k
    }
2393
24.9k
  }
2394
2395
10.4M
  if (Value.isLValue() &&
2396
10.4M
      
CERK == CheckEvaluationResultKind::ConstantExpression124k
) {
2397
94.8k
    LValue LVal;
2398
94.8k
    LVal.setFrom(Info.Ctx, Value);
2399
94.8k
    return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2400
94.8k
                                         CheckedTemps);
2401
94.8k
  }
2402
2403
10.3M
  if (Value.isMemberPointer() &&
2404
10.3M
      
CERK == CheckEvaluationResultKind::ConstantExpression1.55k
)
2405
1.32k
    return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2406
2407
  // Everything else is fine.
2408
10.3M
  return true;
2409
10.3M
}
2410
2411
/// Check that this core constant expression value is a valid value for a
2412
/// constant expression. If not, report an appropriate diagnostic. Does not
2413
/// check that the expression is of literal type.
2414
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2415
                                    QualType Type, const APValue &Value,
2416
8.84M
                                    ConstantExprKind Kind) {
2417
  // Nothing to check for a constant expression of type 'cv void'.
2418
8.84M
  if (Type->isVoidType())
2419
175
    return true;
2420
2421
8.84M
  CheckedTemporaries CheckedTemps;
2422
8.84M
  return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2423
8.84M
                               Info, DiagLoc, Type, Value, Kind,
2424
8.84M
                               SourceLocation(), CheckedTemps);
2425
8.84M
}
2426
2427
/// Check that this evaluated value is fully-initialized and can be loaded by
2428
/// an lvalue-to-rvalue conversion.
2429
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2430
1.52M
                                  QualType Type, const APValue &Value) {
2431
1.52M
  CheckedTemporaries CheckedTemps;
2432
1.52M
  return CheckEvaluationResult(
2433
1.52M
      CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2434
1.52M
      ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2435
1.52M
}
2436
2437
/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2438
/// "the allocated storage is deallocated within the evaluation".
2439
8.80M
static bool CheckMemoryLeaks(EvalInfo &Info) {
2440
8.80M
  if (!Info.HeapAllocs.empty()) {
2441
    // We can still fold to a constant despite a compile-time memory leak,
2442
    // so long as the heap allocation isn't referenced in the result (we check
2443
    // that in CheckConstantExpression).
2444
23
    Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2445
23
                 diag::note_constexpr_memory_leak)
2446
23
        << unsigned(Info.HeapAllocs.size() - 1);
2447
23
  }
2448
8.80M
  return true;
2449
8.80M
}
2450
2451
6.09k
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2452
  // A null base expression indicates a null pointer.  These are always
2453
  // evaluatable, and they are false unless the offset is zero.
2454
6.09k
  if (!Value.getLValueBase()) {
2455
637
    Result = !Value.getLValueOffset().isZero();
2456
637
    return true;
2457
637
  }
2458
2459
  // We have a non-null base.  These are generally known to be true, but if it's
2460
  // a weak declaration it can be null at runtime.
2461
5.45k
  Result = true;
2462
5.45k
  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2463
5.45k
  return !Decl || 
!Decl->isWeak()956
;
2464
6.09k
}
2465
2466
2.26M
static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2467
2.26M
  switch (Val.getKind()) {
2468
121k
  case APValue::None:
2469
121k
  case APValue::Indeterminate:
2470
121k
    return false;
2471
2.14M
  case APValue::Int:
2472
2.14M
    Result = Val.getInt().getBoolValue();
2473
2.14M
    return true;
2474
0
  case APValue::FixedPoint:
2475
0
    Result = Val.getFixedPoint().getBoolValue();
2476
0
    return true;
2477
91
  case APValue::Float:
2478
91
    Result = !Val.getFloat().isZero();
2479
91
    return true;
2480
4
  case APValue::ComplexInt:
2481
4
    Result = Val.getComplexIntReal().getBoolValue() ||
2482
4
             
Val.getComplexIntImag().getBoolValue()2
;
2483
4
    return true;
2484
4
  case APValue::ComplexFloat:
2485
4
    Result = !Val.getComplexFloatReal().isZero() ||
2486
4
             
!Val.getComplexFloatImag().isZero()2
;
2487
4
    return true;
2488
6.09k
  case APValue::LValue:
2489
6.09k
    return EvalPointerValueAsBool(Val, Result);
2490
75
  case APValue::MemberPointer:
2491
75
    Result = Val.getMemberPointerDecl();
2492
75
    return true;
2493
36
  case APValue::Vector:
2494
36
  case APValue::Array:
2495
36
  case APValue::Struct:
2496
36
  case APValue::Union:
2497
36
  case APValue::AddrLabelDiff:
2498
36
    return false;
2499
2.26M
  }
2500
2501
0
  llvm_unreachable("unknown APValue kind");
2502
0
}
2503
2504
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2505
1.74M
                                       EvalInfo &Info) {
2506
1.74M
  assert(!E->isValueDependent());
2507
0
  assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2508
0
  APValue Val;
2509
1.74M
  if (!Evaluate(Val, Info, E))
2510
380k
    return false;
2511
1.36M
  return HandleConversionToBool(Val, Result);
2512
1.74M
}
2513
2514
template<typename T>
2515
static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2516
670
                           const T &SrcValue, QualType DestType) {
2517
670
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2518
670
    << SrcValue << DestType;
2519
670
  return Info.noteUndefinedBehavior();
2520
670
}
ExprConstant.cpp:bool HandleOverflow<llvm::APSInt>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, clang::QualType)
Line
Count
Source
2516
584
                           const T &SrcValue, QualType DestType) {
2517
584
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2518
584
    << SrcValue << DestType;
2519
584
  return Info.noteUndefinedBehavior();
2520
584
}
ExprConstant.cpp:bool HandleOverflow<llvm::APFixedPoint>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFixedPoint const&, clang::QualType)
Line
Count
Source
2516
58
                           const T &SrcValue, QualType DestType) {
2517
58
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2518
58
    << SrcValue << DestType;
2519
58
  return Info.noteUndefinedBehavior();
2520
58
}
ExprConstant.cpp:bool HandleOverflow<llvm::APFloat>((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APFloat const&, clang::QualType)
Line
Count
Source
2516
28
                           const T &SrcValue, QualType DestType) {
2517
28
  Info.CCEDiag(E, diag::note_constexpr_overflow)
2518
28
    << SrcValue << DestType;
2519
28
  return Info.noteUndefinedBehavior();
2520
28
}
2521
2522
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2523
                                 QualType SrcType, const APFloat &Value,
2524
4.50k
                                 QualType DestType, APSInt &Result) {
2525
4.50k
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2526
  // Determine whether we are converting to unsigned or signed.
2527
4.50k
  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2528
2529
4.50k
  Result = APSInt(DestWidth, !DestSigned);
2530
4.50k
  bool ignored;
2531
4.50k
  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2532
4.50k
      & APFloat::opInvalidOp)
2533
28
    return HandleOverflow(Info, E, Value, DestType);
2534
4.47k
  return true;
2535
4.50k
}
2536
2537
/// Get rounding mode used for evaluation of the specified expression.
2538
/// \param[out] DynamicRM Is set to true is the requested rounding mode is
2539
///                       dynamic.
2540
/// If rounding mode is unknown at compile time, still try to evaluate the
2541
/// expression. If the result is exact, it does not depend on rounding mode.
2542
/// So return "tonearest" mode instead of "dynamic".
2543
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2544
26.8k
                                                bool &DynamicRM) {
2545
26.8k
  llvm::RoundingMode RM =
2546
26.8k
      E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2547
26.8k
  DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2548
26.8k
  if (DynamicRM)
2549
176
    RM = llvm::RoundingMode::NearestTiesToEven;
2550
26.8k
  return RM;
2551
26.8k
}
2552
2553
/// Check if the given evaluation result is allowed for constant evaluation.
2554
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2555
26.7k
                                     APFloat::opStatus St) {
2556
  // In a constant context, assume that any dynamic rounding mode or FP
2557
  // exception state matches the default floating-point environment.
2558
26.7k
  if (Info.InConstantContext)
2559
16.9k
    return true;
2560
2561
9.88k
  FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2562
9.88k
  if ((St & APFloat::opInexact) &&
2563
9.88k
      
FPO.getRoundingMode() == llvm::RoundingMode::Dynamic434
) {
2564
    // Inexact result means that it depends on rounding mode. If the requested
2565
    // mode is dynamic, the evaluation cannot be made in compile time.
2566
24
    Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2567
24
    return false;
2568
24
  }
2569
2570
9.85k
  if ((St != APFloat::opOK) &&
2571
9.85k
      
(416
FPO.getRoundingMode() == llvm::RoundingMode::Dynamic416
||
2572
416
       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2573
416
       
FPO.getAllowFEnvAccess()414
)) {
2574
2
    Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2575
2
    return false;
2576
2
  }
2577
2578
9.85k
  if ((St & APFloat::opStatus::opInvalidOp) &&
2579
9.85k
      
FPO.getFPExceptionMode() != LangOptions::FPE_Ignore0
) {
2580
    // There is no usefully definable result.
2581
0
    Info.FFDiag(E);
2582
0
    return false;
2583
0
  }
2584
2585
  // FIXME: if:
2586
  // - evaluation triggered other FP exception, and
2587
  // - exception mode is not "ignore", and
2588
  // - the expression being evaluated is not a part of global variable
2589
  //   initializer,
2590
  // the evaluation probably need to be rejected.
2591
9.85k
  return true;
2592
9.85k
}
2593
2594
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2595
                                   QualType SrcType, QualType DestType,
2596
10.3k
                                   APFloat &Result) {
2597
10.3k
  assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2598
0
  bool DynamicRM;
2599
10.3k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2600
10.3k
  APFloat::opStatus St;
2601
10.3k
  APFloat Value = Result;
2602
10.3k
  bool ignored;
2603
10.3k
  St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2604
10.3k
  return checkFloatingPointResult(Info, E, St);
2605
10.3k
}
2606
2607
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2608
                                 QualType DestType, QualType SrcType,
2609
1.09M
                                 const APSInt &Value) {
2610
1.09M
  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2611
  // Figure out if this is a truncate, extend or noop cast.
2612
  // If the input is signed, do a sign extend, noop, or truncate.
2613
1.09M
  APSInt Result = Value.extOrTrunc(DestWidth);
2614
1.09M
  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2615
1.09M
  if (DestType->isBooleanType())
2616
60
    Result = Value.getBoolValue();
2617
1.09M
  return Result;
2618
1.09M
}
2619
2620
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2621
                                 const FPOptions FPO,
2622
                                 QualType SrcType, const APSInt &Value,
2623
22.5k
                                 QualType DestType, APFloat &Result) {
2624
22.5k
  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2625
22.5k
  APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2626
22.5k
       APFloat::rmNearestTiesToEven);
2627
22.5k
  if (!Info.InConstantContext && 
St != llvm::APFloatBase::opOK11.4k
&&
2628
22.5k
      
FPO.isFPConstrained()4
) {
2629
0
    Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2630
0
    return false;
2631
0
  }
2632
22.5k
  return true;
2633
22.5k
}
2634
2635
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2636
427
                                  APValue &Value, const FieldDecl *FD) {
2637
427
  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2638
2639
427
  if (!Value.isInt()) {
2640
    // Trying to store a pointer-cast-to-integer into a bitfield.
2641
    // FIXME: In this case, we should provide the diagnostic for casting
2642
    // a pointer to an integer.
2643
4
    assert(Value.isLValue() && "integral value neither int nor lvalue?");
2644
0
    Info.FFDiag(E);
2645
4
    return false;
2646
4
  }
2647
2648
423
  APSInt &Int = Value.getInt();
2649
423
  unsigned OldBitWidth = Int.getBitWidth();
2650
423
  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2651
423
  if (NewBitWidth < OldBitWidth)
2652
370
    Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2653
423
  return true;
2654
427
}
2655
2656
static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2657
333k
                                  llvm::APInt &Res) {
2658
333k
  APValue SVal;
2659
333k
  if (!Evaluate(SVal, Info, E))
2660
333k
    return false;
2661
245
  if (SVal.isInt()) {
2662
22
    Res = SVal.getInt();
2663
22
    return true;
2664
22
  }
2665
223
  if (SVal.isFloat()) {
2666
0
    Res = SVal.getFloat().bitcastToAPInt();
2667
0
    return true;
2668
0
  }
2669
223
  if (SVal.isVector()) {
2670
223
    QualType VecTy = E->getType();
2671
223
    unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2672
223
    QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2673
223
    unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2674
223
    bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2675
223
    Res = llvm::APInt::getZero(VecSize);
2676
1.43k
    for (unsigned i = 0; i < SVal.getVectorLength(); 
i++1.20k
) {
2677
1.20k
      APValue &Elt = SVal.getVectorElt(i);
2678
1.20k
      llvm::APInt EltAsInt;
2679
1.20k
      if (Elt.isInt()) {
2680
1.06k
        EltAsInt = Elt.getInt();
2681
1.06k
      } else 
if (148
Elt.isFloat()148
) {
2682
148
        EltAsInt = Elt.getFloat().bitcastToAPInt();
2683
148
      } else {
2684
        // Don't try to handle vectors of anything other than int or float
2685
        // (not sure if it's possible to hit this case).
2686
0
        Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2687
0
        return false;
2688
0
      }
2689
1.20k
      unsigned BaseEltSize = EltAsInt.getBitWidth();
2690
1.20k
      if (BigEndian)
2691
704
        Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2692
504
      else
2693
504
        Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2694
1.20k
    }
2695
223
    return true;
2696
223
  }
2697
  // Give up if the input isn't an int, float, or vector.  For example, we
2698
  // reject "(v4i16)(intptr_t)&a".
2699
0
  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2700
0
  return false;
2701
223
}
2702
2703
/// Perform the given integer operation, which is known to need at most BitWidth
2704
/// bits, and check for overflow in the original type (if that type was not an
2705
/// unsigned type).
2706
template<typename Operation>
2707
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2708
                                 const APSInt &LHS, const APSInt &RHS,
2709
                                 unsigned BitWidth, Operation Op,
2710
2.70M
                                 APSInt &Result) {
2711
2.70M
  if (LHS.isUnsigned()) {
2712
141k
    Result = Op(LHS, RHS);
2713
141k
    return true;
2714
141k
  }
2715
2716
2.56M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2717
2.56M
  Result = Value.trunc(LHS.getBitWidth());
2718
2.56M
  if (Result.extend(BitWidth) != Value) {
2719
557
    if (Info.checkingForUndefinedBehavior())
2720
206
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2721
206
                                       diag::warn_integer_constant_overflow)
2722
206
          << toString(Result, 10) << E->getType();
2723
557
    return HandleOverflow(Info, E, Value, E->getType());
2724
557
  }
2725
2.56M
  return true;
2726
2.56M
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::multiplies<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::multiplies<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2710
201k
                                 APSInt &Result) {
2711
201k
  if (LHS.isUnsigned()) {
2712
57.7k
    Result = Op(LHS, RHS);
2713
57.7k
    return true;
2714
57.7k
  }
2715
2716
144k
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2717
144k
  Result = Value.trunc(LHS.getBitWidth());
2718
144k
  if (Result.extend(BitWidth) != Value) {
2719
535
    if (Info.checkingForUndefinedBehavior())
2720
204
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2721
204
                                       diag::warn_integer_constant_overflow)
2722
204
          << toString(Result, 10) << E->getType();
2723
535
    return HandleOverflow(Info, E, Value, E->getType());
2724
535
  }
2725
143k
  return true;
2726
144k
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::plus<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::plus<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2710
905k
                                 APSInt &Result) {
2711
905k
  if (LHS.isUnsigned()) {
2712
17.4k
    Result = Op(LHS, RHS);
2713
17.4k
    return true;
2714
17.4k
  }
2715
2716
888k
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2717
888k
  Result = Value.trunc(LHS.getBitWidth());
2718
888k
  if (Result.extend(BitWidth) != Value) {
2719
14
    if (Info.checkingForUndefinedBehavior())
2720
2
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2721
2
                                       diag::warn_integer_constant_overflow)
2722
2
          << toString(Result, 10) << E->getType();
2723
14
    return HandleOverflow(Info, E, Value, E->getType());
2724
14
  }
2725
888k
  return true;
2726
888k
}
ExprConstant.cpp:bool CheckedIntArithmetic<std::__1::minus<llvm::APSInt> >((anonymous namespace)::EvalInfo&, clang::Expr const*, llvm::APSInt const&, llvm::APSInt const&, unsigned int, std::__1::minus<llvm::APSInt>, llvm::APSInt&)
Line
Count
Source
2710
1.59M
                                 APSInt &Result) {
2711
1.59M
  if (LHS.isUnsigned()) {
2712
66.3k
    Result = Op(LHS, RHS);
2713
66.3k
    return true;
2714
66.3k
  }
2715
2716
1.53M
  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2717
1.53M
  Result = Value.trunc(LHS.getBitWidth());
2718
1.53M
  if (Result.extend(BitWidth) != Value) {
2719
8
    if (Info.checkingForUndefinedBehavior())
2720
0
      Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2721
0
                                       diag::warn_integer_constant_overflow)
2722
0
          << toString(Result, 10) << E->getType();
2723
8
    return HandleOverflow(Info, E, Value, E->getType());
2724
8
  }
2725
1.53M
  return true;
2726
1.53M
}
2727
2728
/// Perform the given binary integer operation.
2729
static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2730
                              BinaryOperatorKind Opcode, APSInt RHS,
2731
3.98M
                              APSInt &Result) {
2732
3.98M
  switch (Opcode) {
2733
0
  default:
2734
0
    Info.FFDiag(E);
2735
0
    return false;
2736
201k
  case BO_Mul:
2737
201k
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2738
201k
                                std::multiplies<APSInt>(), Result);
2739
905k
  case BO_Add:
2740
905k
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2741
905k
                                std::plus<APSInt>(), Result);
2742
1.59M
  case BO_Sub:
2743
1.59M
    return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2744
1.59M
                                std::minus<APSInt>(), Result);
2745
19.2k
  case BO_And: Result = LHS & RHS; return true;
2746
1.61k
  case BO_Xor: Result = LHS ^ RHS; return true;
2747
65.8k
  case BO_Or:  Result = LHS | RHS; return true;
2748
660k
  case BO_Div:
2749
667k
  case BO_Rem:
2750
667k
    if (RHS == 0) {
2751
139
      Info.FFDiag(E, diag::note_expr_divide_by_zero);
2752
139
      return false;
2753
139
    }
2754
667k
    Result = (Opcode == BO_Rem ? 
LHS % RHS7.29k
:
LHS / RHS660k
);
2755
    // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2756
    // this operation and gives the two's complement result.
2757
667k
    if (RHS.isNegative() && 
RHS.isAllOnes()7
&&
LHS.isSigned()7
&&
2758
667k
        
LHS.isMinSignedValue()7
)
2759
6
      return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2760
6
                            E->getType());
2761
667k
    return true;
2762
255k
  case BO_Shl: {
2763
255k
    if (Info.getLangOpts().OpenCL)
2764
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2765
18
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2766
18
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2767
18
                    RHS.isUnsigned());
2768
255k
    else if (RHS.isSigned() && 
RHS.isNegative()225k
) {
2769
      // During constant-folding, a negative shift is an opposite shift. Such
2770
      // a shift is not a constant expression.
2771
13
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2772
13
      RHS = -RHS;
2773
13
      goto shift_right;
2774
13
    }
2775
255k
  shift_left:
2776
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2777
    // the shifted type.
2778
255k
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2779
255k
    if (SA != RHS) {
2780
19
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2781
19
        << RHS << E->getType() << LHS.getBitWidth();
2782
255k
    } else if (LHS.isSigned() && 
!Info.getLangOpts().CPlusPlus20170k
) {
2783
      // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2784
      // operand, and must not overflow the corresponding unsigned type.
2785
      // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2786
      // E1 x 2^E2 module 2^N.
2787
170k
      if (LHS.isNegative())
2788
13
        Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2789
170k
      else if (LHS.countLeadingZeros() < SA)
2790
9
        Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2791
170k
    }
2792
255k
    Result = LHS << SA;
2793
255k
    return true;
2794
255k
  }
2795
10.9k
  case BO_Shr: {
2796
10.9k
    if (Info.getLangOpts().OpenCL)
2797
      // OpenCL 6.3j: shift values are effectively % word size of LHS.
2798
2
      RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2799
2
                    static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2800
2
                    RHS.isUnsigned());
2801
10.9k
    else if (RHS.isSigned() && 
RHS.isNegative()10.9k
) {
2802
      // During constant-folding, a negative shift is an opposite shift. Such a
2803
      // shift is not a constant expression.
2804
9
      Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2805
9
      RHS = -RHS;
2806
9
      goto shift_left;
2807
9
    }
2808
10.9k
  shift_right:
2809
    // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2810
    // shifted type.
2811
10.9k
    unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2812
10.9k
    if (SA != RHS)
2813
9
      Info.CCEDiag(E, diag::note_constexpr_large_shift)
2814
9
        << RHS << E->getType() << LHS.getBitWidth();
2815
10.9k
    Result = LHS >> SA;
2816
10.9k
    return true;
2817
10.9k
  }
2818
2819
78.1k
  case BO_LT: Result = LHS < RHS; return true;
2820
9.96k
  case BO_GT: Result = LHS > RHS; return true;
2821
23.0k
  case BO_LE: Result = LHS <= RHS; return true;
2822
7.65k
  case BO_GE: Result = LHS >= RHS; return true;
2823
94.9k
  case BO_EQ: Result = LHS == RHS; return true;
2824
49.1k
  case BO_NE: Result = LHS != RHS; return true;
2825
0
  case BO_Cmp:
2826
0
    llvm_unreachable("BO_Cmp should be handled elsewhere");
2827
3.98M
  }
2828
3.98M
}
2829
2830
/// Perform the given binary floating-point operation, in-place, on LHS.
2831
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2832
                                  APFloat &LHS, BinaryOperatorKind Opcode,
2833
16.4k
                                  const APFloat &RHS) {
2834
16.4k
  bool DynamicRM;
2835
16.4k
  llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2836
16.4k
  APFloat::opStatus St;
2837
16.4k
  switch (Opcode) {
2838
0
  default:
2839
0
    Info.FFDiag(E);
2840
0
    return false;
2841
4.23k
  case BO_Mul:
2842
4.23k
    St = LHS.multiply(RHS, RM);
2843
4.23k
    break;
2844
2.20k
  case BO_Add:
2845
2.20k
    St = LHS.add(RHS, RM);
2846
2.20k
    break;
2847
3.85k
  case BO_Sub:
2848
3.85k
    St = LHS.subtract(RHS, RM);
2849
3.85k
    break;
2850
6.15k
  case BO_Div:
2851
    // [expr.mul]p4:
2852
    //   If the second operand of / or % is zero the behavior is undefined.
2853
6.15k
    if (RHS.isZero())
2854
13
      Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2855
6.15k
    St = LHS.divide(RHS, RM);
2856
6.15k
    break;
2857
16.4k
  }
2858
2859
  // [expr.pre]p4:
2860
  //   If during the evaluation of an expression, the result is not
2861
  //   mathematically defined [...], the behavior is undefined.
2862
  // FIXME: C++ rules require us to not conform to IEEE 754 here.
2863
16.4k
  if (LHS.isNaN()) {
2864
9
    Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2865
9
    return Info.noteUndefinedBehavior();
2866
9
  }
2867
2868
16.4k
  return checkFloatingPointResult(Info, E, St);
2869
16.4k
}
2870
2871
static bool handleLogicalOpForVector(const APInt &LHSValue,
2872
                                     BinaryOperatorKind Opcode,
2873
32
                                     const APInt &RHSValue, APInt &Result) {
2874
32
  bool LHS = (LHSValue != 0);
2875
32
  bool RHS = (RHSValue != 0);
2876
2877
32
  if (Opcode == BO_LAnd)
2878
16
    Result = LHS && 
RHS8
;
2879
16
  else
2880
16
    Result = LHS || 
RHS8
;
2881
32
  return true;
2882
32
}
2883
static bool handleLogicalOpForVector(const APFloat &LHSValue,
2884
                                     BinaryOperatorKind Opcode,
2885
96
                                     const APFloat &RHSValue, APInt &Result) {
2886
96
  bool LHS = !LHSValue.isZero();
2887
96
  bool RHS = !RHSValue.isZero();
2888
2889
96
  if (Opcode == BO_LAnd)
2890
48
    Result = LHS && 
RHS24
;
2891
48
  else
2892
48
    Result = LHS || 
RHS40
;
2893
96
  return true;
2894
96
}
2895
2896
static bool handleLogicalOpForVector(const APValue &LHSValue,
2897
                                     BinaryOperatorKind Opcode,
2898
128
                                     const APValue &RHSValue, APInt &Result) {
2899
  // The result is always an int type, however operands match the first.
2900
128
  if (LHSValue.getKind() == APValue::Int)
2901
32
    return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2902
32
                                    RHSValue.getInt(), Result);
2903
96
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2904
0
  return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2905
96
                                  RHSValue.getFloat(), Result);
2906
128
}
2907
2908
template <typename APTy>
2909
static bool
2910
handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2911
200
                               const APTy &RHSValue, APInt &Result) {
2912
200
  switch (Opcode) {
2913
0
  default:
2914
0
    llvm_unreachable("unsupported binary operator");
2915
32
  case BO_EQ:
2916
32
    Result = (LHSValue == RHSValue);
2917
32
    break;
2918
32
  case BO_NE:
2919
32
    Result = (LHSValue != RHSValue);
2920
32
    break;
2921
40
  case BO_LT:
2922
40
    Result = (LHSValue < RHSValue);
2923
40
    break;
2924
32
  case BO_GT:
2925
32
    Result = (LHSValue > RHSValue);
2926
32
    break;
2927
32
  case BO_LE:
2928
32
    Result = (LHSValue <= RHSValue);
2929
32
    break;
2930
32
  case BO_GE:
2931
32
    Result = (LHSValue >= RHSValue);
2932
32
    break;
2933
200
  }
2934
2935
  // The boolean operations on these vector types use an instruction that
2936
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2937
  // to -1 to make sure that we produce the correct value.
2938
200
  Result.negate();
2939
2940
200
  return true;
2941
200
}
ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APSInt>(llvm::APSInt const&, clang::BinaryOperatorKind, llvm::APSInt const&, llvm::APInt&)
Line
Count
Source
2911
104
                               const APTy &RHSValue, APInt &Result) {
2912
104
  switch (Opcode) {
2913
0
  default:
2914
0
    llvm_unreachable("unsupported binary operator");
2915
16
  case BO_EQ:
2916
16
    Result = (LHSValue == RHSValue);
2917
16
    break;
2918
16
  case BO_NE:
2919
16
    Result = (LHSValue != RHSValue);
2920
16
    break;
2921
24
  case BO_LT:
2922
24
    Result = (LHSValue < RHSValue);
2923
24
    break;
2924
16
  case BO_GT:
2925
16
    Result = (LHSValue > RHSValue);
2926
16
    break;
2927
16
  case BO_LE:
2928
16
    Result = (LHSValue <= RHSValue);
2929
16
    break;
2930
16
  case BO_GE:
2931
16
    Result = (LHSValue >= RHSValue);
2932
16
    break;
2933
104
  }
2934
2935
  // The boolean operations on these vector types use an instruction that
2936
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2937
  // to -1 to make sure that we produce the correct value.
2938
104
  Result.negate();
2939
2940
104
  return true;
2941
104
}
ExprConstant.cpp:bool handleCompareOpForVectorHelper<llvm::APFloat>(llvm::APFloat const&, clang::BinaryOperatorKind, llvm::APFloat const&, llvm::APInt&)
Line
Count
Source
2911
96
                               const APTy &RHSValue, APInt &Result) {
2912
96
  switch (Opcode) {
2913
0
  default:
2914
0
    llvm_unreachable("unsupported binary operator");
2915
16
  case BO_EQ:
2916
16
    Result = (LHSValue == RHSValue);
2917
16
    break;
2918
16
  case BO_NE:
2919
16
    Result = (LHSValue != RHSValue);
2920
16
    break;
2921
16
  case BO_LT:
2922
16
    Result = (LHSValue < RHSValue);
2923
16
    break;
2924
16
  case BO_GT:
2925
16
    Result = (LHSValue > RHSValue);
2926
16
    break;
2927
16
  case BO_LE:
2928
16
    Result = (LHSValue <= RHSValue);
2929
16
    break;
2930
16
  case BO_GE:
2931
16
    Result = (LHSValue >= RHSValue);
2932
16
    break;
2933
96
  }
2934
2935
  // The boolean operations on these vector types use an instruction that
2936
  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
2937
  // to -1 to make sure that we produce the correct value.
2938
96
  Result.negate();
2939
2940
96
  return true;
2941
96
}
2942
2943
static bool handleCompareOpForVector(const APValue &LHSValue,
2944
                                     BinaryOperatorKind Opcode,
2945
200
                                     const APValue &RHSValue, APInt &Result) {
2946
  // The result is always an int type, however operands match the first.
2947
200
  if (LHSValue.getKind() == APValue::Int)
2948
104
    return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2949
104
                                          RHSValue.getInt(), Result);
2950
96
  assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2951
0
  return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2952
96
                                        RHSValue.getFloat(), Result);
2953
200
}
2954
2955
// Perform binary operations for vector types, in place on the LHS.
2956
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2957
                                    BinaryOperatorKind Opcode,
2958
                                    APValue &LHSValue,
2959
406
                                    const APValue &RHSValue) {
2960
406
  assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2961
406
         "Operation not supported on vector types");
2962
2963
0
  const auto *VT = E->getType()->castAs<VectorType>();
2964
406
  unsigned NumElements = VT->getNumElements();
2965
406
  QualType EltTy = VT->getElementType();
2966
2967
  // In the cases (typically C as I've observed) where we aren't evaluating
2968
  // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2969
  // just give up.
2970
406
  if (!LHSValue.isVector()) {
2971
218
    assert(LHSValue.isLValue() &&
2972
218
           "A vector result that isn't a vector OR uncalculated LValue");
2973
0
    Info.FFDiag(E);
2974
218
    return false;
2975
218
  }
2976
2977
188
  assert(LHSValue.getVectorLength() == NumElements &&
2978
188
         RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2979
2980
0
  SmallVector<APValue, 4> ResultElements;
2981
2982
940
  for (unsigned EltNum = 0; EltNum < NumElements; 
++EltNum752
) {
2983
752
    APValue LHSElt = LHSValue.getVectorElt(EltNum);
2984
752
    APValue RHSElt = RHSValue.getVectorElt(EltNum);
2985
2986
752
    if (EltTy->isIntegerType()) {
2987
624
      APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2988
624
                       EltTy->isUnsignedIntegerType()};
2989
624
      bool Success = true;
2990
2991
624
      if (BinaryOperator::isLogicalOp(Opcode))
2992
128
        Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2993
496
      else if (BinaryOperator::isComparisonOp(Opcode))
2994
200
        Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2995
296
      else
2996
296
        Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2997
296
                                    RHSElt.getInt(), EltResult);
2998
2999
624
      if (!Success) {
3000
0
        Info.FFDiag(E);
3001
0
        return false;
3002
0
      }
3003
624
      ResultElements.emplace_back(EltResult);
3004
3005
624
    } else 
if (128
EltTy->isFloatingType()128
) {
3006
128
      assert(LHSElt.getKind() == APValue::Float &&
3007
128
             RHSElt.getKind() == APValue::Float &&
3008
128
             "Mismatched LHS/RHS/Result Type");
3009
0
      APFloat LHSFloat = LHSElt.getFloat();
3010
3011
128
      if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3012
128
                                 RHSElt.getFloat())) {
3013
0
        Info.FFDiag(E);
3014
0
        return false;
3015
0
      }
3016
3017
128
      ResultElements.emplace_back(LHSFloat);
3018
128
    }
3019
752
  }
3020
3021
188
  LHSValue = APValue(ResultElements.data(), ResultElements.size());
3022
188
  return true;
3023
188
}
3024
3025
/// Cast an lvalue referring to a base subobject to a derived class, by
3026
/// truncating the lvalue's path to the given length.
3027
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3028
                               const RecordDecl *TruncatedType,
3029
416
                               unsigned TruncatedElements) {
3030
416
  SubobjectDesignator &D = Result.Designator;
3031
3032
  // Check we actually point to a derived class object.
3033
416
  if (TruncatedElements == D.Entries.size())
3034
161
    return true;
3035
255
  assert(TruncatedElements >= D.MostDerivedPathLength &&
3036
255
         "not casting to a derived class");
3037
255
  if (!Result.checkSubobject(Info, E, CSK_Derived))
3038
5
    return false;
3039
3040
  // Truncate the path to the subobject, and remove any derived-to-base offsets.
3041
250
  const RecordDecl *RD = TruncatedType;
3042
1.05k
  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; 
++I807
) {
3043
807
    if (RD->isInvalidDecl()) 
return false0
;
3044
807
    const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3045
807
    const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3046
807
    if (isVirtualBaseClass(D.Entries[I]))
3047
3
      Result.Offset -= Layout.getVBaseClassOffset(Base);
3048
804
    else
3049
804
      Result.Offset -= Layout.getBaseClassOffset(Base);
3050
807
    RD = Base;
3051
807
  }
3052
250
  D.Entries.resize(TruncatedElements);
3053
250
  return true;
3054
250
}
3055
3056
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3057
                                   const CXXRecordDecl *Derived,
3058
                                   const CXXRecordDecl *Base,
3059
12.0k
                                   const ASTRecordLayout *RL = nullptr) {
3060
12.0k
  if (!RL) {
3061
9.27k
    if (Derived->isInvalidDecl()) 
return false0
;
3062
9.27k
    RL = &Info.Ctx.getASTRecordLayout(Derived);
3063
9.27k
  }
3064
3065
12.0k
  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3066
12.0k
  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3067
12.0k
  return true;
3068
12.0k
}
3069
3070
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3071
                             const CXXRecordDecl *DerivedDecl,
3072
9.03k
                             const CXXBaseSpecifier *Base) {
3073
9.03k
  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3074
3075
9.03k
  if (!Base->isVirtual())
3076
8.91k
    return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3077
3078
115
  SubobjectDesignator &D = Obj.Designator;
3079
115
  if (D.Invalid)
3080
0
    return false;
3081
3082
  // Extract most-derived object and corresponding type.
3083
115
  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3084
115
  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3085
0
    return false;
3086
3087
  // Find the virtual base class.
3088
115
  if (DerivedDecl->isInvalidDecl()) 
return false0
;
3089
115
  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3090
115
  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3091
115
  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3092
115
  return true;
3093
115
}
3094
3095
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3096
4.52k
                                 QualType Type, LValue &Result) {
3097
4.52k
  for (CastExpr::path_const_iterator PathI = E->path_begin(),
3098
4.52k
                                     PathE = E->path_end();
3099
13.2k
       PathI != PathE; 
++PathI8.68k
) {
3100
8.68k
    if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3101
8.68k
                          *PathI))
3102
0
      return false;
3103
8.68k
    Type = (*PathI)->getType();
3104
8.68k
  }
3105
4.52k
  return true;
3106
4.52k
}
3107
3108
/// Cast an lvalue referring to a derived class to a known base subobject.
3109
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3110
                            const CXXRecordDecl *DerivedRD,
3111
42
                            const CXXRecordDecl *BaseRD) {
3112
42
  CXXBasePaths Paths(/*FindAmbiguities=*/false,
3113
42
                     /*RecordPaths=*/true, /*DetectVirtual=*/false);
3114
42
  if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3115
0
    llvm_unreachable("Class must be derived from the passed in base class!");
3116
3117
42
  for (CXXBasePathElement &Elem : Paths.front())
3118
63
    if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3119
0
      return false;
3120
42
  return true;
3121
42
}
3122
3123
/// Update LVal to refer to the given field, which must be a member of the type
3124
/// currently described by LVal.
3125
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3126
                               const FieldDecl *FD,
3127
162k
                               const ASTRecordLayout *RL = nullptr) {
3128
162k
  if (!RL) {
3129
128k
    if (FD->getParent()->isInvalidDecl()) 
return false3
;
3130
128k
    RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3131
128k
  }
3132
3133
162k
  unsigned I = FD->getFieldIndex();
3134
162k
  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3135
162k
  LVal.addDecl(Info, E, FD);
3136
162k
  return true;
3137
162k
}
3138
3139
/// Update LVal to refer to the given indirect field.
3140
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3141
                                       LValue &LVal,
3142
0
                                       const IndirectFieldDecl *IFD) {
3143
0
  for (const auto *C : IFD->chain())
3144
0
    if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3145
0
      return false;
3146
0
  return true;
3147
0
}
3148
3149
/// Get the size of the given type in char units.
3150
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3151
254k
                         QualType Type, CharUnits &Size) {
3152
  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3153
  // extension.
3154
254k
  if (Type->isVoidType() || 
Type->isFunctionType()254k
) {
3155
146
    Size = CharUnits::One();
3156
146
    return true;
3157
146
  }
3158
3159
254k
  if (Type->isDependentType()) {
3160
0
    Info.FFDiag(Loc);
3161
0
    return false;
3162
0
  }
3163
3164
254k
  if (!Type->isConstantSizeType()) {
3165
    // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3166
    // FIXME: Better diagnostic.
3167
2.13k
    Info.FFDiag(Loc);
3168
2.13k
    return false;
3169
2.13k
  }
3170
3171
252k
  Size = Info.Ctx.getTypeSizeInChars(Type);
3172
252k
  return true;
3173
254k
}
3174
3175
/// Update a pointer value to model pointer arithmetic.
3176
/// \param Info - Information about the ongoing evaluation.
3177
/// \param E - The expression being evaluated, for diagnostic purposes.
3178
/// \param LVal - The pointer value to be updated.
3179
/// \param EltTy - The pointee type represented by LVal.
3180
/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3181
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3182
                                        LValue &LVal, QualType EltTy,
3183
112k
                                        APSInt Adjustment) {
3184
112k
  CharUnits SizeOfPointee;
3185
112k
  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3186
1.95k
    return false;
3187
3188
110k
  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3189
110k
  return true;
3190
112k
}
3191
3192
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3193
                                        LValue &LVal, QualType EltTy,
3194
75.8k
                                        int64_t Adjustment) {
3195
75.8k
  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3196
75.8k
                                     APSInt::get(Adjustment));
3197
75.8k
}
3198
3199
/// Update an lvalue to refer to a component of a complex number.
3200
/// \param Info - Information about the ongoing evaluation.
3201
/// \param LVal - The lvalue to be updated.
3202
/// \param EltTy - The complex number's component type.
3203
/// \param Imag - False for the real component, true for the imaginary.
3204
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3205
                                       LValue &LVal, QualType EltTy,
3206
233
                                       bool Imag) {
3207
233
  if (Imag) {
3208
111
    CharUnits SizeOfComponent;
3209
111
    if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3210
0
      return false;
3211
111
    LVal.Offset += SizeOfComponent;
3212
111
  }
3213
233
  LVal.addComplex(Info, E, EltTy, Imag);
3214
233
  return true;
3215
233
}
3216
3217
/// Try to evaluate the initializer for a variable declaration.
3218
///
3219
/// \param Info   Information about the ongoing evaluation.
3220
/// \param E      An expression to be used when printing diagnostics.
3221
/// \param VD     The variable whose initializer should be obtained.
3222
/// \param Version The version of the variable within the frame.
3223
/// \param Frame  The frame in which the variable was created. Must be null
3224
///               if this variable is not local to the evaluation.
3225
/// \param Result Filled in with a pointer to the value of the variable.
3226
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3227
                                const VarDecl *VD, CallStackFrame *Frame,
3228
3.51M
                                unsigned Version, APValue *&Result) {
3229
3.51M
  APValue::LValueBase Base(VD, Frame ? 
Frame->Index285k
:
03.22M
, Version);
3230
3231
  // If this is a local variable, dig out its value.
3232
3.51M
  if (Frame) {
3233
285k
    Result = Frame->getTemporary(VD, Version);
3234
285k
    if (Result)
3235
282k
      return true;
3236
3237
3.66k
    if (!isa<ParmVarDecl>(VD)) {
3238
      // Assume variables referenced within a lambda's call operator that were
3239
      // not declared within the call operator are captures and during checking
3240
      // of a potential constant expression, assume they are unknown constant
3241
      // expressions.
3242
0
      assert(isLambdaCallOperator(Frame->Callee) &&
3243
0
             (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3244
0
             "missing value for local variable");
3245
0
      if (Info.checkingPotentialConstantExpression())
3246
0
        return false;
3247
      // FIXME: This diagnostic is bogus; we do support captures. Is this code
3248
      // still reachable at all?
3249
0
      Info.FFDiag(E->getBeginLoc(),
3250
0
                  diag::note_unimplemented_constexpr_lambda_feature_ast)
3251
0
          << "captures not currently allowed";
3252
0
      return false;
3253
0
    }
3254
3.66k
  }
3255
3256
  // If we're currently evaluating the initializer of this declaration, use that
3257
  // in-flight value.
3258
3.23M
  if (Info.EvaluatingDecl == Base) {
3259
84
    Result = Info.EvaluatingDeclValue;
3260
84
    return true;
3261
84
  }
3262
3263
3.23M
  if (isa<ParmVarDecl>(VD)) {
3264
    // Assume parameters of a potential constant expression are usable in
3265
    // constant expressions.
3266
1.69M
    if (!Info.checkingPotentialConstantExpression() ||
3267
1.69M
        
!Info.CurrentCall->Callee51.1k
||
3268
1.69M
        
!Info.CurrentCall->Callee->Equals(VD->getDeclContext())51.1k
) {
3269
1.64M
      if (Info.getLangOpts().CPlusPlus11) {
3270
1.00M
        Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3271
1.00M
            << VD;
3272
1.00M
        NoteLValueLocation(Info, Base);
3273
1.00M
      } else {
3274
642k
        Info.FFDiag(E);
3275
642k
      }
3276
1.64M
    }
3277
1.69M
    return false;
3278
1.69M
  }
3279
3280
  // Dig out the initializer, and use the declaration which it's attached to.
3281
  // FIXME: We should eventually check whether the variable has a reachable
3282
  // initializing declaration.
3283
1.53M
  const Expr *Init = VD->getAnyInitializer(VD);
3284
1.53M
  if (!Init) {
3285
    // Don't diagnose during potential constant expression checking; an
3286
    // initializer might be added later.
3287
100k
    if (!Info.checkingPotentialConstantExpression()) {
3288
100k
      Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3289
100k
        << VD;
3290
100k
      NoteLValueLocation(Info, Base);
3291
100k
    }
3292
100k
    return false;
3293
100k
  }
3294
3295
1.43M
  if (Init->isValueDependent()) {
3296
    // The DeclRefExpr is not value-dependent, but the variable it refers to
3297
    // has a value-dependent initializer. This should only happen in
3298
    // constant-folding cases, where the variable is not actually of a suitable
3299
    // type for use in a constant expression (otherwise the DeclRefExpr would
3300
    // have been value-dependent too), so diagnose that.
3301
2
    assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3302
2
    if (!Info.checkingPotentialConstantExpression()) {
3303
2
      Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3304
2
                         ? 
diag::note_constexpr_ltor_non_constexpr0
3305
2
                         : diag::note_constexpr_ltor_non_integral, 1)
3306
2
          << VD << VD->getType();
3307
2
      NoteLValueLocation(Info, Base);
3308
2
    }
3309
2
    return false;
3310
2
  }
3311
3312
  // Check that we can fold the initializer. In C++, we will have already done
3313
  // this in the cases where it matters for conformance.
3314
1.43M
  if (!VD->evaluateValue()) {
3315
131k
    Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3316
131k
    NoteLValueLocation(Info, Base);
3317
131k
    return false;
3318
131k
  }
3319
3320
  // Check that the variable is actually usable in constant expressions. For a
3321
  // const integral variable or a reference, we might have a non-constant
3322
  // initializer that we can nonetheless evaluate the initializer for. Such
3323
  // variables are not usable in constant expressions. In C++98, the
3324
  // initializer also syntactically needs to be an ICE.
3325
  //
3326
  // FIXME: We don't diagnose cases that aren't potentially usable in constant
3327
  // expressions here; doing so would regress diagnostics for things like
3328
  // reading from a volatile constexpr variable.
3329
1.30M
  if ((Info.getLangOpts().CPlusPlus && 
!VD->hasConstantInitialization()1.30M
&&
3330
1.30M
       
VD->mightBeUsableInConstantExpressions(Info.Ctx)614
) ||
3331
1.30M
      
(1.30M
(1.30M
Info.getLangOpts().CPlusPlus1.30M
||
Info.getLangOpts().OpenCL1.72k
) &&
3332
1.30M
       
!Info.getLangOpts().CPlusPlus111.30M
&&
!VD->hasICEInitializer(Info.Ctx)502
)) {
3333
108
    Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3334
108
    NoteLValueLocation(Info, Base);
3335
108
  }
3336
3337
  // Never use the initializer of a weak variable, not even for constant
3338
  // folding. We can't be sure that this is the definition that will be used.
3339
1.30M
  if (VD->isWeak()) {
3340
10
    Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3341
10
    NoteLValueLocation(Info, Base);
3342
10
    return false;
3343
10
  }
3344
3345
1.30M
  Result = VD->getEvaluatedValue();
3346
1.30M
  return true;
3347
1.30M
}
3348
3349
/// Get the base index of the given base class within an APValue representing
3350
/// the given derived class.
3351
static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3352
1.36k
                             const CXXRecordDecl *Base) {
3353
1.36k
  Base = Base->getCanonicalDecl();
3354
1.36k
  unsigned Index = 0;
3355
1.36k
  for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3356
1.70k
         E = Derived->bases_end(); I != E; 
++I, ++Index345
) {
3357
1.70k
    if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3358
1.36k
      return Index;
3359
1.70k
  }
3360
3361
0
  llvm_unreachable("base class missing from derived class's bases list");
3362
0
}
3363
3364
/// Extract the value of a character from a string literal.
3365
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3366
23.2k
                                            uint64_t Index) {
3367
23.2k
  assert(!isa<SourceLocExpr>(Lit) &&
3368
23.2k
         "SourceLocExpr should have already been converted to a StringLiteral");
3369
3370
  // FIXME: Support MakeStringConstant
3371
23.2k
  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3372
0
    std::string Str;
3373
0
    Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3374
0
    assert(Index <= Str.size() && "Index too large");
3375
0
    return APSInt::getUnsigned(Str.c_str()[Index]);
3376
0
  }
3377
3378
23.2k
  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3379
185
    Lit = PE->getFunctionName();
3380
23.2k
  const StringLiteral *S = cast<StringLiteral>(Lit);
3381
23.2k
  const ConstantArrayType *CAT =
3382
23.2k
      Info.Ctx.getAsConstantArrayType(S->getType());
3383
23.2k
  assert(CAT && "string literal isn't an array");
3384
0
  QualType CharType = CAT->getElementType();
3385
23.2k
  assert(CharType->isIntegerType() && "unexpected character type");
3386
3387
0
  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3388
23.2k
               CharType->isUnsignedIntegerType());
3389
23.2k
  if (Index < S->getLength())
3390
22.0k
    Value = S->getCodeUnit(Index);
3391
23.2k
  return Value;
3392
23.2k
}
3393
3394
// Expand a string literal into an array of characters.
3395
//
3396
// FIXME: This is inefficient; we should probably introduce something similar
3397
// to the LLVM ConstantDataArray to make this cheaper.
3398
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3399
                                APValue &Result,
3400
1.62k
                                QualType AllocType = QualType()) {
3401
1.62k
  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3402
1.62k
      AllocType.isNull() ? 
S->getType()1.60k
:
AllocType19
);
3403
1.62k
  assert(CAT && "string literal isn't an array");
3404
0
  QualType CharType = CAT->getElementType();
3405
1.62k
  assert(CharType->isIntegerType() && "unexpected character type");
3406
3407
0
  unsigned Elts = CAT->getSize().getZExtValue();
3408
1.62k
  Result = APValue(APValue::UninitArray(),
3409
1.62k
                   std::min(S->getLength(), Elts), Elts);
3410
1.62k
  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3411
1.62k
               CharType->isUnsignedIntegerType());
3412
1.62k
  if (Result.hasArrayFiller())
3413
1.61k
    Result.getArrayFiller() = APValue(Value);
3414
66.6k
  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; 
++I65.0k
) {
3415
65.0k
    Value = S->getCodeUnit(I);
3416
65.0k
    Result.getArrayInitializedElt(I) = APValue(Value);
3417
65.0k
  }
3418
1.62k
}
3419
3420
// Expand an array so that it has more than Index filled elements.
3421
343
static void expandArray(APValue &Array, unsigned Index) {
3422
343
  unsigned Size = Array.getArraySize();
3423
343
  assert(Index < Size);
3424
3425
  // Always at least double the number of elements for which we store a value.
3426
0
  unsigned OldElts = Array.getArrayInitializedElts();
3427
343
  unsigned NewElts = std::max(Index+1, OldElts * 2);
3428
343
  NewElts = std::min(Size, std::max(NewElts, 8u));
3429
3430
  // Copy the data across.
3431
343
  APValue NewValue(APValue::UninitArray(), NewElts, Size);
3432
1.46k
  for (unsigned I = 0; I != OldElts; 
++I1.12k
)
3433
1.12k
    NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3434
34.9k
  for (unsigned I = OldElts; I != NewElts; 
++I34.6k
)
3435
34.6k
    NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3436
343
  if (NewValue.hasArrayFiller())
3437
43
    NewValue.getArrayFiller() = Array.getArrayFiller();
3438
343
  Array.swap(NewValue);
3439
343
}
3440
3441
/// Determine whether a type would actually be read by an lvalue-to-rvalue
3442
/// conversion. If it's of class type, we may assume that the copy operation
3443
/// is trivial. Note that this is never true for a union type with fields
3444
/// (because the copy always "reads" the active member) and always true for
3445
/// a non-class type.
3446
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3447
1.70k
static bool isReadByLvalueToRvalueConversion(QualType T) {
3448
1.70k
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3449
1.70k
  return !RD || 
isReadByLvalueToRvalueConversion(RD)169
;
3450
1.70k
}
3451
2.35k
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3452
  // FIXME: A trivial copy of a union copies the object representation, even if
3453
  // the union is empty.
3454
2.35k
  if (RD->isUnion())
3455
22
    return !RD->field_empty();
3456
2.32k
  if (RD->isEmpty())
3457
707
    return false;
3458
3459
1.62k
  for (auto *Field : RD->fields())
3460
1.66k
    if (!Field->isUnnamedBitfield() &&
3461
1.66k
        
isReadByLvalueToRvalueConversion(Field->getType())1.66k
)
3462
1.59k
      return true;
3463
3464
28
  for (auto &BaseSpec : RD->bases())
3465
20
    if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3466
14
      return true;
3467
3468
14
  return false;
3469
28
}
3470
3471
/// Diagnose an attempt to read from any unreadable field within the specified
3472
/// type, which might be a class type.
3473
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3474
687
                                  QualType T) {
3475
687
  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3476
687
  if (!RD)
3477
18
    return false;
3478
3479
669
  if (!RD->hasMutableFields())
3480
650
    return false;
3481
3482
35
  
for (auto *Field : RD->fields())19
{
3483
    // If we're actually going to read this field in some way, then it can't
3484
    // be mutable. If we're in a union, then assigning to a mutable field
3485
    // (even an empty one) can change the active member, so that's not OK.
3486
    // FIXME: Add core issue number for the union case.
3487
35
    if (Field->isMutable() &&
3488
35
        
(22
RD->isUnion()22
||
isReadByLvalueToRvalueConversion(Field->getType())16
)) {
3489
13
      Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3490
13
      Info.Note(Field->getLocation(), diag::note_declared_at);
3491
13
      return true;
3492
13
    }
3493
3494
22
    if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3495
3
      return true;
3496
22
  }
3497
3498
3
  for (auto &BaseSpec : RD->bases())
3499
0
    if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3500
0
      return true;
3501
3502
  // All mutable fields were empty, and thus not actually read.
3503
3
  return false;
3504
3
}
3505
3506
static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3507
                                        APValue::LValueBase Base,
3508
1.57M
                                        bool MutableSubobject = false) {
3509
  // A temporary or transient heap allocation we created.
3510
1.57M
  if (Base.getCallIndex() || 
Base.is<DynamicAllocLValue>()1.57M
)
3511
792
    return true;
3512
3513
1.57M
  switch (Info.IsEvaluatingDecl) {
3514
1.53M
  case EvalInfo::EvaluatingDeclKind::None:
3515
1.53M
    return false;
3516
3517
39.0k
  case EvalInfo::EvaluatingDeclKind::Ctor:
3518
    // The variable whose initializer we're evaluating.
3519
39.0k
    if (Info.EvaluatingDecl == Base)
3520
463
      return true;
3521
3522
    // A temporary lifetime-extended by the variable whose initializer we're
3523
    // evaluating.
3524
38.6k
    if (auto *BaseE = Base.dyn_cast<const Expr *>())
3525
56
      if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3526
56
        return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3527
38.5k
    return false;
3528
3529
109
  case EvalInfo::EvaluatingDeclKind::Dtor:
3530
    // C++2a [expr.const]p6:
3531
    //   [during constant destruction] the lifetime of a and its non-mutable
3532
    //   subobjects (but not its mutable subobjects) [are] considered to start
3533
    //   within e.
3534
109
    if (MutableSubobject || 
Base != Info.EvaluatingDecl106
)
3535
8
      return false;
3536
    // FIXME: We can meaningfully extend this to cover non-const objects, but
3537
    // we will need special handling: we should be able to access only
3538
    // subobjects of such objects that are themselves declared const.
3539
101
    QualType T = getType(Base);
3540
101
    return T.isConstQualified() || 
T->isReferenceType()34
;
3541
1.57M
  }
3542
3543
0
  llvm_unreachable("unknown evaluating decl kind");
3544
0
}
3545
3546
namespace {
3547
/// A handle to a complete object (an object that is not a subobject of
3548
/// another object).
3549
struct CompleteObject {
3550
  /// The identity of the object.
3551
  APValue::LValueBase Base;
3552
  /// The value of the complete object.
3553
  APValue *Value;
3554
  /// The type of the complete object.
3555
  QualType Type;
3556
3557
5.01M
  CompleteObject() : Value(nullptr) {}
3558
  CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3559
1.61M
      : Base(Base), Value(Value), Type(Type) {}
3560
3561
20.3k
  bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3562
    // If this isn't a "real" access (eg, if it's just accessing the type
3563
    // info), allow it. We assume the type doesn't change dynamically for
3564
    // subobjects of constexpr objects (even though we'd hit UB here if it
3565
    // did). FIXME: Is this right?
3566
20.3k
    if (!isAnyAccess(AK))
3567
18.8k
      return true;
3568
3569
    // In C++14 onwards, it is permitted to read a mutable member whose
3570
    // lifetime began within the evaluation.
3571
    // FIXME: Should we also allow this in C++11?
3572
1.49k
    if (!Info.getLangOpts().CPlusPlus14)
3573
84
      return false;
3574
1.41k
    return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3575
1.49k
  }
3576
3577
6.64M
  explicit operator bool() const { return !Type.isNull(); }
3578
};
3579
} // end anonymous namespace
3580
3581
static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3582
23.3k
                                 bool IsMutable = false) {
3583
  // C++ [basic.type.qualifier]p1:
3584
  // - A const object is an object of type const T or a non-mutable subobject
3585
  //   of a const object.
3586
23.3k
  if (ObjType.isConstQualified() && 
!IsMutable15.2k
)
3587
15.2k
    SubobjType.addConst();
3588
  // - A volatile object is an object of type const T or a subobject of a
3589
  //   volatile object.
3590
23.3k
  if (ObjType.isVolatileQualified())
3591
11
    SubobjType.addVolatile();
3592
23.3k
  return SubobjType;
3593
23.3k
}
3594
3595
/// Find the designated sub-object of an rvalue.
3596
template<typename SubobjectHandler>
3597
typename SubobjectHandler::result_type
3598
findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3599
1.59M
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600
1.59M
  if (Sub.Invalid)
3601
    // A diagnostic will have already been produced.
3602
0
    return handler.failed();
3603
1.59M
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()1.59M
) {
3604
300
    if (Info.getLangOpts().CPlusPlus11)
3605
300
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3606
300
                         ? diag::note_constexpr_access_past_end
3607
300
                         : 
diag::note_constexpr_access_unsized_array0
)
3608
300
          << handler.AccessKind;
3609
0
    else
3610
0
      Info.FFDiag(E);
3611
300
    return handler.failed();
3612
300
  }
3613
3614
1.59M
  APValue *O = Obj.Value;
3615
1.59M
  QualType ObjType = Obj.Type;
3616
1.59M
  const FieldDecl *LastField = nullptr;
3617
1.59M
  const FieldDecl *VolatileField = nullptr;
3618
3619
  // Walk the designator's path to find the subobject.
3620
1.62M
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I38.5k
) {
3621
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3622
1.62M
    if ((O->isAbsent() && 
!(363
handler.AccessKind == AK_Construct363
&&
I == N30
)) ||
3623
1.62M
        
(1.62M
O->isIndeterminate()1.62M
&&
3624
1.62M
         
!isValidIndeterminateAccess(handler.AccessKind)670
)) {
3625
397
      if (!Info.checkingPotentialConstantExpression())
3626
379
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627
379
            << handler.AccessKind << O->isIndeterminate();
3628
397
      return handler.failed();
3629
397
    }
3630
3631
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632
    //    const and volatile semantics are not applied on an object under
3633
    //    {con,de}struction.
3634
1.62M
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()272k
) &&
3635
1.62M
        
ObjType->isRecordType()1.35M
&&
3636
1.62M
        Info.isEvaluatingCtorDtor(
3637
28.2k
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638
28.2k
                                         Sub.Entries.begin() + I)) !=
3639
28.2k
                          ConstructionPhase::None) {
3640
367
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3641
367
      ObjType.removeLocalConst();
3642
367
      ObjType.removeLocalVolatile();
3643
367
    }
3644
3645
    // If this is our last pass, check that the final object type is OK.
3646
1.62M
    if (I == N || 
(38.9k
I == N - 138.9k
&&
ObjType->isAnyComplexType()32.7k
)) {
3647
      // Accesses to volatile objects are prohibited.
3648
1.59M
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)24
) {
3649
24
        if (Info.getLangOpts().CPlusPlus) {
3650
24
          int DiagKind;
3651
24
          SourceLocation Loc;
3652
24
          const NamedDecl *Decl = nullptr;
3653
24
          if (VolatileField) {
3654
0
            DiagKind = 2;
3655
0
            Loc = VolatileField->getLocation();
3656
0
            Decl = VolatileField;
3657
24
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658
21
            DiagKind = 1;
3659
21
            Loc = VD->getLocation();
3660
21
            Decl = VD;
3661
21
          } else {
3662
3
            DiagKind = 0;
3663
3
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664
3
              Loc = E->getExprLoc();
3665
3
          }
3666
24
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667
24
              << handler.AccessKind << DiagKind << Decl;
3668
24
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669
24
        } else {
3670
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671
0
        }
3672
24
        return handler.failed();
3673
24
      }
3674
3675
      // If we are reading an object of class type, there may still be more
3676
      // things we need to check: if there are any mutable subobjects, we
3677
      // cannot perform this read. (This only happens when performing a trivial
3678
      // copy or assignment.)
3679
1.59M
      if (ObjType->isRecordType() &&
3680
1.59M
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)20.3k
&&
3681
1.59M
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)665
)
3682
13
        return handler.failed();
3683
1.59M
    }
3684
3685
1.62M
    if (I == N) {
3686
1.59M
      if (!handler.found(*O, ObjType))
3687
37
        return false;
3688
3689
      // If we modified a bit-field, truncate it to the right width.
3690
1.59M
      if (isModification(handler.AccessKind) &&
3691
1.59M
          
LastField43.0k
&&
LastField->isBitField()1.18k
&&
3692
1.59M
          
!truncateBitfieldValue(Info, E, *O, LastField)24
)
3693
0
        return false;
3694
3695
1.59M
      return true;
3696
1.59M
    }
3697
3698
38.9k
    LastField = nullptr;
3699
38.9k
    if (ObjType->isArrayType()) {
3700
      // Next subobject is an array element.
3701
15.2k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702
15.2k
      assert(CAT && "vla in literal type?");
3703
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704
15.2k
      if (CAT->getSize().ule(Index)) {
3705
        // Note, it should not be possible to form a pointer with a valid
3706
        // designator which points more than one past the end of the array.
3707
0
        if (Info.getLangOpts().CPlusPlus11)
3708
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709
0
            << handler.AccessKind;
3710
0
        else
3711
0
          Info.FFDiag(E);
3712
0
        return handler.failed();
3713
0
      }
3714
3715
15.2k
      ObjType = CAT->getElementType();
3716
3717
15.2k
      if (O->getArrayInitializedElts() > Index)
3718
14.3k
        O = &O->getArrayInitializedElt(Index);
3719
926
      else if (!isRead(handler.AccessKind)) {
3720
170
        expandArray(*O, Index);
3721
170
        O = &O->getArrayInitializedElt(Index);
3722
170
      } else
3723
756
        O = &O->getArrayFiller();
3724
23.6k
    } else if (ObjType->isAnyComplexType()) {
3725
      // Next subobject is a complex number.
3726
24
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727
24
      if (Index > 1) {
3728
0
        if (Info.getLangOpts().CPlusPlus11)
3729
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730
0
            << handler.AccessKind;
3731
0
        else
3732
0
          Info.FFDiag(E);
3733
0
        return handler.failed();
3734
0
      }
3735
3736
24
      ObjType = getSubobjectType(
3737
24
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738
3739
24
      assert(I == N - 1 && "extracting subobject of scalar?");
3740
24
      if (O->isComplexInt()) {
3741
12
        return handler.found(Index ? 
O->getComplexIntImag()6
3742
12
                                   : 
O->getComplexIntReal()6
, ObjType);
3743
12
      } else {
3744
12
        assert(O->isComplexFloat());
3745
12
        return handler.found(Index ? 
O->getComplexFloatImag()6
3746
12
                                   : 
O->getComplexFloatReal()6
, ObjType);
3747
12
      }
3748
23.6k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749
22.3k
      if (Field->isMutable() &&
3750
22.3k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)40
) {
3751
29
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752
29
          << handler.AccessKind << Field;
3753
29
        Info.Note(Field->getLocation(), diag::note_declared_at);
3754
29
        return handler.failed();
3755
29
      }
3756
3757
      // Next subobject is a class, struct or union field.
3758
22.3k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759
22.3k
      if (RD->isUnion()) {
3760
988
        const FieldDecl *UnionField = O->getUnionField();
3761
988
        if (!UnionField ||
3762
988
            
UnionField->getCanonicalDecl() != Field->getCanonicalDecl()981
) {
3763
327
          if (I == N - 1 && 
handler.AccessKind == AK_Construct295
) {
3764
            // Placement new onto an inactive union member makes it active.
3765
3
            O->setUnion(Field, APValue());
3766
324
          } else {
3767
            // FIXME: If O->getUnionValue() is absent, report that there's no
3768
            // active union member rather than reporting the prior active union
3769
            // member. We'll need to fix nullptr_t to not use APValue() as its
3770
            // representation first.
3771
324
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772
324
                << handler.AccessKind << Field << !UnionField << UnionField;
3773
324
            return handler.failed();
3774
324
          }
3775
327
        }
3776
664
        O = &O->getUnionValue();
3777
664
      } else
3778
21.3k
        O = &O->getStructField(Field->getFieldIndex());
3779
3780
21.9k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781
21.9k
      LastField = Field;
3782
21.9k
      if (Field->getType().isVolatileQualified())
3783
0
        VolatileField = Field;
3784
21.9k
    } else {
3785
      // Next subobject is a base class.
3786
1.31k
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787
1.31k
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788
1.31k
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3789
3790
1.31k
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791
1.31k
    }
3792
38.9k
  }
3793
1.59M
}
ExprConstant.cpp:(anonymous namespace)::StartLifetimeOfUnionMemberHandler::result_type findSubobject<(anonymous namespace)::StartLifetimeOfUnionMemberHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::StartLifetimeOfUnionMemberHandler&)
Line
Count
Source
3599
149
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600
149
  if (Sub.Invalid)
3601
    // A diagnostic will have already been produced.
3602
0
    return handler.failed();
3603
149
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3604
0
    if (Info.getLangOpts().CPlusPlus11)
3605
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3606
0
                         ? diag::note_constexpr_access_past_end
3607
0
                         : diag::note_constexpr_access_unsized_array)
3608
0
          << handler.AccessKind;
3609
0
    else
3610
0
      Info.FFDiag(E);
3611
0
    return handler.failed();
3612
0
  }
3613
3614
149
  APValue *O = Obj.Value;
3615
149
  QualType ObjType = Obj.Type;
3616
149
  const FieldDecl *LastField = nullptr;
3617
149
  const FieldDecl *VolatileField = nullptr;
3618
3619
  // Walk the designator's path to find the subobject.
3620
173
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I24
) {
3621
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3622
173
    if ((O->isAbsent() && 
!(0
handler.AccessKind == AK_Construct0
&&
I == N0
)) ||
3623
173
        (O->isIndeterminate() &&
3624
173
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3625
0
      if (!Info.checkingPotentialConstantExpression())
3626
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627
0
            << handler.AccessKind << O->isIndeterminate();
3628
0
      return handler.failed();
3629
0
    }
3630
3631
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632
    //    const and volatile semantics are not applied on an object under
3633
    //    {con,de}struction.
3634
173
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3635
173
        
ObjType->isRecordType()0
&&
3636
173
        Info.isEvaluatingCtorDtor(
3637
0
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638
0
                                         Sub.Entries.begin() + I)) !=
3639
0
                          ConstructionPhase::None) {
3640
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3641
0
      ObjType.removeLocalConst();
3642
0
      ObjType.removeLocalVolatile();
3643
0
    }
3644
3645
    // If this is our last pass, check that the final object type is OK.
3646
173
    if (I == N || 
(26
I == N - 126
&&
ObjType->isAnyComplexType()10
)) {
3647
      // Accesses to volatile objects are prohibited.
3648
147
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3649
0
        if (Info.getLangOpts().CPlusPlus) {
3650
0
          int DiagKind;
3651
0
          SourceLocation Loc;
3652
0
          const NamedDecl *Decl = nullptr;
3653
0
          if (VolatileField) {
3654
0
            DiagKind = 2;
3655
0
            Loc = VolatileField->getLocation();
3656
0
            Decl = VolatileField;
3657
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658
0
            DiagKind = 1;
3659
0
            Loc = VD->getLocation();
3660
0
            Decl = VD;
3661
0
          } else {
3662
0
            DiagKind = 0;
3663
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664
0
              Loc = E->getExprLoc();
3665
0
          }
3666
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667
0
              << handler.AccessKind << DiagKind << Decl;
3668
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669
0
        } else {
3670
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671
0
        }
3672
0
        return handler.failed();
3673
0
      }
3674
3675
      // If we are reading an object of class type, there may still be more
3676
      // things we need to check: if there are any mutable subobjects, we
3677
      // cannot perform this read. (This only happens when performing a trivial
3678
      // copy or assignment.)
3679
147
      if (ObjType->isRecordType() &&
3680
147
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3681
147
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3682
0
        return handler.failed();
3683
147
    }
3684
3685
173
    if (I == N) {
3686
147
      if (!handler.found(*O, ObjType))
3687
3
        return false;
3688
3689
      // If we modified a bit-field, truncate it to the right width.
3690
144
      if (isModification(handler.AccessKind) &&
3691
144
          LastField && 
LastField->isBitField()10
&&
3692
144
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3693
0
        return false;
3694
3695
144
      return true;
3696
144
    }
3697
3698
26
    LastField = nullptr;
3699
26
    if (ObjType->isArrayType()) {
3700
      // Next subobject is an array element.
3701
0
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702
0
      assert(CAT && "vla in literal type?");
3703
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704
0
      if (CAT->getSize().ule(Index)) {
3705
        // Note, it should not be possible to form a pointer with a valid
3706
        // designator which points more than one past the end of the array.
3707
0
        if (Info.getLangOpts().CPlusPlus11)
3708
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709
0
            << handler.AccessKind;
3710
0
        else
3711
0
          Info.FFDiag(E);
3712
0
        return handler.failed();
3713
0
      }
3714
3715
0
      ObjType = CAT->getElementType();
3716
3717
0
      if (O->getArrayInitializedElts() > Index)
3718
0
        O = &O->getArrayInitializedElt(Index);
3719
0
      else if (!isRead(handler.AccessKind)) {
3720
0
        expandArray(*O, Index);
3721
0
        O = &O->getArrayInitializedElt(Index);
3722
0
      } else
3723
0
        O = &O->getArrayFiller();
3724
26
    } else if (ObjType->isAnyComplexType()) {
3725
      // Next subobject is a complex number.
3726
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727
0
      if (Index > 1) {
3728
0
        if (Info.getLangOpts().CPlusPlus11)
3729
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730
0
            << handler.AccessKind;
3731
0
        else
3732
0
          Info.FFDiag(E);
3733
0
        return handler.failed();
3734
0
      }
3735
3736
0
      ObjType = getSubobjectType(
3737
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738
3739
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3740
0
      if (O->isComplexInt()) {
3741
0
        return handler.found(Index ? O->getComplexIntImag()
3742
0
                                   : O->getComplexIntReal(), ObjType);
3743
0
      } else {
3744
0
        assert(O->isComplexFloat());
3745
0
        return handler.found(Index ? O->getComplexFloatImag()
3746
0
                                   : O->getComplexFloatReal(), ObjType);
3747
0
      }
3748
26
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749
22
      if (Field->isMutable() &&
3750
22
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3751
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752
0
          << handler.AccessKind << Field;
3753
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3754
0
        return handler.failed();
3755
0
      }
3756
3757
      // Next subobject is a class, struct or union field.
3758
22
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759
22
      if (RD->isUnion()) {
3760
6
        const FieldDecl *UnionField = O->getUnionField();
3761
6
        if (!UnionField ||
3762
6
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3763
2
          if (I == N - 1 && 
handler.AccessKind == AK_Construct0
) {
3764
            // Placement new onto an inactive union member makes it active.
3765
0
            O->setUnion(Field, APValue());
3766
2
          } else {
3767
            // FIXME: If O->getUnionValue() is absent, report that there's no
3768
            // active union member rather than reporting the prior active union
3769
            // member. We'll need to fix nullptr_t to not use APValue() as its
3770
            // representation first.
3771
2
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772
2
                << handler.AccessKind << Field << !UnionField << UnionField;
3773
2
            return handler.failed();
3774
2
          }
3775
2
        }
3776
4
        O = &O->getUnionValue();
3777
4
      } else
3778
16
        O = &O->getStructField(Field->getFieldIndex());
3779
3780
20
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781
20
      LastField = Field;
3782
20
      if (Field->getType().isVolatileQualified())
3783
0
        VolatileField = Field;
3784
20
    } else {
3785
      // Next subobject is a base class.
3786
4
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787
4
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788
4
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3789
3790
4
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791
4
    }
3792
26
  }
3793
149
}
ExprConstant.cpp:(anonymous namespace)::ModifySubobjectHandler::result_type findSubobject<(anonymous namespace)::ModifySubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::ModifySubobjectHandler&)
Line
Count
Source
3599
4.16k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600
4.16k
  if (Sub.Invalid)
3601
    // A diagnostic will have already been produced.
3602
0
    return handler.failed();
3603
4.16k
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()4.15k
) {
3604
12
    if (Info.getLangOpts().CPlusPlus11)
3605
12
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3606
12
                         ? diag::note_constexpr_access_past_end
3607
12
                         : 
diag::note_constexpr_access_unsized_array0
)
3608
12
          << handler.AccessKind;
3609
0
    else
3610
0
      Info.FFDiag(E);
3611
12
    return handler.failed();
3612
12
  }
3613
3614
4.15k
  APValue *O = Obj.Value;
3615
4.15k
  QualType ObjType = Obj.Type;
3616
4.15k
  const FieldDecl *LastField = nullptr;
3617
4.15k
  const FieldDecl *VolatileField = nullptr;
3618
3619
  // Walk the designator's path to find the subobject.
3620
7.44k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I3.29k
) {
3621
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3622
7.44k
    if ((O->isAbsent() && 
!(53
handler.AccessKind == AK_Construct53
&&
I == N0
)) ||
3623
7.44k
        
(7.39k
O->isIndeterminate()7.39k
&&
3624
7.39k
         
!isValidIndeterminateAccess(handler.AccessKind)598
)) {
3625
53
      if (!Info.checkingPotentialConstantExpression())
3626
50
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627
50
            << handler.AccessKind << O->isIndeterminate();
3628
53
      return handler.failed();
3629
53
    }
3630
3631
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632
    //    const and volatile semantics are not applied on an object under
3633
    //    {con,de}struction.
3634
7.39k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()7.23k
) &&
3635
7.39k
        
ObjType->isRecordType()179
&&
3636
7.39k
        Info.isEvaluatingCtorDtor(
3637
153
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638
153
                                         Sub.Entries.begin() + I)) !=
3639
153
                          ConstructionPhase::None) {
3640
147
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3641
147
      ObjType.removeLocalConst();
3642
147
      ObjType.removeLocalVolatile();
3643
147
    }
3644
3645
    // If this is our last pass, check that the final object type is OK.
3646
7.39k
    if (I == N || 
(3.30k
I == N - 13.30k
&&
ObjType->isAnyComplexType()2.66k
)) {
3647
      // Accesses to volatile objects are prohibited.
3648
4.09k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3649
0
        if (Info.getLangOpts().CPlusPlus) {
3650
0
          int DiagKind;
3651
0
          SourceLocation Loc;
3652
0
          const NamedDecl *Decl = nullptr;
3653
0
          if (VolatileField) {
3654
0
            DiagKind = 2;
3655
0
            Loc = VolatileField->getLocation();
3656
0
            Decl = VolatileField;
3657
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658
0
            DiagKind = 1;
3659
0
            Loc = VD->getLocation();
3660
0
            Decl = VD;
3661
0
          } else {
3662
0
            DiagKind = 0;
3663
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664
0
              Loc = E->getExprLoc();
3665
0
          }
3666
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667
0
              << handler.AccessKind << DiagKind << Decl;
3668
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669
0
        } else {
3670
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671
0
        }
3672
0
        return handler.failed();
3673
0
      }
3674
3675
      // If we are reading an object of class type, there may still be more
3676
      // things we need to check: if there are any mutable subobjects, we
3677
      // cannot perform this read. (This only happens when performing a trivial
3678
      // copy or assignment.)
3679
4.09k
      if (ObjType->isRecordType() &&
3680
4.09k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)68
&&
3681
4.09k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3682
0
        return handler.failed();
3683
4.09k
    }
3684
3685
7.39k
    if (I == N) {
3686
4.09k
      if (!handler.found(*O, ObjType))
3687
21
        return false;
3688
3689
      // If we modified a bit-field, truncate it to the right width.
3690
4.07k
      if (isModification(handler.AccessKind) &&
3691
4.07k
          LastField && 
LastField->isBitField()945
&&
3692
4.07k
          
!truncateBitfieldValue(Info, E, *O, LastField)6
)
3693
0
        return false;
3694
3695
4.07k
      return true;
3696
4.07k
    }
3697
3698
3.30k
    LastField = nullptr;
3699
3.30k
    if (ObjType->isArrayType()) {
3700
      // Next subobject is an array element.
3701
1.74k
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702
1.74k
      assert(CAT && "vla in literal type?");
3703
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704
1.74k
      if (CAT->getSize().ule(Index)) {
3705
        // Note, it should not be possible to form a pointer with a valid
3706
        // designator which points more than one past the end of the array.
3707
0
        if (Info.getLangOpts().CPlusPlus11)
3708
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709
0
            << handler.AccessKind;
3710
0
        else
3711
0
          Info.FFDiag(E);
3712
0
        return handler.failed();
3713
0
      }
3714
3715
1.74k
      ObjType = CAT->getElementType();
3716
3717
1.74k
      if (O->getArrayInitializedElts() > Index)
3718
1.57k
        O = &O->getArrayInitializedElt(Index);
3719
164
      else if (!isRead(handler.AccessKind)) {
3720
164
        expandArray(*O, Index);
3721
164
        O = &O->getArrayInitializedElt(Index);
3722
164
      } else
3723
0
        O = &O->getArrayFiller();
3724
1.74k
    } else 
if (1.56k
ObjType->isAnyComplexType()1.56k
) {
3725
      // Next subobject is a complex number.
3726
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727
0
      if (Index > 1) {
3728
0
        if (Info.getLangOpts().CPlusPlus11)
3729
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730
0
            << handler.AccessKind;
3731
0
        else
3732
0
          Info.FFDiag(E);
3733
0
        return handler.failed();
3734
0
      }
3735
3736
0
      ObjType = getSubobjectType(
3737
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738
3739
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3740
0
      if (O->isComplexInt()) {
3741
0
        return handler.found(Index ? O->getComplexIntImag()
3742
0
                                   : O->getComplexIntReal(), ObjType);
3743
0
      } else {
3744
0
        assert(O->isComplexFloat());
3745
0
        return handler.found(Index ? O->getComplexFloatImag()
3746
0
                                   : O->getComplexFloatReal(), ObjType);
3747
0
      }
3748
1.56k
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749
1.49k
      if (Field->isMutable() &&
3750
1.49k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)1
) {
3751
1
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752
1
          << handler.AccessKind << Field;
3753
1
        Info.Note(Field->getLocation(), diag::note_declared_at);
3754
1
        return handler.failed();
3755
1
      }
3756
3757
      // Next subobject is a class, struct or union field.
3758
1.49k
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759
1.49k
      if (RD->isUnion()) {
3760
177
        const FieldDecl *UnionField = O->getUnionField();
3761
177
        if (!UnionField ||
3762
177
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3763
7
          if (I == N - 1 && 
handler.AccessKind == AK_Construct1
) {
3764
            // Placement new onto an inactive union member makes it active.
3765
0
            O->setUnion(Field, APValue());
3766
7
          } else {
3767
            // FIXME: If O->getUnionValue() is absent, report that there's no
3768
            // active union member rather than reporting the prior active union
3769
            // member. We'll need to fix nullptr_t to not use APValue() as its
3770
            // representation first.
3771
7
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772
7
                << handler.AccessKind << Field << !UnionField << UnionField;
3773
7
            return handler.failed();
3774
7
          }
3775
7
        }
3776
170
        O = &O->getUnionValue();
3777
170
      } else
3778
1.32k
        O = &O->getStructField(Field->getFieldIndex());
3779
3780
1.49k
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781
1.49k
      LastField = Field;
3782
1.49k
      if (Field->getType().isVolatileQualified())
3783
0
        VolatileField = Field;
3784
1.49k
    } else {
3785
      // Next subobject is a base class.
3786
65
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787
65
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788
65
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3789
3790
65
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791
65
    }
3792
3.30k
  }
3793
4.15k
}
ExprConstant.cpp:(anonymous namespace)::IncDecSubobjectHandler::result_type findSubobject<(anonymous namespace)::IncDecSubobjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::IncDecSubobjectHandler&)
Line
Count
Source
3599
33.7k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600
33.7k
  if (Sub.Invalid)
3601
    // A diagnostic will have already been produced.
3602
0
    return handler.failed();
3603
33.7k
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3604
0
    if (Info.getLangOpts().CPlusPlus11)
3605
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3606
0
                         ? diag::note_constexpr_access_past_end
3607
0
                         : diag::note_constexpr_access_unsized_array)
3608
0
          << handler.AccessKind;
3609
0
    else
3610
0
      Info.FFDiag(E);
3611
0
    return handler.failed();
3612
0
  }
3613
3614
33.7k
  APValue *O = Obj.Value;
3615
33.7k
  QualType ObjType = Obj.Type;
3616
33.7k
  const FieldDecl *LastField = nullptr;
3617
33.7k
  const FieldDecl *VolatileField = nullptr;
3618
3619
  // Walk the designator's path to find the subobject.
3620
34.0k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I243
) {
3621
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3622
34.0k
    if ((O->isAbsent() && 
!(17
handler.AccessKind == AK_Construct17
&&
I == N0
)) ||
3623
34.0k
        
(34.0k
O->isIndeterminate()34.0k
&&
3624
34.0k
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3625
17
      if (!Info.checkingPotentialConstantExpression())
3626
14
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627
14
            << handler.AccessKind << O->isIndeterminate();
3628
17
      return handler.failed();
3629
17
    }
3630
3631
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632
    //    const and volatile semantics are not applied on an object under
3633
    //    {con,de}struction.
3634
34.0k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()34.0k
) &&
3635
34.0k
        
ObjType->isRecordType()18
&&
3636
34.0k
        Info.isEvaluatingCtorDtor(
3637
18
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638
18
                                         Sub.Entries.begin() + I)) !=
3639
18
                          ConstructionPhase::None) {
3640
18
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3641
18
      ObjType.removeLocalConst();
3642
18
      ObjType.removeLocalVolatile();
3643
18
    }
3644
3645
    // If this is our last pass, check that the final object type is OK.
3646
34.0k
    if (I == N || 
(249
I == N - 1249
&&
ObjType->isAnyComplexType()190
)) {
3647
      // Accesses to volatile objects are prohibited.
3648
33.7k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3649
0
        if (Info.getLangOpts().CPlusPlus) {
3650
0
          int DiagKind;
3651
0
          SourceLocation Loc;
3652
0
          const NamedDecl *Decl = nullptr;
3653
0
          if (VolatileField) {
3654
0
            DiagKind = 2;
3655
0
            Loc = VolatileField->getLocation();
3656
0
            Decl = VolatileField;
3657
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658
0
            DiagKind = 1;
3659
0
            Loc = VD->getLocation();
3660
0
            Decl = VD;
3661
0
          } else {
3662
0
            DiagKind = 0;
3663
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664
0
              Loc = E->getExprLoc();
3665
0
          }
3666
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667
0
              << handler.AccessKind << DiagKind << Decl;
3668
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669
0
        } else {
3670
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671
0
        }
3672
0
        return handler.failed();
3673
0
      }
3674
3675
      // If we are reading an object of class type, there may still be more
3676
      // things we need to check: if there are any mutable subobjects, we
3677
      // cannot perform this read. (This only happens when performing a trivial
3678
      // copy or assignment.)
3679
33.7k
      if (ObjType->isRecordType() &&
3680
33.7k
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
&&
3681
33.7k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3682
0
        return handler.failed();
3683
33.7k
    }
3684
3685
34.0k
    if (I == N) {
3686
33.7k
      if (!handler.found(*O, ObjType))
3687
4
        return false;
3688
3689
      // If we modified a bit-field, truncate it to the right width.
3690
33.7k
      if (isModification(handler.AccessKind) &&
3691
33.7k
          LastField && 
LastField->isBitField()184
&&
3692
33.7k
          
!truncateBitfieldValue(Info, E, *O, LastField)12
)
3693
0
        return false;
3694
3695
33.7k
      return true;
3696
33.7k
    }
3697
3698
249
    LastField = nullptr;
3699
249
    if (ObjType->isArrayType()) {
3700
      // Next subobject is an array element.
3701
7
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702
7
      assert(CAT && "vla in literal type?");
3703
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704
7
      if (CAT->getSize().ule(Index)) {
3705
        // Note, it should not be possible to form a pointer with a valid
3706
        // designator which points more than one past the end of the array.
3707
0
        if (Info.getLangOpts().CPlusPlus11)
3708
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709
0
            << handler.AccessKind;
3710
0
        else
3711
0
          Info.FFDiag(E);
3712
0
        return handler.failed();
3713
0
      }
3714
3715
7
      ObjType = CAT->getElementType();
3716
3717
7
      if (O->getArrayInitializedElts() > Index)
3718
7
        O = &O->getArrayInitializedElt(Index);
3719
0
      else if (!isRead(handler.AccessKind)) {
3720
0
        expandArray(*O, Index);
3721
0
        O = &O->getArrayInitializedElt(Index);
3722
0
      } else
3723
0
        O = &O->getArrayFiller();
3724
242
    } else if (ObjType->isAnyComplexType()) {
3725
      // Next subobject is a complex number.
3726
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727
0
      if (Index > 1) {
3728
0
        if (Info.getLangOpts().CPlusPlus11)
3729
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730
0
            << handler.AccessKind;
3731
0
        else
3732
0
          Info.FFDiag(E);
3733
0
        return handler.failed();
3734
0
      }
3735
3736
0
      ObjType = getSubobjectType(
3737
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738
3739
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3740
0
      if (O->isComplexInt()) {
3741
0
        return handler.found(Index ? O->getComplexIntImag()
3742
0
                                   : O->getComplexIntReal(), ObjType);
3743
0
      } else {
3744
0
        assert(O->isComplexFloat());
3745
0
        return handler.found(Index ? O->getComplexFloatImag()
3746
0
                                   : O->getComplexFloatReal(), ObjType);
3747
0
      }
3748
242
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749
216
      if (Field->isMutable() &&
3750
216
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3751
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752
0
          << handler.AccessKind << Field;
3753
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3754
0
        return handler.failed();
3755
0
      }
3756
3757
      // Next subobject is a class, struct or union field.
3758
216
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759
216
      if (RD->isUnion()) {
3760
25
        const FieldDecl *UnionField = O->getUnionField();
3761
25
        if (!UnionField ||
3762
25
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3763
6
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3764
            // Placement new onto an inactive union member makes it active.
3765
0
            O->setUnion(Field, APValue());
3766
6
          } else {
3767
            // FIXME: If O->getUnionValue() is absent, report that there's no
3768
            // active union member rather than reporting the prior active union
3769
            // member. We'll need to fix nullptr_t to not use APValue() as its
3770
            // representation first.
3771
6
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772
6
                << handler.AccessKind << Field << !UnionField << UnionField;
3773
6
            return handler.failed();
3774
6
          }
3775
6
        }
3776
19
        O = &O->getUnionValue();
3777
19
      } else
3778
191
        O = &O->getStructField(Field->getFieldIndex());
3779
3780
210
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781
210
      LastField = Field;
3782
210
      if (Field->getType().isVolatileQualified())
3783
0
        VolatileField = Field;
3784
210
    } else {
3785
      // Next subobject is a base class.
3786
26
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787
26
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788
26
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3789
3790
26
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791
26
    }
3792
249
  }
3793
33.7k
}
ExprConstant.cpp:(anonymous namespace)::DestroyObjectHandler::result_type findSubobject<(anonymous namespace)::DestroyObjectHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::DestroyObjectHandler&)
Line
Count
Source
3599
52
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600
52
  if (Sub.Invalid)
3601
    // A diagnostic will have already been produced.
3602
0
    return handler.failed();
3603
52
  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3604
0
    if (Info.getLangOpts().CPlusPlus11)
3605
0
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3606
0
                         ? diag::note_constexpr_access_past_end
3607
0
                         : diag::note_constexpr_access_unsized_array)
3608
0
          << handler.AccessKind;
3609
0
    else
3610
0
      Info.FFDiag(E);
3611
0
    return handler.failed();
3612
0
  }
3613
3614
52
  APValue *O = Obj.Value;
3615
52
  QualType ObjType = Obj.Type;
3616
52
  const FieldDecl *LastField = nullptr;
3617
52
  const FieldDecl *VolatileField = nullptr;
3618
3619
  // Walk the designator's path to find the subobject.
3620
79
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I27
) {
3621
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3622
79
    if ((O->isAbsent() && 
!(0
handler.AccessKind == AK_Construct0
&&
I == N0
)) ||
3623
79
        (O->isIndeterminate() &&
3624
79
         
!isValidIndeterminateAccess(handler.AccessKind)2
)) {
3625
0
      if (!Info.checkingPotentialConstantExpression())
3626
0
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627
0
            << handler.AccessKind << O->isIndeterminate();
3628
0
      return handler.failed();
3629
0
    }
3630
3631
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632
    //    const and volatile semantics are not applied on an object under
3633
    //    {con,de}struction.
3634
79
    if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3635
79
        
ObjType->isRecordType()0
&&
3636
79
        Info.isEvaluatingCtorDtor(
3637
0
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638
0
                                         Sub.Entries.begin() + I)) !=
3639
0
                          ConstructionPhase::None) {
3640
0
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3641
0
      ObjType.removeLocalConst();
3642
0
      ObjType.removeLocalVolatile();
3643
0
    }
3644
3645
    // If this is our last pass, check that the final object type is OK.
3646
79
    if (I == N || 
(27
I == N - 127
&&
ObjType->isAnyComplexType()22
)) {
3647
      // Accesses to volatile objects are prohibited.
3648
52
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3649
0
        if (Info.getLangOpts().CPlusPlus) {
3650
0
          int DiagKind;
3651
0
          SourceLocation Loc;
3652
0
          const NamedDecl *Decl = nullptr;
3653
0
          if (VolatileField) {
3654
0
            DiagKind = 2;
3655
0
            Loc = VolatileField->getLocation();
3656
0
            Decl = VolatileField;
3657
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658
0
            DiagKind = 1;
3659
0
            Loc = VD->getLocation();
3660
0
            Decl = VD;
3661
0
          } else {
3662
0
            DiagKind = 0;
3663
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664
0
              Loc = E->getExprLoc();
3665
0
          }
3666
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667
0
              << handler.AccessKind << DiagKind << Decl;
3668
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669
0
        } else {
3670
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671
0
        }
3672
0
        return handler.failed();
3673
0
      }
3674
3675
      // If we are reading an object of class type, there may still be more
3676
      // things we need to check: if there are any mutable subobjects, we
3677
      // cannot perform this read. (This only happens when performing a trivial
3678
      // copy or assignment.)
3679
52
      if (ObjType->isRecordType() &&
3680
52
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)34
&&
3681
52
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3682
0
        return handler.failed();
3683
52
    }
3684
3685
79
    if (I == N) {
3686
52
      if (!handler.found(*O, ObjType))
3687
0
        return false;
3688
3689
      // If we modified a bit-field, truncate it to the right width.
3690
52
      if (isModification(handler.AccessKind) &&
3691
52
          LastField && 
LastField->isBitField()13
&&
3692
52
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3693
0
        return false;
3694
3695
52
      return true;
3696
52
    }
3697
3698
27
    LastField = nullptr;
3699
27
    if (ObjType->isArrayType()) {
3700
      // Next subobject is an array element.
3701
6
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702
6
      assert(CAT && "vla in literal type?");
3703
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704
6
      if (CAT->getSize().ule(Index)) {
3705
        // Note, it should not be possible to form a pointer with a valid
3706
        // designator which points more than one past the end of the array.
3707
0
        if (Info.getLangOpts().CPlusPlus11)
3708
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3709
0
            << handler.AccessKind;
3710
0
        else
3711
0
          Info.FFDiag(E);
3712
0
        return handler.failed();
3713
0
      }
3714
3715
6
      ObjType = CAT->getElementType();
3716
3717
6
      if (O->getArrayInitializedElts() > Index)
3718
6
        O = &O->getArrayInitializedElt(Index);
3719
0
      else if (!isRead(handler.AccessKind)) {
3720
0
        expandArray(*O, Index);
3721
0
        O = &O->getArrayInitializedElt(Index);
3722
0
      } else
3723
0
        O = &O->getArrayFiller();
3724
21
    } else if (ObjType->isAnyComplexType()) {
3725
      // Next subobject is a complex number.
3726
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3727
0
      if (Index > 1) {
3728
0
        if (Info.getLangOpts().CPlusPlus11)
3729
0
          Info.FFDiag(E, diag::note_constexpr_access_past_end)
3730
0
            << handler.AccessKind;
3731
0
        else
3732
0
          Info.FFDiag(E);
3733
0
        return handler.failed();
3734
0
      }
3735
3736
0
      ObjType = getSubobjectType(
3737
0
          ObjType, ObjType->castAs<ComplexType>()->getElementType());
3738
3739
0
      assert(I == N - 1 && "extracting subobject of scalar?");
3740
0
      if (O->isComplexInt()) {
3741
0
        return handler.found(Index ? O->getComplexIntImag()
3742
0
                                   : O->getComplexIntReal(), ObjType);
3743
0
      } else {
3744
0
        assert(O->isComplexFloat());
3745
0
        return handler.found(Index ? O->getComplexFloatImag()
3746
0
                                   : O->getComplexFloatReal(), ObjType);
3747
0
      }
3748
21
    } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3749
16
      if (Field->isMutable() &&
3750
16
          
!Obj.mayAccessMutableMembers(Info, handler.AccessKind)0
) {
3751
0
        Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3752
0
          << handler.AccessKind << Field;
3753
0
        Info.Note(Field->getLocation(), diag::note_declared_at);
3754
0
        return handler.failed();
3755
0
      }
3756
3757
      // Next subobject is a class, struct or union field.
3758
16
      RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3759
16
      if (RD->isUnion()) {
3760
16
        const FieldDecl *UnionField = O->getUnionField();
3761
16
        if (!UnionField ||
3762
16
            UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3763
0
          if (I == N - 1 && handler.AccessKind == AK_Construct) {
3764
            // Placement new onto an inactive union member makes it active.
3765
0
            O->setUnion(Field, APValue());
3766
0
          } else {
3767
            // FIXME: If O->getUnionValue() is absent, report that there's no
3768
            // active union member rather than reporting the prior active union
3769
            // member. We'll need to fix nullptr_t to not use APValue() as its
3770
            // representation first.
3771
0
            Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3772
0
                << handler.AccessKind << Field << !UnionField << UnionField;
3773
0
            return handler.failed();
3774
0
          }
3775
0
        }
3776
16
        O = &O->getUnionValue();
3777
16
      } else
3778
0
        O = &O->getStructField(Field->getFieldIndex());
3779
3780
16
      ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3781
16
      LastField = Field;
3782
16
      if (Field->getType().isVolatileQualified())
3783
0
        VolatileField = Field;
3784
16
    } else {
3785
      // Next subobject is a base class.
3786
5
      const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3787
5
      const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3788
5
      O = &O->getStructBase(getBaseIndex(Derived, Base));
3789
3790
5
      ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3791
5
    }
3792
27
  }
3793
52
}
ExprConstant.cpp:(anonymous namespace)::CheckDynamicTypeHandler::result_type findSubobject<(anonymous namespace)::CheckDynamicTypeHandler>((anonymous namespace)::EvalInfo&, clang::Expr const*, (anonymous namespace)::CompleteObject const&, (anonymous namespace)::SubobjectDesignator const&, (anonymous namespace)::CheckDynamicTypeHandler&)
Line
Count
Source
3599
18.9k
              const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3600
18.9k
  if (Sub.Invalid)
3601
    // A diagnostic will have already been produced.
3602
0
    return handler.failed();
3603
18.9k
  if (Sub.isOnePastTheEnd() || 
Sub.isMostDerivedAnUnsizedArray()18.9k
) {
3604
18
    if (Info.getLangOpts().CPlusPlus11)
3605
18
      Info.FFDiag(E, Sub.isOnePastTheEnd()
3606
18
                         ? diag::note_constexpr_access_past_end
3607
18
                         : 
diag::note_constexpr_access_unsized_array0
)
3608
18
          << handler.AccessKind;
3609
0
    else
3610
0
      Info.FFDiag(E);
3611
18
    return handler.failed();
3612
18
  }
3613
3614
18.9k
  APValue *O = Obj.Value;
3615
18.9k
  QualType ObjType = Obj.Type;
3616
18.9k
  const FieldDecl *LastField = nullptr;
3617
18.9k
  const FieldDecl *VolatileField = nullptr;
3618
3619
  // Walk the designator's path to find the subobject.
3620
19.5k
  for (unsigned I = 0, N = Sub.Entries.size(); /**/; 
++I695
) {
3621
    // Reading an indeterminate value is undefined, but assigning over one is OK.
3622
19.5k
    if ((O->isAbsent() && 
!(20
handler.AccessKind == AK_Construct20
&&
I == N0
)) ||
3623
19.5k
        
(19.5k
O->isIndeterminate()19.5k
&&
3624
19.5k
         
!isValidIndeterminateAccess(handler.AccessKind)0
)) {
3625
20
      if (!Info.checkingPotentialConstantExpression())
3626
18
        Info.FFDiag(E, diag::note_constexpr_access_uninit)
3627
18
            << handler.AccessKind << O->isIndeterminate();
3628
20
      return handler.failed();
3629
20
    }
3630
3631
    // C++ [class.ctor]p5, C++ [class.dtor]p5:
3632
    //    const and volatile semantics are not applied on an object under
3633
    //    {con,de}struction.
3634
19.5k
    if ((ObjType.isConstQualified() || 
ObjType.isVolatileQualified()7.31k
) &&
3635
19.5k
        
ObjType->isRecordType()12.2k
&&
3636
19.5k
        Info.isEvaluatingCtorDtor(
3637
12.2k
            Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3638
12.2k
                                         Sub.Entries.begin() + I)) !=
3639
12.2k
                          ConstructionPhase::None) {
3640
51
      ObjType = Info.Ctx.getCanonicalType(ObjType);
3641
51
      ObjType.removeLocalConst();
3642
51
      ObjType.removeLocalVolatile();
3643
51
    }
3644
3645
    // If this is our last pass, check that the final object type is OK.
3646
19.5k
    if (I == N || 
(704
I == N - 1704
&&
ObjType->isAnyComplexType()423
)) {
3647
      // Accesses to volatile objects are prohibited.
3648
18.8k
      if (ObjType.isVolatileQualified() && 
isFormalAccess(handler.AccessKind)0
) {
3649
0
        if (Info.getLangOpts().CPlusPlus) {
3650
0
          int DiagKind;
3651
0
          SourceLocation Loc;
3652
0
          const NamedDecl *Decl = nullptr;
3653
0
          if (VolatileField) {
3654
0
            DiagKind = 2;
3655
0
            Loc = VolatileField->getLocation();
3656
0
            Decl = VolatileField;
3657
0
          } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3658
0
            DiagKind = 1;
3659
0
            Loc = VD->getLocation();
3660
0
            Decl = VD;
3661
0
          } else {
3662
0
            DiagKind = 0;
3663
0
            if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3664
0
              Loc = E->getExprLoc();
3665
0
          }
3666
0
          Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3667
0
              << handler.AccessKind << DiagKind << Decl;
3668
0
          Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3669
0
        } else {
3670
0
          Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3671
0
        }
3672
0
        return handler.failed();
3673
0
      }
3674
3675
      // If we are reading an object of class type, there may still be more
3676
      // things we need to check: if there are any mutable subobjects, we
3677
      // cannot perform this read. (This only happens when performing a trivial
3678
      // copy or assignment.)
3679
18.8k
      if (ObjType->isRecordType() &&
3680
18.8k
          !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3681
18.8k
          
diagnoseMutableFields(Info, E, handler.AccessKind, ObjType)0
)
3682
0
        return handler.failed();
3683
18.8k
    }
3684
3685
19.5k
    if (I == N) {
3686
18.8k
      if (!handler.found(*O, ObjType))
3687
0
        return false;
3688
3689
      // If we modified a bit-field, truncate it to the right width.
3690
18.8k
      if (isModification(handler.AccessKind) &&
3691
18.8k
          
LastField34
&&
LastField->isBitField()6
&&
3692
18.8k
          
!truncateBitfieldValue(Info, E, *O, LastField)0
)
3693
0
        return false;
3694
3695
18.8k
      return true;
3696
18.8k
    }
3697
3698
704
    LastField = nullptr;
3699
704
    if (ObjType->isArrayType()) {
3700
      // Next subobject is an array element.
3701
64
      const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3702
64
      assert(CAT && "vla in literal type?");
3703
0
      uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3704
64
      if (CAT->getSize().ule(Index)) {
3705
        // Note, it should not be possible to form a pointer with a valid
3706
        // designator which points more than one past the end of the array.
3707
0
        if (Info.getLangOpts().CPlusPlus11)
3708
0