Coverage Report

Created: 2020-02-25 14:32

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