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