clang 20.0.0git
ExprConstant.cpp
Go to the documentation of this file.
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 "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
42#include "clang/AST/ASTLambda.h"
43#include "clang/AST/Attr.h"
45#include "clang/AST/CharUnits.h"
47#include "clang/AST/Expr.h"
48#include "clang/AST/OSLog.h"
52#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/SmallBitVector.h"
58#include "llvm/ADT/StringExtras.h"
59#include "llvm/Support/Debug.h"
60#include "llvm/Support/SaveAndRestore.h"
61#include "llvm/Support/SipHash.h"
62#include "llvm/Support/TimeProfiler.h"
63#include "llvm/Support/raw_ostream.h"
64#include <cstring>
65#include <functional>
66#include <optional>
67
68#define DEBUG_TYPE "exprconstant"
69
70using namespace clang;
71using llvm::APFixedPoint;
72using llvm::APInt;
73using llvm::APSInt;
74using llvm::APFloat;
75using llvm::FixedPointSemantics;
76
77namespace {
78 struct LValue;
79 class CallStackFrame;
80 class EvalInfo;
81
82 using SourceLocExprScopeGuard =
84
85 static QualType getType(APValue::LValueBase B) {
86 return B.getType();
87 }
88
89 /// Get an LValue path entry, which is known to not be an array index, as a
90 /// field declaration.
91 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
92 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
93 }
94 /// Get an LValue path entry, which is known to not be an array index, as a
95 /// base class declaration.
96 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
97 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
98 }
99 /// Determine whether this LValue path entry for a base class names a virtual
100 /// base class.
101 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
102 return E.getAsBaseOrMember().getInt();
103 }
104
105 /// Given an expression, determine the type used to store the result of
106 /// evaluating that expression.
107 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
108 if (E->isPRValue())
109 return E->getType();
110 return Ctx.getLValueReferenceType(E->getType());
111 }
112
113 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
114 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
115 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
116 return DirectCallee->getAttr<AllocSizeAttr>();
117 if (const Decl *IndirectCallee = CE->getCalleeDecl())
118 return IndirectCallee->getAttr<AllocSizeAttr>();
119 return nullptr;
120 }
121
122 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
123 /// This will look through a single cast.
124 ///
125 /// Returns null if we couldn't unwrap a function with alloc_size.
126 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
127 if (!E->getType()->isPointerType())
128 return nullptr;
129
130 E = E->IgnoreParens();
131 // If we're doing a variable assignment from e.g. malloc(N), there will
132 // probably be a cast of some kind. In exotic cases, we might also see a
133 // top-level ExprWithCleanups. Ignore them either way.
134 if (const auto *FE = dyn_cast<FullExpr>(E))
135 E = FE->getSubExpr()->IgnoreParens();
136
137 if (const auto *Cast = dyn_cast<CastExpr>(E))
138 E = Cast->getSubExpr()->IgnoreParens();
139
140 if (const auto *CE = dyn_cast<CallExpr>(E))
141 return getAllocSizeAttr(CE) ? CE : nullptr;
142 return nullptr;
143 }
144
145 /// Determines whether or not the given Base contains a call to a function
146 /// with the alloc_size attribute.
147 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148 const auto *E = Base.dyn_cast<const Expr *>();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 }
151
152 /// Determines whether the given kind of constant expression is only ever
153 /// used for name mangling. If so, it's permitted to reference things that we
154 /// can't generate code for (in particular, dllimported functions).
155 static bool isForManglingOnly(ConstantExprKind Kind) {
156 switch (Kind) {
157 case ConstantExprKind::Normal:
158 case ConstantExprKind::ClassTemplateArgument:
159 case ConstantExprKind::ImmediateInvocation:
160 // Note that non-type template arguments of class type are emitted as
161 // template parameter objects.
162 return false;
163
164 case ConstantExprKind::NonClassTemplateArgument:
165 return true;
166 }
167 llvm_unreachable("unknown ConstantExprKind");
168 }
169
170 static bool isTemplateArgument(ConstantExprKind Kind) {
171 switch (Kind) {
172 case ConstantExprKind::Normal:
173 case ConstantExprKind::ImmediateInvocation:
174 return false;
175
176 case ConstantExprKind::ClassTemplateArgument:
177 case ConstantExprKind::NonClassTemplateArgument:
178 return true;
179 }
180 llvm_unreachable("unknown ConstantExprKind");
181 }
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,
196 uint64_t &ArraySize, QualType &Type, bool &IsArray,
197 bool &FirstEntryIsUnsizedArray) {
198 // This only accepts LValueBases from APValues, and APValues don't support
199 // arrays that lack size info.
200 assert(!isBaseAnAllocSizeCall(Base) &&
201 "Unsized arrays shouldn't appear here");
202 unsigned MostDerivedLength = 0;
203 Type = getType(Base);
204
205 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
206 if (Type->isArrayType()) {
207 const ArrayType *AT = Ctx.getAsArrayType(Type);
208 Type = AT->getElementType();
209 MostDerivedLength = I + 1;
210 IsArray = true;
211
212 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
213 ArraySize = CAT->getZExtSize();
214 } else {
215 assert(I == 0 && "unexpected unsized array designator");
216 FirstEntryIsUnsizedArray = true;
217 ArraySize = AssumedSizeForUnsizedArray;
218 }
219 } else if (Type->isAnyComplexType()) {
220 const ComplexType *CT = Type->castAs<ComplexType>();
221 Type = CT->getElementType();
222 ArraySize = 2;
223 MostDerivedLength = I + 1;
224 IsArray = true;
225 } else if (const auto *VT = Type->getAs<VectorType>()) {
226 Type = VT->getElementType();
227 ArraySize = VT->getNumElements();
228 MostDerivedLength = I + 1;
229 IsArray = true;
230 } else if (const FieldDecl *FD = getAsField(Path[I])) {
231 Type = FD->getType();
232 ArraySize = 0;
233 MostDerivedLength = I + 1;
234 IsArray = false;
235 } else {
236 // Path[I] describes a base class.
237 ArraySize = 0;
238 IsArray = false;
239 }
240 }
241 return MostDerivedLength;
242 }
243
244 /// A path from a glvalue to a subobject of that glvalue.
245 struct SubobjectDesignator {
246 /// True if the subobject was named in a manner not supported by C++11. Such
247 /// lvalues can still be folded, but they are not core constant expressions
248 /// and we cannot perform lvalue-to-rvalue conversions on them.
249 LLVM_PREFERRED_TYPE(bool)
250 unsigned Invalid : 1;
251
252 /// Is this a pointer one past the end of an object?
253 LLVM_PREFERRED_TYPE(bool)
254 unsigned IsOnePastTheEnd : 1;
255
256 /// Indicator of whether the first entry is an unsized array.
257 LLVM_PREFERRED_TYPE(bool)
258 unsigned FirstEntryIsAnUnsizedArray : 1;
259
260 /// Indicator of whether the most-derived object is an array element.
261 LLVM_PREFERRED_TYPE(bool)
262 unsigned MostDerivedIsArrayElement : 1;
263
264 /// The length of the path to the most-derived object of which this is a
265 /// subobject.
266 unsigned MostDerivedPathLength : 28;
267
268 /// The size of the array of which the most-derived object is an element.
269 /// This will always be 0 if the most-derived object is not an array
270 /// element. 0 is not an indicator of whether or not the most-derived object
271 /// is an array, however, because 0-length arrays are allowed.
272 ///
273 /// If the current array is an unsized array, the value of this is
274 /// undefined.
275 uint64_t MostDerivedArraySize;
276 /// The type of the most derived object referred to by this address.
277 QualType MostDerivedType;
278
279 typedef APValue::LValuePathEntry PathEntry;
280
281 /// The entries on the path from the glvalue to the designated subobject.
283
284 SubobjectDesignator() : Invalid(true) {}
285
286 explicit SubobjectDesignator(QualType T)
287 : Invalid(false), IsOnePastTheEnd(false),
288 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
289 MostDerivedPathLength(0), MostDerivedArraySize(0),
290 MostDerivedType(T) {}
291
292 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
293 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
294 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
295 MostDerivedPathLength(0), MostDerivedArraySize(0) {
296 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
297 if (!Invalid) {
298 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
299 ArrayRef<PathEntry> VEntries = V.getLValuePath();
300 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
301 if (V.getLValueBase()) {
302 bool IsArray = false;
303 bool FirstIsUnsizedArray = false;
304 MostDerivedPathLength = findMostDerivedSubobject(
305 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
306 MostDerivedType, IsArray, FirstIsUnsizedArray);
307 MostDerivedIsArrayElement = IsArray;
308 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
309 }
310 }
311 }
312
313 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
314 unsigned NewLength) {
315 if (Invalid)
316 return;
317
318 assert(Base && "cannot truncate path for null pointer");
319 assert(NewLength <= Entries.size() && "not a truncation");
320
321 if (NewLength == Entries.size())
322 return;
323 Entries.resize(NewLength);
324
325 bool IsArray = false;
326 bool FirstIsUnsizedArray = false;
327 MostDerivedPathLength = findMostDerivedSubobject(
328 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
329 FirstIsUnsizedArray);
330 MostDerivedIsArrayElement = IsArray;
331 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
332 }
333
334 void setInvalid() {
335 Invalid = true;
336 Entries.clear();
337 }
338
339 /// Determine whether the most derived subobject is an array without a
340 /// known bound.
341 bool isMostDerivedAnUnsizedArray() const {
342 assert(!Invalid && "Calling this makes no sense on invalid designators");
343 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
344 }
345
346 /// Determine what the most derived array's size is. Results in an assertion
347 /// failure if the most derived array lacks a size.
348 uint64_t getMostDerivedArraySize() const {
349 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
350 return MostDerivedArraySize;
351 }
352
353 /// Determine whether this is a one-past-the-end pointer.
354 bool isOnePastTheEnd() const {
355 assert(!Invalid);
356 if (IsOnePastTheEnd)
357 return true;
358 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
359 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
360 MostDerivedArraySize)
361 return true;
362 return false;
363 }
364
365 /// Get the range of valid index adjustments in the form
366 /// {maximum value that can be subtracted from this pointer,
367 /// maximum value that can be added to this pointer}
368 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
369 if (Invalid || isMostDerivedAnUnsizedArray())
370 return {0, 0};
371
372 // [expr.add]p4: For the purposes of these operators, a pointer to a
373 // nonarray object behaves the same as a pointer to the first element of
374 // an array of length one with the type of the object as its element type.
375 bool IsArray = MostDerivedPathLength == Entries.size() &&
376 MostDerivedIsArrayElement;
377 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
378 : (uint64_t)IsOnePastTheEnd;
379 uint64_t ArraySize =
380 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
381 return {ArrayIndex, ArraySize - ArrayIndex};
382 }
383
384 /// Check that this refers to a valid subobject.
385 bool isValidSubobject() const {
386 if (Invalid)
387 return false;
388 return !isOnePastTheEnd();
389 }
390 /// Check that this refers to a valid subobject, and if not, produce a
391 /// relevant diagnostic and set the designator as invalid.
392 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
393
394 /// Get the type of the designated object.
395 QualType getType(ASTContext &Ctx) const {
396 assert(!Invalid && "invalid designator has no subobject type");
397 return MostDerivedPathLength == Entries.size()
398 ? MostDerivedType
399 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
400 }
401
402 /// Update this designator to refer to the first element within this array.
403 void addArrayUnchecked(const ConstantArrayType *CAT) {
404 Entries.push_back(PathEntry::ArrayIndex(0));
405
406 // This is a most-derived object.
407 MostDerivedType = CAT->getElementType();
408 MostDerivedIsArrayElement = true;
409 MostDerivedArraySize = CAT->getZExtSize();
410 MostDerivedPathLength = Entries.size();
411 }
412 /// Update this designator to refer to the first element within the array of
413 /// elements of type T. This is an array of unknown size.
414 void addUnsizedArrayUnchecked(QualType ElemTy) {
415 Entries.push_back(PathEntry::ArrayIndex(0));
416
417 MostDerivedType = ElemTy;
418 MostDerivedIsArrayElement = true;
419 // The value in MostDerivedArraySize is undefined in this case. So, set it
420 // to an arbitrary value that's likely to loudly break things if it's
421 // used.
422 MostDerivedArraySize = AssumedSizeForUnsizedArray;
423 MostDerivedPathLength = Entries.size();
424 }
425 /// Update this designator to refer to the given base or member of this
426 /// object.
427 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
428 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
429
430 // If this isn't a base class, it's a new most-derived object.
431 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
432 MostDerivedType = FD->getType();
433 MostDerivedIsArrayElement = false;
434 MostDerivedArraySize = 0;
435 MostDerivedPathLength = Entries.size();
436 }
437 }
438 /// Update this designator to refer to the given complex component.
439 void addComplexUnchecked(QualType EltTy, bool Imag) {
440 Entries.push_back(PathEntry::ArrayIndex(Imag));
441
442 // This is technically a most-derived object, though in practice this
443 // is unlikely to matter.
444 MostDerivedType = EltTy;
445 MostDerivedIsArrayElement = true;
446 MostDerivedArraySize = 2;
447 MostDerivedPathLength = Entries.size();
448 }
449
450 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
451 uint64_t Idx) {
452 Entries.push_back(PathEntry::ArrayIndex(Idx));
453 MostDerivedType = EltTy;
454 MostDerivedPathLength = Entries.size();
455 MostDerivedArraySize = 0;
456 MostDerivedIsArrayElement = false;
457 }
458
459 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
460 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
461 const APSInt &N);
462 /// Add N to the address of this subobject.
463 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
464 if (Invalid || !N) return;
465 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
466 if (isMostDerivedAnUnsizedArray()) {
467 diagnoseUnsizedArrayPointerArithmetic(Info, E);
468 // Can't verify -- trust that the user is doing the right thing (or if
469 // not, trust that the caller will catch the bad behavior).
470 // FIXME: Should we reject if this overflows, at least?
471 Entries.back() = PathEntry::ArrayIndex(
472 Entries.back().getAsArrayIndex() + TruncatedN);
473 return;
474 }
475
476 // [expr.add]p4: For the purposes of these operators, a pointer to a
477 // nonarray object behaves the same as a pointer to the first element of
478 // an array of length one with the type of the object as its element type.
479 bool IsArray = MostDerivedPathLength == Entries.size() &&
480 MostDerivedIsArrayElement;
481 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
482 : (uint64_t)IsOnePastTheEnd;
483 uint64_t ArraySize =
484 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
485
486 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
487 // Calculate the actual index in a wide enough type, so we can include
488 // it in the note.
489 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
490 (llvm::APInt&)N += ArrayIndex;
491 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
492 diagnosePointerArithmetic(Info, E, N);
493 setInvalid();
494 return;
495 }
496
497 ArrayIndex += TruncatedN;
498 assert(ArrayIndex <= ArraySize &&
499 "bounds check succeeded for out-of-bounds index");
500
501 if (IsArray)
502 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
503 else
504 IsOnePastTheEnd = (ArrayIndex != 0);
505 }
506 };
507
508 /// A scope at the end of which an object can need to be destroyed.
509 enum class ScopeKind {
510 Block,
511 FullExpression,
512 Call
513 };
514
515 /// A reference to a particular call and its arguments.
516 struct CallRef {
517 CallRef() : OrigCallee(), CallIndex(0), Version() {}
518 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
519 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
520
521 explicit operator bool() const { return OrigCallee; }
522
523 /// Get the parameter that the caller initialized, corresponding to the
524 /// given parameter in the callee.
525 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
526 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
527 : PVD;
528 }
529
530 /// The callee at the point where the arguments were evaluated. This might
531 /// be different from the actual callee (a different redeclaration, or a
532 /// virtual override), but this function's parameters are the ones that
533 /// appear in the parameter map.
534 const FunctionDecl *OrigCallee;
535 /// The call index of the frame that holds the argument values.
536 unsigned CallIndex;
537 /// The version of the parameters corresponding to this call.
538 unsigned Version;
539 };
540
541 /// A stack frame in the constexpr call stack.
542 class CallStackFrame : public interp::Frame {
543 public:
544 EvalInfo &Info;
545
546 /// Parent - The caller of this stack frame.
547 CallStackFrame *Caller;
548
549 /// Callee - The function which was called.
550 const FunctionDecl *Callee;
551
552 /// This - The binding for the this pointer in this call, if any.
553 const LValue *This;
554
555 /// CallExpr - The syntactical structure of member function calls
556 const Expr *CallExpr;
557
558 /// Information on how to find the arguments to this call. Our arguments
559 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
560 /// key and this value as the version.
561 CallRef Arguments;
562
563 /// Source location information about the default argument or default
564 /// initializer expression we're evaluating, if any.
565 CurrentSourceLocExprScope CurSourceLocExprScope;
566
567 // Note that we intentionally use std::map here so that references to
568 // values are stable.
569 typedef std::pair<const void *, unsigned> MapKeyTy;
570 typedef std::map<MapKeyTy, APValue> MapTy;
571 /// Temporaries - Temporary lvalues materialized within this stack frame.
572 MapTy Temporaries;
573
574 /// CallRange - The source range of the call expression for this call.
575 SourceRange CallRange;
576
577 /// Index - The call index of this call.
578 unsigned Index;
579
580 /// The stack of integers for tracking version numbers for temporaries.
581 SmallVector<unsigned, 2> TempVersionStack = {1};
582 unsigned CurTempVersion = TempVersionStack.back();
583
584 unsigned getTempVersion() const { return TempVersionStack.back(); }
585
586 void pushTempVersion() {
587 TempVersionStack.push_back(++CurTempVersion);
588 }
589
590 void popTempVersion() {
591 TempVersionStack.pop_back();
592 }
593
594 CallRef createCall(const FunctionDecl *Callee) {
595 return {Callee, Index, ++CurTempVersion};
596 }
597
598 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
599 // on the overall stack usage of deeply-recursing constexpr evaluations.
600 // (We should cache this map rather than recomputing it repeatedly.)
601 // But let's try this and see how it goes; we can look into caching the map
602 // as a later change.
603
604 /// LambdaCaptureFields - Mapping from captured variables/this to
605 /// corresponding data members in the closure class.
606 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
607 FieldDecl *LambdaThisCaptureField = nullptr;
608
609 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
610 const FunctionDecl *Callee, const LValue *This,
611 const Expr *CallExpr, CallRef Arguments);
612 ~CallStackFrame();
613
614 // Return the temporary for Key whose version number is Version.
615 APValue *getTemporary(const void *Key, unsigned Version) {
616 MapKeyTy KV(Key, Version);
617 auto LB = Temporaries.lower_bound(KV);
618 if (LB != Temporaries.end() && LB->first == KV)
619 return &LB->second;
620 return nullptr;
621 }
622
623 // Return the current temporary for Key in the map.
624 APValue *getCurrentTemporary(const void *Key) {
625 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
626 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
627 return &std::prev(UB)->second;
628 return nullptr;
629 }
630
631 // Return the version number of the current temporary for Key.
632 unsigned getCurrentTemporaryVersion(const void *Key) const {
633 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
634 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
635 return std::prev(UB)->first.second;
636 return 0;
637 }
638
639 /// Allocate storage for an object of type T in this stack frame.
640 /// Populates LV with a handle to the created object. Key identifies
641 /// the temporary within the stack frame, and must not be reused without
642 /// bumping the temporary version number.
643 template<typename KeyT>
644 APValue &createTemporary(const KeyT *Key, QualType T,
645 ScopeKind Scope, LValue &LV);
646
647 /// Allocate storage for a parameter of a function call made in this frame.
648 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
649
650 void describe(llvm::raw_ostream &OS) const override;
651
652 Frame *getCaller() const override { return Caller; }
653 SourceRange getCallRange() const override { return CallRange; }
654 const FunctionDecl *getCallee() const override { return Callee; }
655
656 bool isStdFunction() const {
657 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
658 if (DC->isStdNamespace())
659 return true;
660 return false;
661 }
662
663 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
664 /// permitted. See MSConstexprDocs for description of permitted contexts.
665 bool CanEvalMSConstexpr = false;
666
667 private:
668 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
669 ScopeKind Scope);
670 };
671
672 /// Temporarily override 'this'.
673 class ThisOverrideRAII {
674 public:
675 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
676 : Frame(Frame), OldThis(Frame.This) {
677 if (Enable)
678 Frame.This = NewThis;
679 }
680 ~ThisOverrideRAII() {
681 Frame.This = OldThis;
682 }
683 private:
684 CallStackFrame &Frame;
685 const LValue *OldThis;
686 };
687
688 // A shorthand time trace scope struct, prints source range, for example
689 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
690 class ExprTimeTraceScope {
691 public:
692 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
693 : TimeScope(Name, [E, &Ctx] {
694 return E->getSourceRange().printToString(Ctx.getSourceManager());
695 }) {}
696
697 private:
698 llvm::TimeTraceScope TimeScope;
699 };
700
701 /// RAII object used to change the current ability of
702 /// [[msvc::constexpr]] evaulation.
703 struct MSConstexprContextRAII {
704 CallStackFrame &Frame;
705 bool OldValue;
706 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
707 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
708 Frame.CanEvalMSConstexpr = Value;
709 }
710
711 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
712 };
713}
714
715static bool HandleDestruction(EvalInfo &Info, const Expr *E,
716 const LValue &This, QualType ThisType);
717static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
719 QualType T);
720
721namespace {
722 /// A cleanup, and a flag indicating whether it is lifetime-extended.
723 class Cleanup {
724 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
726 QualType T;
727
728 public:
729 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
730 ScopeKind Scope)
731 : Value(Val, Scope), Base(Base), T(T) {}
732
733 /// Determine whether this cleanup should be performed at the end of the
734 /// given kind of scope.
735 bool isDestroyedAtEndOf(ScopeKind K) const {
736 return (int)Value.getInt() >= (int)K;
737 }
738 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
739 if (RunDestructors) {
741 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
742 Loc = VD->getLocation();
743 else if (const Expr *E = Base.dyn_cast<const Expr*>())
744 Loc = E->getExprLoc();
745 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
746 }
747 *Value.getPointer() = APValue();
748 return true;
749 }
750
751 bool hasSideEffect() {
752 return T.isDestructedType();
753 }
754 };
755
756 /// A reference to an object whose construction we are currently evaluating.
757 struct ObjectUnderConstruction {
760 friend bool operator==(const ObjectUnderConstruction &LHS,
761 const ObjectUnderConstruction &RHS) {
762 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
763 }
764 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
765 return llvm::hash_combine(Obj.Base, Obj.Path);
766 }
767 };
768 enum class ConstructionPhase {
769 None,
770 Bases,
771 AfterBases,
772 AfterFields,
773 Destroying,
774 DestroyingBases
775 };
776}
777
778namespace llvm {
779template<> struct DenseMapInfo<ObjectUnderConstruction> {
780 using Base = DenseMapInfo<APValue::LValueBase>;
781 static ObjectUnderConstruction getEmptyKey() {
782 return {Base::getEmptyKey(), {}}; }
783 static ObjectUnderConstruction getTombstoneKey() {
784 return {Base::getTombstoneKey(), {}};
785 }
786 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
787 return hash_value(Object);
788 }
789 static bool isEqual(const ObjectUnderConstruction &LHS,
790 const ObjectUnderConstruction &RHS) {
791 return LHS == RHS;
792 }
793};
794}
795
796namespace {
797 /// A dynamically-allocated heap object.
798 struct DynAlloc {
799 /// The value of this heap-allocated object.
801 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
802 /// or a CallExpr (the latter is for direct calls to operator new inside
803 /// std::allocator<T>::allocate).
804 const Expr *AllocExpr = nullptr;
805
806 enum Kind {
807 New,
808 ArrayNew,
809 StdAllocator
810 };
811
812 /// Get the kind of the allocation. This must match between allocation
813 /// and deallocation.
814 Kind getKind() const {
815 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
816 return NE->isArray() ? ArrayNew : New;
817 assert(isa<CallExpr>(AllocExpr));
818 return StdAllocator;
819 }
820 };
821
822 struct DynAllocOrder {
823 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
824 return L.getIndex() < R.getIndex();
825 }
826 };
827
828 /// EvalInfo - This is a private struct used by the evaluator to capture
829 /// information about a subexpression as it is folded. It retains information
830 /// about the AST context, but also maintains information about the folded
831 /// expression.
832 ///
833 /// If an expression could be evaluated, it is still possible it is not a C
834 /// "integer constant expression" or constant expression. If not, this struct
835 /// captures information about how and why not.
836 ///
837 /// One bit of information passed *into* the request for constant folding
838 /// indicates whether the subexpression is "evaluated" or not according to C
839 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
840 /// evaluate the expression regardless of what the RHS is, but C only allows
841 /// certain things in certain situations.
842 class EvalInfo : public interp::State {
843 public:
844 ASTContext &Ctx;
845
846 /// EvalStatus - Contains information about the evaluation.
847 Expr::EvalStatus &EvalStatus;
848
849 /// CurrentCall - The top of the constexpr call stack.
850 CallStackFrame *CurrentCall;
851
852 /// CallStackDepth - The number of calls in the call stack right now.
853 unsigned CallStackDepth;
854
855 /// NextCallIndex - The next call index to assign.
856 unsigned NextCallIndex;
857
858 /// StepsLeft - The remaining number of evaluation steps we're permitted
859 /// to perform. This is essentially a limit for the number of statements
860 /// we will evaluate.
861 unsigned StepsLeft;
862
863 /// Enable the experimental new constant interpreter. If an expression is
864 /// not supported by the interpreter, an error is triggered.
865 bool EnableNewConstInterp;
866
867 /// BottomFrame - The frame in which evaluation started. This must be
868 /// initialized after CurrentCall and CallStackDepth.
869 CallStackFrame BottomFrame;
870
871 /// A stack of values whose lifetimes end at the end of some surrounding
872 /// evaluation frame.
874
875 /// EvaluatingDecl - This is the declaration whose initializer is being
876 /// evaluated, if any.
877 APValue::LValueBase EvaluatingDecl;
878
879 enum class EvaluatingDeclKind {
880 None,
881 /// We're evaluating the construction of EvaluatingDecl.
882 Ctor,
883 /// We're evaluating the destruction of EvaluatingDecl.
884 Dtor,
885 };
886 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
887
888 /// EvaluatingDeclValue - This is the value being constructed for the
889 /// declaration whose initializer is being evaluated, if any.
890 APValue *EvaluatingDeclValue;
891
892 /// Set of objects that are currently being constructed.
893 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
894 ObjectsUnderConstruction;
895
896 /// Current heap allocations, along with the location where each was
897 /// allocated. We use std::map here because we need stable addresses
898 /// for the stored APValues.
899 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
900
901 /// The number of heap allocations performed so far in this evaluation.
902 unsigned NumHeapAllocs = 0;
903
904 struct EvaluatingConstructorRAII {
905 EvalInfo &EI;
906 ObjectUnderConstruction Object;
907 bool DidInsert;
908 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
909 bool HasBases)
910 : EI(EI), Object(Object) {
911 DidInsert =
912 EI.ObjectsUnderConstruction
913 .insert({Object, HasBases ? ConstructionPhase::Bases
914 : ConstructionPhase::AfterBases})
915 .second;
916 }
917 void finishedConstructingBases() {
918 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
919 }
920 void finishedConstructingFields() {
921 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
922 }
923 ~EvaluatingConstructorRAII() {
924 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
925 }
926 };
927
928 struct EvaluatingDestructorRAII {
929 EvalInfo &EI;
930 ObjectUnderConstruction Object;
931 bool DidInsert;
932 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
933 : EI(EI), Object(Object) {
934 DidInsert = EI.ObjectsUnderConstruction
935 .insert({Object, ConstructionPhase::Destroying})
936 .second;
937 }
938 void startedDestroyingBases() {
939 EI.ObjectsUnderConstruction[Object] =
940 ConstructionPhase::DestroyingBases;
941 }
942 ~EvaluatingDestructorRAII() {
943 if (DidInsert)
944 EI.ObjectsUnderConstruction.erase(Object);
945 }
946 };
947
948 ConstructionPhase
949 isEvaluatingCtorDtor(APValue::LValueBase Base,
951 return ObjectsUnderConstruction.lookup({Base, Path});
952 }
953
954 /// If we're currently speculatively evaluating, the outermost call stack
955 /// depth at which we can mutate state, otherwise 0.
956 unsigned SpeculativeEvaluationDepth = 0;
957
958 /// The current array initialization index, if we're performing array
959 /// initialization.
960 uint64_t ArrayInitIndex = -1;
961
962 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
963 /// notes attached to it will also be stored, otherwise they will not be.
964 bool HasActiveDiagnostic;
965
966 /// Have we emitted a diagnostic explaining why we couldn't constant
967 /// fold (not just why it's not strictly a constant expression)?
968 bool HasFoldFailureDiagnostic;
969
970 /// Whether we're checking that an expression is a potential constant
971 /// expression. If so, do not fail on constructs that could become constant
972 /// later on (such as a use of an undefined global).
973 bool CheckingPotentialConstantExpression = false;
974
975 /// Whether we're checking for an expression that has undefined behavior.
976 /// If so, we will produce warnings if we encounter an operation that is
977 /// always undefined.
978 ///
979 /// Note that we still need to evaluate the expression normally when this
980 /// is set; this is used when evaluating ICEs in C.
981 bool CheckingForUndefinedBehavior = false;
982
983 enum EvaluationMode {
984 /// Evaluate as a constant expression. Stop if we find that the expression
985 /// is not a constant expression.
986 EM_ConstantExpression,
987
988 /// Evaluate as a constant expression. Stop if we find that the expression
989 /// is not a constant expression. Some expressions can be retried in the
990 /// optimizer if we don't constant fold them here, but in an unevaluated
991 /// context we try to fold them immediately since the optimizer never
992 /// gets a chance to look at it.
993 EM_ConstantExpressionUnevaluated,
994
995 /// Fold the expression to a constant. Stop if we hit a side-effect that
996 /// we can't model.
997 EM_ConstantFold,
998
999 /// Evaluate in any way we know how. Don't worry about side-effects that
1000 /// can't be modeled.
1001 EM_IgnoreSideEffects,
1002 } EvalMode;
1003
1004 /// Are we checking whether the expression is a potential constant
1005 /// expression?
1006 bool checkingPotentialConstantExpression() const override {
1007 return CheckingPotentialConstantExpression;
1008 }
1009
1010 /// Are we checking an expression for overflow?
1011 // FIXME: We should check for any kind of undefined or suspicious behavior
1012 // in such constructs, not just overflow.
1013 bool checkingForUndefinedBehavior() const override {
1014 return CheckingForUndefinedBehavior;
1015 }
1016
1017 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1018 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1019 CallStackDepth(0), NextCallIndex(1),
1020 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1021 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1022 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1023 /*This=*/nullptr,
1024 /*CallExpr=*/nullptr, CallRef()),
1025 EvaluatingDecl((const ValueDecl *)nullptr),
1026 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1027 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1028
1029 ~EvalInfo() {
1030 discardCleanups();
1031 }
1032
1033 ASTContext &getCtx() const override { return Ctx; }
1034
1035 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1036 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1037 EvaluatingDecl = Base;
1038 IsEvaluatingDecl = EDK;
1039 EvaluatingDeclValue = &Value;
1040 }
1041
1042 bool CheckCallLimit(SourceLocation Loc) {
1043 // Don't perform any constexpr calls (other than the call we're checking)
1044 // when checking a potential constant expression.
1045 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1046 return false;
1047 if (NextCallIndex == 0) {
1048 // NextCallIndex has wrapped around.
1049 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1050 return false;
1051 }
1052 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1053 return true;
1054 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1055 << getLangOpts().ConstexprCallDepth;
1056 return false;
1057 }
1058
1059 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1060 uint64_t ElemCount, bool Diag) {
1061 // FIXME: GH63562
1062 // APValue stores array extents as unsigned,
1063 // so anything that is greater that unsigned would overflow when
1064 // constructing the array, we catch this here.
1065 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1066 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1067 if (Diag)
1068 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1069 return false;
1070 }
1071
1072 // FIXME: GH63562
1073 // Arrays allocate an APValue per element.
1074 // We use the number of constexpr steps as a proxy for the maximum size
1075 // of arrays to avoid exhausting the system resources, as initialization
1076 // of each element is likely to take some number of steps anyway.
1077 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1078 if (ElemCount > Limit) {
1079 if (Diag)
1080 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1081 << ElemCount << Limit;
1082 return false;
1083 }
1084 return true;
1085 }
1086
1087 std::pair<CallStackFrame *, unsigned>
1088 getCallFrameAndDepth(unsigned CallIndex) {
1089 assert(CallIndex && "no call index in getCallFrameAndDepth");
1090 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1091 // be null in this loop.
1092 unsigned Depth = CallStackDepth;
1093 CallStackFrame *Frame = CurrentCall;
1094 while (Frame->Index > CallIndex) {
1095 Frame = Frame->Caller;
1096 --Depth;
1097 }
1098 if (Frame->Index == CallIndex)
1099 return {Frame, Depth};
1100 return {nullptr, 0};
1101 }
1102
1103 bool nextStep(const Stmt *S) {
1104 if (!StepsLeft) {
1105 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1106 return false;
1107 }
1108 --StepsLeft;
1109 return true;
1110 }
1111
1112 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1113
1114 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1115 std::optional<DynAlloc *> Result;
1116 auto It = HeapAllocs.find(DA);
1117 if (It != HeapAllocs.end())
1118 Result = &It->second;
1119 return Result;
1120 }
1121
1122 /// Get the allocated storage for the given parameter of the given call.
1123 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1124 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1125 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1126 : nullptr;
1127 }
1128
1129 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1130 struct StdAllocatorCaller {
1131 unsigned FrameIndex;
1132 QualType ElemType;
1133 explicit operator bool() const { return FrameIndex != 0; };
1134 };
1135
1136 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1137 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1138 Call = Call->Caller) {
1139 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1140 if (!MD)
1141 continue;
1142 const IdentifierInfo *FnII = MD->getIdentifier();
1143 if (!FnII || !FnII->isStr(FnName))
1144 continue;
1145
1146 const auto *CTSD =
1147 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1148 if (!CTSD)
1149 continue;
1150
1151 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1152 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1153 if (CTSD->isInStdNamespace() && ClassII &&
1154 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1155 TAL[0].getKind() == TemplateArgument::Type)
1156 return {Call->Index, TAL[0].getAsType()};
1157 }
1158
1159 return {};
1160 }
1161
1162 void performLifetimeExtension() {
1163 // Disable the cleanups for lifetime-extended temporaries.
1164 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1165 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1166 });
1167 }
1168
1169 /// Throw away any remaining cleanups at the end of evaluation. If any
1170 /// cleanups would have had a side-effect, note that as an unmodeled
1171 /// side-effect and return false. Otherwise, return true.
1172 bool discardCleanups() {
1173 for (Cleanup &C : CleanupStack) {
1174 if (C.hasSideEffect() && !noteSideEffect()) {
1175 CleanupStack.clear();
1176 return false;
1177 }
1178 }
1179 CleanupStack.clear();
1180 return true;
1181 }
1182
1183 private:
1184 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1185 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1186
1187 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1188 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1189
1190 void setFoldFailureDiagnostic(bool Flag) override {
1191 HasFoldFailureDiagnostic = Flag;
1192 }
1193
1194 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1195
1196 // If we have a prior diagnostic, it will be noting that the expression
1197 // isn't a constant expression. This diagnostic is more important,
1198 // unless we require this evaluation to produce a constant expression.
1199 //
1200 // FIXME: We might want to show both diagnostics to the user in
1201 // EM_ConstantFold mode.
1202 bool hasPriorDiagnostic() override {
1203 if (!EvalStatus.Diag->empty()) {
1204 switch (EvalMode) {
1205 case EM_ConstantFold:
1206 case EM_IgnoreSideEffects:
1207 if (!HasFoldFailureDiagnostic)
1208 break;
1209 // We've already failed to fold something. Keep that diagnostic.
1210 [[fallthrough]];
1211 case EM_ConstantExpression:
1212 case EM_ConstantExpressionUnevaluated:
1213 setActiveDiagnostic(false);
1214 return true;
1215 }
1216 }
1217 return false;
1218 }
1219
1220 unsigned getCallStackDepth() override { return CallStackDepth; }
1221
1222 public:
1223 /// Should we continue evaluation after encountering a side-effect that we
1224 /// couldn't model?
1225 bool keepEvaluatingAfterSideEffect() {
1226 switch (EvalMode) {
1227 case EM_IgnoreSideEffects:
1228 return true;
1229
1230 case EM_ConstantExpression:
1231 case EM_ConstantExpressionUnevaluated:
1232 case EM_ConstantFold:
1233 // By default, assume any side effect might be valid in some other
1234 // evaluation of this expression from a different context.
1235 return checkingPotentialConstantExpression() ||
1236 checkingForUndefinedBehavior();
1237 }
1238 llvm_unreachable("Missed EvalMode case");
1239 }
1240
1241 /// Note that we have had a side-effect, and determine whether we should
1242 /// keep evaluating.
1243 bool noteSideEffect() {
1244 EvalStatus.HasSideEffects = true;
1245 return keepEvaluatingAfterSideEffect();
1246 }
1247
1248 /// Should we continue evaluation after encountering undefined behavior?
1249 bool keepEvaluatingAfterUndefinedBehavior() {
1250 switch (EvalMode) {
1251 case EM_IgnoreSideEffects:
1252 case EM_ConstantFold:
1253 return true;
1254
1255 case EM_ConstantExpression:
1256 case EM_ConstantExpressionUnevaluated:
1257 return checkingForUndefinedBehavior();
1258 }
1259 llvm_unreachable("Missed EvalMode case");
1260 }
1261
1262 /// Note that we hit something that was technically undefined behavior, but
1263 /// that we can evaluate past it (such as signed overflow or floating-point
1264 /// division by zero.)
1265 bool noteUndefinedBehavior() override {
1266 EvalStatus.HasUndefinedBehavior = true;
1267 return keepEvaluatingAfterUndefinedBehavior();
1268 }
1269
1270 /// Should we continue evaluation as much as possible after encountering a
1271 /// construct which can't be reduced to a value?
1272 bool keepEvaluatingAfterFailure() const override {
1273 if (!StepsLeft)
1274 return false;
1275
1276 switch (EvalMode) {
1277 case EM_ConstantExpression:
1278 case EM_ConstantExpressionUnevaluated:
1279 case EM_ConstantFold:
1280 case EM_IgnoreSideEffects:
1281 return checkingPotentialConstantExpression() ||
1282 checkingForUndefinedBehavior();
1283 }
1284 llvm_unreachable("Missed EvalMode case");
1285 }
1286
1287 /// Notes that we failed to evaluate an expression that other expressions
1288 /// directly depend on, and determine if we should keep evaluating. This
1289 /// should only be called if we actually intend to keep evaluating.
1290 ///
1291 /// Call noteSideEffect() instead if we may be able to ignore the value that
1292 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1293 ///
1294 /// (Foo(), 1) // use noteSideEffect
1295 /// (Foo() || true) // use noteSideEffect
1296 /// Foo() + 1 // use noteFailure
1297 [[nodiscard]] bool noteFailure() {
1298 // Failure when evaluating some expression often means there is some
1299 // subexpression whose evaluation was skipped. Therefore, (because we
1300 // don't track whether we skipped an expression when unwinding after an
1301 // evaluation failure) every evaluation failure that bubbles up from a
1302 // subexpression implies that a side-effect has potentially happened. We
1303 // skip setting the HasSideEffects flag to true until we decide to
1304 // continue evaluating after that point, which happens here.
1305 bool KeepGoing = keepEvaluatingAfterFailure();
1306 EvalStatus.HasSideEffects |= KeepGoing;
1307 return KeepGoing;
1308 }
1309
1310 class ArrayInitLoopIndex {
1311 EvalInfo &Info;
1312 uint64_t OuterIndex;
1313
1314 public:
1315 ArrayInitLoopIndex(EvalInfo &Info)
1316 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1317 Info.ArrayInitIndex = 0;
1318 }
1319 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1320
1321 operator uint64_t&() { return Info.ArrayInitIndex; }
1322 };
1323 };
1324
1325 /// Object used to treat all foldable expressions as constant expressions.
1326 struct FoldConstant {
1327 EvalInfo &Info;
1328 bool Enabled;
1329 bool HadNoPriorDiags;
1330 EvalInfo::EvaluationMode OldMode;
1331
1332 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1333 : Info(Info),
1334 Enabled(Enabled),
1335 HadNoPriorDiags(Info.EvalStatus.Diag &&
1336 Info.EvalStatus.Diag->empty() &&
1337 !Info.EvalStatus.HasSideEffects),
1338 OldMode(Info.EvalMode) {
1339 if (Enabled)
1340 Info.EvalMode = EvalInfo::EM_ConstantFold;
1341 }
1342 void keepDiagnostics() { Enabled = false; }
1343 ~FoldConstant() {
1344 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1345 !Info.EvalStatus.HasSideEffects)
1346 Info.EvalStatus.Diag->clear();
1347 Info.EvalMode = OldMode;
1348 }
1349 };
1350
1351 /// RAII object used to set the current evaluation mode to ignore
1352 /// side-effects.
1353 struct IgnoreSideEffectsRAII {
1354 EvalInfo &Info;
1355 EvalInfo::EvaluationMode OldMode;
1356 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1357 : Info(Info), OldMode(Info.EvalMode) {
1358 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1359 }
1360
1361 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1362 };
1363
1364 /// RAII object used to optionally suppress diagnostics and side-effects from
1365 /// a speculative evaluation.
1366 class SpeculativeEvaluationRAII {
1367 EvalInfo *Info = nullptr;
1368 Expr::EvalStatus OldStatus;
1369 unsigned OldSpeculativeEvaluationDepth = 0;
1370
1371 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1372 Info = Other.Info;
1373 OldStatus = Other.OldStatus;
1374 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1375 Other.Info = nullptr;
1376 }
1377
1378 void maybeRestoreState() {
1379 if (!Info)
1380 return;
1381
1382 Info->EvalStatus = OldStatus;
1383 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1384 }
1385
1386 public:
1387 SpeculativeEvaluationRAII() = default;
1388
1389 SpeculativeEvaluationRAII(
1390 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1391 : Info(&Info), OldStatus(Info.EvalStatus),
1392 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1393 Info.EvalStatus.Diag = NewDiag;
1394 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1395 }
1396
1397 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1398 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1399 moveFromAndCancel(std::move(Other));
1400 }
1401
1402 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1403 maybeRestoreState();
1404 moveFromAndCancel(std::move(Other));
1405 return *this;
1406 }
1407
1408 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1409 };
1410
1411 /// RAII object wrapping a full-expression or block scope, and handling
1412 /// the ending of the lifetime of temporaries created within it.
1413 template<ScopeKind Kind>
1414 class ScopeRAII {
1415 EvalInfo &Info;
1416 unsigned OldStackSize;
1417 public:
1418 ScopeRAII(EvalInfo &Info)
1419 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1420 // Push a new temporary version. This is needed to distinguish between
1421 // temporaries created in different iterations of a loop.
1422 Info.CurrentCall->pushTempVersion();
1423 }
1424 bool destroy(bool RunDestructors = true) {
1425 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1426 OldStackSize = -1U;
1427 return OK;
1428 }
1429 ~ScopeRAII() {
1430 if (OldStackSize != -1U)
1431 destroy(false);
1432 // Body moved to a static method to encourage the compiler to inline away
1433 // instances of this class.
1434 Info.CurrentCall->popTempVersion();
1435 }
1436 private:
1437 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1438 unsigned OldStackSize) {
1439 assert(OldStackSize <= Info.CleanupStack.size() &&
1440 "running cleanups out of order?");
1441
1442 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1443 // for a full-expression scope.
1444 bool Success = true;
1445 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1446 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1447 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1448 Success = false;
1449 break;
1450 }
1451 }
1452 }
1453
1454 // Compact any retained cleanups.
1455 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1456 if (Kind != ScopeKind::Block)
1457 NewEnd =
1458 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1459 return C.isDestroyedAtEndOf(Kind);
1460 });
1461 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1462 return Success;
1463 }
1464 };
1465 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1466 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1467 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1468}
1469
1470bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1471 CheckSubobjectKind CSK) {
1472 if (Invalid)
1473 return false;
1474 if (isOnePastTheEnd()) {
1475 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1476 << CSK;
1477 setInvalid();
1478 return false;
1479 }
1480 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1481 // must actually be at least one array element; even a VLA cannot have a
1482 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1483 return true;
1484}
1485
1486void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1487 const Expr *E) {
1488 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1489 // Do not set the designator as invalid: we can represent this situation,
1490 // and correct handling of __builtin_object_size requires us to do so.
1491}
1492
1493void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1494 const Expr *E,
1495 const APSInt &N) {
1496 // If we're complaining, we must be able to statically determine the size of
1497 // the most derived array.
1498 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1499 Info.CCEDiag(E, diag::note_constexpr_array_index)
1500 << N << /*array*/ 0
1501 << static_cast<unsigned>(getMostDerivedArraySize());
1502 else
1503 Info.CCEDiag(E, diag::note_constexpr_array_index)
1504 << N << /*non-array*/ 1;
1505 setInvalid();
1506}
1507
1508CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1509 const FunctionDecl *Callee, const LValue *This,
1510 const Expr *CallExpr, CallRef Call)
1511 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1512 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1513 Index(Info.NextCallIndex++) {
1514 Info.CurrentCall = this;
1515 ++Info.CallStackDepth;
1516}
1517
1518CallStackFrame::~CallStackFrame() {
1519 assert(Info.CurrentCall == this && "calls retired out of order");
1520 --Info.CallStackDepth;
1521 Info.CurrentCall = Caller;
1522}
1523
1524static bool isRead(AccessKinds AK) {
1525 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1526}
1527
1529 switch (AK) {
1530 case AK_Read:
1532 case AK_MemberCall:
1533 case AK_DynamicCast:
1534 case AK_TypeId:
1535 return false;
1536 case AK_Assign:
1537 case AK_Increment:
1538 case AK_Decrement:
1539 case AK_Construct:
1540 case AK_Destroy:
1541 return true;
1542 }
1543 llvm_unreachable("unknown access kind");
1544}
1545
1546static bool isAnyAccess(AccessKinds AK) {
1547 return isRead(AK) || isModification(AK);
1548}
1549
1550/// Is this an access per the C++ definition?
1552 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1553}
1554
1555/// Is this kind of axcess valid on an indeterminate object value?
1557 switch (AK) {
1558 case AK_Read:
1559 case AK_Increment:
1560 case AK_Decrement:
1561 // These need the object's value.
1562 return false;
1563
1565 case AK_Assign:
1566 case AK_Construct:
1567 case AK_Destroy:
1568 // Construction and destruction don't need the value.
1569 return true;
1570
1571 case AK_MemberCall:
1572 case AK_DynamicCast:
1573 case AK_TypeId:
1574 // These aren't really meaningful on scalars.
1575 return true;
1576 }
1577 llvm_unreachable("unknown access kind");
1578}
1579
1580namespace {
1581 struct ComplexValue {
1582 private:
1583 bool IsInt;
1584
1585 public:
1586 APSInt IntReal, IntImag;
1587 APFloat FloatReal, FloatImag;
1588
1589 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1590
1591 void makeComplexFloat() { IsInt = false; }
1592 bool isComplexFloat() const { return !IsInt; }
1593 APFloat &getComplexFloatReal() { return FloatReal; }
1594 APFloat &getComplexFloatImag() { return FloatImag; }
1595
1596 void makeComplexInt() { IsInt = true; }
1597 bool isComplexInt() const { return IsInt; }
1598 APSInt &getComplexIntReal() { return IntReal; }
1599 APSInt &getComplexIntImag() { return IntImag; }
1600
1601 void moveInto(APValue &v) const {
1602 if (isComplexFloat())
1603 v = APValue(FloatReal, FloatImag);
1604 else
1605 v = APValue(IntReal, IntImag);
1606 }
1607 void setFrom(const APValue &v) {
1608 assert(v.isComplexFloat() || v.isComplexInt());
1609 if (v.isComplexFloat()) {
1610 makeComplexFloat();
1611 FloatReal = v.getComplexFloatReal();
1612 FloatImag = v.getComplexFloatImag();
1613 } else {
1614 makeComplexInt();
1615 IntReal = v.getComplexIntReal();
1616 IntImag = v.getComplexIntImag();
1617 }
1618 }
1619 };
1620
1621 struct LValue {
1623 CharUnits Offset;
1624 SubobjectDesignator Designator;
1625 bool IsNullPtr : 1;
1626 bool InvalidBase : 1;
1627
1628 const APValue::LValueBase getLValueBase() const { return Base; }
1629 CharUnits &getLValueOffset() { return Offset; }
1630 const CharUnits &getLValueOffset() const { return Offset; }
1631 SubobjectDesignator &getLValueDesignator() { return Designator; }
1632 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1633 bool isNullPointer() const { return IsNullPtr;}
1634
1635 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1636 unsigned getLValueVersion() const { return Base.getVersion(); }
1637
1638 void moveInto(APValue &V) const {
1639 if (Designator.Invalid)
1640 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1641 else {
1642 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1643 V = APValue(Base, Offset, Designator.Entries,
1644 Designator.IsOnePastTheEnd, IsNullPtr);
1645 }
1646 }
1647 void setFrom(ASTContext &Ctx, const APValue &V) {
1648 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1649 Base = V.getLValueBase();
1650 Offset = V.getLValueOffset();
1651 InvalidBase = false;
1652 Designator = SubobjectDesignator(Ctx, V);
1653 IsNullPtr = V.isNullPointer();
1654 }
1655
1656 void set(APValue::LValueBase B, bool BInvalid = false) {
1657#ifndef NDEBUG
1658 // We only allow a few types of invalid bases. Enforce that here.
1659 if (BInvalid) {
1660 const auto *E = B.get<const Expr *>();
1661 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1662 "Unexpected type of invalid base");
1663 }
1664#endif
1665
1666 Base = B;
1667 Offset = CharUnits::fromQuantity(0);
1668 InvalidBase = BInvalid;
1669 Designator = SubobjectDesignator(getType(B));
1670 IsNullPtr = false;
1671 }
1672
1673 void setNull(ASTContext &Ctx, QualType PointerTy) {
1674 Base = (const ValueDecl *)nullptr;
1675 Offset =
1677 InvalidBase = false;
1678 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1679 IsNullPtr = true;
1680 }
1681
1682 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1683 set(B, true);
1684 }
1685
1686 std::string toString(ASTContext &Ctx, QualType T) const {
1687 APValue Printable;
1688 moveInto(Printable);
1689 return Printable.getAsString(Ctx, T);
1690 }
1691
1692 private:
1693 // Check that this LValue is not based on a null pointer. If it is, produce
1694 // a diagnostic and mark the designator as invalid.
1695 template <typename GenDiagType>
1696 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1697 if (Designator.Invalid)
1698 return false;
1699 if (IsNullPtr) {
1700 GenDiag();
1701 Designator.setInvalid();
1702 return false;
1703 }
1704 return true;
1705 }
1706
1707 public:
1708 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1709 CheckSubobjectKind CSK) {
1710 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1711 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1712 });
1713 }
1714
1715 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1716 AccessKinds AK) {
1717 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1718 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1719 });
1720 }
1721
1722 // Check this LValue refers to an object. If not, set the designator to be
1723 // invalid and emit a diagnostic.
1724 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1725 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1726 Designator.checkSubobject(Info, E, CSK);
1727 }
1728
1729 void addDecl(EvalInfo &Info, const Expr *E,
1730 const Decl *D, bool Virtual = false) {
1731 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1732 Designator.addDeclUnchecked(D, Virtual);
1733 }
1734 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1735 if (!Designator.Entries.empty()) {
1736 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1737 Designator.setInvalid();
1738 return;
1739 }
1740 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1741 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1742 Designator.FirstEntryIsAnUnsizedArray = true;
1743 Designator.addUnsizedArrayUnchecked(ElemTy);
1744 }
1745 }
1746 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1747 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1748 Designator.addArrayUnchecked(CAT);
1749 }
1750 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1751 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1752 Designator.addComplexUnchecked(EltTy, Imag);
1753 }
1754 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1755 uint64_t Size, uint64_t Idx) {
1756 if (checkSubobject(Info, E, CSK_VectorElement))
1757 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1758 }
1759 void clearIsNullPointer() {
1760 IsNullPtr = false;
1761 }
1762 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1763 const APSInt &Index, CharUnits ElementSize) {
1764 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1765 // but we're not required to diagnose it and it's valid in C++.)
1766 if (!Index)
1767 return;
1768
1769 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1770 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1771 // offsets.
1772 uint64_t Offset64 = Offset.getQuantity();
1773 uint64_t ElemSize64 = ElementSize.getQuantity();
1774 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1775 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1776
1777 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1778 Designator.adjustIndex(Info, E, Index);
1779 clearIsNullPointer();
1780 }
1781 void adjustOffset(CharUnits N) {
1782 Offset += N;
1783 if (N.getQuantity())
1784 clearIsNullPointer();
1785 }
1786 };
1787
1788 struct MemberPtr {
1789 MemberPtr() {}
1790 explicit MemberPtr(const ValueDecl *Decl)
1791 : DeclAndIsDerivedMember(Decl, false) {}
1792
1793 /// The member or (direct or indirect) field referred to by this member
1794 /// pointer, or 0 if this is a null member pointer.
1795 const ValueDecl *getDecl() const {
1796 return DeclAndIsDerivedMember.getPointer();
1797 }
1798 /// Is this actually a member of some type derived from the relevant class?
1799 bool isDerivedMember() const {
1800 return DeclAndIsDerivedMember.getInt();
1801 }
1802 /// Get the class which the declaration actually lives in.
1803 const CXXRecordDecl *getContainingRecord() const {
1804 return cast<CXXRecordDecl>(
1805 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1806 }
1807
1808 void moveInto(APValue &V) const {
1809 V = APValue(getDecl(), isDerivedMember(), Path);
1810 }
1811 void setFrom(const APValue &V) {
1812 assert(V.isMemberPointer());
1813 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1814 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1815 Path.clear();
1816 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1817 Path.insert(Path.end(), P.begin(), P.end());
1818 }
1819
1820 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1821 /// whether the member is a member of some class derived from the class type
1822 /// of the member pointer.
1823 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1824 /// Path - The path of base/derived classes from the member declaration's
1825 /// class (exclusive) to the class type of the member pointer (inclusive).
1827
1828 /// Perform a cast towards the class of the Decl (either up or down the
1829 /// hierarchy).
1830 bool castBack(const CXXRecordDecl *Class) {
1831 assert(!Path.empty());
1832 const CXXRecordDecl *Expected;
1833 if (Path.size() >= 2)
1834 Expected = Path[Path.size() - 2];
1835 else
1836 Expected = getContainingRecord();
1837 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1838 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1839 // if B does not contain the original member and is not a base or
1840 // derived class of the class containing the original member, the result
1841 // of the cast is undefined.
1842 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1843 // (D::*). We consider that to be a language defect.
1844 return false;
1845 }
1846 Path.pop_back();
1847 return true;
1848 }
1849 /// Perform a base-to-derived member pointer cast.
1850 bool castToDerived(const CXXRecordDecl *Derived) {
1851 if (!getDecl())
1852 return true;
1853 if (!isDerivedMember()) {
1854 Path.push_back(Derived);
1855 return true;
1856 }
1857 if (!castBack(Derived))
1858 return false;
1859 if (Path.empty())
1860 DeclAndIsDerivedMember.setInt(false);
1861 return true;
1862 }
1863 /// Perform a derived-to-base member pointer cast.
1864 bool castToBase(const CXXRecordDecl *Base) {
1865 if (!getDecl())
1866 return true;
1867 if (Path.empty())
1868 DeclAndIsDerivedMember.setInt(true);
1869 if (isDerivedMember()) {
1870 Path.push_back(Base);
1871 return true;
1872 }
1873 return castBack(Base);
1874 }
1875 };
1876
1877 /// Compare two member pointers, which are assumed to be of the same type.
1878 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1879 if (!LHS.getDecl() || !RHS.getDecl())
1880 return !LHS.getDecl() && !RHS.getDecl();
1881 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1882 return false;
1883 return LHS.Path == RHS.Path;
1884 }
1885}
1886
1887static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1888static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1889 const LValue &This, const Expr *E,
1890 bool AllowNonLiteralTypes = false);
1891static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1892 bool InvalidBaseOK = false);
1893static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1894 bool InvalidBaseOK = false);
1895static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1896 EvalInfo &Info);
1897static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1898static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1899static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1900 EvalInfo &Info);
1901static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1902static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1903static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1904 EvalInfo &Info);
1905static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1906static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1907 EvalInfo &Info,
1908 std::string *StringResult = nullptr);
1909
1910/// Evaluate an integer or fixed point expression into an APResult.
1911static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1912 EvalInfo &Info);
1913
1914/// Evaluate only a fixed point expression into an APResult.
1915static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1916 EvalInfo &Info);
1917
1918//===----------------------------------------------------------------------===//
1919// Misc utilities
1920//===----------------------------------------------------------------------===//
1921
1922/// Negate an APSInt in place, converting it to a signed form if necessary, and
1923/// preserving its value (by extending by up to one bit as needed).
1924static void negateAsSigned(APSInt &Int) {
1925 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1926 Int = Int.extend(Int.getBitWidth() + 1);
1927 Int.setIsSigned(true);
1928 }
1929 Int = -Int;
1930}
1931
1932template<typename KeyT>
1933APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1934 ScopeKind Scope, LValue &LV) {
1935 unsigned Version = getTempVersion();
1936 APValue::LValueBase Base(Key, Index, Version);
1937 LV.set(Base);
1938 return createLocal(Base, Key, T, Scope);
1939}
1940
1941/// Allocate storage for a parameter of a function call made in this frame.
1942APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1943 LValue &LV) {
1944 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1945 APValue::LValueBase Base(PVD, Index, Args.Version);
1946 LV.set(Base);
1947 // We always destroy parameters at the end of the call, even if we'd allow
1948 // them to live to the end of the full-expression at runtime, in order to
1949 // give portable results and match other compilers.
1950 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1951}
1952
1953APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1954 QualType T, ScopeKind Scope) {
1955 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1956 unsigned Version = Base.getVersion();
1957 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1958 assert(Result.isAbsent() && "local created multiple times");
1959
1960 // If we're creating a local immediately in the operand of a speculative
1961 // evaluation, don't register a cleanup to be run outside the speculative
1962 // evaluation context, since we won't actually be able to initialize this
1963 // object.
1964 if (Index <= Info.SpeculativeEvaluationDepth) {
1965 if (T.isDestructedType())
1966 Info.noteSideEffect();
1967 } else {
1968 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1969 }
1970 return Result;
1971}
1972
1973APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1974 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1975 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1976 return nullptr;
1977 }
1978
1979 DynamicAllocLValue DA(NumHeapAllocs++);
1981 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1982 std::forward_as_tuple(DA), std::tuple<>());
1983 assert(Result.second && "reused a heap alloc index?");
1984 Result.first->second.AllocExpr = E;
1985 return &Result.first->second.Value;
1986}
1987
1988/// Produce a string describing the given constexpr call.
1989void CallStackFrame::describe(raw_ostream &Out) const {
1990 unsigned ArgIndex = 0;
1991 bool IsMemberCall =
1992 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
1993 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1994
1995 if (!IsMemberCall)
1996 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1997 /*Qualified=*/false);
1998
1999 if (This && IsMemberCall) {
2000 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2001 const Expr *Object = MCE->getImplicitObjectArgument();
2002 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2003 /*Indentation=*/0);
2004 if (Object->getType()->isPointerType())
2005 Out << "->";
2006 else
2007 Out << ".";
2008 } else if (const auto *OCE =
2009 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2010 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2011 Info.Ctx.getPrintingPolicy(),
2012 /*Indentation=*/0);
2013 Out << ".";
2014 } else {
2015 APValue Val;
2016 This->moveInto(Val);
2017 Val.printPretty(
2018 Out, Info.Ctx,
2019 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2020 Out << ".";
2021 }
2022 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2023 /*Qualified=*/false);
2024 IsMemberCall = false;
2025 }
2026
2027 Out << '(';
2028
2029 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2030 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2031 if (ArgIndex > (unsigned)IsMemberCall)
2032 Out << ", ";
2033
2034 const ParmVarDecl *Param = *I;
2035 APValue *V = Info.getParamSlot(Arguments, Param);
2036 if (V)
2037 V->printPretty(Out, Info.Ctx, Param->getType());
2038 else
2039 Out << "<...>";
2040
2041 if (ArgIndex == 0 && IsMemberCall)
2042 Out << "->" << *Callee << '(';
2043 }
2044
2045 Out << ')';
2046}
2047
2048/// Evaluate an expression to see if it had side-effects, and discard its
2049/// result.
2050/// \return \c true if the caller should keep evaluating.
2051static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2052 assert(!E->isValueDependent());
2053 APValue Scratch;
2054 if (!Evaluate(Scratch, Info, E))
2055 // We don't need the value, but we might have skipped a side effect here.
2056 return Info.noteSideEffect();
2057 return true;
2058}
2059
2060/// Should this call expression be treated as a no-op?
2061static bool IsNoOpCall(const CallExpr *E) {
2062 unsigned Builtin = E->getBuiltinCallee();
2063 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2064 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2065 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2066 Builtin == Builtin::BI__builtin_function_start);
2067}
2068
2070 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2071 // constant expression of pointer type that evaluates to...
2072
2073 // ... a null pointer value, or a prvalue core constant expression of type
2074 // std::nullptr_t.
2075 if (!B)
2076 return true;
2077
2078 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2079 // ... the address of an object with static storage duration,
2080 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2081 return VD->hasGlobalStorage();
2082 if (isa<TemplateParamObjectDecl>(D))
2083 return true;
2084 // ... the address of a function,
2085 // ... the address of a GUID [MS extension],
2086 // ... the address of an unnamed global constant
2087 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2088 }
2089
2090 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2091 return true;
2092
2093 const Expr *E = B.get<const Expr*>();
2094 switch (E->getStmtClass()) {
2095 default:
2096 return false;
2097 case Expr::CompoundLiteralExprClass: {
2098 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2099 return CLE->isFileScope() && CLE->isLValue();
2100 }
2101 case Expr::MaterializeTemporaryExprClass:
2102 // A materialized temporary might have been lifetime-extended to static
2103 // storage duration.
2104 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2105 // A string literal has static storage duration.
2106 case Expr::StringLiteralClass:
2107 case Expr::PredefinedExprClass:
2108 case Expr::ObjCStringLiteralClass:
2109 case Expr::ObjCEncodeExprClass:
2110 return true;
2111 case Expr::ObjCBoxedExprClass:
2112 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2113 case Expr::CallExprClass:
2114 return IsNoOpCall(cast<CallExpr>(E));
2115 // For GCC compatibility, &&label has static storage duration.
2116 case Expr::AddrLabelExprClass:
2117 return true;
2118 // A Block literal expression may be used as the initialization value for
2119 // Block variables at global or local static scope.
2120 case Expr::BlockExprClass:
2121 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2122 // The APValue generated from a __builtin_source_location will be emitted as a
2123 // literal.
2124 case Expr::SourceLocExprClass:
2125 return true;
2126 case Expr::ImplicitValueInitExprClass:
2127 // FIXME:
2128 // We can never form an lvalue with an implicit value initialization as its
2129 // base through expression evaluation, so these only appear in one case: the
2130 // implicit variable declaration we invent when checking whether a constexpr
2131 // constructor can produce a constant expression. We must assume that such
2132 // an expression might be a global lvalue.
2133 return true;
2134 }
2135}
2136
2137static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2138 return LVal.Base.dyn_cast<const ValueDecl*>();
2139}
2140
2141static bool IsLiteralLValue(const LValue &Value) {
2142 if (Value.getLValueCallIndex())
2143 return false;
2144 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2145 return E && !isa<MaterializeTemporaryExpr>(E);
2146}
2147
2148static bool IsWeakLValue(const LValue &Value) {
2150 return Decl && Decl->isWeak();
2151}
2152
2153static bool isZeroSized(const LValue &Value) {
2155 if (isa_and_nonnull<VarDecl>(Decl)) {
2156 QualType Ty = Decl->getType();
2157 if (Ty->isArrayType())
2158 return Ty->isIncompleteType() ||
2159 Decl->getASTContext().getTypeSize(Ty) == 0;
2160 }
2161 return false;
2162}
2163
2164static bool HasSameBase(const LValue &A, const LValue &B) {
2165 if (!A.getLValueBase())
2166 return !B.getLValueBase();
2167 if (!B.getLValueBase())
2168 return false;
2169
2170 if (A.getLValueBase().getOpaqueValue() !=
2171 B.getLValueBase().getOpaqueValue())
2172 return false;
2173
2174 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2175 A.getLValueVersion() == B.getLValueVersion();
2176}
2177
2178static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2179 assert(Base && "no location for a null lvalue");
2180 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2181
2182 // For a parameter, find the corresponding call stack frame (if it still
2183 // exists), and point at the parameter of the function definition we actually
2184 // invoked.
2185 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2186 unsigned Idx = PVD->getFunctionScopeIndex();
2187 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2188 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2189 F->Arguments.Version == Base.getVersion() && F->Callee &&
2190 Idx < F->Callee->getNumParams()) {
2191 VD = F->Callee->getParamDecl(Idx);
2192 break;
2193 }
2194 }
2195 }
2196
2197 if (VD)
2198 Info.Note(VD->getLocation(), diag::note_declared_at);
2199 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2200 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2201 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2202 // FIXME: Produce a note for dangling pointers too.
2203 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2204 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2205 diag::note_constexpr_dynamic_alloc_here);
2206 }
2207
2208 // We have no information to show for a typeid(T) object.
2209}
2210
2214};
2215
2216/// Materialized temporaries that we've already checked to determine if they're
2217/// initializsed by a constant expression.
2220
2222 EvalInfo &Info, SourceLocation DiagLoc,
2223 QualType Type, const APValue &Value,
2224 ConstantExprKind Kind,
2225 const FieldDecl *SubobjectDecl,
2226 CheckedTemporaries &CheckedTemps);
2227
2228/// Check that this reference or pointer core constant expression is a valid
2229/// value for an address or reference constant expression. Return true if we
2230/// can fold this expression, whether or not it's a constant expression.
2232 QualType Type, const LValue &LVal,
2233 ConstantExprKind Kind,
2234 CheckedTemporaries &CheckedTemps) {
2235 bool IsReferenceType = Type->isReferenceType();
2236
2237 APValue::LValueBase Base = LVal.getLValueBase();
2238 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2239
2240 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2241 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2242
2243 // Additional restrictions apply in a template argument. We only enforce the
2244 // C++20 restrictions here; additional syntactic and semantic restrictions
2245 // are applied elsewhere.
2246 if (isTemplateArgument(Kind)) {
2247 int InvalidBaseKind = -1;
2248 StringRef Ident;
2249 if (Base.is<TypeInfoLValue>())
2250 InvalidBaseKind = 0;
2251 else if (isa_and_nonnull<StringLiteral>(BaseE))
2252 InvalidBaseKind = 1;
2253 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2254 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2255 InvalidBaseKind = 2;
2256 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2257 InvalidBaseKind = 3;
2258 Ident = PE->getIdentKindName();
2259 }
2260
2261 if (InvalidBaseKind != -1) {
2262 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2263 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2264 << Ident;
2265 return false;
2266 }
2267 }
2268
2269 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2270 FD && FD->isImmediateFunction()) {
2271 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2272 << !Type->isAnyPointerType();
2273 Info.Note(FD->getLocation(), diag::note_declared_at);
2274 return false;
2275 }
2276
2277 // Check that the object is a global. Note that the fake 'this' object we
2278 // manufacture when checking potential constant expressions is conservatively
2279 // assumed to be global here.
2280 if (!IsGlobalLValue(Base)) {
2281 if (Info.getLangOpts().CPlusPlus11) {
2282 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2283 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2284 << BaseVD;
2285 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2286 if (VarD && VarD->isConstexpr()) {
2287 // Non-static local constexpr variables have unintuitive semantics:
2288 // constexpr int a = 1;
2289 // constexpr const int *p = &a;
2290 // ... is invalid because the address of 'a' is not constant. Suggest
2291 // adding a 'static' in this case.
2292 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2293 << VarD
2294 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2295 } else {
2296 NoteLValueLocation(Info, Base);
2297 }
2298 } else {
2299 Info.FFDiag(Loc);
2300 }
2301 // Don't allow references to temporaries to escape.
2302 return false;
2303 }
2304 assert((Info.checkingPotentialConstantExpression() ||
2305 LVal.getLValueCallIndex() == 0) &&
2306 "have call index for global lvalue");
2307
2308 if (Base.is<DynamicAllocLValue>()) {
2309 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2310 << IsReferenceType << !Designator.Entries.empty();
2311 NoteLValueLocation(Info, Base);
2312 return false;
2313 }
2314
2315 if (BaseVD) {
2316 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2317 // Check if this is a thread-local variable.
2318 if (Var->getTLSKind())
2319 // FIXME: Diagnostic!
2320 return false;
2321
2322 // A dllimport variable never acts like a constant, unless we're
2323 // evaluating a value for use only in name mangling.
2324 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2325 // FIXME: Diagnostic!
2326 return false;
2327
2328 // In CUDA/HIP device compilation, only device side variables have
2329 // constant addresses.
2330 if (Info.getCtx().getLangOpts().CUDA &&
2331 Info.getCtx().getLangOpts().CUDAIsDevice &&
2332 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2333 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2334 !Var->hasAttr<CUDAConstantAttr>() &&
2335 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2336 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2337 Var->hasAttr<HIPManagedAttr>())
2338 return false;
2339 }
2340 }
2341 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2342 // __declspec(dllimport) must be handled very carefully:
2343 // We must never initialize an expression with the thunk in C++.
2344 // Doing otherwise would allow the same id-expression to yield
2345 // different addresses for the same function in different translation
2346 // units. However, this means that we must dynamically initialize the
2347 // expression with the contents of the import address table at runtime.
2348 //
2349 // The C language has no notion of ODR; furthermore, it has no notion of
2350 // dynamic initialization. This means that we are permitted to
2351 // perform initialization with the address of the thunk.
2352 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2353 FD->hasAttr<DLLImportAttr>())
2354 // FIXME: Diagnostic!
2355 return false;
2356 }
2357 } else if (const auto *MTE =
2358 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2359 if (CheckedTemps.insert(MTE).second) {
2360 QualType TempType = getType(Base);
2361 if (TempType.isDestructedType()) {
2362 Info.FFDiag(MTE->getExprLoc(),
2363 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2364 << TempType;
2365 return false;
2366 }
2367
2368 APValue *V = MTE->getOrCreateValue(false);
2369 assert(V && "evasluation result refers to uninitialised temporary");
2370 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2371 Info, MTE->getExprLoc(), TempType, *V, Kind,
2372 /*SubobjectDecl=*/nullptr, CheckedTemps))
2373 return false;
2374 }
2375 }
2376
2377 // Allow address constant expressions to be past-the-end pointers. This is
2378 // an extension: the standard requires them to point to an object.
2379 if (!IsReferenceType)
2380 return true;
2381
2382 // A reference constant expression must refer to an object.
2383 if (!Base) {
2384 // FIXME: diagnostic
2385 Info.CCEDiag(Loc);
2386 return true;
2387 }
2388
2389 // Does this refer one past the end of some object?
2390 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2391 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2392 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2393 NoteLValueLocation(Info, Base);
2394 }
2395
2396 return true;
2397}
2398
2399/// Member pointers are constant expressions unless they point to a
2400/// non-virtual dllimport member function.
2401static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2403 QualType Type,
2404 const APValue &Value,
2405 ConstantExprKind Kind) {
2406 const ValueDecl *Member = Value.getMemberPointerDecl();
2407 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2408 if (!FD)
2409 return true;
2410 if (FD->isImmediateFunction()) {
2411 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2412 Info.Note(FD->getLocation(), diag::note_declared_at);
2413 return false;
2414 }
2415 return isForManglingOnly(Kind) || FD->isVirtual() ||
2416 !FD->hasAttr<DLLImportAttr>();
2417}
2418
2419/// Check that this core constant expression is of literal type, and if not,
2420/// produce an appropriate diagnostic.
2421static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2422 const LValue *This = nullptr) {
2423 // The restriction to literal types does not exist in C++23 anymore.
2424 if (Info.getLangOpts().CPlusPlus23)
2425 return true;
2426
2427 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2428 return true;
2429
2430 // C++1y: A constant initializer for an object o [...] may also invoke
2431 // constexpr constructors for o and its subobjects even if those objects
2432 // are of non-literal class types.
2433 //
2434 // C++11 missed this detail for aggregates, so classes like this:
2435 // struct foo_t { union { int i; volatile int j; } u; };
2436 // are not (obviously) initializable like so:
2437 // __attribute__((__require_constant_initialization__))
2438 // static const foo_t x = {{0}};
2439 // because "i" is a subobject with non-literal initialization (due to the
2440 // volatile member of the union). See:
2441 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2442 // Therefore, we use the C++1y behavior.
2443 if (This && Info.EvaluatingDecl == This->getLValueBase())
2444 return true;
2445
2446 // Prvalue constant expressions must be of literal types.
2447 if (Info.getLangOpts().CPlusPlus11)
2448 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2449 << E->getType();
2450 else
2451 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2452 return false;
2453}
2454
2456 EvalInfo &Info, SourceLocation DiagLoc,
2457 QualType Type, const APValue &Value,
2458 ConstantExprKind Kind,
2459 const FieldDecl *SubobjectDecl,
2460 CheckedTemporaries &CheckedTemps) {
2461 if (!Value.hasValue()) {
2462 if (SubobjectDecl) {
2463 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2464 << /*(name)*/ 1 << SubobjectDecl;
2465 Info.Note(SubobjectDecl->getLocation(),
2466 diag::note_constexpr_subobject_declared_here);
2467 } else {
2468 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2469 << /*of type*/ 0 << Type;
2470 }
2471 return false;
2472 }
2473
2474 // We allow _Atomic(T) to be initialized from anything that T can be
2475 // initialized from.
2476 if (const AtomicType *AT = Type->getAs<AtomicType>())
2477 Type = AT->getValueType();
2478
2479 // Core issue 1454: For a literal constant expression of array or class type,
2480 // each subobject of its value shall have been initialized by a constant
2481 // expression.
2482 if (Value.isArray()) {
2484 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2485 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2486 Value.getArrayInitializedElt(I), Kind,
2487 SubobjectDecl, CheckedTemps))
2488 return false;
2489 }
2490 if (!Value.hasArrayFiller())
2491 return true;
2492 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2493 Value.getArrayFiller(), Kind, SubobjectDecl,
2494 CheckedTemps);
2495 }
2496 if (Value.isUnion() && Value.getUnionField()) {
2497 return CheckEvaluationResult(
2498 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2499 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2500 }
2501 if (Value.isStruct()) {
2502 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2503 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2504 unsigned BaseIndex = 0;
2505 for (const CXXBaseSpecifier &BS : CD->bases()) {
2506 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2507 if (!BaseValue.hasValue()) {
2508 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2509 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2510 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2511 return false;
2512 }
2513 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2514 Kind, /*SubobjectDecl=*/nullptr,
2515 CheckedTemps))
2516 return false;
2517 ++BaseIndex;
2518 }
2519 }
2520 for (const auto *I : RD->fields()) {
2521 if (I->isUnnamedBitField())
2522 continue;
2523
2524 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2525 Value.getStructField(I->getFieldIndex()), Kind,
2526 I, CheckedTemps))
2527 return false;
2528 }
2529 }
2530
2531 if (Value.isLValue() &&
2532 CERK == CheckEvaluationResultKind::ConstantExpression) {
2533 LValue LVal;
2534 LVal.setFrom(Info.Ctx, Value);
2535 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2536 CheckedTemps);
2537 }
2538
2539 if (Value.isMemberPointer() &&
2540 CERK == CheckEvaluationResultKind::ConstantExpression)
2541 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2542
2543 // Everything else is fine.
2544 return true;
2545}
2546
2547/// Check that this core constant expression value is a valid value for a
2548/// constant expression. If not, report an appropriate diagnostic. Does not
2549/// check that the expression is of literal type.
2550static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2551 QualType Type, const APValue &Value,
2552 ConstantExprKind Kind) {
2553 // Nothing to check for a constant expression of type 'cv void'.
2554 if (Type->isVoidType())
2555 return true;
2556
2557 CheckedTemporaries CheckedTemps;
2558 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2559 Info, DiagLoc, Type, Value, Kind,
2560 /*SubobjectDecl=*/nullptr, CheckedTemps);
2561}
2562
2563/// Check that this evaluated value is fully-initialized and can be loaded by
2564/// an lvalue-to-rvalue conversion.
2565static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2566 QualType Type, const APValue &Value) {
2567 CheckedTemporaries CheckedTemps;
2568 return CheckEvaluationResult(
2569 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2570 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2571}
2572
2573/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2574/// "the allocated storage is deallocated within the evaluation".
2575static bool CheckMemoryLeaks(EvalInfo &Info) {
2576 if (!Info.HeapAllocs.empty()) {
2577 // We can still fold to a constant despite a compile-time memory leak,
2578 // so long as the heap allocation isn't referenced in the result (we check
2579 // that in CheckConstantExpression).
2580 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2581 diag::note_constexpr_memory_leak)
2582 << unsigned(Info.HeapAllocs.size() - 1);
2583 }
2584 return true;
2585}
2586
2587static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2588 // A null base expression indicates a null pointer. These are always
2589 // evaluatable, and they are false unless the offset is zero.
2590 if (!Value.getLValueBase()) {
2591 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2592 Result = !Value.getLValueOffset().isZero();
2593 return true;
2594 }
2595
2596 // We have a non-null base. These are generally known to be true, but if it's
2597 // a weak declaration it can be null at runtime.
2598 Result = true;
2599 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2600 return !Decl || !Decl->isWeak();
2601}
2602
2603static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2604 // TODO: This function should produce notes if it fails.
2605 switch (Val.getKind()) {
2606 case APValue::None:
2608 return false;
2609 case APValue::Int:
2610 Result = Val.getInt().getBoolValue();
2611 return true;
2613 Result = Val.getFixedPoint().getBoolValue();
2614 return true;
2615 case APValue::Float:
2616 Result = !Val.getFloat().isZero();
2617 return true;
2619 Result = Val.getComplexIntReal().getBoolValue() ||
2620 Val.getComplexIntImag().getBoolValue();
2621 return true;
2623 Result = !Val.getComplexFloatReal().isZero() ||
2624 !Val.getComplexFloatImag().isZero();
2625 return true;
2626 case APValue::LValue:
2627 return EvalPointerValueAsBool(Val, Result);
2629 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2630 return false;
2631 }
2632 Result = Val.getMemberPointerDecl();
2633 return true;
2634 case APValue::Vector:
2635 case APValue::Array:
2636 case APValue::Struct:
2637 case APValue::Union:
2639 return false;
2640 }
2641
2642 llvm_unreachable("unknown APValue kind");
2643}
2644
2645static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2646 EvalInfo &Info) {
2647 assert(!E->isValueDependent());
2648 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2649 APValue Val;
2650 if (!Evaluate(Val, Info, E))
2651 return false;
2652 return HandleConversionToBool(Val, Result);
2653}
2654
2655template<typename T>
2656static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2657 const T &SrcValue, QualType DestType) {
2658 Info.CCEDiag(E, diag::note_constexpr_overflow)
2659 << SrcValue << DestType;
2660 return Info.noteUndefinedBehavior();
2661}
2662
2663static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2664 QualType SrcType, const APFloat &Value,
2665 QualType DestType, APSInt &Result) {
2666 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2667 // Determine whether we are converting to unsigned or signed.
2668 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2669
2670 Result = APSInt(DestWidth, !DestSigned);
2671 bool ignored;
2672 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2673 & APFloat::opInvalidOp)
2674 return HandleOverflow(Info, E, Value, DestType);
2675 return true;
2676}
2677
2678/// Get rounding mode to use in evaluation of the specified expression.
2679///
2680/// If rounding mode is unknown at compile time, still try to evaluate the
2681/// expression. If the result is exact, it does not depend on rounding mode.
2682/// So return "tonearest" mode instead of "dynamic".
2683static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2684 llvm::RoundingMode RM =
2685 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2686 if (RM == llvm::RoundingMode::Dynamic)
2687 RM = llvm::RoundingMode::NearestTiesToEven;
2688 return RM;
2689}
2690
2691/// Check if the given evaluation result is allowed for constant evaluation.
2692static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2693 APFloat::opStatus St) {
2694 // In a constant context, assume that any dynamic rounding mode or FP
2695 // exception state matches the default floating-point environment.
2696 if (Info.InConstantContext)
2697 return true;
2698
2699 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2700 if ((St & APFloat::opInexact) &&
2701 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2702 // Inexact result means that it depends on rounding mode. If the requested
2703 // mode is dynamic, the evaluation cannot be made in compile time.
2704 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2705 return false;
2706 }
2707
2708 if ((St != APFloat::opOK) &&
2709 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2710 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2711 FPO.getAllowFEnvAccess())) {
2712 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2713 return false;
2714 }
2715
2716 if ((St & APFloat::opStatus::opInvalidOp) &&
2717 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2718 // There is no usefully definable result.
2719 Info.FFDiag(E);
2720 return false;
2721 }
2722
2723 // FIXME: if:
2724 // - evaluation triggered other FP exception, and
2725 // - exception mode is not "ignore", and
2726 // - the expression being evaluated is not a part of global variable
2727 // initializer,
2728 // the evaluation probably need to be rejected.
2729 return true;
2730}
2731
2732static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2733 QualType SrcType, QualType DestType,
2734 APFloat &Result) {
2735 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2736 isa<ConvertVectorExpr>(E)) &&
2737 "HandleFloatToFloatCast has been checked with only CastExpr, "
2738 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2739 "the new expression or address the root cause of this usage.");
2740 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2741 APFloat::opStatus St;
2742 APFloat Value = Result;
2743 bool ignored;
2744 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2745 return checkFloatingPointResult(Info, E, St);
2746}
2747
2748static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2749 QualType DestType, QualType SrcType,
2750 const APSInt &Value) {
2751 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2752 // Figure out if this is a truncate, extend or noop cast.
2753 // If the input is signed, do a sign extend, noop, or truncate.
2754 APSInt Result = Value.extOrTrunc(DestWidth);
2755 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2756 if (DestType->isBooleanType())
2757 Result = Value.getBoolValue();
2758 return Result;
2759}
2760
2761static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2762 const FPOptions FPO,
2763 QualType SrcType, const APSInt &Value,
2764 QualType DestType, APFloat &Result) {
2765 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2766 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2767 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2768 return checkFloatingPointResult(Info, E, St);
2769}
2770
2771static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2772 APValue &Value, const FieldDecl *FD) {
2773 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2774
2775 if (!Value.isInt()) {
2776 // Trying to store a pointer-cast-to-integer into a bitfield.
2777 // FIXME: In this case, we should provide the diagnostic for casting
2778 // a pointer to an integer.
2779 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2780 Info.FFDiag(E);
2781 return false;
2782 }
2783
2784 APSInt &Int = Value.getInt();
2785 unsigned OldBitWidth = Int.getBitWidth();
2786 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2787 if (NewBitWidth < OldBitWidth)
2788 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2789 return true;
2790}
2791
2792/// Perform the given integer operation, which is known to need at most BitWidth
2793/// bits, and check for overflow in the original type (if that type was not an
2794/// unsigned type).
2795template<typename Operation>
2796static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2797 const APSInt &LHS, const APSInt &RHS,
2798 unsigned BitWidth, Operation Op,
2799 APSInt &Result) {
2800 if (LHS.isUnsigned()) {
2801 Result = Op(LHS, RHS);
2802 return true;
2803 }
2804
2805 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2806 Result = Value.trunc(LHS.getBitWidth());
2807 if (Result.extend(BitWidth) != Value) {
2808 if (Info.checkingForUndefinedBehavior())
2809 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2810 diag::warn_integer_constant_overflow)
2811 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2812 /*UpperCase=*/true, /*InsertSeparators=*/true)
2813 << E->getType() << E->getSourceRange();
2814 return HandleOverflow(Info, E, Value, E->getType());
2815 }
2816 return true;
2817}
2818
2819/// Perform the given binary integer operation.
2820static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2821 const APSInt &LHS, BinaryOperatorKind Opcode,
2822 APSInt RHS, APSInt &Result) {
2823 bool HandleOverflowResult = true;
2824 switch (Opcode) {
2825 default:
2826 Info.FFDiag(E);
2827 return false;
2828 case BO_Mul:
2829 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2830 std::multiplies<APSInt>(), Result);
2831 case BO_Add:
2832 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2833 std::plus<APSInt>(), Result);
2834 case BO_Sub:
2835 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2836 std::minus<APSInt>(), Result);
2837 case BO_And: Result = LHS & RHS; return true;
2838 case BO_Xor: Result = LHS ^ RHS; return true;
2839 case BO_Or: Result = LHS | RHS; return true;
2840 case BO_Div:
2841 case BO_Rem:
2842 if (RHS == 0) {
2843 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2844 << E->getRHS()->getSourceRange();
2845 return false;
2846 }
2847 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2848 // this operation and gives the two's complement result.
2849 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2850 LHS.isMinSignedValue())
2851 HandleOverflowResult = HandleOverflow(
2852 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2853 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2854 return HandleOverflowResult;
2855 case BO_Shl: {
2856 if (Info.getLangOpts().OpenCL)
2857 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2858 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2859 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2860 RHS.isUnsigned());
2861 else if (RHS.isSigned() && RHS.isNegative()) {
2862 // During constant-folding, a negative shift is an opposite shift. Such
2863 // a shift is not a constant expression.
2864 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2865 if (!Info.noteUndefinedBehavior())
2866 return false;
2867 RHS = -RHS;
2868 goto shift_right;
2869 }
2870 shift_left:
2871 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2872 // the shifted type.
2873 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2874 if (SA != RHS) {
2875 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2876 << RHS << E->getType() << LHS.getBitWidth();
2877 if (!Info.noteUndefinedBehavior())
2878 return false;
2879 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2880 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2881 // operand, and must not overflow the corresponding unsigned type.
2882 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2883 // E1 x 2^E2 module 2^N.
2884 if (LHS.isNegative()) {
2885 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2886 if (!Info.noteUndefinedBehavior())
2887 return false;
2888 } else if (LHS.countl_zero() < SA) {
2889 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2890 if (!Info.noteUndefinedBehavior())
2891 return false;
2892 }
2893 }
2894 Result = LHS << SA;
2895 return true;
2896 }
2897 case BO_Shr: {
2898 if (Info.getLangOpts().OpenCL)
2899 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2900 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2901 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2902 RHS.isUnsigned());
2903 else if (RHS.isSigned() && RHS.isNegative()) {
2904 // During constant-folding, a negative shift is an opposite shift. Such a
2905 // shift is not a constant expression.
2906 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2907 if (!Info.noteUndefinedBehavior())
2908 return false;
2909 RHS = -RHS;
2910 goto shift_left;
2911 }
2912 shift_right:
2913 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2914 // shifted type.
2915 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2916 if (SA != RHS) {
2917 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2918 << RHS << E->getType() << LHS.getBitWidth();
2919 if (!Info.noteUndefinedBehavior())
2920 return false;
2921 }
2922
2923 Result = LHS >> SA;
2924 return true;
2925 }
2926
2927 case BO_LT: Result = LHS < RHS; return true;
2928 case BO_GT: Result = LHS > RHS; return true;
2929 case BO_LE: Result = LHS <= RHS; return true;
2930 case BO_GE: Result = LHS >= RHS; return true;
2931 case BO_EQ: Result = LHS == RHS; return true;
2932 case BO_NE: Result = LHS != RHS; return true;
2933 case BO_Cmp:
2934 llvm_unreachable("BO_Cmp should be handled elsewhere");
2935 }
2936}
2937
2938/// Perform the given binary floating-point operation, in-place, on LHS.
2939static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2940 APFloat &LHS, BinaryOperatorKind Opcode,
2941 const APFloat &RHS) {
2942 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2943 APFloat::opStatus St;
2944 switch (Opcode) {
2945 default:
2946 Info.FFDiag(E);
2947 return false;
2948 case BO_Mul:
2949 St = LHS.multiply(RHS, RM);
2950 break;
2951 case BO_Add:
2952 St = LHS.add(RHS, RM);
2953 break;
2954 case BO_Sub:
2955 St = LHS.subtract(RHS, RM);
2956 break;
2957 case BO_Div:
2958 // [expr.mul]p4:
2959 // If the second operand of / or % is zero the behavior is undefined.
2960 if (RHS.isZero())
2961 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2962 St = LHS.divide(RHS, RM);
2963 break;
2964 }
2965
2966 // [expr.pre]p4:
2967 // If during the evaluation of an expression, the result is not
2968 // mathematically defined [...], the behavior is undefined.
2969 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2970 if (LHS.isNaN()) {
2971 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2972 return Info.noteUndefinedBehavior();
2973 }
2974
2975 return checkFloatingPointResult(Info, E, St);
2976}
2977
2978static bool handleLogicalOpForVector(const APInt &LHSValue,
2979 BinaryOperatorKind Opcode,
2980 const APInt &RHSValue, APInt &Result) {
2981 bool LHS = (LHSValue != 0);
2982 bool RHS = (RHSValue != 0);
2983
2984 if (Opcode == BO_LAnd)
2985 Result = LHS && RHS;
2986 else
2987 Result = LHS || RHS;
2988 return true;
2989}
2990static bool handleLogicalOpForVector(const APFloat &LHSValue,
2991 BinaryOperatorKind Opcode,
2992 const APFloat &RHSValue, APInt &Result) {
2993 bool LHS = !LHSValue.isZero();
2994 bool RHS = !RHSValue.isZero();
2995
2996 if (Opcode == BO_LAnd)
2997 Result = LHS && RHS;
2998 else
2999 Result = LHS || RHS;
3000 return true;
3001}
3002
3003static bool handleLogicalOpForVector(const APValue &LHSValue,
3004 BinaryOperatorKind Opcode,
3005 const APValue &RHSValue, APInt &Result) {
3006 // The result is always an int type, however operands match the first.
3007 if (LHSValue.getKind() == APValue::Int)
3008 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3009 RHSValue.getInt(), Result);
3010 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3011 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3012 RHSValue.getFloat(), Result);
3013}
3014
3015template <typename APTy>
3016static bool
3018 const APTy &RHSValue, APInt &Result) {
3019 switch (Opcode) {
3020 default:
3021 llvm_unreachable("unsupported binary operator");
3022 case BO_EQ:
3023 Result = (LHSValue == RHSValue);
3024 break;
3025 case BO_NE:
3026 Result = (LHSValue != RHSValue);
3027 break;
3028 case BO_LT:
3029 Result = (LHSValue < RHSValue);
3030 break;
3031 case BO_GT:
3032 Result = (LHSValue > RHSValue);
3033 break;
3034 case BO_LE:
3035 Result = (LHSValue <= RHSValue);
3036 break;
3037 case BO_GE:
3038 Result = (LHSValue >= RHSValue);
3039 break;
3040 }
3041
3042 // The boolean operations on these vector types use an instruction that
3043 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3044 // to -1 to make sure that we produce the correct value.
3045 Result.negate();
3046
3047 return true;
3048}
3049
3050static bool handleCompareOpForVector(const APValue &LHSValue,
3051 BinaryOperatorKind Opcode,
3052 const APValue &RHSValue, APInt &Result) {
3053 // The result is always an int type, however operands match the first.
3054 if (LHSValue.getKind() == APValue::Int)
3055 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3056 RHSValue.getInt(), Result);
3057 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3058 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3059 RHSValue.getFloat(), Result);
3060}
3061
3062// Perform binary operations for vector types, in place on the LHS.
3063static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3064 BinaryOperatorKind Opcode,
3065 APValue &LHSValue,
3066 const APValue &RHSValue) {
3067 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3068 "Operation not supported on vector types");
3069
3070 const auto *VT = E->getType()->castAs<VectorType>();
3071 unsigned NumElements = VT->getNumElements();
3072 QualType EltTy = VT->getElementType();
3073
3074 // In the cases (typically C as I've observed) where we aren't evaluating
3075 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3076 // just give up.
3077 if (!LHSValue.isVector()) {
3078 assert(LHSValue.isLValue() &&
3079 "A vector result that isn't a vector OR uncalculated LValue");
3080 Info.FFDiag(E);
3081 return false;
3082 }
3083
3084 assert(LHSValue.getVectorLength() == NumElements &&
3085 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3086
3087 SmallVector<APValue, 4> ResultElements;
3088
3089 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3090 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3091 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3092
3093 if (EltTy->isIntegerType()) {
3094 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3095 EltTy->isUnsignedIntegerType()};
3096 bool Success = true;
3097
3098 if (BinaryOperator::isLogicalOp(Opcode))
3099 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3100 else if (BinaryOperator::isComparisonOp(Opcode))
3101 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3102 else
3103 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3104 RHSElt.getInt(), EltResult);
3105
3106 if (!Success) {
3107 Info.FFDiag(E);
3108 return false;
3109 }
3110 ResultElements.emplace_back(EltResult);
3111
3112 } else if (EltTy->isFloatingType()) {
3113 assert(LHSElt.getKind() == APValue::Float &&
3114 RHSElt.getKind() == APValue::Float &&
3115 "Mismatched LHS/RHS/Result Type");
3116 APFloat LHSFloat = LHSElt.getFloat();
3117
3118 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3119 RHSElt.getFloat())) {
3120 Info.FFDiag(E);
3121 return false;
3122 }
3123
3124 ResultElements.emplace_back(LHSFloat);
3125 }
3126 }
3127
3128 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3129 return true;
3130}
3131
3132/// Cast an lvalue referring to a base subobject to a derived class, by
3133/// truncating the lvalue's path to the given length.
3134static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3135 const RecordDecl *TruncatedType,
3136 unsigned TruncatedElements) {
3137 SubobjectDesignator &D = Result.Designator;
3138
3139 // Check we actually point to a derived class object.
3140 if (TruncatedElements == D.Entries.size())
3141 return true;
3142 assert(TruncatedElements >= D.MostDerivedPathLength &&
3143 "not casting to a derived class");
3144 if (!Result.checkSubobject(Info, E, CSK_Derived))
3145 return false;
3146
3147 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3148 const RecordDecl *RD = TruncatedType;
3149 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3150 if (RD->isInvalidDecl()) return false;
3151 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3152 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3153 if (isVirtualBaseClass(D.Entries[I]))
3154 Result.Offset -= Layout.getVBaseClassOffset(Base);
3155 else
3156 Result.Offset -= Layout.getBaseClassOffset(Base);
3157 RD = Base;
3158 }
3159 D.Entries.resize(TruncatedElements);
3160 return true;
3161}
3162
3163static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3164 const CXXRecordDecl *Derived,
3165 const CXXRecordDecl *Base,
3166 const ASTRecordLayout *RL = nullptr) {
3167 if (!RL) {
3168 if (Derived->isInvalidDecl()) return false;
3169 RL = &Info.Ctx.getASTRecordLayout(Derived);
3170 }
3171
3172 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3173 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3174 return true;
3175}
3176
3177static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3178 const CXXRecordDecl *DerivedDecl,
3179 const CXXBaseSpecifier *Base) {
3180 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3181
3182 if (!Base->isVirtual())
3183 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3184
3185 SubobjectDesignator &D = Obj.Designator;
3186 if (D.Invalid)
3187 return false;
3188
3189 // Extract most-derived object and corresponding type.
3190 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3191 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3192 return false;
3193
3194 // Find the virtual base class.
3195 if (DerivedDecl->isInvalidDecl()) return false;
3196 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3197 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3198 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3199 return true;
3200}
3201
3202static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3203 QualType Type, LValue &Result) {
3204 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3205 PathE = E->path_end();
3206 PathI != PathE; ++PathI) {
3207 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3208 *PathI))
3209 return false;
3210 Type = (*PathI)->getType();
3211 }
3212 return true;
3213}
3214
3215/// Cast an lvalue referring to a derived class to a known base subobject.
3216static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3217 const CXXRecordDecl *DerivedRD,
3218 const CXXRecordDecl *BaseRD) {
3219 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3220 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3221 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3222 llvm_unreachable("Class must be derived from the passed in base class!");
3223
3224 for (CXXBasePathElement &Elem : Paths.front())
3225 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3226 return false;
3227 return true;
3228}
3229
3230/// Update LVal to refer to the given field, which must be a member of the type
3231/// currently described by LVal.
3232static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3233 const FieldDecl *FD,
3234 const ASTRecordLayout *RL = nullptr) {
3235 if (!RL) {
3236 if (FD->getParent()->isInvalidDecl()) return false;
3237 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3238 }
3239
3240 unsigned I = FD->getFieldIndex();
3241 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3242 LVal.addDecl(Info, E, FD);
3243 return true;
3244}
3245
3246/// Update LVal to refer to the given indirect field.
3247static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3248 LValue &LVal,
3249 const IndirectFieldDecl *IFD) {
3250 for (const auto *C : IFD->chain())
3251 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3252 return false;
3253 return true;
3254}
3255
3256enum class SizeOfType {
3257 SizeOf,
3258 DataSizeOf,
3259};
3260
3261/// Get the size of the given type in char units.
3262static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3263 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3264 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3265 // extension.
3266 if (Type->isVoidType() || Type->isFunctionType()) {
3267 Size = CharUnits::One();
3268 return true;
3269 }
3270
3271 if (Type->isDependentType()) {
3272 Info.FFDiag(Loc);
3273 return false;
3274 }
3275
3276 if (!Type->isConstantSizeType()) {
3277 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3278 // FIXME: Better diagnostic.
3279 Info.FFDiag(Loc);
3280 return false;
3281 }
3282
3283 if (SOT == SizeOfType::SizeOf)
3284 Size = Info.Ctx.getTypeSizeInChars(Type);
3285 else
3286 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3287 return true;
3288}
3289
3290/// Update a pointer value to model pointer arithmetic.
3291/// \param Info - Information about the ongoing evaluation.
3292/// \param E - The expression being evaluated, for diagnostic purposes.
3293/// \param LVal - The pointer value to be updated.
3294/// \param EltTy - The pointee type represented by LVal.
3295/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3296static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3297 LValue &LVal, QualType EltTy,
3298 APSInt Adjustment) {
3299 CharUnits SizeOfPointee;
3300 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3301 return false;
3302
3303 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3304 return true;
3305}
3306
3307static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3308 LValue &LVal, QualType EltTy,
3309 int64_t Adjustment) {
3310 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3311 APSInt::get(Adjustment));
3312}
3313
3314/// Update an lvalue to refer to a component of a complex number.
3315/// \param Info - Information about the ongoing evaluation.
3316/// \param LVal - The lvalue to be updated.
3317/// \param EltTy - The complex number's component type.
3318/// \param Imag - False for the real component, true for the imaginary.
3319static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3320 LValue &LVal, QualType EltTy,
3321 bool Imag) {
3322 if (Imag) {
3323 CharUnits SizeOfComponent;
3324 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3325 return false;
3326 LVal.Offset += SizeOfComponent;
3327 }
3328 LVal.addComplex(Info, E, EltTy, Imag);
3329 return true;
3330}
3331
3332static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3333 LValue &LVal, QualType EltTy,
3334 uint64_t Size, uint64_t Idx) {
3335 if (Idx) {
3336 CharUnits SizeOfElement;
3337 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3338 return false;
3339 LVal.Offset += SizeOfElement * Idx;
3340 }
3341 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3342 return true;
3343}
3344
3345/// Try to evaluate the initializer for a variable declaration.
3346///
3347/// \param Info Information about the ongoing evaluation.
3348/// \param E An expression to be used when printing diagnostics.
3349/// \param VD The variable whose initializer should be obtained.
3350/// \param Version The version of the variable within the frame.
3351/// \param Frame The frame in which the variable was created. Must be null
3352/// if this variable is not local to the evaluation.
3353/// \param Result Filled in with a pointer to the value of the variable.
3354static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3355 const VarDecl *VD, CallStackFrame *Frame,
3356 unsigned Version, APValue *&Result) {
3357 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3358
3359 // If this is a local variable, dig out its value.
3360 if (Frame) {
3361 Result = Frame->getTemporary(VD, Version);
3362 if (Result)
3363 return true;
3364
3365 if (!isa<ParmVarDecl>(VD)) {
3366 // Assume variables referenced within a lambda's call operator that were
3367 // not declared within the call operator are captures and during checking
3368 // of a potential constant expression, assume they are unknown constant
3369 // expressions.
3370 assert(isLambdaCallOperator(Frame->Callee) &&
3371 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3372 "missing value for local variable");
3373 if (Info.checkingPotentialConstantExpression())
3374 return false;
3375 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3376 // still reachable at all?
3377 Info.FFDiag(E->getBeginLoc(),
3378 diag::note_unimplemented_constexpr_lambda_feature_ast)
3379 << "captures not currently allowed";
3380 return false;
3381 }
3382 }
3383
3384 // If we're currently evaluating the initializer of this declaration, use that
3385 // in-flight value.
3386 if (Info.EvaluatingDecl == Base) {
3387 Result = Info.EvaluatingDeclValue;
3388 return true;
3389 }
3390
3391 if (isa<ParmVarDecl>(VD)) {
3392 // Assume parameters of a potential constant expression are usable in
3393 // constant expressions.
3394 if (!Info.checkingPotentialConstantExpression() ||
3395 !Info.CurrentCall->Callee ||
3396 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3397 if (Info.getLangOpts().CPlusPlus11) {
3398 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3399 << VD;
3400 NoteLValueLocation(Info, Base);
3401 } else {
3402 Info.FFDiag(E);
3403 }
3404 }
3405 return false;
3406 }
3407
3408 if (E->isValueDependent())
3409 return false;
3410
3411 // Dig out the initializer, and use the declaration which it's attached to.
3412 // FIXME: We should eventually check whether the variable has a reachable
3413 // initializing declaration.
3414 const Expr *Init = VD->getAnyInitializer(VD);
3415 if (!Init) {
3416 // Don't diagnose during potential constant expression checking; an
3417 // initializer might be added later.
3418 if (!Info.checkingPotentialConstantExpression()) {
3419 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3420 << VD;
3421 NoteLValueLocation(Info, Base);
3422 }
3423 return false;
3424 }
3425
3426 if (Init->isValueDependent()) {
3427 // The DeclRefExpr is not value-dependent, but the variable it refers to
3428 // has a value-dependent initializer. This should only happen in
3429 // constant-folding cases, where the variable is not actually of a suitable
3430 // type for use in a constant expression (otherwise the DeclRefExpr would
3431 // have been value-dependent too), so diagnose that.
3432 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3433 if (!Info.checkingPotentialConstantExpression()) {
3434 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3435 ? diag::note_constexpr_ltor_non_constexpr
3436 : diag::note_constexpr_ltor_non_integral, 1)
3437 << VD << VD->getType();
3438 NoteLValueLocation(Info, Base);
3439 }
3440 return false;
3441 }
3442
3443 // Check that we can fold the initializer. In C++, we will have already done
3444 // this in the cases where it matters for conformance.
3445 if (!VD->evaluateValue()) {
3446 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3447 NoteLValueLocation(Info, Base);
3448 return false;
3449 }
3450
3451 // Check that the variable is actually usable in constant expressions. For a
3452 // const integral variable or a reference, we might have a non-constant
3453 // initializer that we can nonetheless evaluate the initializer for. Such
3454 // variables are not usable in constant expressions. In C++98, the
3455 // initializer also syntactically needs to be an ICE.
3456 //
3457 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3458 // expressions here; doing so would regress diagnostics for things like
3459 // reading from a volatile constexpr variable.
3460 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3461 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3462 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3463 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3464 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3465 NoteLValueLocation(Info, Base);
3466 }
3467
3468 // Never use the initializer of a weak variable, not even for constant
3469 // folding. We can't be sure that this is the definition that will be used.
3470 if (VD->isWeak()) {
3471 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3472 NoteLValueLocation(Info, Base);
3473 return false;
3474 }
3475
3476 Result = VD->getEvaluatedValue();
3477 return true;
3478}
3479
3480/// Get the base index of the given base class within an APValue representing
3481/// the given derived class.
3482static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3483 const CXXRecordDecl *Base) {
3484 Base = Base->getCanonicalDecl();
3485 unsigned Index = 0;
3487 E = Derived->bases_end(); I != E; ++I, ++Index) {
3488 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3489 return Index;
3490 }
3491
3492 llvm_unreachable("base class missing from derived class's bases list");
3493}
3494
3495/// Extract the value of a character from a string literal.
3496static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3497 uint64_t Index) {
3498 assert(!isa<SourceLocExpr>(Lit) &&
3499 "SourceLocExpr should have already been converted to a StringLiteral");
3500
3501 // FIXME: Support MakeStringConstant
3502 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3503 std::string Str;
3504 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3505 assert(Index <= Str.size() && "Index too large");
3506 return APSInt::getUnsigned(Str.c_str()[Index]);
3507 }
3508
3509 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3510 Lit = PE->getFunctionName();
3511 const StringLiteral *S = cast<StringLiteral>(Lit);
3512 const ConstantArrayType *CAT =
3513 Info.Ctx.getAsConstantArrayType(S->getType());
3514 assert(CAT && "string literal isn't an array");
3515 QualType CharType = CAT->getElementType();
3516 assert(CharType->isIntegerType() && "unexpected character type");
3517 APSInt Value(Info.Ctx.getTypeSize(CharType),
3518 CharType->isUnsignedIntegerType());
3519 if (Index < S->getLength())
3520 Value = S->getCodeUnit(Index);
3521 return Value;
3522}
3523
3524// Expand a string literal into an array of characters.
3525//
3526// FIXME: This is inefficient; we should probably introduce something similar
3527// to the LLVM ConstantDataArray to make this cheaper.
3528static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3529 APValue &Result,
3530 QualType AllocType = QualType()) {
3531 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3532 AllocType.isNull() ? S->getType() : AllocType);
3533 assert(CAT && "string literal isn't an array");
3534 QualType CharType = CAT->getElementType();
3535 assert(CharType->isIntegerType() && "unexpected character type");
3536
3537 unsigned Elts = CAT->getZExtSize();
3538 Result = APValue(APValue::UninitArray(),
3539 std::min(S->getLength(), Elts), Elts);
3540 APSInt Value(Info.Ctx.getTypeSize(CharType),
3541 CharType->isUnsignedIntegerType());
3542 if (Result.hasArrayFiller())
3543 Result.getArrayFiller() = APValue(Value);
3544 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3545 Value = S->getCodeUnit(I);
3546 Result.getArrayInitializedElt(I) = APValue(Value);
3547 }
3548}
3549
3550// Expand an array so that it has more than Index filled elements.
3551static void expandArray(APValue &Array, unsigned Index) {
3552 unsigned Size = Array.getArraySize();
3553 assert(Index < Size);
3554
3555 // Always at least double the number of elements for which we store a value.
3556 unsigned OldElts = Array.getArrayInitializedElts();
3557 unsigned NewElts = std::max(Index+1, OldElts * 2);
3558 NewElts = std::min(Size, std::max(NewElts, 8u));
3559
3560 // Copy the data across.
3561 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3562 for (unsigned I = 0; I != OldElts; ++I)
3563 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3564 for (unsigned I = OldElts; I != NewElts; ++I)
3565 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3566 if (NewValue.hasArrayFiller())
3567 NewValue.getArrayFiller() = Array.getArrayFiller();
3568 Array.swap(NewValue);
3569}
3570
3571/// Determine whether a type would actually be read by an lvalue-to-rvalue
3572/// conversion. If it's of class type, we may assume that the copy operation
3573/// is trivial. Note that this is never true for a union type with fields
3574/// (because the copy always "reads" the active member) and always true for
3575/// a non-class type.
3576static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3579 return !RD || isReadByLvalueToRvalueConversion(RD);
3580}
3582 // FIXME: A trivial copy of a union copies the object representation, even if
3583 // the union is empty.
3584 if (RD->isUnion())
3585 return !RD->field_empty();
3586 if (RD->isEmpty())
3587 return false;
3588
3589 for (auto *Field : RD->fields())
3590 if (!Field->isUnnamedBitField() &&
3591 isReadByLvalueToRvalueConversion(Field->getType()))
3592 return true;
3593
3594 for (auto &BaseSpec : RD->bases())
3595 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3596 return true;
3597
3598 return false;
3599}
3600
3601/// Diagnose an attempt to read from any unreadable field within the specified
3602/// type, which might be a class type.
3603static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3604 QualType T) {
3606 if (!RD)
3607 return false;
3608
3609 if (!RD->hasMutableFields())
3610 return false;
3611
3612 for (auto *Field : RD->fields()) {
3613 // If we're actually going to read this field in some way, then it can't
3614 // be mutable. If we're in a union, then assigning to a mutable field
3615 // (even an empty one) can change the active member, so that's not OK.
3616 // FIXME: Add core issue number for the union case.
3617 if (Field->isMutable() &&
3618 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3619 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3620 Info.Note(Field->getLocation(), diag::note_declared_at);
3621 return true;
3622 }
3623
3624 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3625 return true;
3626 }
3627
3628 for (auto &BaseSpec : RD->bases())
3629 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3630 return true;
3631
3632 // All mutable fields were empty, and thus not actually read.
3633 return false;
3634}
3635
3636static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3638 bool MutableSubobject = false) {
3639 // A temporary or transient heap allocation we created.
3640 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3641 return true;
3642
3643 switch (Info.IsEvaluatingDecl) {
3644 case EvalInfo::EvaluatingDeclKind::None:
3645 return false;
3646
3647 case EvalInfo::EvaluatingDeclKind::Ctor:
3648 // The variable whose initializer we're evaluating.
3649 if (Info.EvaluatingDecl == Base)
3650 return true;
3651
3652 // A temporary lifetime-extended by the variable whose initializer we're
3653 // evaluating.
3654 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3655 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3656 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3657 return false;
3658
3659 case EvalInfo::EvaluatingDeclKind::Dtor:
3660 // C++2a [expr.const]p6:
3661 // [during constant destruction] the lifetime of a and its non-mutable
3662 // subobjects (but not its mutable subobjects) [are] considered to start
3663 // within e.
3664 if (MutableSubobject || Base != Info.EvaluatingDecl)
3665 return false;
3666 // FIXME: We can meaningfully extend this to cover non-const objects, but
3667 // we will need special handling: we should be able to access only
3668 // subobjects of such objects that are themselves declared const.
3669 QualType T = getType(Base);
3670 return T.isConstQualified() || T->isReferenceType();
3671 }
3672
3673 llvm_unreachable("unknown evaluating decl kind");
3674}
3675
3676static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3677 SourceLocation CallLoc = {}) {
3678 return Info.CheckArraySize(
3679 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3680 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3681 /*Diag=*/true);
3682}
3683
3684namespace {
3685/// A handle to a complete object (an object that is not a subobject of
3686/// another object).
3687struct CompleteObject {
3688 /// The identity of the object.
3690 /// The value of the complete object.
3691 APValue *Value;
3692 /// The type of the complete object.
3693 QualType Type;
3694
3695 CompleteObject() : Value(nullptr) {}
3697 : Base(Base), Value(Value), Type(Type) {}
3698
3699 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3700 // If this isn't a "real" access (eg, if it's just accessing the type
3701 // info), allow it. We assume the type doesn't change dynamically for
3702 // subobjects of constexpr objects (even though we'd hit UB here if it
3703 // did). FIXME: Is this right?
3704 if (!isAnyAccess(AK))
3705 return true;
3706
3707 // In C++14 onwards, it is permitted to read a mutable member whose
3708 // lifetime began within the evaluation.
3709 // FIXME: Should we also allow this in C++11?
3710 if (!Info.getLangOpts().CPlusPlus14)
3711 return false;
3712 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3713 }
3714
3715 explicit operator bool() const { return !Type.isNull(); }
3716};
3717} // end anonymous namespace
3718
3719static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3720 bool IsMutable = false) {
3721 // C++ [basic.type.qualifier]p1:
3722 // - A const object is an object of type const T or a non-mutable subobject
3723 // of a const object.
3724 if (ObjType.isConstQualified() && !IsMutable)
3725 SubobjType.addConst();
3726 // - A volatile object is an object of type const T or a subobject of a
3727 // volatile object.
3728 if (ObjType.isVolatileQualified())
3729 SubobjType.addVolatile();
3730 return SubobjType;
3731}
3732
3733/// Find the designated sub-object of an rvalue.
3734template<typename SubobjectHandler>
3735typename SubobjectHandler::result_type
3736findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3737 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3738 if (Sub.Invalid)
3739 // A diagnostic will have already been produced.
3740 return handler.failed();
3741 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3742 if (Info.getLangOpts().CPlusPlus11)
3743 Info.FFDiag(E, Sub.isOnePastTheEnd()
3744 ? diag::note_constexpr_access_past_end
3745 : diag::note_constexpr_access_unsized_array)
3746 << handler.AccessKind;
3747 else
3748 Info.FFDiag(E);
3749 return handler.failed();
3750 }
3751
3752 APValue *O = Obj.Value;
3753 QualType ObjType = Obj.Type;
3754 const FieldDecl *LastField = nullptr;
3755 const FieldDecl *VolatileField = nullptr;
3756
3757 // Walk the designator's path to find the subobject.
3758 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3759 // Reading an indeterminate value is undefined, but assigning over one is OK.
3760 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3761 (O->isIndeterminate() &&
3762 !isValidIndeterminateAccess(handler.AccessKind))) {
3763 if (!Info.checkingPotentialConstantExpression())
3764 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3765 << handler.AccessKind << O->isIndeterminate()
3766 << E->getSourceRange();
3767 return handler.failed();
3768 }
3769
3770 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3771 // const and volatile semantics are not applied on an object under
3772 // {con,de}struction.
3773 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3774 ObjType->isRecordType() &&
3775 Info.isEvaluatingCtorDtor(
3776 Obj.Base,
3777 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3778 ConstructionPhase::None) {
3779 ObjType = Info.Ctx.getCanonicalType(ObjType);
3780 ObjType.removeLocalConst();
3781 ObjType.removeLocalVolatile();
3782 }
3783
3784 // If this is our last pass, check that the final object type is OK.
3785 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3786 // Accesses to volatile objects are prohibited.
3787 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3788 if (Info.getLangOpts().CPlusPlus) {
3789 int DiagKind;
3791 const NamedDecl *Decl = nullptr;
3792 if (VolatileField) {
3793 DiagKind = 2;
3794 Loc = VolatileField->getLocation();
3795 Decl = VolatileField;
3796 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3797 DiagKind = 1;
3798 Loc = VD->getLocation();
3799 Decl = VD;
3800 } else {
3801 DiagKind = 0;
3802 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3803 Loc = E->getExprLoc();
3804 }
3805 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3806 << handler.AccessKind << DiagKind << Decl;
3807 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3808 } else {
3809 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3810 }
3811 return handler.failed();
3812 }
3813
3814 // If we are reading an object of class type, there may still be more
3815 // things we need to check: if there are any mutable subobjects, we
3816 // cannot perform this read. (This only happens when performing a trivial
3817 // copy or assignment.)
3818 if (ObjType->isRecordType() &&
3819 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3820 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3821 return handler.failed();
3822 }
3823
3824 if (I == N) {
3825 if (!handler.found(*O, ObjType))
3826 return false;
3827
3828 // If we modified a bit-field, truncate it to the right width.
3829 if (isModification(handler.AccessKind) &&
3830 LastField && LastField->isBitField() &&
3831 !truncateBitfieldValue(Info, E, *O, LastField))
3832 return false;
3833
3834 return true;
3835 }
3836
3837 LastField = nullptr;
3838 if (ObjType->isArrayType()) {
3839 // Next subobject is an array element.
3840 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3841 assert(CAT && "vla in literal type?");
3842 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3843 if (CAT->getSize().ule(Index)) {
3844 // Note, it should not be possible to form a pointer with a valid
3845 // designator which points more than one past the end of the array.
3846 if (Info.getLangOpts().CPlusPlus11)
3847 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3848 << handler.AccessKind;
3849 else
3850 Info.FFDiag(E);
3851 return handler.failed();
3852 }
3853
3854 ObjType = CAT->getElementType();
3855
3856 if (O->getArrayInitializedElts() > Index)
3857 O = &O->getArrayInitializedElt(Index);
3858 else if (!isRead(handler.AccessKind)) {
3859 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3860 return handler.failed();
3861
3862 expandArray(*O, Index);
3863 O = &O->getArrayInitializedElt(Index);
3864 } else
3865 O = &O->getArrayFiller();
3866 } else if (ObjType->isAnyComplexType()) {
3867 // Next subobject is a complex number.
3868 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3869 if (Index > 1) {
3870 if (Info.getLangOpts().CPlusPlus11)
3871 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3872 << handler.AccessKind;
3873 else
3874 Info.FFDiag(E);
3875 return handler.failed();
3876 }
3877
3878 ObjType = getSubobjectType(
3879 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3880
3881 assert(I == N - 1 && "extracting subobject of scalar?");
3882 if (O->isComplexInt()) {
3883 return handler.found(Index ? O->getComplexIntImag()
3884 : O->getComplexIntReal(), ObjType);
3885 } else {
3886 assert(O->isComplexFloat());
3887 return handler.found(Index ? O->getComplexFloatImag()
3888 : O->getComplexFloatReal(), ObjType);
3889 }
3890 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
3891 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3892 unsigned NumElements = VT->getNumElements();
3893 if (Index == NumElements) {
3894 if (Info.getLangOpts().CPlusPlus11)
3895 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3896 << handler.AccessKind;
3897 else
3898 Info.FFDiag(E);
3899 return handler.failed();
3900 }
3901
3902 if (Index > NumElements) {
3903 Info.CCEDiag(E, diag::note_constexpr_array_index)
3904 << Index << /*array*/ 0 << NumElements;
3905 return handler.failed();
3906 }
3907
3908 ObjType = VT->getElementType();
3909 assert(I == N - 1 && "extracting subobject of scalar?");
3910 return handler.found(O->getVectorElt(Index), ObjType);
3911 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3912 if (Field->isMutable() &&
3913 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3914 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3915 << handler.AccessKind << Field;
3916 Info.Note(Field->getLocation(), diag::note_declared_at);
3917 return handler.failed();
3918 }
3919
3920 // Next subobject is a class, struct or union field.
3921 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3922 if (RD->isUnion()) {
3923 const FieldDecl *UnionField = O->getUnionField();
3924 if (!UnionField ||
3925 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3926 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3927 // Placement new onto an inactive union member makes it active.
3928 O->setUnion(Field, APValue());
3929 } else {
3930 // FIXME: If O->getUnionValue() is absent, report that there's no
3931 // active union member rather than reporting the prior active union
3932 // member. We'll need to fix nullptr_t to not use APValue() as its
3933 // representation first.
3934 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3935 << handler.AccessKind << Field << !UnionField << UnionField;
3936 return handler.failed();
3937 }
3938 }
3939 O = &O->getUnionValue();
3940 } else
3941 O = &O->getStructField(Field->getFieldIndex());
3942
3943 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3944 LastField = Field;
3945 if (Field->getType().isVolatileQualified())
3946 VolatileField = Field;
3947 } else {
3948 // Next subobject is a base class.
3949 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3950 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3951 O = &O->getStructBase(getBaseIndex(Derived, Base));
3952
3953 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3954 }
3955 }
3956}
3957
3958namespace {
3959struct ExtractSubobjectHandler {
3960 EvalInfo &Info;
3961 const Expr *E;
3962 APValue &Result;
3963 const AccessKinds AccessKind;
3964
3965 typedef bool result_type;
3966 bool failed() { return false; }
3967 bool found(APValue &Subobj, QualType SubobjType) {
3968 Result = Subobj;
3969 if (AccessKind == AK_ReadObjectRepresentation)
3970 return true;
3971 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3972 }
3973 bool found(APSInt &Value, QualType SubobjType) {
3974 Result = APValue(Value);
3975 return true;
3976 }
3977 bool found(APFloat &Value, QualType SubobjType) {
3978 Result = APValue(Value);
3979 return true;
3980 }
3981};
3982} // end anonymous namespace
3983
3984/// Extract the designated sub-object of an rvalue.
3985static bool extractSubobject(EvalInfo &Info, const Expr *E,
3986 const CompleteObject &Obj,
3987 const SubobjectDesignator &Sub, APValue &Result,
3988 AccessKinds AK = AK_Read) {
3989 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3990 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3991 return findSubobject(Info, E, Obj, Sub, Handler);
3992}
3993
3994namespace {
3995struct ModifySubobjectHandler {
3996 EvalInfo &Info;
3997 APValue &NewVal;
3998 const Expr *E;
3999
4000 typedef bool result_type;
4001 static const AccessKinds AccessKind = AK_Assign;
4002
4003 bool checkConst(QualType QT) {
4004 // Assigning to a const object has undefined behavior.
4005 if (QT.isConstQualified()) {
4006 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4007 return false;
4008 }
4009 return true;
4010 }
4011
4012 bool failed() { return false; }
4013 bool found(APValue &Subobj, QualType SubobjType) {
4014 if (!checkConst(SubobjType))
4015 return false;
4016 // We've been given ownership of NewVal, so just swap it in.
4017 Subobj.swap(NewVal);
4018 return true;
4019 }
4020 bool found(APSInt &Value, QualType SubobjType) {
4021 if (!checkConst(SubobjType))
4022 return false;
4023 if (!NewVal.isInt()) {
4024 // Maybe trying to write a cast pointer value into a complex?
4025 Info.FFDiag(E);
4026 return false;
4027 }
4028 Value = NewVal.getInt();
4029 return true;
4030 }
4031 bool found(APFloat &Value, QualType SubobjType) {
4032 if (!checkConst(SubobjType))
4033 return false;
4034 Value = NewVal.getFloat();
4035 return true;
4036 }
4037};
4038} // end anonymous namespace
4039
4040const AccessKinds ModifySubobjectHandler::AccessKind;
4041
4042/// Update the designated sub-object of an rvalue to the given value.
4043static bool modifySubobject(EvalInfo &Info, const Expr *E,
4044 const CompleteObject &Obj,
4045 const SubobjectDesignator &Sub,
4046 APValue &NewVal) {
4047 ModifySubobjectHandler Handler = { Info, NewVal, E };
4048 return findSubobject(Info, E, Obj, Sub, Handler);
4049}
4050
4051/// Find the position where two subobject designators diverge, or equivalently
4052/// the length of the common initial subsequence.
4053static unsigned FindDesignatorMismatch(QualType ObjType,
4054 const SubobjectDesignator &A,
4055 const SubobjectDesignator &B,
4056 bool &WasArrayIndex) {
4057 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4058 for (/**/; I != N; ++I) {
4059 if (!ObjType.isNull() &&
4060 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4061 // Next subobject is an array element.
4062 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4063 WasArrayIndex = true;
4064 return I;
4065 }
4066 if (ObjType->isAnyComplexType())
4067 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4068 else
4069 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4070 } else {
4071 if (A.Entries[I].getAsBaseOrMember() !=
4072 B.Entries[I].getAsBaseOrMember()) {
4073 WasArrayIndex = false;
4074 return I;
4075 }
4076 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4077 // Next subobject is a field.
4078 ObjType = FD->getType();
4079 else
4080 // Next subobject is a base class.
4081 ObjType = QualType();
4082 }
4083 }
4084 WasArrayIndex = false;
4085 return I;
4086}
4087
4088/// Determine whether the given subobject designators refer to elements of the
4089/// same array object.
4091 const SubobjectDesignator &A,
4092 const SubobjectDesignator &B) {
4093 if (A.Entries.size() != B.Entries.size())
4094 return false;
4095
4096 bool IsArray = A.MostDerivedIsArrayElement;
4097 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4098 // A is a subobject of the array element.
4099 return false;
4100
4101 // If A (and B) designates an array element, the last entry will be the array
4102 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4103 // of length 1' case, and the entire path must match.
4104 bool WasArrayIndex;
4105 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4106 return CommonLength >= A.Entries.size() - IsArray;
4107}
4108
4109/// Find the complete object to which an LValue refers.
4110static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4111 AccessKinds AK, const LValue &LVal,
4112 QualType LValType) {
4113 if (LVal.InvalidBase) {
4114 Info.FFDiag(E);
4115 return CompleteObject();
4116 }
4117
4118 if (!LVal.Base) {
4119 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4120 return CompleteObject();
4121 }
4122
4123 CallStackFrame *Frame = nullptr;
4124 unsigned Depth = 0;
4125 if (LVal.getLValueCallIndex()) {
4126 std::tie(Frame, Depth) =
4127 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4128 if (!Frame) {
4129 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4130 << AK << LVal.Base.is<const ValueDecl*>();
4131 NoteLValueLocation(Info, LVal.Base);
4132 return CompleteObject();
4133 }
4134 }
4135
4136 bool IsAccess = isAnyAccess(AK);
4137
4138 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4139 // is not a constant expression (even if the object is non-volatile). We also
4140 // apply this rule to C++98, in order to conform to the expected 'volatile'
4141 // semantics.
4142 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4143 if (Info.getLangOpts().CPlusPlus)
4144 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4145 << AK << LValType;
4146 else
4147 Info.FFDiag(E);
4148 return CompleteObject();
4149 }
4150
4151 // Compute value storage location and type of base object.
4152 APValue *BaseVal = nullptr;
4153 QualType BaseType = getType(LVal.Base);
4154
4155 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4156 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4157 // This is the object whose initializer we're evaluating, so its lifetime
4158 // started in the current evaluation.
4159 BaseVal = Info.EvaluatingDeclValue;
4160 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4161 // Allow reading from a GUID declaration.
4162 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4163 if (isModification(AK)) {
4164 // All the remaining cases do not permit modification of the object.
4165 Info.FFDiag(E, diag::note_constexpr_modify_global);
4166 return CompleteObject();
4167 }
4168 APValue &V = GD->getAsAPValue();
4169 if (V.isAbsent()) {
4170 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4171 << GD->getType();
4172 return CompleteObject();
4173 }
4174 return CompleteObject(LVal.Base, &V, GD->getType());
4175 }
4176
4177 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4178 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4179 if (isModification(AK)) {
4180 Info.FFDiag(E, diag::note_constexpr_modify_global);
4181 return CompleteObject();
4182 }
4183 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4184 GCD->getType());
4185 }
4186
4187 // Allow reading from template parameter objects.
4188 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4189 if (isModification(AK)) {
4190 Info.FFDiag(E, diag::note_constexpr_modify_global);
4191 return CompleteObject();
4192 }
4193 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4194 TPO->getType());
4195 }
4196
4197 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4198 // In C++11, constexpr, non-volatile variables initialized with constant
4199 // expressions are constant expressions too. Inside constexpr functions,
4200 // parameters are constant expressions even if they're non-const.
4201 // In C++1y, objects local to a constant expression (those with a Frame) are
4202 // both readable and writable inside constant expressions.
4203 // In C, such things can also be folded, although they are not ICEs.
4204 const VarDecl *VD = dyn_cast<VarDecl>(D);
4205 if (VD) {
4206 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4207 VD = VDef;
4208 }
4209 if (!VD || VD->isInvalidDecl()) {
4210 Info.FFDiag(E);
4211 return CompleteObject();
4212 }
4213
4214 bool IsConstant = BaseType.isConstant(Info.Ctx);
4215 bool ConstexprVar = false;
4216 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4217 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4218 ConstexprVar = VD->isConstexpr();
4219
4220 // Unless we're looking at a local variable or argument in a constexpr call,
4221 // the variable we're reading must be const.
4222 if (!Frame) {
4223 if (IsAccess && isa<ParmVarDecl>(VD)) {
4224 // Access of a parameter that's not associated with a frame isn't going
4225 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4226 // suitable diagnostic.
4227 } else if (Info.getLangOpts().CPlusPlus14 &&
4228 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4229 // OK, we can read and modify an object if we're in the process of
4230 // evaluating its initializer, because its lifetime began in this
4231 // evaluation.
4232 } else if (isModification(AK)) {
4233 // All the remaining cases do not permit modification of the object.
4234 Info.FFDiag(E, diag::note_constexpr_modify_global);
4235 return CompleteObject();
4236 } else if (VD->isConstexpr()) {
4237 // OK, we can read this variable.
4238 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4239 Info.FFDiag(E);
4240 return CompleteObject();
4241 } else if (BaseType->isIntegralOrEnumerationType()) {
4242 if (!IsConstant) {
4243 if (!IsAccess)
4244 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4245 if (Info.getLangOpts().CPlusPlus) {
4246 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4247 Info.Note(VD->getLocation(), diag::note_declared_at);
4248 } else {
4249 Info.FFDiag(E);
4250 }
4251 return CompleteObject();
4252 }
4253 } else if (!IsAccess) {
4254 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4255 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4256 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4257 // This variable might end up being constexpr. Don't diagnose it yet.
4258 } else if (IsConstant) {
4259 // Keep evaluating to see what we can do. In particular, we support
4260 // folding of const floating-point types, in order to make static const
4261 // data members of such types (supported as an extension) more useful.
4262 if (Info.getLangOpts().CPlusPlus) {
4263 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4264 ? diag::note_constexpr_ltor_non_constexpr
4265 : diag::note_constexpr_ltor_non_integral, 1)
4266 << VD << BaseType;
4267 Info.Note(VD->getLocation(), diag::note_declared_at);
4268 } else {
4269 Info.CCEDiag(E);
4270 }
4271 } else {
4272 // Never allow reading a non-const value.
4273 if (Info.getLangOpts().CPlusPlus) {
4274 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4275 ? diag::note_constexpr_ltor_non_constexpr
4276 : diag::note_constexpr_ltor_non_integral, 1)
4277 << VD << BaseType;
4278 Info.Note(VD->getLocation(), diag::note_declared_at);
4279 } else {
4280 Info.FFDiag(E);
4281 }
4282 return CompleteObject();
4283 }
4284 }
4285
4286 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4287 return CompleteObject();
4288 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4289 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4290 if (!Alloc) {
4291 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4292 return CompleteObject();
4293 }
4294 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4295 LVal.Base.getDynamicAllocType());
4296 } else {
4297 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4298
4299 if (!Frame) {
4300 if (const MaterializeTemporaryExpr *MTE =
4301 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4302 assert(MTE->getStorageDuration() == SD_Static &&
4303 "should have a frame for a non-global materialized temporary");
4304
4305 // C++20 [expr.const]p4: [DR2126]
4306 // An object or reference is usable in constant expressions if it is
4307 // - a temporary object of non-volatile const-qualified literal type
4308 // whose lifetime is extended to that of a variable that is usable
4309 // in constant expressions
4310 //
4311 // C++20 [expr.const]p5:
4312 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4313 // - a non-volatile glvalue that refers to an object that is usable
4314 // in constant expressions, or
4315 // - a non-volatile glvalue of literal type that refers to a
4316 // non-volatile object whose lifetime began within the evaluation
4317 // of E;
4318 //
4319 // C++11 misses the 'began within the evaluation of e' check and
4320 // instead allows all temporaries, including things like:
4321 // int &&r = 1;
4322 // int x = ++r;
4323 // constexpr int k = r;
4324 // Therefore we use the C++14-onwards rules in C++11 too.
4325 //
4326 // Note that temporaries whose lifetimes began while evaluating a
4327 // variable's constructor are not usable while evaluating the
4328 // corresponding destructor, not even if they're of const-qualified
4329 // types.
4330 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4331 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4332 if (!IsAccess)
4333 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4334 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4335 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4336 return CompleteObject();
4337 }
4338
4339 BaseVal = MTE->getOrCreateValue(false);
4340 assert(BaseVal && "got reference to unevaluated temporary");
4341 } else {
4342 if (!IsAccess)
4343 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4344 APValue Val;
4345 LVal.moveInto(Val);
4346 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4347 << AK
4348 << Val.getAsString(Info.Ctx,
4349 Info.Ctx.getLValueReferenceType(LValType));
4350 NoteLValueLocation(Info, LVal.Base);
4351 return CompleteObject();
4352 }
4353 } else {
4354 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4355 assert(BaseVal && "missing value for temporary");
4356 }
4357 }
4358
4359 // In C++14, we can't safely access any mutable state when we might be
4360 // evaluating after an unmodeled side effect. Parameters are modeled as state
4361 // in the caller, but aren't visible once the call returns, so they can be
4362 // modified in a speculatively-evaluated call.
4363 //
4364 // FIXME: Not all local state is mutable. Allow local constant subobjects
4365 // to be read here (but take care with 'mutable' fields).
4366 unsigned VisibleDepth = Depth;
4367 if (llvm::isa_and_nonnull<ParmVarDecl>(
4368 LVal.Base.dyn_cast<const ValueDecl *>()))
4369 ++VisibleDepth;
4370 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4371 Info.EvalStatus.HasSideEffects) ||
4372 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4373 return CompleteObject();
4374
4375 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4376}
4377
4378/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4379/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4380/// glvalue referred to by an entity of reference type.
4381///
4382/// \param Info - Information about the ongoing evaluation.
4383/// \param Conv - The expression for which we are performing the conversion.
4384/// Used for diagnostics.
4385/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4386/// case of a non-class type).
4387/// \param LVal - The glvalue on which we are attempting to perform this action.
4388/// \param RVal - The produced value will be placed here.
4389/// \param WantObjectRepresentation - If true, we're looking for the object
4390/// representation rather than the value, and in particular,
4391/// there is no requirement that the result be fully initialized.
4392static bool
4394 const LValue &LVal, APValue &RVal,
4395 bool WantObjectRepresentation = false) {
4396 if (LVal.Designator.Invalid)
4397 return false;
4398
4399 // Check for special cases where there is no existing APValue to look at.
4400 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4401
4402 AccessKinds AK =
4403 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4404
4405 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4406 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4407 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4408 // initializer until now for such expressions. Such an expression can't be
4409 // an ICE in C, so this only matters for fold.
4410 if (Type.isVolatileQualified()) {
4411 Info.FFDiag(Conv);
4412 return false;
4413 }
4414
4415 APValue Lit;
4416 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4417 return false;
4418
4419 // According to GCC info page:
4420 //
4421 // 6.28 Compound Literals
4422 //
4423 // As an optimization, G++ sometimes gives array compound literals longer
4424 // lifetimes: when the array either appears outside a function or has a
4425 // const-qualified type. If foo and its initializer had elements of type
4426 // char *const rather than char *, or if foo were a global variable, the
4427 // array would have static storage duration. But it is probably safest
4428 // just to avoid the use of array compound literals in C++ code.
4429 //
4430 // Obey that rule by checking constness for converted array types.
4431
4432 QualType CLETy = CLE->getType();
4433 if (CLETy->isArrayType() && !Type->isArrayType()) {
4434 if (!CLETy.isConstant(Info.Ctx)) {
4435 Info.FFDiag(Conv);
4436 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4437 return false;
4438 }
4439 }
4440
4441 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4442 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4443 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4444 // Special-case character extraction so we don't have to construct an
4445 // APValue for the whole string.
4446 assert(LVal.Designator.Entries.size() <= 1 &&
4447 "Can only read characters from string literals");
4448 if (LVal.Designator.Entries.empty()) {
4449 // Fail for now for LValue to RValue conversion of an array.
4450 // (This shouldn't show up in C/C++, but it could be triggered by a
4451 // weird EvaluateAsRValue call from a tool.)
4452 Info.FFDiag(Conv);
4453 return false;
4454 }
4455 if (LVal.Designator.isOnePastTheEnd()) {
4456 if (Info.getLangOpts().CPlusPlus11)
4457 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4458 else
4459 Info.FFDiag(Conv);
4460 return false;
4461 }
4462 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4463 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4464 return true;
4465 }
4466 }
4467
4468 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4469 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4470}
4471
4472/// Perform an assignment of Val to LVal. Takes ownership of Val.
4473static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4474 QualType LValType, APValue &Val) {
4475 if (LVal.Designator.Invalid)
4476 return false;
4477
4478 if (!Info.getLangOpts().CPlusPlus14) {
4479 Info.FFDiag(E);
4480 return false;
4481 }
4482
4483 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4484 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4485}
4486
4487namespace {
4488struct CompoundAssignSubobjectHandler {
4489 EvalInfo &Info;
4491 QualType PromotedLHSType;
4493 const APValue &RHS;
4494
4495 static const AccessKinds AccessKind = AK_Assign;
4496
4497 typedef bool result_type;
4498
4499 bool checkConst(QualType QT) {
4500 // Assigning to a const object has undefined behavior.
4501 if (QT.isConstQualified()) {
4502 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4503 return false;
4504 }
4505 return true;
4506 }
4507
4508 bool failed() { return false; }
4509 bool found(APValue &Subobj, QualType SubobjType) {
4510 switch (Subobj.getKind()) {
4511 case APValue::Int:
4512 return found(Subobj.getInt(), SubobjType);
4513 case APValue::Float:
4514 return found(Subobj.getFloat(), SubobjType);
4517 // FIXME: Implement complex compound assignment.
4518 Info.FFDiag(E);
4519 return false;
4520 case APValue::LValue:
4521 return foundPointer(Subobj, SubobjType);
4522 case APValue::Vector:
4523 return foundVector(Subobj, SubobjType);
4525 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4526 << /*read of=*/0 << /*uninitialized object=*/1
4527 << E->getLHS()->getSourceRange();
4528 return false;
4529 default:
4530 // FIXME: can this happen?
4531 Info.FFDiag(E);
4532 return false;
4533 }
4534 }
4535
4536 bool foundVector(APValue &Value, QualType SubobjType) {
4537 if (!checkConst(SubobjType))
4538 return false;
4539
4540 if (!SubobjType->isVectorType()) {
4541 Info.FFDiag(E);
4542 return false;
4543 }
4544 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4545 }
4546
4547 bool found(APSInt &Value, QualType SubobjType) {
4548 if (!checkConst(SubobjType))
4549 return false;
4550
4551 if (!SubobjType->isIntegerType()) {
4552 // We don't support compound assignment on integer-cast-to-pointer
4553 // values.
4554 Info.FFDiag(E);
4555 return false;
4556 }
4557
4558 if (RHS.isInt()) {
4559 APSInt LHS =
4560 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4561 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4562 return false;
4563 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4564 return true;
4565 } else if (RHS.isFloat()) {
4566 const FPOptions FPO = E->getFPFeaturesInEffect(
4567 Info.Ctx.getLangOpts());
4568 APFloat FValue(0.0);
4569 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4570 PromotedLHSType, FValue) &&
4571 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4572 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4573 Value);
4574 }
4575
4576 Info.FFDiag(E);
4577 return false;
4578 }
4579 bool found(APFloat &Value, QualType SubobjType) {
4580 return checkConst(SubobjType) &&
4581 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4582 Value) &&
4583 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4584 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4585 }
4586 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4587 if (!checkConst(SubobjType))
4588 return false;
4589
4590 QualType PointeeType;
4591 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4592 PointeeType = PT->getPointeeType();
4593
4594 if (PointeeType.isNull() || !RHS.isInt() ||
4595 (Opcode != BO_Add && Opcode != BO_Sub)) {
4596 Info.FFDiag(E);
4597 return false;
4598 }
4599
4600 APSInt Offset = RHS.getInt();
4601 if (Opcode == BO_Sub)
4602 negateAsSigned(Offset);
4603
4604 LValue LVal;
4605 LVal.setFrom(Info.Ctx, Subobj);
4606 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4607 return false;
4608 LVal.moveInto(Subobj);
4609 return true;
4610 }
4611};
4612} // end anonymous namespace
4613
4614const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4615
4616/// Perform a compound assignment of LVal <op>= RVal.
4617static bool handleCompoundAssignment(EvalInfo &Info,
4619 const LValue &LVal, QualType LValType,
4620 QualType PromotedLValType,
4621 BinaryOperatorKind Opcode,
4622 const APValue &RVal) {
4623 if (LVal.Designator.Invalid)
4624 return false;
4625
4626 if (!Info.getLangOpts().CPlusPlus14) {
4627 Info.FFDiag(E);
4628 return false;
4629 }
4630
4631 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4632 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4633 RVal };
4634 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4635}
4636
4637namespace {
4638struct IncDecSubobjectHandler {
4639 EvalInfo &Info;
4640 const UnaryOperator *E;
4641 AccessKinds AccessKind;
4642 APValue *Old;
4643
4644 typedef bool result_type;
4645
4646 bool checkConst(QualType QT) {
4647 // Assigning to a const object has undefined behavior.
4648 if (QT.isConstQualified()) {
4649 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4650 return false;
4651 }
4652 return true;
4653 }
4654
4655 bool failed() { return false; }
4656 bool found(APValue &Subobj, QualType SubobjType) {
4657 // Stash the old value. Also clear Old, so we don't clobber it later
4658 // if we're post-incrementing a complex.
4659 if (Old) {
4660 *Old = Subobj;
4661 Old = nullptr;
4662 }
4663
4664 switch (Subobj.getKind()) {
4665 case APValue::Int:
4666 return found(Subobj.getInt(), SubobjType);
4667 case APValue::Float:
4668 return found(Subobj.getFloat(), SubobjType);
4670 return found(Subobj.getComplexIntReal(),
4671 SubobjType->castAs<ComplexType>()->getElementType()
4672 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4674 return found(Subobj.getComplexFloatReal(),
4675 SubobjType->castAs<ComplexType>()->getElementType()
4676 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4677 case APValue::LValue:
4678 return foundPointer(Subobj, SubobjType);
4679 default:
4680 // FIXME: can this happen?
4681 Info.FFDiag(E);
4682 return false;
4683 }
4684 }
4685 bool found(APSInt &Value, QualType SubobjType) {
4686 if (!checkConst(SubobjType))
4687 return false;
4688
4689 if (!SubobjType->isIntegerType()) {
4690 // We don't support increment / decrement on integer-cast-to-pointer
4691 // values.
4692 Info.FFDiag(E);
4693 return false;
4694 }
4695
4696 if (Old) *Old = APValue(Value);
4697
4698 // bool arithmetic promotes to int, and the conversion back to bool
4699 // doesn't reduce mod 2^n, so special-case it.
4700 if (SubobjType->isBooleanType()) {
4701 if (AccessKind == AK_Increment)
4702 Value = 1;
4703 else
4704 Value = !Value;
4705 return true;
4706 }
4707
4708 bool WasNegative = Value.isNegative();
4709 if (AccessKind == AK_Increment) {
4710 ++Value;
4711
4712 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4713 APSInt ActualValue(Value, /*IsUnsigned*/true);
4714 return HandleOverflow(Info, E, ActualValue, SubobjType);
4715 }
4716 } else {
4717 --Value;
4718
4719 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4720 unsigned BitWidth = Value.getBitWidth();
4721 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4722 ActualValue.setBit(BitWidth);
4723 return HandleOverflow(Info, E, ActualValue, SubobjType);
4724 }
4725 }
4726 return true;
4727 }
4728 bool found(APFloat &Value, QualType SubobjType) {
4729 if (!checkConst(SubobjType))
4730 return false;
4731
4732 if (Old) *Old = APValue(Value);
4733
4734 APFloat One(Value.getSemantics(), 1);
4735 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4736 APFloat::opStatus St;
4737 if (AccessKind == AK_Increment)
4738 St = Value.add(One, RM);
4739 else
4740 St = Value.subtract(One, RM);
4741 return checkFloatingPointResult(Info, E, St);
4742 }
4743 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4744 if (!checkConst(SubobjType))
4745 return false;
4746
4747 QualType PointeeType;
4748 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4749 PointeeType = PT->getPointeeType();
4750 else {
4751 Info.FFDiag(E);
4752 return false;
4753 }
4754
4755 LValue LVal;
4756 LVal.setFrom(Info.Ctx, Subobj);
4757 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4758 AccessKind == AK_Increment ? 1 : -1))
4759 return false;
4760 LVal.moveInto(Subobj);
4761 return true;
4762 }
4763};
4764} // end anonymous namespace
4765
4766/// Perform an increment or decrement on LVal.
4767static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4768 QualType LValType, bool IsIncrement, APValue *Old) {
4769 if (LVal.Designator.Invalid)
4770 return false;
4771
4772 if (!Info.getLangOpts().CPlusPlus14) {
4773 Info.FFDiag(E);
4774 return false;
4775 }
4776
4777 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4778 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4779 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4780 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4781}
4782
4783/// Build an lvalue for the object argument of a member function call.
4784static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4785 LValue &This) {
4786 if (Object->getType()->isPointerType() && Object->isPRValue())
4787 return EvaluatePointer(Object, This, Info);
4788
4789 if (Object->isGLValue())
4790 return EvaluateLValue(Object, This, Info);
4791
4792 if (Object->getType()->isLiteralType(Info.Ctx))
4793 return EvaluateTemporary(Object, This, Info);
4794
4795 if (Object->getType()->isRecordType() && Object->isPRValue())
4796 return EvaluateTemporary(Object, This, Info);
4797
4798 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4799 return false;
4800}
4801
4802/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4803/// lvalue referring to the result.
4804///
4805/// \param Info - Information about the ongoing evaluation.
4806/// \param LV - An lvalue referring to the base of the member pointer.
4807/// \param RHS - The member pointer expression.
4808/// \param IncludeMember - Specifies whether the member itself is included in
4809/// the resulting LValue subobject designator. This is not possible when
4810/// creating a bound member function.
4811/// \return The field or method declaration to which the member pointer refers,
4812/// or 0 if evaluation fails.
4813static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4814 QualType LVType,
4815 LValue &LV,
4816 const Expr *RHS,
4817 bool IncludeMember = true) {
4818 MemberPtr MemPtr;
4819 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4820 return nullptr;
4821
4822 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4823 // member value, the behavior is undefined.
4824 if (!MemPtr.getDecl()) {
4825 // FIXME: Specific diagnostic.
4826 Info.FFDiag(RHS);
4827 return nullptr;
4828 }
4829
4830 if (MemPtr.isDerivedMember()) {
4831 // This is a member of some derived class. Truncate LV appropriately.
4832 // The end of the derived-to-base path for the base object must match the
4833 // derived-to-base path for the member pointer.
4834 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4835 LV.Designator.Entries.size()) {
4836 Info.FFDiag(RHS);
4837 return nullptr;
4838 }
4839 unsigned PathLengthToMember =
4840 LV.Designator.Entries.size() - MemPtr.Path.size();
4841 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4842 const CXXRecordDecl *LVDecl = getAsBaseClass(
4843 LV.Designator.Entries[PathLengthToMember + I]);
4844 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4845 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4846 Info.FFDiag(RHS);
4847 return nullptr;
4848 }
4849 }
4850
4851 // Truncate the lvalue to the appropriate derived class.
4852 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4853 PathLengthToMember))
4854 return nullptr;
4855 } else if (!MemPtr.Path.empty()) {
4856 // Extend the LValue path with the member pointer's path.
4857 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4858 MemPtr.Path.size() + IncludeMember);
4859
4860 // Walk down to the appropriate base class.
4861 if (const PointerType *PT = LVType->getAs<PointerType>())
4862 LVType = PT->getPointeeType();
4863 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4864 assert(RD && "member pointer access on non-class-type expression");
4865 // The first class in the path is that of the lvalue.
4866 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4867 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4868 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4869 return nullptr;
4870 RD = Base;
4871 }
4872 // Finally cast to the class containing the member.
4873 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4874 MemPtr.getContainingRecord()))
4875 return nullptr;
4876 }
4877
4878 // Add the member. Note that we cannot build bound member functions here.
4879 if (IncludeMember) {
4880 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4881 if (!HandleLValueMember(Info, RHS, LV, FD))
4882 return nullptr;
4883 } else if (const IndirectFieldDecl *IFD =
4884 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4885 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4886 return nullptr;
4887 } else {
4888 llvm_unreachable("can't construct reference to bound member function");
4889 }
4890 }
4891
4892 return MemPtr.getDecl();
4893}
4894
4895static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4896 const BinaryOperator *BO,
4897 LValue &LV,
4898 bool IncludeMember = true) {
4899 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4900
4901 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4902 if (Info.noteFailure()) {
4903 MemberPtr MemPtr;
4904 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4905 }
4906 return nullptr;
4907 }
4908
4909 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4910 BO->getRHS(), IncludeMember);
4911}
4912
4913/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4914/// the provided lvalue, which currently refers to the base object.
4915static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4916 LValue &Result) {
4917 SubobjectDesignator &D = Result.Designator;
4918 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4919 return false;
4920
4921 QualType TargetQT = E->getType();
4922 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4923 TargetQT = PT->getPointeeType();
4924
4925 // Check this cast lands within the final derived-to-base subobject path.
4926 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4927 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4928 << D.MostDerivedType << TargetQT;
4929 return false;
4930 }
4931
4932 // Check the type of the final cast. We don't need to check the path,
4933 // since a cast can only be formed if the path is unique.
4934 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4935 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4936 const CXXRecordDecl *FinalType;
4937 if (NewEntriesSize == D.MostDerivedPathLength)
4938 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4939 else
4940 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4941 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4942 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4943 << D.MostDerivedType << TargetQT;
4944 return false;
4945 }
4946
4947 // Truncate the lvalue to the appropriate derived class.
4948 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4949}
4950
4951/// Get the value to use for a default-initialized object of type T.
4952/// Return false if it encounters something invalid.
4954 bool Success = true;
4955
4956 // If there is already a value present don't overwrite it.
4957 if (!Result.isAbsent())
4958 return true;
4959
4960 if (auto *RD = T->getAsCXXRecordDecl()) {
4961 if (RD->isInvalidDecl()) {
4962 Result = APValue();
4963 return false;
4964 }
4965 if (RD->isUnion()) {
4966 Result = APValue((const FieldDecl *)nullptr);
4967 return true;
4968 }
4969 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4970 std::distance(RD->field_begin(), RD->field_end()));
4971
4972 unsigned Index = 0;
4973 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4974 End = RD->bases_end();
4975 I != End; ++I, ++Index)
4976 Success &=
4977 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4978
4979 for (const auto *I : RD->fields()) {
4980 if (I->isUnnamedBitField())
4981 continue;
4983 I->getType(), Result.getStructField(I->getFieldIndex()));
4984 }
4985 return Success;
4986 }
4987
4988 if (auto *AT =
4989 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4990 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
4991 if (Result.hasArrayFiller())
4992 Success &=
4993 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4994
4995 return Success;
4996 }
4997
4998 Result = APValue::IndeterminateValue();
4999 return true;
5000}
5001
5002namespace {
5003enum EvalStmtResult {
5004 /// Evaluation failed.
5005 ESR_Failed,
5006 /// Hit a 'return' statement.
5007 ESR_Returned,
5008 /// Evaluation succeeded.
5009 ESR_Succeeded,
5010 /// Hit a 'continue' statement.
5011 ESR_Continue,
5012 /// Hit a 'break' statement.
5013 ESR_Break,
5014 /// Still scanning for 'case' or 'default' statement.
5015 ESR_CaseNotFound
5016};
5017}
5018
5019static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5020 if (VD->isInvalidDecl())
5021 return false;
5022 // We don't need to evaluate the initializer for a static local.
5023 if (!VD->hasLocalStorage())
5024 return true;
5025
5026 LValue Result;
5027 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5028 ScopeKind::Block, Result);
5029
5030 const Expr *InitE = VD->getInit();
5031 if (!InitE) {
5032 if (VD->getType()->isDependentType())
5033 return Info.noteSideEffect();
5034 return handleDefaultInitValue(VD->getType(), Val);
5035 }
5036 if (InitE->isValueDependent())
5037 return false;
5038
5039 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5040 // Wipe out any partially-computed value, to allow tracking that this
5041 // evaluation failed.
5042 Val = APValue();
5043 return false;
5044 }
5045
5046 return true;
5047}
5048
5049static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5050 bool OK = true;
5051
5052 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5053 OK &= EvaluateVarDecl(Info, VD);
5054
5055 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5056 for (auto *BD : DD->bindings())
5057 if (auto *VD = BD->getHoldingVar())
5058 OK &= EvaluateDecl(Info, VD);
5059
5060 return OK;
5061}
5062
5063static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5064 assert(E->isValueDependent());
5065 if (Info.noteSideEffect())
5066 return true;
5067 assert(E->containsErrors() && "valid value-dependent expression should never "
5068 "reach invalid code path.");
5069 return false;
5070}
5071
5072/// Evaluate a condition (either a variable declaration or an expression).
5073static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5074 const Expr *Cond, bool &Result) {
5075 if (Cond->isValueDependent())
5076 return false;
5077 FullExpressionRAII Scope(Info);
5078 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5079 return false;
5080 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5081 return false;
5082 return Scope.destroy();
5083}
5084
5085namespace {
5086/// A location where the result (returned value) of evaluating a
5087/// statement should be stored.
5088struct StmtResult {
5089 /// The APValue that should be filled in with the returned value.
5090 APValue &Value;
5091 /// The location containing the result, if any (used to support RVO).
5092 const LValue *Slot;
5093};
5094
5095struct TempVersionRAII {
5096 CallStackFrame &Frame;
5097
5098 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5099 Frame.pushTempVersion();
5100 }
5101
5102 ~TempVersionRAII() {
5103 Frame.popTempVersion();
5104 }
5105};
5106
5107}
5108
5109static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5110 const Stmt *S,
5111 const SwitchCase *SC = nullptr);
5112
5113/// Evaluate the body of a loop, and translate the result as appropriate.
5114static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5115 const Stmt *Body,
5116 const SwitchCase *Case = nullptr) {
5117 BlockScopeRAII Scope(Info);
5118
5119 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5120 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5121 ESR = ESR_Failed;
5122
5123 switch (ESR) {
5124 case ESR_Break:
5125 return ESR_Succeeded;
5126 case ESR_Succeeded:
5127 case ESR_Continue:
5128 return ESR_Continue;
5129 case ESR_Failed:
5130 case ESR_Returned:
5131 case ESR_CaseNotFound:
5132 return ESR;
5133 }
5134 llvm_unreachable("Invalid EvalStmtResult!");
5135}
5136
5137/// Evaluate a switch statement.
5138static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5139 const SwitchStmt *SS) {
5140 BlockScopeRAII Scope(Info);
5141
5142 // Evaluate the switch condition.
5143 APSInt Value;
5144 {
5145 if (const Stmt *Init = SS->getInit()) {
5146 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5147 if (ESR != ESR_Succeeded) {
5148 if (ESR != ESR_Failed && !Scope.destroy())
5149 ESR = ESR_Failed;
5150 return ESR;
5151 }
5152 }
5153
5154 FullExpressionRAII CondScope(Info);
5155 if (SS->getConditionVariable() &&
5156 !EvaluateDecl(Info, SS->getConditionVariable()))
5157 return ESR_Failed;
5158 if (SS->getCond()->isValueDependent()) {
5159 // We don't know what the value is, and which branch should jump to.
5160 EvaluateDependentExpr(SS->getCond(), Info);
5161 return ESR_Failed;
5162 }
5163 if (!EvaluateInteger(SS->getCond(), Value, Info))
5164 return ESR_Failed;
5165
5166 if (!CondScope.destroy())
5167 return ESR_Failed;
5168 }
5169
5170 // Find the switch case corresponding to the value of the condition.
5171 // FIXME: Cache this lookup.
5172 const SwitchCase *Found = nullptr;
5173 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5174 SC = SC->getNextSwitchCase()) {
5175 if (isa<DefaultStmt>(SC)) {
5176 Found = SC;
5177 continue;
5178 }
5179
5180 const CaseStmt *CS = cast<CaseStmt>(SC);
5181 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5182 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5183 : LHS;
5184 if (LHS <= Value && Value <= RHS) {
5185 Found = SC;
5186 break;
5187 }
5188 }
5189
5190 if (!Found)
5191 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5192
5193 // Search the switch body for the switch case and evaluate it from there.
5194 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5195 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5196 return ESR_Failed;
5197
5198 switch (ESR) {
5199 case ESR_Break:
5200 return ESR_Succeeded;
5201 case ESR_Succeeded:
5202 case ESR_Continue:
5203 case ESR_Failed:
5204 case ESR_Returned:
5205 return ESR;
5206 case ESR_CaseNotFound:
5207 // This can only happen if the switch case is nested within a statement
5208 // expression. We have no intention of supporting that.
5209 Info.FFDiag(Found->getBeginLoc(),
5210 diag::note_constexpr_stmt_expr_unsupported);
5211 return ESR_Failed;
5212 }
5213 llvm_unreachable("Invalid EvalStmtResult!");
5214}
5215
5216static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5217 // An expression E is a core constant expression unless the evaluation of E
5218 // would evaluate one of the following: [C++23] - a control flow that passes
5219 // through a declaration of a variable with static or thread storage duration
5220 // unless that variable is usable in constant expressions.
5221 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5222 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5223 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5224 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5225 return false;
5226 }
5227 return true;
5228}
5229
5230// Evaluate a statement.
5231static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5232 const Stmt *S, const SwitchCase *Case) {
5233 if (!Info.nextStep(S))
5234 return ESR_Failed;
5235
5236 // If we're hunting down a 'case' or 'default' label, recurse through
5237 // substatements until we hit the label.
5238 if (Case) {
5239 switch (S->getStmtClass()) {
5240 case Stmt::CompoundStmtClass:
5241 // FIXME: Precompute which substatement of a compound statement we
5242 // would jump to, and go straight there rather than performing a
5243 // linear scan each time.
5244 case Stmt::LabelStmtClass:
5245 case Stmt::AttributedStmtClass:
5246 case Stmt::DoStmtClass:
5247 break;
5248
5249 case Stmt::CaseStmtClass:
5250 case Stmt::DefaultStmtClass:
5251 if (Case == S)
5252 Case = nullptr;
5253 break;
5254
5255 case Stmt::IfStmtClass: {
5256 // FIXME: Precompute which side of an 'if' we would jump to, and go
5257 // straight there rather than scanning both sides.
5258 const IfStmt *IS = cast<IfStmt>(S);
5259
5260 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5261 // preceded by our switch label.
5262 BlockScopeRAII Scope(Info);
5263
5264 // Step into the init statement in case it brings an (uninitialized)
5265 // variable into scope.
5266 if (const Stmt *Init = IS->getInit()) {
5267 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5268 if (ESR != ESR_CaseNotFound) {
5269 assert(ESR != ESR_Succeeded);
5270 return ESR;
5271 }
5272 }
5273
5274 // Condition variable must be initialized if it exists.
5275 // FIXME: We can skip evaluating the body if there's a condition
5276 // variable, as there can't be any case labels within it.
5277 // (The same is true for 'for' statements.)
5278
5279 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5280 if (ESR == ESR_Failed)
5281 return ESR;
5282 if (ESR != ESR_CaseNotFound)
5283 return Scope.destroy() ? ESR : ESR_Failed;
5284 if (!IS->getElse())
5285 return ESR_CaseNotFound;
5286
5287 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5288 if (ESR == ESR_Failed)
5289 return ESR;
5290 if (ESR != ESR_CaseNotFound)
5291 return Scope.destroy() ? ESR : ESR_Failed;
5292 return ESR_CaseNotFound;
5293 }
5294
5295 case Stmt::WhileStmtClass: {
5296 EvalStmtResult ESR =
5297 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5298 if (ESR != ESR_Continue)
5299 return ESR;
5300 break;
5301 }
5302
5303 case Stmt::ForStmtClass: {
5304 const ForStmt *FS = cast<ForStmt>(S);
5305 BlockScopeRAII Scope(Info);
5306
5307 // Step into the init statement in case it brings an (uninitialized)
5308 // variable into scope.
5309 if (const Stmt *Init = FS->getInit()) {
5310 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5311 if (ESR != ESR_CaseNotFound) {
5312 assert(ESR != ESR_Succeeded);
5313 return ESR;
5314 }
5315 }
5316
5317 EvalStmtResult ESR =
5318 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5319 if (ESR != ESR_Continue)
5320 return ESR;
5321 if (const auto *Inc = FS->getInc()) {
5322 if (Inc->isValueDependent()) {
5323 if (!EvaluateDependentExpr(Inc, Info))
5324 return ESR_Failed;
5325 } else {
5326 FullExpressionRAII IncScope(Info);
5327 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5328 return ESR_Failed;
5329 }
5330 }
5331 break;
5332 }
5333
5334 case Stmt::DeclStmtClass: {
5335 // Start the lifetime of any uninitialized variables we encounter. They
5336 // might be used by the selected branch of the switch.
5337 const DeclStmt *DS = cast<DeclStmt>(S);
5338 for (const auto *D : DS->