[clang] Handle __declspec() attributes in using
[llvm-project.git] / clang / lib / AST / ExprConstant.cpp
blob9b2367b6459e32b07dbfa1b109f8bb0fc6ad2823
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.
11 // Constant expression evaluation produces four main results:
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.
18 // * An evaluated result, valid only if constant folding has not failed.
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.
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.
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).
33 //===----------------------------------------------------------------------===//
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/SmallBitVector.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TimeProfiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 #include <optional>
64 #define DEBUG_TYPE "exprconstant"
66 using namespace clang;
67 using llvm::APFixedPoint;
68 using llvm::APInt;
69 using llvm::APSInt;
70 using llvm::APFloat;
71 using llvm::FixedPointSemantics;
73 namespace {
74 struct LValue;
75 class CallStackFrame;
76 class EvalInfo;
78 using SourceLocExprScopeGuard =
79 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
81 static QualType getType(APValue::LValueBase B) {
82 return B.getType();
85 /// Get an LValue path entry, which is known to not be an array index, as a
86 /// field declaration.
87 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
90 /// Get an LValue path entry, which is known to not be an array index, as a
91 /// base class declaration.
92 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
95 /// Determine whether this LValue path entry for a base class names a virtual
96 /// base class.
97 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98 return E.getAsBaseOrMember().getInt();
101 /// Given an expression, determine the type used to store the result of
102 /// evaluating that expression.
103 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104 if (E->isPRValue())
105 return E->getType();
106 return Ctx.getLValueReferenceType(E->getType());
109 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112 return DirectCallee->getAttr<AllocSizeAttr>();
113 if (const Decl *IndirectCallee = CE->getCalleeDecl())
114 return IndirectCallee->getAttr<AllocSizeAttr>();
115 return nullptr;
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
124 return nullptr;
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. In exotic cases, we might also see a
129 // top-level ExprWithCleanups. Ignore them either way.
130 if (const auto *FE = dyn_cast<FullExpr>(E))
131 E = FE->getSubExpr()->IgnoreParens();
133 if (const auto *Cast = dyn_cast<CastExpr>(E))
134 E = Cast->getSubExpr()->IgnoreParens();
136 if (const auto *CE = dyn_cast<CallExpr>(E))
137 return getAllocSizeAttr(CE) ? CE : nullptr;
138 return nullptr;
141 /// Determines whether or not the given Base contains a call to a function
142 /// with the alloc_size attribute.
143 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144 const auto *E = Base.dyn_cast<const Expr *>();
145 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
148 /// Determines whether the given kind of constant expression is only ever
149 /// used for name mangling. If so, it's permitted to reference things that we
150 /// can't generate code for (in particular, dllimported functions).
151 static bool isForManglingOnly(ConstantExprKind Kind) {
152 switch (Kind) {
153 case ConstantExprKind::Normal:
154 case ConstantExprKind::ClassTemplateArgument:
155 case ConstantExprKind::ImmediateInvocation:
156 // Note that non-type template arguments of class type are emitted as
157 // template parameter objects.
158 return false;
160 case ConstantExprKind::NonClassTemplateArgument:
161 return true;
163 llvm_unreachable("unknown ConstantExprKind");
166 static bool isTemplateArgument(ConstantExprKind Kind) {
167 switch (Kind) {
168 case ConstantExprKind::Normal:
169 case ConstantExprKind::ImmediateInvocation:
170 return false;
172 case ConstantExprKind::ClassTemplateArgument:
173 case ConstantExprKind::NonClassTemplateArgument:
174 return true;
176 llvm_unreachable("unknown ConstantExprKind");
179 /// The bound to claim that an array of unknown bound has.
180 /// The value in MostDerivedArraySize is undefined in this case. So, set it
181 /// to an arbitrary value that's likely to loudly break things if it's used.
182 static const uint64_t AssumedSizeForUnsizedArray =
183 std::numeric_limits<uint64_t>::max() / 2;
185 /// Determines if an LValue with the given LValueBase will have an unsized
186 /// array in its designator.
187 /// Find the path length and type of the most-derived subobject in the given
188 /// path, and find the size of the containing array, if any.
189 static unsigned
190 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191 ArrayRef<APValue::LValuePathEntry> Path,
192 uint64_t &ArraySize, QualType &Type, bool &IsArray,
193 bool &FirstEntryIsUnsizedArray) {
194 // This only accepts LValueBases from APValues, and APValues don't support
195 // arrays that lack size info.
196 assert(!isBaseAnAllocSizeCall(Base) &&
197 "Unsized arrays shouldn't appear here");
198 unsigned MostDerivedLength = 0;
199 Type = getType(Base);
201 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202 if (Type->isArrayType()) {
203 const ArrayType *AT = Ctx.getAsArrayType(Type);
204 Type = AT->getElementType();
205 MostDerivedLength = I + 1;
206 IsArray = true;
208 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209 ArraySize = CAT->getSize().getZExtValue();
210 } else {
211 assert(I == 0 && "unexpected unsized array designator");
212 FirstEntryIsUnsizedArray = true;
213 ArraySize = AssumedSizeForUnsizedArray;
215 } else if (Type->isAnyComplexType()) {
216 const ComplexType *CT = Type->castAs<ComplexType>();
217 Type = CT->getElementType();
218 ArraySize = 2;
219 MostDerivedLength = I + 1;
220 IsArray = true;
221 } else if (const FieldDecl *FD = getAsField(Path[I])) {
222 Type = FD->getType();
223 ArraySize = 0;
224 MostDerivedLength = I + 1;
225 IsArray = false;
226 } else {
227 // Path[I] describes a base class.
228 ArraySize = 0;
229 IsArray = false;
232 return MostDerivedLength;
235 /// A path from a glvalue to a subobject of that glvalue.
236 struct SubobjectDesignator {
237 /// True if the subobject was named in a manner not supported by C++11. Such
238 /// lvalues can still be folded, but they are not core constant expressions
239 /// and we cannot perform lvalue-to-rvalue conversions on them.
240 unsigned Invalid : 1;
242 /// Is this a pointer one past the end of an object?
243 unsigned IsOnePastTheEnd : 1;
245 /// Indicator of whether the first entry is an unsized array.
246 unsigned FirstEntryIsAnUnsizedArray : 1;
248 /// Indicator of whether the most-derived object is an array element.
249 unsigned MostDerivedIsArrayElement : 1;
251 /// The length of the path to the most-derived object of which this is a
252 /// subobject.
253 unsigned MostDerivedPathLength : 28;
255 /// The size of the array of which the most-derived object is an element.
256 /// This will always be 0 if the most-derived object is not an array
257 /// element. 0 is not an indicator of whether or not the most-derived object
258 /// is an array, however, because 0-length arrays are allowed.
260 /// If the current array is an unsized array, the value of this is
261 /// undefined.
262 uint64_t MostDerivedArraySize;
264 /// The type of the most derived object referred to by this address.
265 QualType MostDerivedType;
267 typedef APValue::LValuePathEntry PathEntry;
269 /// The entries on the path from the glvalue to the designated subobject.
270 SmallVector<PathEntry, 8> Entries;
272 SubobjectDesignator() : Invalid(true) {}
274 explicit SubobjectDesignator(QualType T)
275 : Invalid(false), IsOnePastTheEnd(false),
276 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277 MostDerivedPathLength(0), MostDerivedArraySize(0),
278 MostDerivedType(T) {}
280 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283 MostDerivedPathLength(0), MostDerivedArraySize(0) {
284 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285 if (!Invalid) {
286 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287 ArrayRef<PathEntry> VEntries = V.getLValuePath();
288 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289 if (V.getLValueBase()) {
290 bool IsArray = false;
291 bool FirstIsUnsizedArray = false;
292 MostDerivedPathLength = findMostDerivedSubobject(
293 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294 MostDerivedType, IsArray, FirstIsUnsizedArray);
295 MostDerivedIsArrayElement = IsArray;
296 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
301 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302 unsigned NewLength) {
303 if (Invalid)
304 return;
306 assert(Base && "cannot truncate path for null pointer");
307 assert(NewLength <= Entries.size() && "not a truncation");
309 if (NewLength == Entries.size())
310 return;
311 Entries.resize(NewLength);
313 bool IsArray = false;
314 bool FirstIsUnsizedArray = false;
315 MostDerivedPathLength = findMostDerivedSubobject(
316 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317 FirstIsUnsizedArray);
318 MostDerivedIsArrayElement = IsArray;
319 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
322 void setInvalid() {
323 Invalid = true;
324 Entries.clear();
327 /// Determine whether the most derived subobject is an array without a
328 /// known bound.
329 bool isMostDerivedAnUnsizedArray() const {
330 assert(!Invalid && "Calling this makes no sense on invalid designators");
331 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
334 /// Determine what the most derived array's size is. Results in an assertion
335 /// failure if the most derived array lacks a size.
336 uint64_t getMostDerivedArraySize() const {
337 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338 return MostDerivedArraySize;
341 /// Determine whether this is a one-past-the-end pointer.
342 bool isOnePastTheEnd() const {
343 assert(!Invalid);
344 if (IsOnePastTheEnd)
345 return true;
346 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348 MostDerivedArraySize)
349 return true;
350 return false;
353 /// Get the range of valid index adjustments in the form
354 /// {maximum value that can be subtracted from this pointer,
355 /// maximum value that can be added to this pointer}
356 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357 if (Invalid || isMostDerivedAnUnsizedArray())
358 return {0, 0};
360 // [expr.add]p4: For the purposes of these operators, a pointer to a
361 // nonarray object behaves the same as a pointer to the first element of
362 // an array of length one with the type of the object as its element type.
363 bool IsArray = MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement;
365 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366 : (uint64_t)IsOnePastTheEnd;
367 uint64_t ArraySize =
368 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369 return {ArrayIndex, ArraySize - ArrayIndex};
372 /// Check that this refers to a valid subobject.
373 bool isValidSubobject() const {
374 if (Invalid)
375 return false;
376 return !isOnePastTheEnd();
378 /// Check that this refers to a valid subobject, and if not, produce a
379 /// relevant diagnostic and set the designator as invalid.
380 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
382 /// Get the type of the designated object.
383 QualType getType(ASTContext &Ctx) const {
384 assert(!Invalid && "invalid designator has no subobject type");
385 return MostDerivedPathLength == Entries.size()
386 ? MostDerivedType
387 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
390 /// Update this designator to refer to the first element within this array.
391 void addArrayUnchecked(const ConstantArrayType *CAT) {
392 Entries.push_back(PathEntry::ArrayIndex(0));
394 // This is a most-derived object.
395 MostDerivedType = CAT->getElementType();
396 MostDerivedIsArrayElement = true;
397 MostDerivedArraySize = CAT->getSize().getZExtValue();
398 MostDerivedPathLength = Entries.size();
400 /// Update this designator to refer to the first element within the array of
401 /// elements of type T. This is an array of unknown size.
402 void addUnsizedArrayUnchecked(QualType ElemTy) {
403 Entries.push_back(PathEntry::ArrayIndex(0));
405 MostDerivedType = ElemTy;
406 MostDerivedIsArrayElement = true;
407 // The value in MostDerivedArraySize is undefined in this case. So, set it
408 // to an arbitrary value that's likely to loudly break things if it's
409 // used.
410 MostDerivedArraySize = AssumedSizeForUnsizedArray;
411 MostDerivedPathLength = Entries.size();
413 /// Update this designator to refer to the given base or member of this
414 /// object.
415 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
418 // If this isn't a base class, it's a new most-derived object.
419 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420 MostDerivedType = FD->getType();
421 MostDerivedIsArrayElement = false;
422 MostDerivedArraySize = 0;
423 MostDerivedPathLength = Entries.size();
426 /// Update this designator to refer to the given complex component.
427 void addComplexUnchecked(QualType EltTy, bool Imag) {
428 Entries.push_back(PathEntry::ArrayIndex(Imag));
430 // This is technically a most-derived object, though in practice this
431 // is unlikely to matter.
432 MostDerivedType = EltTy;
433 MostDerivedIsArrayElement = true;
434 MostDerivedArraySize = 2;
435 MostDerivedPathLength = Entries.size();
437 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439 const APSInt &N);
440 /// Add N to the address of this subobject.
441 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442 if (Invalid || !N) return;
443 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444 if (isMostDerivedAnUnsizedArray()) {
445 diagnoseUnsizedArrayPointerArithmetic(Info, E);
446 // Can't verify -- trust that the user is doing the right thing (or if
447 // not, trust that the caller will catch the bad behavior).
448 // FIXME: Should we reject if this overflows, at least?
449 Entries.back() = PathEntry::ArrayIndex(
450 Entries.back().getAsArrayIndex() + TruncatedN);
451 return;
454 // [expr.add]p4: For the purposes of these operators, a pointer to a
455 // nonarray object behaves the same as a pointer to the first element of
456 // an array of length one with the type of the object as its element type.
457 bool IsArray = MostDerivedPathLength == Entries.size() &&
458 MostDerivedIsArrayElement;
459 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460 : (uint64_t)IsOnePastTheEnd;
461 uint64_t ArraySize =
462 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
464 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465 // Calculate the actual index in a wide enough type, so we can include
466 // it in the note.
467 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468 (llvm::APInt&)N += ArrayIndex;
469 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470 diagnosePointerArithmetic(Info, E, N);
471 setInvalid();
472 return;
475 ArrayIndex += TruncatedN;
476 assert(ArrayIndex <= ArraySize &&
477 "bounds check succeeded for out-of-bounds index");
479 if (IsArray)
480 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481 else
482 IsOnePastTheEnd = (ArrayIndex != 0);
486 /// A scope at the end of which an object can need to be destroyed.
487 enum class ScopeKind {
488 Block,
489 FullExpression,
490 Call
493 /// A reference to a particular call and its arguments.
494 struct CallRef {
495 CallRef() : OrigCallee(), CallIndex(0), Version() {}
496 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
499 explicit operator bool() const { return OrigCallee; }
501 /// Get the parameter that the caller initialized, corresponding to the
502 /// given parameter in the callee.
503 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505 : PVD;
508 /// The callee at the point where the arguments were evaluated. This might
509 /// be different from the actual callee (a different redeclaration, or a
510 /// virtual override), but this function's parameters are the ones that
511 /// appear in the parameter map.
512 const FunctionDecl *OrigCallee;
513 /// The call index of the frame that holds the argument values.
514 unsigned CallIndex;
515 /// The version of the parameters corresponding to this call.
516 unsigned Version;
519 /// A stack frame in the constexpr call stack.
520 class CallStackFrame : public interp::Frame {
521 public:
522 EvalInfo &Info;
524 /// Parent - The caller of this stack frame.
525 CallStackFrame *Caller;
527 /// Callee - The function which was called.
528 const FunctionDecl *Callee;
530 /// This - The binding for the this pointer in this call, if any.
531 const LValue *This;
533 /// Information on how to find the arguments to this call. Our arguments
534 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535 /// key and this value as the version.
536 CallRef Arguments;
538 /// Source location information about the default argument or default
539 /// initializer expression we're evaluating, if any.
540 CurrentSourceLocExprScope CurSourceLocExprScope;
542 // Note that we intentionally use std::map here so that references to
543 // values are stable.
544 typedef std::pair<const void *, unsigned> MapKeyTy;
545 typedef std::map<MapKeyTy, APValue> MapTy;
546 /// Temporaries - Temporary lvalues materialized within this stack frame.
547 MapTy Temporaries;
549 /// CallLoc - The location of the call expression for this call.
550 SourceLocation CallLoc;
552 /// Index - The call index of this call.
553 unsigned Index;
555 /// The stack of integers for tracking version numbers for temporaries.
556 SmallVector<unsigned, 2> TempVersionStack = {1};
557 unsigned CurTempVersion = TempVersionStack.back();
559 unsigned getTempVersion() const { return TempVersionStack.back(); }
561 void pushTempVersion() {
562 TempVersionStack.push_back(++CurTempVersion);
565 void popTempVersion() {
566 TempVersionStack.pop_back();
569 CallRef createCall(const FunctionDecl *Callee) {
570 return {Callee, Index, ++CurTempVersion};
573 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574 // on the overall stack usage of deeply-recursing constexpr evaluations.
575 // (We should cache this map rather than recomputing it repeatedly.)
576 // But let's try this and see how it goes; we can look into caching the map
577 // as a later change.
579 /// LambdaCaptureFields - Mapping from captured variables/this to
580 /// corresponding data members in the closure class.
581 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
582 FieldDecl *LambdaThisCaptureField;
584 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585 const FunctionDecl *Callee, const LValue *This,
586 CallRef Arguments);
587 ~CallStackFrame();
589 // Return the temporary for Key whose version number is Version.
590 APValue *getTemporary(const void *Key, unsigned Version) {
591 MapKeyTy KV(Key, Version);
592 auto LB = Temporaries.lower_bound(KV);
593 if (LB != Temporaries.end() && LB->first == KV)
594 return &LB->second;
595 return nullptr;
598 // Return the current temporary for Key in the map.
599 APValue *getCurrentTemporary(const void *Key) {
600 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
601 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
602 return &std::prev(UB)->second;
603 return nullptr;
606 // Return the version number of the current temporary for Key.
607 unsigned getCurrentTemporaryVersion(const void *Key) const {
608 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
609 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
610 return std::prev(UB)->first.second;
611 return 0;
614 /// Allocate storage for an object of type T in this stack frame.
615 /// Populates LV with a handle to the created object. Key identifies
616 /// the temporary within the stack frame, and must not be reused without
617 /// bumping the temporary version number.
618 template<typename KeyT>
619 APValue &createTemporary(const KeyT *Key, QualType T,
620 ScopeKind Scope, LValue &LV);
622 /// Allocate storage for a parameter of a function call made in this frame.
623 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
625 void describe(llvm::raw_ostream &OS) override;
627 Frame *getCaller() const override { return Caller; }
628 SourceLocation getCallLocation() const override { return CallLoc; }
629 const FunctionDecl *getCallee() const override { return Callee; }
631 bool isStdFunction() const {
632 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
633 if (DC->isStdNamespace())
634 return true;
635 return false;
638 private:
639 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
640 ScopeKind Scope);
643 /// Temporarily override 'this'.
644 class ThisOverrideRAII {
645 public:
646 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
647 : Frame(Frame), OldThis(Frame.This) {
648 if (Enable)
649 Frame.This = NewThis;
651 ~ThisOverrideRAII() {
652 Frame.This = OldThis;
654 private:
655 CallStackFrame &Frame;
656 const LValue *OldThis;
659 // A shorthand time trace scope struct, prints source range, for example
660 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
661 class ExprTimeTraceScope {
662 public:
663 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
664 : TimeScope(Name, [E, &Ctx] {
665 return E->getSourceRange().printToString(Ctx.getSourceManager());
666 }) {}
668 private:
669 llvm::TimeTraceScope TimeScope;
673 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
674 const LValue &This, QualType ThisType);
675 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
676 APValue::LValueBase LVBase, APValue &Value,
677 QualType T);
679 namespace {
680 /// A cleanup, and a flag indicating whether it is lifetime-extended.
681 class Cleanup {
682 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
683 APValue::LValueBase Base;
684 QualType T;
686 public:
687 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
688 ScopeKind Scope)
689 : Value(Val, Scope), Base(Base), T(T) {}
691 /// Determine whether this cleanup should be performed at the end of the
692 /// given kind of scope.
693 bool isDestroyedAtEndOf(ScopeKind K) const {
694 return (int)Value.getInt() >= (int)K;
696 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
697 if (RunDestructors) {
698 SourceLocation Loc;
699 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
700 Loc = VD->getLocation();
701 else if (const Expr *E = Base.dyn_cast<const Expr*>())
702 Loc = E->getExprLoc();
703 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
705 *Value.getPointer() = APValue();
706 return true;
709 bool hasSideEffect() {
710 return T.isDestructedType();
714 /// A reference to an object whose construction we are currently evaluating.
715 struct ObjectUnderConstruction {
716 APValue::LValueBase Base;
717 ArrayRef<APValue::LValuePathEntry> Path;
718 friend bool operator==(const ObjectUnderConstruction &LHS,
719 const ObjectUnderConstruction &RHS) {
720 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
722 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
723 return llvm::hash_combine(Obj.Base, Obj.Path);
726 enum class ConstructionPhase {
727 None,
728 Bases,
729 AfterBases,
730 AfterFields,
731 Destroying,
732 DestroyingBases
736 namespace llvm {
737 template<> struct DenseMapInfo<ObjectUnderConstruction> {
738 using Base = DenseMapInfo<APValue::LValueBase>;
739 static ObjectUnderConstruction getEmptyKey() {
740 return {Base::getEmptyKey(), {}}; }
741 static ObjectUnderConstruction getTombstoneKey() {
742 return {Base::getTombstoneKey(), {}};
744 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
745 return hash_value(Object);
747 static bool isEqual(const ObjectUnderConstruction &LHS,
748 const ObjectUnderConstruction &RHS) {
749 return LHS == RHS;
754 namespace {
755 /// A dynamically-allocated heap object.
756 struct DynAlloc {
757 /// The value of this heap-allocated object.
758 APValue Value;
759 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
760 /// or a CallExpr (the latter is for direct calls to operator new inside
761 /// std::allocator<T>::allocate).
762 const Expr *AllocExpr = nullptr;
764 enum Kind {
765 New,
766 ArrayNew,
767 StdAllocator
770 /// Get the kind of the allocation. This must match between allocation
771 /// and deallocation.
772 Kind getKind() const {
773 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
774 return NE->isArray() ? ArrayNew : New;
775 assert(isa<CallExpr>(AllocExpr));
776 return StdAllocator;
780 struct DynAllocOrder {
781 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
782 return L.getIndex() < R.getIndex();
786 /// EvalInfo - This is a private struct used by the evaluator to capture
787 /// information about a subexpression as it is folded. It retains information
788 /// about the AST context, but also maintains information about the folded
789 /// expression.
791 /// If an expression could be evaluated, it is still possible it is not a C
792 /// "integer constant expression" or constant expression. If not, this struct
793 /// captures information about how and why not.
795 /// One bit of information passed *into* the request for constant folding
796 /// indicates whether the subexpression is "evaluated" or not according to C
797 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
798 /// evaluate the expression regardless of what the RHS is, but C only allows
799 /// certain things in certain situations.
800 class EvalInfo : public interp::State {
801 public:
802 ASTContext &Ctx;
804 /// EvalStatus - Contains information about the evaluation.
805 Expr::EvalStatus &EvalStatus;
807 /// CurrentCall - The top of the constexpr call stack.
808 CallStackFrame *CurrentCall;
810 /// CallStackDepth - The number of calls in the call stack right now.
811 unsigned CallStackDepth;
813 /// NextCallIndex - The next call index to assign.
814 unsigned NextCallIndex;
816 /// StepsLeft - The remaining number of evaluation steps we're permitted
817 /// to perform. This is essentially a limit for the number of statements
818 /// we will evaluate.
819 unsigned StepsLeft;
821 /// Enable the experimental new constant interpreter. If an expression is
822 /// not supported by the interpreter, an error is triggered.
823 bool EnableNewConstInterp;
825 /// BottomFrame - The frame in which evaluation started. This must be
826 /// initialized after CurrentCall and CallStackDepth.
827 CallStackFrame BottomFrame;
829 /// A stack of values whose lifetimes end at the end of some surrounding
830 /// evaluation frame.
831 llvm::SmallVector<Cleanup, 16> CleanupStack;
833 /// EvaluatingDecl - This is the declaration whose initializer is being
834 /// evaluated, if any.
835 APValue::LValueBase EvaluatingDecl;
837 enum class EvaluatingDeclKind {
838 None,
839 /// We're evaluating the construction of EvaluatingDecl.
840 Ctor,
841 /// We're evaluating the destruction of EvaluatingDecl.
842 Dtor,
844 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
846 /// EvaluatingDeclValue - This is the value being constructed for the
847 /// declaration whose initializer is being evaluated, if any.
848 APValue *EvaluatingDeclValue;
850 /// Set of objects that are currently being constructed.
851 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
852 ObjectsUnderConstruction;
854 /// Current heap allocations, along with the location where each was
855 /// allocated. We use std::map here because we need stable addresses
856 /// for the stored APValues.
857 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
859 /// The number of heap allocations performed so far in this evaluation.
860 unsigned NumHeapAllocs = 0;
862 struct EvaluatingConstructorRAII {
863 EvalInfo &EI;
864 ObjectUnderConstruction Object;
865 bool DidInsert;
866 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
867 bool HasBases)
868 : EI(EI), Object(Object) {
869 DidInsert =
870 EI.ObjectsUnderConstruction
871 .insert({Object, HasBases ? ConstructionPhase::Bases
872 : ConstructionPhase::AfterBases})
873 .second;
875 void finishedConstructingBases() {
876 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
878 void finishedConstructingFields() {
879 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
881 ~EvaluatingConstructorRAII() {
882 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
886 struct EvaluatingDestructorRAII {
887 EvalInfo &EI;
888 ObjectUnderConstruction Object;
889 bool DidInsert;
890 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
891 : EI(EI), Object(Object) {
892 DidInsert = EI.ObjectsUnderConstruction
893 .insert({Object, ConstructionPhase::Destroying})
894 .second;
896 void startedDestroyingBases() {
897 EI.ObjectsUnderConstruction[Object] =
898 ConstructionPhase::DestroyingBases;
900 ~EvaluatingDestructorRAII() {
901 if (DidInsert)
902 EI.ObjectsUnderConstruction.erase(Object);
906 ConstructionPhase
907 isEvaluatingCtorDtor(APValue::LValueBase Base,
908 ArrayRef<APValue::LValuePathEntry> Path) {
909 return ObjectsUnderConstruction.lookup({Base, Path});
912 /// If we're currently speculatively evaluating, the outermost call stack
913 /// depth at which we can mutate state, otherwise 0.
914 unsigned SpeculativeEvaluationDepth = 0;
916 /// The current array initialization index, if we're performing array
917 /// initialization.
918 uint64_t ArrayInitIndex = -1;
920 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
921 /// notes attached to it will also be stored, otherwise they will not be.
922 bool HasActiveDiagnostic;
924 /// Have we emitted a diagnostic explaining why we couldn't constant
925 /// fold (not just why it's not strictly a constant expression)?
926 bool HasFoldFailureDiagnostic;
928 /// Whether we're checking that an expression is a potential constant
929 /// expression. If so, do not fail on constructs that could become constant
930 /// later on (such as a use of an undefined global).
931 bool CheckingPotentialConstantExpression = false;
933 /// Whether we're checking for an expression that has undefined behavior.
934 /// If so, we will produce warnings if we encounter an operation that is
935 /// always undefined.
937 /// Note that we still need to evaluate the expression normally when this
938 /// is set; this is used when evaluating ICEs in C.
939 bool CheckingForUndefinedBehavior = false;
941 enum EvaluationMode {
942 /// Evaluate as a constant expression. Stop if we find that the expression
943 /// is not a constant expression.
944 EM_ConstantExpression,
946 /// Evaluate as a constant expression. Stop if we find that the expression
947 /// is not a constant expression. Some expressions can be retried in the
948 /// optimizer if we don't constant fold them here, but in an unevaluated
949 /// context we try to fold them immediately since the optimizer never
950 /// gets a chance to look at it.
951 EM_ConstantExpressionUnevaluated,
953 /// Fold the expression to a constant. Stop if we hit a side-effect that
954 /// we can't model.
955 EM_ConstantFold,
957 /// Evaluate in any way we know how. Don't worry about side-effects that
958 /// can't be modeled.
959 EM_IgnoreSideEffects,
960 } EvalMode;
962 /// Are we checking whether the expression is a potential constant
963 /// expression?
964 bool checkingPotentialConstantExpression() const override {
965 return CheckingPotentialConstantExpression;
968 /// Are we checking an expression for overflow?
969 // FIXME: We should check for any kind of undefined or suspicious behavior
970 // in such constructs, not just overflow.
971 bool checkingForUndefinedBehavior() const override {
972 return CheckingForUndefinedBehavior;
975 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
976 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
977 CallStackDepth(0), NextCallIndex(1),
978 StepsLeft(C.getLangOpts().ConstexprStepLimit),
979 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
980 BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
981 EvaluatingDecl((const ValueDecl *)nullptr),
982 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
983 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
985 ~EvalInfo() {
986 discardCleanups();
989 ASTContext &getCtx() const override { return Ctx; }
991 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
992 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
993 EvaluatingDecl = Base;
994 IsEvaluatingDecl = EDK;
995 EvaluatingDeclValue = &Value;
998 bool CheckCallLimit(SourceLocation Loc) {
999 // Don't perform any constexpr calls (other than the call we're checking)
1000 // when checking a potential constant expression.
1001 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1002 return false;
1003 if (NextCallIndex == 0) {
1004 // NextCallIndex has wrapped around.
1005 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1006 return false;
1008 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1009 return true;
1010 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1011 << getLangOpts().ConstexprCallDepth;
1012 return false;
1015 std::pair<CallStackFrame *, unsigned>
1016 getCallFrameAndDepth(unsigned CallIndex) {
1017 assert(CallIndex && "no call index in getCallFrameAndDepth");
1018 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1019 // be null in this loop.
1020 unsigned Depth = CallStackDepth;
1021 CallStackFrame *Frame = CurrentCall;
1022 while (Frame->Index > CallIndex) {
1023 Frame = Frame->Caller;
1024 --Depth;
1026 if (Frame->Index == CallIndex)
1027 return {Frame, Depth};
1028 return {nullptr, 0};
1031 bool nextStep(const Stmt *S) {
1032 if (!StepsLeft) {
1033 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1034 return false;
1036 --StepsLeft;
1037 return true;
1040 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1042 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1043 std::optional<DynAlloc *> Result;
1044 auto It = HeapAllocs.find(DA);
1045 if (It != HeapAllocs.end())
1046 Result = &It->second;
1047 return Result;
1050 /// Get the allocated storage for the given parameter of the given call.
1051 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1052 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1053 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1054 : nullptr;
1057 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1058 struct StdAllocatorCaller {
1059 unsigned FrameIndex;
1060 QualType ElemType;
1061 explicit operator bool() const { return FrameIndex != 0; };
1064 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1065 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1066 Call = Call->Caller) {
1067 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1068 if (!MD)
1069 continue;
1070 const IdentifierInfo *FnII = MD->getIdentifier();
1071 if (!FnII || !FnII->isStr(FnName))
1072 continue;
1074 const auto *CTSD =
1075 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1076 if (!CTSD)
1077 continue;
1079 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1080 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1081 if (CTSD->isInStdNamespace() && ClassII &&
1082 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1083 TAL[0].getKind() == TemplateArgument::Type)
1084 return {Call->Index, TAL[0].getAsType()};
1087 return {};
1090 void performLifetimeExtension() {
1091 // Disable the cleanups for lifetime-extended temporaries.
1092 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1093 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1097 /// Throw away any remaining cleanups at the end of evaluation. If any
1098 /// cleanups would have had a side-effect, note that as an unmodeled
1099 /// side-effect and return false. Otherwise, return true.
1100 bool discardCleanups() {
1101 for (Cleanup &C : CleanupStack) {
1102 if (C.hasSideEffect() && !noteSideEffect()) {
1103 CleanupStack.clear();
1104 return false;
1107 CleanupStack.clear();
1108 return true;
1111 private:
1112 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1113 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1115 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1116 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1118 void setFoldFailureDiagnostic(bool Flag) override {
1119 HasFoldFailureDiagnostic = Flag;
1122 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1124 // If we have a prior diagnostic, it will be noting that the expression
1125 // isn't a constant expression. This diagnostic is more important,
1126 // unless we require this evaluation to produce a constant expression.
1128 // FIXME: We might want to show both diagnostics to the user in
1129 // EM_ConstantFold mode.
1130 bool hasPriorDiagnostic() override {
1131 if (!EvalStatus.Diag->empty()) {
1132 switch (EvalMode) {
1133 case EM_ConstantFold:
1134 case EM_IgnoreSideEffects:
1135 if (!HasFoldFailureDiagnostic)
1136 break;
1137 // We've already failed to fold something. Keep that diagnostic.
1138 [[fallthrough]];
1139 case EM_ConstantExpression:
1140 case EM_ConstantExpressionUnevaluated:
1141 setActiveDiagnostic(false);
1142 return true;
1145 return false;
1148 unsigned getCallStackDepth() override { return CallStackDepth; }
1150 public:
1151 /// Should we continue evaluation after encountering a side-effect that we
1152 /// couldn't model?
1153 bool keepEvaluatingAfterSideEffect() {
1154 switch (EvalMode) {
1155 case EM_IgnoreSideEffects:
1156 return true;
1158 case EM_ConstantExpression:
1159 case EM_ConstantExpressionUnevaluated:
1160 case EM_ConstantFold:
1161 // By default, assume any side effect might be valid in some other
1162 // evaluation of this expression from a different context.
1163 return checkingPotentialConstantExpression() ||
1164 checkingForUndefinedBehavior();
1166 llvm_unreachable("Missed EvalMode case");
1169 /// Note that we have had a side-effect, and determine whether we should
1170 /// keep evaluating.
1171 bool noteSideEffect() {
1172 EvalStatus.HasSideEffects = true;
1173 return keepEvaluatingAfterSideEffect();
1176 /// Should we continue evaluation after encountering undefined behavior?
1177 bool keepEvaluatingAfterUndefinedBehavior() {
1178 switch (EvalMode) {
1179 case EM_IgnoreSideEffects:
1180 case EM_ConstantFold:
1181 return true;
1183 case EM_ConstantExpression:
1184 case EM_ConstantExpressionUnevaluated:
1185 return checkingForUndefinedBehavior();
1187 llvm_unreachable("Missed EvalMode case");
1190 /// Note that we hit something that was technically undefined behavior, but
1191 /// that we can evaluate past it (such as signed overflow or floating-point
1192 /// division by zero.)
1193 bool noteUndefinedBehavior() override {
1194 EvalStatus.HasUndefinedBehavior = true;
1195 return keepEvaluatingAfterUndefinedBehavior();
1198 /// Should we continue evaluation as much as possible after encountering a
1199 /// construct which can't be reduced to a value?
1200 bool keepEvaluatingAfterFailure() const override {
1201 if (!StepsLeft)
1202 return false;
1204 switch (EvalMode) {
1205 case EM_ConstantExpression:
1206 case EM_ConstantExpressionUnevaluated:
1207 case EM_ConstantFold:
1208 case EM_IgnoreSideEffects:
1209 return checkingPotentialConstantExpression() ||
1210 checkingForUndefinedBehavior();
1212 llvm_unreachable("Missed EvalMode case");
1215 /// Notes that we failed to evaluate an expression that other expressions
1216 /// directly depend on, and determine if we should keep evaluating. This
1217 /// should only be called if we actually intend to keep evaluating.
1219 /// Call noteSideEffect() instead if we may be able to ignore the value that
1220 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1222 /// (Foo(), 1) // use noteSideEffect
1223 /// (Foo() || true) // use noteSideEffect
1224 /// Foo() + 1 // use noteFailure
1225 [[nodiscard]] bool noteFailure() {
1226 // Failure when evaluating some expression often means there is some
1227 // subexpression whose evaluation was skipped. Therefore, (because we
1228 // don't track whether we skipped an expression when unwinding after an
1229 // evaluation failure) every evaluation failure that bubbles up from a
1230 // subexpression implies that a side-effect has potentially happened. We
1231 // skip setting the HasSideEffects flag to true until we decide to
1232 // continue evaluating after that point, which happens here.
1233 bool KeepGoing = keepEvaluatingAfterFailure();
1234 EvalStatus.HasSideEffects |= KeepGoing;
1235 return KeepGoing;
1238 class ArrayInitLoopIndex {
1239 EvalInfo &Info;
1240 uint64_t OuterIndex;
1242 public:
1243 ArrayInitLoopIndex(EvalInfo &Info)
1244 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1245 Info.ArrayInitIndex = 0;
1247 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1249 operator uint64_t&() { return Info.ArrayInitIndex; }
1253 /// Object used to treat all foldable expressions as constant expressions.
1254 struct FoldConstant {
1255 EvalInfo &Info;
1256 bool Enabled;
1257 bool HadNoPriorDiags;
1258 EvalInfo::EvaluationMode OldMode;
1260 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1261 : Info(Info),
1262 Enabled(Enabled),
1263 HadNoPriorDiags(Info.EvalStatus.Diag &&
1264 Info.EvalStatus.Diag->empty() &&
1265 !Info.EvalStatus.HasSideEffects),
1266 OldMode(Info.EvalMode) {
1267 if (Enabled)
1268 Info.EvalMode = EvalInfo::EM_ConstantFold;
1270 void keepDiagnostics() { Enabled = false; }
1271 ~FoldConstant() {
1272 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1273 !Info.EvalStatus.HasSideEffects)
1274 Info.EvalStatus.Diag->clear();
1275 Info.EvalMode = OldMode;
1279 /// RAII object used to set the current evaluation mode to ignore
1280 /// side-effects.
1281 struct IgnoreSideEffectsRAII {
1282 EvalInfo &Info;
1283 EvalInfo::EvaluationMode OldMode;
1284 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1285 : Info(Info), OldMode(Info.EvalMode) {
1286 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1289 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1292 /// RAII object used to optionally suppress diagnostics and side-effects from
1293 /// a speculative evaluation.
1294 class SpeculativeEvaluationRAII {
1295 EvalInfo *Info = nullptr;
1296 Expr::EvalStatus OldStatus;
1297 unsigned OldSpeculativeEvaluationDepth;
1299 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1300 Info = Other.Info;
1301 OldStatus = Other.OldStatus;
1302 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1303 Other.Info = nullptr;
1306 void maybeRestoreState() {
1307 if (!Info)
1308 return;
1310 Info->EvalStatus = OldStatus;
1311 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1314 public:
1315 SpeculativeEvaluationRAII() = default;
1317 SpeculativeEvaluationRAII(
1318 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1319 : Info(&Info), OldStatus(Info.EvalStatus),
1320 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1321 Info.EvalStatus.Diag = NewDiag;
1322 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1325 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1326 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1327 moveFromAndCancel(std::move(Other));
1330 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1331 maybeRestoreState();
1332 moveFromAndCancel(std::move(Other));
1333 return *this;
1336 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1339 /// RAII object wrapping a full-expression or block scope, and handling
1340 /// the ending of the lifetime of temporaries created within it.
1341 template<ScopeKind Kind>
1342 class ScopeRAII {
1343 EvalInfo &Info;
1344 unsigned OldStackSize;
1345 public:
1346 ScopeRAII(EvalInfo &Info)
1347 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1348 // Push a new temporary version. This is needed to distinguish between
1349 // temporaries created in different iterations of a loop.
1350 Info.CurrentCall->pushTempVersion();
1352 bool destroy(bool RunDestructors = true) {
1353 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1354 OldStackSize = -1U;
1355 return OK;
1357 ~ScopeRAII() {
1358 if (OldStackSize != -1U)
1359 destroy(false);
1360 // Body moved to a static method to encourage the compiler to inline away
1361 // instances of this class.
1362 Info.CurrentCall->popTempVersion();
1364 private:
1365 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1366 unsigned OldStackSize) {
1367 assert(OldStackSize <= Info.CleanupStack.size() &&
1368 "running cleanups out of order?");
1370 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1371 // for a full-expression scope.
1372 bool Success = true;
1373 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1374 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1375 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1376 Success = false;
1377 break;
1382 // Compact any retained cleanups.
1383 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1384 if (Kind != ScopeKind::Block)
1385 NewEnd =
1386 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1387 return C.isDestroyedAtEndOf(Kind);
1389 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1390 return Success;
1393 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1394 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1395 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1398 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1399 CheckSubobjectKind CSK) {
1400 if (Invalid)
1401 return false;
1402 if (isOnePastTheEnd()) {
1403 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1404 << CSK;
1405 setInvalid();
1406 return false;
1408 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1409 // must actually be at least one array element; even a VLA cannot have a
1410 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1411 return true;
1414 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1415 const Expr *E) {
1416 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1417 // Do not set the designator as invalid: we can represent this situation,
1418 // and correct handling of __builtin_object_size requires us to do so.
1421 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1422 const Expr *E,
1423 const APSInt &N) {
1424 // If we're complaining, we must be able to statically determine the size of
1425 // the most derived array.
1426 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1427 Info.CCEDiag(E, diag::note_constexpr_array_index)
1428 << N << /*array*/ 0
1429 << static_cast<unsigned>(getMostDerivedArraySize());
1430 else
1431 Info.CCEDiag(E, diag::note_constexpr_array_index)
1432 << N << /*non-array*/ 1;
1433 setInvalid();
1436 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1437 const FunctionDecl *Callee, const LValue *This,
1438 CallRef Call)
1439 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1440 Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1441 Info.CurrentCall = this;
1442 ++Info.CallStackDepth;
1445 CallStackFrame::~CallStackFrame() {
1446 assert(Info.CurrentCall == this && "calls retired out of order");
1447 --Info.CallStackDepth;
1448 Info.CurrentCall = Caller;
1451 static bool isRead(AccessKinds AK) {
1452 return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1455 static bool isModification(AccessKinds AK) {
1456 switch (AK) {
1457 case AK_Read:
1458 case AK_ReadObjectRepresentation:
1459 case AK_MemberCall:
1460 case AK_DynamicCast:
1461 case AK_TypeId:
1462 return false;
1463 case AK_Assign:
1464 case AK_Increment:
1465 case AK_Decrement:
1466 case AK_Construct:
1467 case AK_Destroy:
1468 return true;
1470 llvm_unreachable("unknown access kind");
1473 static bool isAnyAccess(AccessKinds AK) {
1474 return isRead(AK) || isModification(AK);
1477 /// Is this an access per the C++ definition?
1478 static bool isFormalAccess(AccessKinds AK) {
1479 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1482 /// Is this kind of axcess valid on an indeterminate object value?
1483 static bool isValidIndeterminateAccess(AccessKinds AK) {
1484 switch (AK) {
1485 case AK_Read:
1486 case AK_Increment:
1487 case AK_Decrement:
1488 // These need the object's value.
1489 return false;
1491 case AK_ReadObjectRepresentation:
1492 case AK_Assign:
1493 case AK_Construct:
1494 case AK_Destroy:
1495 // Construction and destruction don't need the value.
1496 return true;
1498 case AK_MemberCall:
1499 case AK_DynamicCast:
1500 case AK_TypeId:
1501 // These aren't really meaningful on scalars.
1502 return true;
1504 llvm_unreachable("unknown access kind");
1507 namespace {
1508 struct ComplexValue {
1509 private:
1510 bool IsInt;
1512 public:
1513 APSInt IntReal, IntImag;
1514 APFloat FloatReal, FloatImag;
1516 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1518 void makeComplexFloat() { IsInt = false; }
1519 bool isComplexFloat() const { return !IsInt; }
1520 APFloat &getComplexFloatReal() { return FloatReal; }
1521 APFloat &getComplexFloatImag() { return FloatImag; }
1523 void makeComplexInt() { IsInt = true; }
1524 bool isComplexInt() const { return IsInt; }
1525 APSInt &getComplexIntReal() { return IntReal; }
1526 APSInt &getComplexIntImag() { return IntImag; }
1528 void moveInto(APValue &v) const {
1529 if (isComplexFloat())
1530 v = APValue(FloatReal, FloatImag);
1531 else
1532 v = APValue(IntReal, IntImag);
1534 void setFrom(const APValue &v) {
1535 assert(v.isComplexFloat() || v.isComplexInt());
1536 if (v.isComplexFloat()) {
1537 makeComplexFloat();
1538 FloatReal = v.getComplexFloatReal();
1539 FloatImag = v.getComplexFloatImag();
1540 } else {
1541 makeComplexInt();
1542 IntReal = v.getComplexIntReal();
1543 IntImag = v.getComplexIntImag();
1548 struct LValue {
1549 APValue::LValueBase Base;
1550 CharUnits Offset;
1551 SubobjectDesignator Designator;
1552 bool IsNullPtr : 1;
1553 bool InvalidBase : 1;
1555 const APValue::LValueBase getLValueBase() const { return Base; }
1556 CharUnits &getLValueOffset() { return Offset; }
1557 const CharUnits &getLValueOffset() const { return Offset; }
1558 SubobjectDesignator &getLValueDesignator() { return Designator; }
1559 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1560 bool isNullPointer() const { return IsNullPtr;}
1562 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1563 unsigned getLValueVersion() const { return Base.getVersion(); }
1565 void moveInto(APValue &V) const {
1566 if (Designator.Invalid)
1567 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1568 else {
1569 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1570 V = APValue(Base, Offset, Designator.Entries,
1571 Designator.IsOnePastTheEnd, IsNullPtr);
1574 void setFrom(ASTContext &Ctx, const APValue &V) {
1575 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1576 Base = V.getLValueBase();
1577 Offset = V.getLValueOffset();
1578 InvalidBase = false;
1579 Designator = SubobjectDesignator(Ctx, V);
1580 IsNullPtr = V.isNullPointer();
1583 void set(APValue::LValueBase B, bool BInvalid = false) {
1584 #ifndef NDEBUG
1585 // We only allow a few types of invalid bases. Enforce that here.
1586 if (BInvalid) {
1587 const auto *E = B.get<const Expr *>();
1588 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1589 "Unexpected type of invalid base");
1591 #endif
1593 Base = B;
1594 Offset = CharUnits::fromQuantity(0);
1595 InvalidBase = BInvalid;
1596 Designator = SubobjectDesignator(getType(B));
1597 IsNullPtr = false;
1600 void setNull(ASTContext &Ctx, QualType PointerTy) {
1601 Base = (const ValueDecl *)nullptr;
1602 Offset =
1603 CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1604 InvalidBase = false;
1605 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1606 IsNullPtr = true;
1609 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1610 set(B, true);
1613 std::string toString(ASTContext &Ctx, QualType T) const {
1614 APValue Printable;
1615 moveInto(Printable);
1616 return Printable.getAsString(Ctx, T);
1619 private:
1620 // Check that this LValue is not based on a null pointer. If it is, produce
1621 // a diagnostic and mark the designator as invalid.
1622 template <typename GenDiagType>
1623 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1624 if (Designator.Invalid)
1625 return false;
1626 if (IsNullPtr) {
1627 GenDiag();
1628 Designator.setInvalid();
1629 return false;
1631 return true;
1634 public:
1635 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1636 CheckSubobjectKind CSK) {
1637 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1638 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1642 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1643 AccessKinds AK) {
1644 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1645 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1649 // Check this LValue refers to an object. If not, set the designator to be
1650 // invalid and emit a diagnostic.
1651 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1652 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1653 Designator.checkSubobject(Info, E, CSK);
1656 void addDecl(EvalInfo &Info, const Expr *E,
1657 const Decl *D, bool Virtual = false) {
1658 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1659 Designator.addDeclUnchecked(D, Virtual);
1661 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1662 if (!Designator.Entries.empty()) {
1663 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1664 Designator.setInvalid();
1665 return;
1667 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1668 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1669 Designator.FirstEntryIsAnUnsizedArray = true;
1670 Designator.addUnsizedArrayUnchecked(ElemTy);
1673 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1674 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1675 Designator.addArrayUnchecked(CAT);
1677 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1678 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1679 Designator.addComplexUnchecked(EltTy, Imag);
1681 void clearIsNullPointer() {
1682 IsNullPtr = false;
1684 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1685 const APSInt &Index, CharUnits ElementSize) {
1686 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1687 // but we're not required to diagnose it and it's valid in C++.)
1688 if (!Index)
1689 return;
1691 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1692 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1693 // offsets.
1694 uint64_t Offset64 = Offset.getQuantity();
1695 uint64_t ElemSize64 = ElementSize.getQuantity();
1696 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1697 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1699 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1700 Designator.adjustIndex(Info, E, Index);
1701 clearIsNullPointer();
1703 void adjustOffset(CharUnits N) {
1704 Offset += N;
1705 if (N.getQuantity())
1706 clearIsNullPointer();
1710 struct MemberPtr {
1711 MemberPtr() {}
1712 explicit MemberPtr(const ValueDecl *Decl)
1713 : DeclAndIsDerivedMember(Decl, false) {}
1715 /// The member or (direct or indirect) field referred to by this member
1716 /// pointer, or 0 if this is a null member pointer.
1717 const ValueDecl *getDecl() const {
1718 return DeclAndIsDerivedMember.getPointer();
1720 /// Is this actually a member of some type derived from the relevant class?
1721 bool isDerivedMember() const {
1722 return DeclAndIsDerivedMember.getInt();
1724 /// Get the class which the declaration actually lives in.
1725 const CXXRecordDecl *getContainingRecord() const {
1726 return cast<CXXRecordDecl>(
1727 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1730 void moveInto(APValue &V) const {
1731 V = APValue(getDecl(), isDerivedMember(), Path);
1733 void setFrom(const APValue &V) {
1734 assert(V.isMemberPointer());
1735 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1736 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1737 Path.clear();
1738 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1739 Path.insert(Path.end(), P.begin(), P.end());
1742 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1743 /// whether the member is a member of some class derived from the class type
1744 /// of the member pointer.
1745 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1746 /// Path - The path of base/derived classes from the member declaration's
1747 /// class (exclusive) to the class type of the member pointer (inclusive).
1748 SmallVector<const CXXRecordDecl*, 4> Path;
1750 /// Perform a cast towards the class of the Decl (either up or down the
1751 /// hierarchy).
1752 bool castBack(const CXXRecordDecl *Class) {
1753 assert(!Path.empty());
1754 const CXXRecordDecl *Expected;
1755 if (Path.size() >= 2)
1756 Expected = Path[Path.size() - 2];
1757 else
1758 Expected = getContainingRecord();
1759 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1760 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1761 // if B does not contain the original member and is not a base or
1762 // derived class of the class containing the original member, the result
1763 // of the cast is undefined.
1764 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1765 // (D::*). We consider that to be a language defect.
1766 return false;
1768 Path.pop_back();
1769 return true;
1771 /// Perform a base-to-derived member pointer cast.
1772 bool castToDerived(const CXXRecordDecl *Derived) {
1773 if (!getDecl())
1774 return true;
1775 if (!isDerivedMember()) {
1776 Path.push_back(Derived);
1777 return true;
1779 if (!castBack(Derived))
1780 return false;
1781 if (Path.empty())
1782 DeclAndIsDerivedMember.setInt(false);
1783 return true;
1785 /// Perform a derived-to-base member pointer cast.
1786 bool castToBase(const CXXRecordDecl *Base) {
1787 if (!getDecl())
1788 return true;
1789 if (Path.empty())
1790 DeclAndIsDerivedMember.setInt(true);
1791 if (isDerivedMember()) {
1792 Path.push_back(Base);
1793 return true;
1795 return castBack(Base);
1799 /// Compare two member pointers, which are assumed to be of the same type.
1800 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1801 if (!LHS.getDecl() || !RHS.getDecl())
1802 return !LHS.getDecl() && !RHS.getDecl();
1803 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1804 return false;
1805 return LHS.Path == RHS.Path;
1809 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1810 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1811 const LValue &This, const Expr *E,
1812 bool AllowNonLiteralTypes = false);
1813 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1814 bool InvalidBaseOK = false);
1815 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1816 bool InvalidBaseOK = false);
1817 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1818 EvalInfo &Info);
1819 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1820 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1821 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1822 EvalInfo &Info);
1823 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1824 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1825 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1826 EvalInfo &Info);
1827 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1828 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1829 EvalInfo &Info);
1831 /// Evaluate an integer or fixed point expression into an APResult.
1832 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1833 EvalInfo &Info);
1835 /// Evaluate only a fixed point expression into an APResult.
1836 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1837 EvalInfo &Info);
1839 //===----------------------------------------------------------------------===//
1840 // Misc utilities
1841 //===----------------------------------------------------------------------===//
1843 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1844 /// preserving its value (by extending by up to one bit as needed).
1845 static void negateAsSigned(APSInt &Int) {
1846 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1847 Int = Int.extend(Int.getBitWidth() + 1);
1848 Int.setIsSigned(true);
1850 Int = -Int;
1853 template<typename KeyT>
1854 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1855 ScopeKind Scope, LValue &LV) {
1856 unsigned Version = getTempVersion();
1857 APValue::LValueBase Base(Key, Index, Version);
1858 LV.set(Base);
1859 return createLocal(Base, Key, T, Scope);
1862 /// Allocate storage for a parameter of a function call made in this frame.
1863 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1864 LValue &LV) {
1865 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1866 APValue::LValueBase Base(PVD, Index, Args.Version);
1867 LV.set(Base);
1868 // We always destroy parameters at the end of the call, even if we'd allow
1869 // them to live to the end of the full-expression at runtime, in order to
1870 // give portable results and match other compilers.
1871 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1874 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1875 QualType T, ScopeKind Scope) {
1876 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1877 unsigned Version = Base.getVersion();
1878 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1879 assert(Result.isAbsent() && "local created multiple times");
1881 // If we're creating a local immediately in the operand of a speculative
1882 // evaluation, don't register a cleanup to be run outside the speculative
1883 // evaluation context, since we won't actually be able to initialize this
1884 // object.
1885 if (Index <= Info.SpeculativeEvaluationDepth) {
1886 if (T.isDestructedType())
1887 Info.noteSideEffect();
1888 } else {
1889 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1891 return Result;
1894 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1895 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1896 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1897 return nullptr;
1900 DynamicAllocLValue DA(NumHeapAllocs++);
1901 LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1902 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1903 std::forward_as_tuple(DA), std::tuple<>());
1904 assert(Result.second && "reused a heap alloc index?");
1905 Result.first->second.AllocExpr = E;
1906 return &Result.first->second.Value;
1909 /// Produce a string describing the given constexpr call.
1910 void CallStackFrame::describe(raw_ostream &Out) {
1911 unsigned ArgIndex = 0;
1912 bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1913 !isa<CXXConstructorDecl>(Callee) &&
1914 cast<CXXMethodDecl>(Callee)->isInstance();
1916 if (!IsMemberCall)
1917 Out << *Callee << '(';
1919 if (This && IsMemberCall) {
1920 APValue Val;
1921 This->moveInto(Val);
1922 Val.printPretty(Out, Info.Ctx,
1923 This->Designator.MostDerivedType);
1924 // FIXME: Add parens around Val if needed.
1925 Out << "->" << *Callee << '(';
1926 IsMemberCall = false;
1929 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1930 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1931 if (ArgIndex > (unsigned)IsMemberCall)
1932 Out << ", ";
1934 const ParmVarDecl *Param = *I;
1935 APValue *V = Info.getParamSlot(Arguments, Param);
1936 if (V)
1937 V->printPretty(Out, Info.Ctx, Param->getType());
1938 else
1939 Out << "<...>";
1941 if (ArgIndex == 0 && IsMemberCall)
1942 Out << "->" << *Callee << '(';
1945 Out << ')';
1948 /// Evaluate an expression to see if it had side-effects, and discard its
1949 /// result.
1950 /// \return \c true if the caller should keep evaluating.
1951 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1952 assert(!E->isValueDependent());
1953 APValue Scratch;
1954 if (!Evaluate(Scratch, Info, E))
1955 // We don't need the value, but we might have skipped a side effect here.
1956 return Info.noteSideEffect();
1957 return true;
1960 /// Should this call expression be treated as a no-op?
1961 static bool IsNoOpCall(const CallExpr *E) {
1962 unsigned Builtin = E->getBuiltinCallee();
1963 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1964 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
1965 Builtin == Builtin::BI__builtin_function_start);
1968 static bool IsGlobalLValue(APValue::LValueBase B) {
1969 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970 // constant expression of pointer type that evaluates to...
1972 // ... a null pointer value, or a prvalue core constant expression of type
1973 // std::nullptr_t.
1974 if (!B) return true;
1976 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977 // ... the address of an object with static storage duration,
1978 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979 return VD->hasGlobalStorage();
1980 if (isa<TemplateParamObjectDecl>(D))
1981 return true;
1982 // ... the address of a function,
1983 // ... the address of a GUID [MS extension],
1984 // ... the address of an unnamed global constant
1985 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
1988 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1989 return true;
1991 const Expr *E = B.get<const Expr*>();
1992 switch (E->getStmtClass()) {
1993 default:
1994 return false;
1995 case Expr::CompoundLiteralExprClass: {
1996 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1997 return CLE->isFileScope() && CLE->isLValue();
1999 case Expr::MaterializeTemporaryExprClass:
2000 // A materialized temporary might have been lifetime-extended to static
2001 // storage duration.
2002 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2003 // A string literal has static storage duration.
2004 case Expr::StringLiteralClass:
2005 case Expr::PredefinedExprClass:
2006 case Expr::ObjCStringLiteralClass:
2007 case Expr::ObjCEncodeExprClass:
2008 return true;
2009 case Expr::ObjCBoxedExprClass:
2010 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2011 case Expr::CallExprClass:
2012 return IsNoOpCall(cast<CallExpr>(E));
2013 // For GCC compatibility, &&label has static storage duration.
2014 case Expr::AddrLabelExprClass:
2015 return true;
2016 // A Block literal expression may be used as the initialization value for
2017 // Block variables at global or local static scope.
2018 case Expr::BlockExprClass:
2019 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2020 // The APValue generated from a __builtin_source_location will be emitted as a
2021 // literal.
2022 case Expr::SourceLocExprClass:
2023 return true;
2024 case Expr::ImplicitValueInitExprClass:
2025 // FIXME:
2026 // We can never form an lvalue with an implicit value initialization as its
2027 // base through expression evaluation, so these only appear in one case: the
2028 // implicit variable declaration we invent when checking whether a constexpr
2029 // constructor can produce a constant expression. We must assume that such
2030 // an expression might be a global lvalue.
2031 return true;
2035 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2036 return LVal.Base.dyn_cast<const ValueDecl*>();
2039 static bool IsLiteralLValue(const LValue &Value) {
2040 if (Value.getLValueCallIndex())
2041 return false;
2042 const Expr *E = Value.Base.dyn_cast<const Expr*>();
2043 return E && !isa<MaterializeTemporaryExpr>(E);
2046 static bool IsWeakLValue(const LValue &Value) {
2047 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048 return Decl && Decl->isWeak();
2051 static bool isZeroSized(const LValue &Value) {
2052 const ValueDecl *Decl = GetLValueBaseDecl(Value);
2053 if (Decl && isa<VarDecl>(Decl)) {
2054 QualType Ty = Decl->getType();
2055 if (Ty->isArrayType())
2056 return Ty->isIncompleteType() ||
2057 Decl->getASTContext().getTypeSize(Ty) == 0;
2059 return false;
2062 static bool HasSameBase(const LValue &A, const LValue &B) {
2063 if (!A.getLValueBase())
2064 return !B.getLValueBase();
2065 if (!B.getLValueBase())
2066 return false;
2068 if (A.getLValueBase().getOpaqueValue() !=
2069 B.getLValueBase().getOpaqueValue())
2070 return false;
2072 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2073 A.getLValueVersion() == B.getLValueVersion();
2076 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2077 assert(Base && "no location for a null lvalue");
2078 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2080 // For a parameter, find the corresponding call stack frame (if it still
2081 // exists), and point at the parameter of the function definition we actually
2082 // invoked.
2083 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2084 unsigned Idx = PVD->getFunctionScopeIndex();
2085 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2086 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2087 F->Arguments.Version == Base.getVersion() && F->Callee &&
2088 Idx < F->Callee->getNumParams()) {
2089 VD = F->Callee->getParamDecl(Idx);
2090 break;
2095 if (VD)
2096 Info.Note(VD->getLocation(), diag::note_declared_at);
2097 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2098 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2099 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2100 // FIXME: Produce a note for dangling pointers too.
2101 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2102 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2103 diag::note_constexpr_dynamic_alloc_here);
2105 // We have no information to show for a typeid(T) object.
2108 enum class CheckEvaluationResultKind {
2109 ConstantExpression,
2110 FullyInitialized,
2113 /// Materialized temporaries that we've already checked to determine if they're
2114 /// initializsed by a constant expression.
2115 using CheckedTemporaries =
2116 llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2118 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2119 EvalInfo &Info, SourceLocation DiagLoc,
2120 QualType Type, const APValue &Value,
2121 ConstantExprKind Kind,
2122 SourceLocation SubobjectLoc,
2123 CheckedTemporaries &CheckedTemps);
2125 /// Check that this reference or pointer core constant expression is a valid
2126 /// value for an address or reference constant expression. Return true if we
2127 /// can fold this expression, whether or not it's a constant expression.
2128 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2129 QualType Type, const LValue &LVal,
2130 ConstantExprKind Kind,
2131 CheckedTemporaries &CheckedTemps) {
2132 bool IsReferenceType = Type->isReferenceType();
2134 APValue::LValueBase Base = LVal.getLValueBase();
2135 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2137 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2138 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2140 // Additional restrictions apply in a template argument. We only enforce the
2141 // C++20 restrictions here; additional syntactic and semantic restrictions
2142 // are applied elsewhere.
2143 if (isTemplateArgument(Kind)) {
2144 int InvalidBaseKind = -1;
2145 StringRef Ident;
2146 if (Base.is<TypeInfoLValue>())
2147 InvalidBaseKind = 0;
2148 else if (isa_and_nonnull<StringLiteral>(BaseE))
2149 InvalidBaseKind = 1;
2150 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2151 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2152 InvalidBaseKind = 2;
2153 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2154 InvalidBaseKind = 3;
2155 Ident = PE->getIdentKindName();
2158 if (InvalidBaseKind != -1) {
2159 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2160 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2161 << Ident;
2162 return false;
2166 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2167 if (FD->isConsteval()) {
2168 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2169 << !Type->isAnyPointerType();
2170 Info.Note(FD->getLocation(), diag::note_declared_at);
2171 return false;
2175 // Check that the object is a global. Note that the fake 'this' object we
2176 // manufacture when checking potential constant expressions is conservatively
2177 // assumed to be global here.
2178 if (!IsGlobalLValue(Base)) {
2179 if (Info.getLangOpts().CPlusPlus11) {
2180 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2181 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2182 << BaseVD;
2183 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2184 if (VarD && VarD->isConstexpr()) {
2185 // Non-static local constexpr variables have unintuitive semantics:
2186 // constexpr int a = 1;
2187 // constexpr const int *p = &a;
2188 // ... is invalid because the address of 'a' is not constant. Suggest
2189 // adding a 'static' in this case.
2190 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2191 << VarD
2192 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2193 } else {
2194 NoteLValueLocation(Info, Base);
2196 } else {
2197 Info.FFDiag(Loc);
2199 // Don't allow references to temporaries to escape.
2200 return false;
2202 assert((Info.checkingPotentialConstantExpression() ||
2203 LVal.getLValueCallIndex() == 0) &&
2204 "have call index for global lvalue");
2206 if (Base.is<DynamicAllocLValue>()) {
2207 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2208 << IsReferenceType << !Designator.Entries.empty();
2209 NoteLValueLocation(Info, Base);
2210 return false;
2213 if (BaseVD) {
2214 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2215 // Check if this is a thread-local variable.
2216 if (Var->getTLSKind())
2217 // FIXME: Diagnostic!
2218 return false;
2220 // A dllimport variable never acts like a constant, unless we're
2221 // evaluating a value for use only in name mangling.
2222 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2223 // FIXME: Diagnostic!
2224 return false;
2226 // In CUDA/HIP device compilation, only device side variables have
2227 // constant addresses.
2228 if (Info.getCtx().getLangOpts().CUDA &&
2229 Info.getCtx().getLangOpts().CUDAIsDevice &&
2230 Info.getCtx().CUDAConstantEvalCtx.NoWrongSidedVars) {
2231 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2232 !Var->hasAttr<CUDAConstantAttr>() &&
2233 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2234 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2235 Var->hasAttr<HIPManagedAttr>())
2236 return false;
2239 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2240 // __declspec(dllimport) must be handled very carefully:
2241 // We must never initialize an expression with the thunk in C++.
2242 // Doing otherwise would allow the same id-expression to yield
2243 // different addresses for the same function in different translation
2244 // units. However, this means that we must dynamically initialize the
2245 // expression with the contents of the import address table at runtime.
2247 // The C language has no notion of ODR; furthermore, it has no notion of
2248 // dynamic initialization. This means that we are permitted to
2249 // perform initialization with the address of the thunk.
2250 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2251 FD->hasAttr<DLLImportAttr>())
2252 // FIXME: Diagnostic!
2253 return false;
2255 } else if (const auto *MTE =
2256 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2257 if (CheckedTemps.insert(MTE).second) {
2258 QualType TempType = getType(Base);
2259 if (TempType.isDestructedType()) {
2260 Info.FFDiag(MTE->getExprLoc(),
2261 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2262 << TempType;
2263 return false;
2266 APValue *V = MTE->getOrCreateValue(false);
2267 assert(V && "evasluation result refers to uninitialised temporary");
2268 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2269 Info, MTE->getExprLoc(), TempType, *V,
2270 Kind, SourceLocation(), CheckedTemps))
2271 return false;
2275 // Allow address constant expressions to be past-the-end pointers. This is
2276 // an extension: the standard requires them to point to an object.
2277 if (!IsReferenceType)
2278 return true;
2280 // A reference constant expression must refer to an object.
2281 if (!Base) {
2282 // FIXME: diagnostic
2283 Info.CCEDiag(Loc);
2284 return true;
2287 // Does this refer one past the end of some object?
2288 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2289 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2290 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2291 NoteLValueLocation(Info, Base);
2294 return true;
2297 /// Member pointers are constant expressions unless they point to a
2298 /// non-virtual dllimport member function.
2299 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2300 SourceLocation Loc,
2301 QualType Type,
2302 const APValue &Value,
2303 ConstantExprKind Kind) {
2304 const ValueDecl *Member = Value.getMemberPointerDecl();
2305 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2306 if (!FD)
2307 return true;
2308 if (FD->isConsteval()) {
2309 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2310 Info.Note(FD->getLocation(), diag::note_declared_at);
2311 return false;
2313 return isForManglingOnly(Kind) || FD->isVirtual() ||
2314 !FD->hasAttr<DLLImportAttr>();
2317 /// Check that this core constant expression is of literal type, and if not,
2318 /// produce an appropriate diagnostic.
2319 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2320 const LValue *This = nullptr) {
2321 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2322 return true;
2324 // C++1y: A constant initializer for an object o [...] may also invoke
2325 // constexpr constructors for o and its subobjects even if those objects
2326 // are of non-literal class types.
2328 // C++11 missed this detail for aggregates, so classes like this:
2329 // struct foo_t { union { int i; volatile int j; } u; };
2330 // are not (obviously) initializable like so:
2331 // __attribute__((__require_constant_initialization__))
2332 // static const foo_t x = {{0}};
2333 // because "i" is a subobject with non-literal initialization (due to the
2334 // volatile member of the union). See:
2335 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2336 // Therefore, we use the C++1y behavior.
2337 if (This && Info.EvaluatingDecl == This->getLValueBase())
2338 return true;
2340 // Prvalue constant expressions must be of literal types.
2341 if (Info.getLangOpts().CPlusPlus11)
2342 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2343 << E->getType();
2344 else
2345 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2346 return false;
2349 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2350 EvalInfo &Info, SourceLocation DiagLoc,
2351 QualType Type, const APValue &Value,
2352 ConstantExprKind Kind,
2353 SourceLocation SubobjectLoc,
2354 CheckedTemporaries &CheckedTemps) {
2355 if (!Value.hasValue()) {
2356 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2357 << true << Type;
2358 if (SubobjectLoc.isValid())
2359 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2360 return false;
2363 // We allow _Atomic(T) to be initialized from anything that T can be
2364 // initialized from.
2365 if (const AtomicType *AT = Type->getAs<AtomicType>())
2366 Type = AT->getValueType();
2368 // Core issue 1454: For a literal constant expression of array or class type,
2369 // each subobject of its value shall have been initialized by a constant
2370 // expression.
2371 if (Value.isArray()) {
2372 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2373 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2374 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2375 Value.getArrayInitializedElt(I), Kind,
2376 SubobjectLoc, CheckedTemps))
2377 return false;
2379 if (!Value.hasArrayFiller())
2380 return true;
2381 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2382 Value.getArrayFiller(), Kind, SubobjectLoc,
2383 CheckedTemps);
2385 if (Value.isUnion() && Value.getUnionField()) {
2386 return CheckEvaluationResult(
2387 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2388 Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2389 CheckedTemps);
2391 if (Value.isStruct()) {
2392 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2393 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2394 unsigned BaseIndex = 0;
2395 for (const CXXBaseSpecifier &BS : CD->bases()) {
2396 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2397 Value.getStructBase(BaseIndex), Kind,
2398 BS.getBeginLoc(), CheckedTemps))
2399 return false;
2400 ++BaseIndex;
2403 for (const auto *I : RD->fields()) {
2404 if (I->isUnnamedBitfield())
2405 continue;
2407 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2408 Value.getStructField(I->getFieldIndex()),
2409 Kind, I->getLocation(), CheckedTemps))
2410 return false;
2414 if (Value.isLValue() &&
2415 CERK == CheckEvaluationResultKind::ConstantExpression) {
2416 LValue LVal;
2417 LVal.setFrom(Info.Ctx, Value);
2418 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2419 CheckedTemps);
2422 if (Value.isMemberPointer() &&
2423 CERK == CheckEvaluationResultKind::ConstantExpression)
2424 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2426 // Everything else is fine.
2427 return true;
2430 /// Check that this core constant expression value is a valid value for a
2431 /// constant expression. If not, report an appropriate diagnostic. Does not
2432 /// check that the expression is of literal type.
2433 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2434 QualType Type, const APValue &Value,
2435 ConstantExprKind Kind) {
2436 // Nothing to check for a constant expression of type 'cv void'.
2437 if (Type->isVoidType())
2438 return true;
2440 CheckedTemporaries CheckedTemps;
2441 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2442 Info, DiagLoc, Type, Value, Kind,
2443 SourceLocation(), CheckedTemps);
2446 /// Check that this evaluated value is fully-initialized and can be loaded by
2447 /// an lvalue-to-rvalue conversion.
2448 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2449 QualType Type, const APValue &Value) {
2450 CheckedTemporaries CheckedTemps;
2451 return CheckEvaluationResult(
2452 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2453 ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2456 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2457 /// "the allocated storage is deallocated within the evaluation".
2458 static bool CheckMemoryLeaks(EvalInfo &Info) {
2459 if (!Info.HeapAllocs.empty()) {
2460 // We can still fold to a constant despite a compile-time memory leak,
2461 // so long as the heap allocation isn't referenced in the result (we check
2462 // that in CheckConstantExpression).
2463 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2464 diag::note_constexpr_memory_leak)
2465 << unsigned(Info.HeapAllocs.size() - 1);
2467 return true;
2470 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2471 // A null base expression indicates a null pointer. These are always
2472 // evaluatable, and they are false unless the offset is zero.
2473 if (!Value.getLValueBase()) {
2474 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2475 Result = !Value.getLValueOffset().isZero();
2476 return true;
2479 // We have a non-null base. These are generally known to be true, but if it's
2480 // a weak declaration it can be null at runtime.
2481 Result = true;
2482 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2483 return !Decl || !Decl->isWeak();
2486 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2487 // TODO: This function should produce notes if it fails.
2488 switch (Val.getKind()) {
2489 case APValue::None:
2490 case APValue::Indeterminate:
2491 return false;
2492 case APValue::Int:
2493 Result = Val.getInt().getBoolValue();
2494 return true;
2495 case APValue::FixedPoint:
2496 Result = Val.getFixedPoint().getBoolValue();
2497 return true;
2498 case APValue::Float:
2499 Result = !Val.getFloat().isZero();
2500 return true;
2501 case APValue::ComplexInt:
2502 Result = Val.getComplexIntReal().getBoolValue() ||
2503 Val.getComplexIntImag().getBoolValue();
2504 return true;
2505 case APValue::ComplexFloat:
2506 Result = !Val.getComplexFloatReal().isZero() ||
2507 !Val.getComplexFloatImag().isZero();
2508 return true;
2509 case APValue::LValue:
2510 return EvalPointerValueAsBool(Val, Result);
2511 case APValue::MemberPointer:
2512 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2513 return false;
2515 Result = Val.getMemberPointerDecl();
2516 return true;
2517 case APValue::Vector:
2518 case APValue::Array:
2519 case APValue::Struct:
2520 case APValue::Union:
2521 case APValue::AddrLabelDiff:
2522 return false;
2525 llvm_unreachable("unknown APValue kind");
2528 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2529 EvalInfo &Info) {
2530 assert(!E->isValueDependent());
2531 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2532 APValue Val;
2533 if (!Evaluate(Val, Info, E))
2534 return false;
2535 return HandleConversionToBool(Val, Result);
2538 template<typename T>
2539 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2540 const T &SrcValue, QualType DestType) {
2541 Info.CCEDiag(E, diag::note_constexpr_overflow)
2542 << SrcValue << DestType;
2543 return Info.noteUndefinedBehavior();
2546 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2547 QualType SrcType, const APFloat &Value,
2548 QualType DestType, APSInt &Result) {
2549 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2550 // Determine whether we are converting to unsigned or signed.
2551 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2553 Result = APSInt(DestWidth, !DestSigned);
2554 bool ignored;
2555 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2556 & APFloat::opInvalidOp)
2557 return HandleOverflow(Info, E, Value, DestType);
2558 return true;
2561 /// Get rounding mode to use in evaluation of the specified expression.
2563 /// If rounding mode is unknown at compile time, still try to evaluate the
2564 /// expression. If the result is exact, it does not depend on rounding mode.
2565 /// So return "tonearest" mode instead of "dynamic".
2566 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2567 llvm::RoundingMode RM =
2568 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2569 if (RM == llvm::RoundingMode::Dynamic)
2570 RM = llvm::RoundingMode::NearestTiesToEven;
2571 return RM;
2574 /// Check if the given evaluation result is allowed for constant evaluation.
2575 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2576 APFloat::opStatus St) {
2577 // In a constant context, assume that any dynamic rounding mode or FP
2578 // exception state matches the default floating-point environment.
2579 if (Info.InConstantContext)
2580 return true;
2582 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2583 if ((St & APFloat::opInexact) &&
2584 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2585 // Inexact result means that it depends on rounding mode. If the requested
2586 // mode is dynamic, the evaluation cannot be made in compile time.
2587 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2588 return false;
2591 if ((St != APFloat::opOK) &&
2592 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2593 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2594 FPO.getAllowFEnvAccess())) {
2595 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2596 return false;
2599 if ((St & APFloat::opStatus::opInvalidOp) &&
2600 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2601 // There is no usefully definable result.
2602 Info.FFDiag(E);
2603 return false;
2606 // FIXME: if:
2607 // - evaluation triggered other FP exception, and
2608 // - exception mode is not "ignore", and
2609 // - the expression being evaluated is not a part of global variable
2610 // initializer,
2611 // the evaluation probably need to be rejected.
2612 return true;
2615 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2616 QualType SrcType, QualType DestType,
2617 APFloat &Result) {
2618 assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2619 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2620 APFloat::opStatus St;
2621 APFloat Value = Result;
2622 bool ignored;
2623 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2624 return checkFloatingPointResult(Info, E, St);
2627 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2628 QualType DestType, QualType SrcType,
2629 const APSInt &Value) {
2630 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2631 // Figure out if this is a truncate, extend or noop cast.
2632 // If the input is signed, do a sign extend, noop, or truncate.
2633 APSInt Result = Value.extOrTrunc(DestWidth);
2634 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2635 if (DestType->isBooleanType())
2636 Result = Value.getBoolValue();
2637 return Result;
2640 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2641 const FPOptions FPO,
2642 QualType SrcType, const APSInt &Value,
2643 QualType DestType, APFloat &Result) {
2644 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2645 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2646 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2647 return checkFloatingPointResult(Info, E, St);
2650 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2651 APValue &Value, const FieldDecl *FD) {
2652 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2654 if (!Value.isInt()) {
2655 // Trying to store a pointer-cast-to-integer into a bitfield.
2656 // FIXME: In this case, we should provide the diagnostic for casting
2657 // a pointer to an integer.
2658 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2659 Info.FFDiag(E);
2660 return false;
2663 APSInt &Int = Value.getInt();
2664 unsigned OldBitWidth = Int.getBitWidth();
2665 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2666 if (NewBitWidth < OldBitWidth)
2667 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2668 return true;
2671 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2672 llvm::APInt &Res) {
2673 APValue SVal;
2674 if (!Evaluate(SVal, Info, E))
2675 return false;
2676 if (SVal.isInt()) {
2677 Res = SVal.getInt();
2678 return true;
2680 if (SVal.isFloat()) {
2681 Res = SVal.getFloat().bitcastToAPInt();
2682 return true;
2684 if (SVal.isVector()) {
2685 QualType VecTy = E->getType();
2686 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2687 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2688 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2689 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2690 Res = llvm::APInt::getZero(VecSize);
2691 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2692 APValue &Elt = SVal.getVectorElt(i);
2693 llvm::APInt EltAsInt;
2694 if (Elt.isInt()) {
2695 EltAsInt = Elt.getInt();
2696 } else if (Elt.isFloat()) {
2697 EltAsInt = Elt.getFloat().bitcastToAPInt();
2698 } else {
2699 // Don't try to handle vectors of anything other than int or float
2700 // (not sure if it's possible to hit this case).
2701 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2702 return false;
2704 unsigned BaseEltSize = EltAsInt.getBitWidth();
2705 if (BigEndian)
2706 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2707 else
2708 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2710 return true;
2712 // Give up if the input isn't an int, float, or vector. For example, we
2713 // reject "(v4i16)(intptr_t)&a".
2714 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2715 return false;
2718 /// Perform the given integer operation, which is known to need at most BitWidth
2719 /// bits, and check for overflow in the original type (if that type was not an
2720 /// unsigned type).
2721 template<typename Operation>
2722 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2723 const APSInt &LHS, const APSInt &RHS,
2724 unsigned BitWidth, Operation Op,
2725 APSInt &Result) {
2726 if (LHS.isUnsigned()) {
2727 Result = Op(LHS, RHS);
2728 return true;
2731 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2732 Result = Value.trunc(LHS.getBitWidth());
2733 if (Result.extend(BitWidth) != Value) {
2734 if (Info.checkingForUndefinedBehavior())
2735 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2736 diag::warn_integer_constant_overflow)
2737 << toString(Result, 10) << E->getType();
2738 return HandleOverflow(Info, E, Value, E->getType());
2740 return true;
2743 /// Perform the given binary integer operation.
2744 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2745 BinaryOperatorKind Opcode, APSInt RHS,
2746 APSInt &Result) {
2747 bool HandleOverflowResult = true;
2748 switch (Opcode) {
2749 default:
2750 Info.FFDiag(E);
2751 return false;
2752 case BO_Mul:
2753 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2754 std::multiplies<APSInt>(), Result);
2755 case BO_Add:
2756 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2757 std::plus<APSInt>(), Result);
2758 case BO_Sub:
2759 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2760 std::minus<APSInt>(), Result);
2761 case BO_And: Result = LHS & RHS; return true;
2762 case BO_Xor: Result = LHS ^ RHS; return true;
2763 case BO_Or: Result = LHS | RHS; return true;
2764 case BO_Div:
2765 case BO_Rem:
2766 if (RHS == 0) {
2767 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2768 return false;
2770 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2771 // this operation and gives the two's complement result.
2772 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2773 LHS.isMinSignedValue())
2774 HandleOverflowResult = HandleOverflow(
2775 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2776 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2777 return HandleOverflowResult;
2778 case BO_Shl: {
2779 if (Info.getLangOpts().OpenCL)
2780 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2781 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2782 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2783 RHS.isUnsigned());
2784 else if (RHS.isSigned() && RHS.isNegative()) {
2785 // During constant-folding, a negative shift is an opposite shift. Such
2786 // a shift is not a constant expression.
2787 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2788 RHS = -RHS;
2789 goto shift_right;
2791 shift_left:
2792 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2793 // the shifted type.
2794 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2795 if (SA != RHS) {
2796 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2797 << RHS << E->getType() << LHS.getBitWidth();
2798 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2799 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2800 // operand, and must not overflow the corresponding unsigned type.
2801 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2802 // E1 x 2^E2 module 2^N.
2803 if (LHS.isNegative())
2804 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2805 else if (LHS.countLeadingZeros() < SA)
2806 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2808 Result = LHS << SA;
2809 return true;
2811 case BO_Shr: {
2812 if (Info.getLangOpts().OpenCL)
2813 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2814 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2815 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2816 RHS.isUnsigned());
2817 else if (RHS.isSigned() && RHS.isNegative()) {
2818 // During constant-folding, a negative shift is an opposite shift. Such a
2819 // shift is not a constant expression.
2820 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2821 RHS = -RHS;
2822 goto shift_left;
2824 shift_right:
2825 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2826 // shifted type.
2827 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2828 if (SA != RHS)
2829 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2830 << RHS << E->getType() << LHS.getBitWidth();
2831 Result = LHS >> SA;
2832 return true;
2835 case BO_LT: Result = LHS < RHS; return true;
2836 case BO_GT: Result = LHS > RHS; return true;
2837 case BO_LE: Result = LHS <= RHS; return true;
2838 case BO_GE: Result = LHS >= RHS; return true;
2839 case BO_EQ: Result = LHS == RHS; return true;
2840 case BO_NE: Result = LHS != RHS; return true;
2841 case BO_Cmp:
2842 llvm_unreachable("BO_Cmp should be handled elsewhere");
2846 /// Perform the given binary floating-point operation, in-place, on LHS.
2847 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2848 APFloat &LHS, BinaryOperatorKind Opcode,
2849 const APFloat &RHS) {
2850 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2851 APFloat::opStatus St;
2852 switch (Opcode) {
2853 default:
2854 Info.FFDiag(E);
2855 return false;
2856 case BO_Mul:
2857 St = LHS.multiply(RHS, RM);
2858 break;
2859 case BO_Add:
2860 St = LHS.add(RHS, RM);
2861 break;
2862 case BO_Sub:
2863 St = LHS.subtract(RHS, RM);
2864 break;
2865 case BO_Div:
2866 // [expr.mul]p4:
2867 // If the second operand of / or % is zero the behavior is undefined.
2868 if (RHS.isZero())
2869 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2870 St = LHS.divide(RHS, RM);
2871 break;
2874 // [expr.pre]p4:
2875 // If during the evaluation of an expression, the result is not
2876 // mathematically defined [...], the behavior is undefined.
2877 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2878 if (LHS.isNaN()) {
2879 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2880 return Info.noteUndefinedBehavior();
2883 return checkFloatingPointResult(Info, E, St);
2886 static bool handleLogicalOpForVector(const APInt &LHSValue,
2887 BinaryOperatorKind Opcode,
2888 const APInt &RHSValue, APInt &Result) {
2889 bool LHS = (LHSValue != 0);
2890 bool RHS = (RHSValue != 0);
2892 if (Opcode == BO_LAnd)
2893 Result = LHS && RHS;
2894 else
2895 Result = LHS || RHS;
2896 return true;
2898 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2899 BinaryOperatorKind Opcode,
2900 const APFloat &RHSValue, APInt &Result) {
2901 bool LHS = !LHSValue.isZero();
2902 bool RHS = !RHSValue.isZero();
2904 if (Opcode == BO_LAnd)
2905 Result = LHS && RHS;
2906 else
2907 Result = LHS || RHS;
2908 return true;
2911 static bool handleLogicalOpForVector(const APValue &LHSValue,
2912 BinaryOperatorKind Opcode,
2913 const APValue &RHSValue, APInt &Result) {
2914 // The result is always an int type, however operands match the first.
2915 if (LHSValue.getKind() == APValue::Int)
2916 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2917 RHSValue.getInt(), Result);
2918 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2919 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2920 RHSValue.getFloat(), Result);
2923 template <typename APTy>
2924 static bool
2925 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2926 const APTy &RHSValue, APInt &Result) {
2927 switch (Opcode) {
2928 default:
2929 llvm_unreachable("unsupported binary operator");
2930 case BO_EQ:
2931 Result = (LHSValue == RHSValue);
2932 break;
2933 case BO_NE:
2934 Result = (LHSValue != RHSValue);
2935 break;
2936 case BO_LT:
2937 Result = (LHSValue < RHSValue);
2938 break;
2939 case BO_GT:
2940 Result = (LHSValue > RHSValue);
2941 break;
2942 case BO_LE:
2943 Result = (LHSValue <= RHSValue);
2944 break;
2945 case BO_GE:
2946 Result = (LHSValue >= RHSValue);
2947 break;
2950 // The boolean operations on these vector types use an instruction that
2951 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
2952 // to -1 to make sure that we produce the correct value.
2953 Result.negate();
2955 return true;
2958 static bool handleCompareOpForVector(const APValue &LHSValue,
2959 BinaryOperatorKind Opcode,
2960 const APValue &RHSValue, APInt &Result) {
2961 // The result is always an int type, however operands match the first.
2962 if (LHSValue.getKind() == APValue::Int)
2963 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2964 RHSValue.getInt(), Result);
2965 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2966 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2967 RHSValue.getFloat(), Result);
2970 // Perform binary operations for vector types, in place on the LHS.
2971 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2972 BinaryOperatorKind Opcode,
2973 APValue &LHSValue,
2974 const APValue &RHSValue) {
2975 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2976 "Operation not supported on vector types");
2978 const auto *VT = E->getType()->castAs<VectorType>();
2979 unsigned NumElements = VT->getNumElements();
2980 QualType EltTy = VT->getElementType();
2982 // In the cases (typically C as I've observed) where we aren't evaluating
2983 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2984 // just give up.
2985 if (!LHSValue.isVector()) {
2986 assert(LHSValue.isLValue() &&
2987 "A vector result that isn't a vector OR uncalculated LValue");
2988 Info.FFDiag(E);
2989 return false;
2992 assert(LHSValue.getVectorLength() == NumElements &&
2993 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2995 SmallVector<APValue, 4> ResultElements;
2997 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2998 APValue LHSElt = LHSValue.getVectorElt(EltNum);
2999 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3001 if (EltTy->isIntegerType()) {
3002 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3003 EltTy->isUnsignedIntegerType()};
3004 bool Success = true;
3006 if (BinaryOperator::isLogicalOp(Opcode))
3007 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3008 else if (BinaryOperator::isComparisonOp(Opcode))
3009 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3010 else
3011 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3012 RHSElt.getInt(), EltResult);
3014 if (!Success) {
3015 Info.FFDiag(E);
3016 return false;
3018 ResultElements.emplace_back(EltResult);
3020 } else if (EltTy->isFloatingType()) {
3021 assert(LHSElt.getKind() == APValue::Float &&
3022 RHSElt.getKind() == APValue::Float &&
3023 "Mismatched LHS/RHS/Result Type");
3024 APFloat LHSFloat = LHSElt.getFloat();
3026 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3027 RHSElt.getFloat())) {
3028 Info.FFDiag(E);
3029 return false;
3032 ResultElements.emplace_back(LHSFloat);
3036 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3037 return true;
3040 /// Cast an lvalue referring to a base subobject to a derived class, by
3041 /// truncating the lvalue's path to the given length.
3042 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3043 const RecordDecl *TruncatedType,
3044 unsigned TruncatedElements) {
3045 SubobjectDesignator &D = Result.Designator;
3047 // Check we actually point to a derived class object.
3048 if (TruncatedElements == D.Entries.size())
3049 return true;
3050 assert(TruncatedElements >= D.MostDerivedPathLength &&
3051 "not casting to a derived class");
3052 if (!Result.checkSubobject(Info, E, CSK_Derived))
3053 return false;
3055 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3056 const RecordDecl *RD = TruncatedType;
3057 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3058 if (RD->isInvalidDecl()) return false;
3059 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3060 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3061 if (isVirtualBaseClass(D.Entries[I]))
3062 Result.Offset -= Layout.getVBaseClassOffset(Base);
3063 else
3064 Result.Offset -= Layout.getBaseClassOffset(Base);
3065 RD = Base;
3067 D.Entries.resize(TruncatedElements);
3068 return true;
3071 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3072 const CXXRecordDecl *Derived,
3073 const CXXRecordDecl *Base,
3074 const ASTRecordLayout *RL = nullptr) {
3075 if (!RL) {
3076 if (Derived->isInvalidDecl()) return false;
3077 RL = &Info.Ctx.getASTRecordLayout(Derived);
3080 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3081 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3082 return true;
3085 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3086 const CXXRecordDecl *DerivedDecl,
3087 const CXXBaseSpecifier *Base) {
3088 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3090 if (!Base->isVirtual())
3091 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3093 SubobjectDesignator &D = Obj.Designator;
3094 if (D.Invalid)
3095 return false;
3097 // Extract most-derived object and corresponding type.
3098 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3099 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3100 return false;
3102 // Find the virtual base class.
3103 if (DerivedDecl->isInvalidDecl()) return false;
3104 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3105 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3106 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3107 return true;
3110 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3111 QualType Type, LValue &Result) {
3112 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3113 PathE = E->path_end();
3114 PathI != PathE; ++PathI) {
3115 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3116 *PathI))
3117 return false;
3118 Type = (*PathI)->getType();
3120 return true;
3123 /// Cast an lvalue referring to a derived class to a known base subobject.
3124 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3125 const CXXRecordDecl *DerivedRD,
3126 const CXXRecordDecl *BaseRD) {
3127 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3128 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3129 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3130 llvm_unreachable("Class must be derived from the passed in base class!");
3132 for (CXXBasePathElement &Elem : Paths.front())
3133 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3134 return false;
3135 return true;
3138 /// Update LVal to refer to the given field, which must be a member of the type
3139 /// currently described by LVal.
3140 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3141 const FieldDecl *FD,
3142 const ASTRecordLayout *RL = nullptr) {
3143 if (!RL) {
3144 if (FD->getParent()->isInvalidDecl()) return false;
3145 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3148 unsigned I = FD->getFieldIndex();
3149 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3150 LVal.addDecl(Info, E, FD);
3151 return true;
3154 /// Update LVal to refer to the given indirect field.
3155 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3156 LValue &LVal,
3157 const IndirectFieldDecl *IFD) {
3158 for (const auto *C : IFD->chain())
3159 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3160 return false;
3161 return true;
3164 /// Get the size of the given type in char units.
3165 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3166 QualType Type, CharUnits &Size) {
3167 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3168 // extension.
3169 if (Type->isVoidType() || Type->isFunctionType()) {
3170 Size = CharUnits::One();
3171 return true;
3174 if (Type->isDependentType()) {
3175 Info.FFDiag(Loc);
3176 return false;
3179 if (!Type->isConstantSizeType()) {
3180 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3181 // FIXME: Better diagnostic.
3182 Info.FFDiag(Loc);
3183 return false;
3186 Size = Info.Ctx.getTypeSizeInChars(Type);
3187 return true;
3190 /// Update a pointer value to model pointer arithmetic.
3191 /// \param Info - Information about the ongoing evaluation.
3192 /// \param E - The expression being evaluated, for diagnostic purposes.
3193 /// \param LVal - The pointer value to be updated.
3194 /// \param EltTy - The pointee type represented by LVal.
3195 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3196 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3197 LValue &LVal, QualType EltTy,
3198 APSInt Adjustment) {
3199 CharUnits SizeOfPointee;
3200 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3201 return false;
3203 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3204 return true;
3207 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3208 LValue &LVal, QualType EltTy,
3209 int64_t Adjustment) {
3210 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3211 APSInt::get(Adjustment));
3214 /// Update an lvalue to refer to a component of a complex number.
3215 /// \param Info - Information about the ongoing evaluation.
3216 /// \param LVal - The lvalue to be updated.
3217 /// \param EltTy - The complex number's component type.
3218 /// \param Imag - False for the real component, true for the imaginary.
3219 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3220 LValue &LVal, QualType EltTy,
3221 bool Imag) {
3222 if (Imag) {
3223 CharUnits SizeOfComponent;
3224 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3225 return false;
3226 LVal.Offset += SizeOfComponent;
3228 LVal.addComplex(Info, E, EltTy, Imag);
3229 return true;
3232 /// Try to evaluate the initializer for a variable declaration.
3234 /// \param Info Information about the ongoing evaluation.
3235 /// \param E An expression to be used when printing diagnostics.
3236 /// \param VD The variable whose initializer should be obtained.
3237 /// \param Version The version of the variable within the frame.
3238 /// \param Frame The frame in which the variable was created. Must be null
3239 /// if this variable is not local to the evaluation.
3240 /// \param Result Filled in with a pointer to the value of the variable.
3241 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3242 const VarDecl *VD, CallStackFrame *Frame,
3243 unsigned Version, APValue *&Result) {
3244 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3246 // If this is a local variable, dig out its value.
3247 if (Frame) {
3248 Result = Frame->getTemporary(VD, Version);
3249 if (Result)
3250 return true;
3252 if (!isa<ParmVarDecl>(VD)) {
3253 // Assume variables referenced within a lambda's call operator that were
3254 // not declared within the call operator are captures and during checking
3255 // of a potential constant expression, assume they are unknown constant
3256 // expressions.
3257 assert(isLambdaCallOperator(Frame->Callee) &&
3258 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3259 "missing value for local variable");
3260 if (Info.checkingPotentialConstantExpression())
3261 return false;
3262 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3263 // still reachable at all?
3264 Info.FFDiag(E->getBeginLoc(),
3265 diag::note_unimplemented_constexpr_lambda_feature_ast)
3266 << "captures not currently allowed";
3267 return false;
3271 // If we're currently evaluating the initializer of this declaration, use that
3272 // in-flight value.
3273 if (Info.EvaluatingDecl == Base) {
3274 Result = Info.EvaluatingDeclValue;
3275 return true;
3278 if (isa<ParmVarDecl>(VD)) {
3279 // Assume parameters of a potential constant expression are usable in
3280 // constant expressions.
3281 if (!Info.checkingPotentialConstantExpression() ||
3282 !Info.CurrentCall->Callee ||
3283 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3284 if (Info.getLangOpts().CPlusPlus11) {
3285 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3286 << VD;
3287 NoteLValueLocation(Info, Base);
3288 } else {
3289 Info.FFDiag(E);
3292 return false;
3295 // Dig out the initializer, and use the declaration which it's attached to.
3296 // FIXME: We should eventually check whether the variable has a reachable
3297 // initializing declaration.
3298 const Expr *Init = VD->getAnyInitializer(VD);
3299 if (!Init) {
3300 // Don't diagnose during potential constant expression checking; an
3301 // initializer might be added later.
3302 if (!Info.checkingPotentialConstantExpression()) {
3303 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3304 << VD;
3305 NoteLValueLocation(Info, Base);
3307 return false;
3310 if (Init->isValueDependent()) {
3311 // The DeclRefExpr is not value-dependent, but the variable it refers to
3312 // has a value-dependent initializer. This should only happen in
3313 // constant-folding cases, where the variable is not actually of a suitable
3314 // type for use in a constant expression (otherwise the DeclRefExpr would
3315 // have been value-dependent too), so diagnose that.
3316 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3317 if (!Info.checkingPotentialConstantExpression()) {
3318 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3319 ? diag::note_constexpr_ltor_non_constexpr
3320 : diag::note_constexpr_ltor_non_integral, 1)
3321 << VD << VD->getType();
3322 NoteLValueLocation(Info, Base);
3324 return false;
3327 // Check that we can fold the initializer. In C++, we will have already done
3328 // this in the cases where it matters for conformance.
3329 if (!VD->evaluateValue()) {
3330 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3331 NoteLValueLocation(Info, Base);
3332 return false;
3335 // Check that the variable is actually usable in constant expressions. For a
3336 // const integral variable or a reference, we might have a non-constant
3337 // initializer that we can nonetheless evaluate the initializer for. Such
3338 // variables are not usable in constant expressions. In C++98, the
3339 // initializer also syntactically needs to be an ICE.
3341 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3342 // expressions here; doing so would regress diagnostics for things like
3343 // reading from a volatile constexpr variable.
3344 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3345 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3346 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3347 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3348 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3349 NoteLValueLocation(Info, Base);
3352 // Never use the initializer of a weak variable, not even for constant
3353 // folding. We can't be sure that this is the definition that will be used.
3354 if (VD->isWeak()) {
3355 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3356 NoteLValueLocation(Info, Base);
3357 return false;
3360 Result = VD->getEvaluatedValue();
3361 return true;
3364 /// Get the base index of the given base class within an APValue representing
3365 /// the given derived class.
3366 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3367 const CXXRecordDecl *Base) {
3368 Base = Base->getCanonicalDecl();
3369 unsigned Index = 0;
3370 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3371 E = Derived->bases_end(); I != E; ++I, ++Index) {
3372 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3373 return Index;
3376 llvm_unreachable("base class missing from derived class's bases list");
3379 /// Extract the value of a character from a string literal.
3380 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3381 uint64_t Index) {
3382 assert(!isa<SourceLocExpr>(Lit) &&
3383 "SourceLocExpr should have already been converted to a StringLiteral");
3385 // FIXME: Support MakeStringConstant
3386 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3387 std::string Str;
3388 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3389 assert(Index <= Str.size() && "Index too large");
3390 return APSInt::getUnsigned(Str.c_str()[Index]);
3393 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3394 Lit = PE->getFunctionName();
3395 const StringLiteral *S = cast<StringLiteral>(Lit);
3396 const ConstantArrayType *CAT =
3397 Info.Ctx.getAsConstantArrayType(S->getType());
3398 assert(CAT && "string literal isn't an array");
3399 QualType CharType = CAT->getElementType();
3400 assert(CharType->isIntegerType() && "unexpected character type");
3402 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3403 CharType->isUnsignedIntegerType());
3404 if (Index < S->getLength())
3405 Value = S->getCodeUnit(Index);
3406 return Value;
3409 // Expand a string literal into an array of characters.
3411 // FIXME: This is inefficient; we should probably introduce something similar
3412 // to the LLVM ConstantDataArray to make this cheaper.
3413 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3414 APValue &Result,
3415 QualType AllocType = QualType()) {
3416 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3417 AllocType.isNull() ? S->getType() : AllocType);
3418 assert(CAT && "string literal isn't an array");
3419 QualType CharType = CAT->getElementType();
3420 assert(CharType->isIntegerType() && "unexpected character type");
3422 unsigned Elts = CAT->getSize().getZExtValue();
3423 Result = APValue(APValue::UninitArray(),
3424 std::min(S->getLength(), Elts), Elts);
3425 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3426 CharType->isUnsignedIntegerType());
3427 if (Result.hasArrayFiller())
3428 Result.getArrayFiller() = APValue(Value);
3429 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3430 Value = S->getCodeUnit(I);
3431 Result.getArrayInitializedElt(I) = APValue(Value);
3435 // Expand an array so that it has more than Index filled elements.
3436 static void expandArray(APValue &Array, unsigned Index) {
3437 unsigned Size = Array.getArraySize();
3438 assert(Index < Size);
3440 // Always at least double the number of elements for which we store a value.
3441 unsigned OldElts = Array.getArrayInitializedElts();
3442 unsigned NewElts = std::max(Index+1, OldElts * 2);
3443 NewElts = std::min(Size, std::max(NewElts, 8u));
3445 // Copy the data across.
3446 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3447 for (unsigned I = 0; I != OldElts; ++I)
3448 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3449 for (unsigned I = OldElts; I != NewElts; ++I)
3450 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3451 if (NewValue.hasArrayFiller())
3452 NewValue.getArrayFiller() = Array.getArrayFiller();
3453 Array.swap(NewValue);
3456 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3457 /// conversion. If it's of class type, we may assume that the copy operation
3458 /// is trivial. Note that this is never true for a union type with fields
3459 /// (because the copy always "reads" the active member) and always true for
3460 /// a non-class type.
3461 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3462 static bool isReadByLvalueToRvalueConversion(QualType T) {
3463 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3464 return !RD || isReadByLvalueToRvalueConversion(RD);
3466 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3467 // FIXME: A trivial copy of a union copies the object representation, even if
3468 // the union is empty.
3469 if (RD->isUnion())
3470 return !RD->field_empty();
3471 if (RD->isEmpty())
3472 return false;
3474 for (auto *Field : RD->fields())
3475 if (!Field->isUnnamedBitfield() &&
3476 isReadByLvalueToRvalueConversion(Field->getType()))
3477 return true;
3479 for (auto &BaseSpec : RD->bases())
3480 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3481 return true;
3483 return false;
3486 /// Diagnose an attempt to read from any unreadable field within the specified
3487 /// type, which might be a class type.
3488 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3489 QualType T) {
3490 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3491 if (!RD)
3492 return false;
3494 if (!RD->hasMutableFields())
3495 return false;
3497 for (auto *Field : RD->fields()) {
3498 // If we're actually going to read this field in some way, then it can't
3499 // be mutable. If we're in a union, then assigning to a mutable field
3500 // (even an empty one) can change the active member, so that's not OK.
3501 // FIXME: Add core issue number for the union case.
3502 if (Field->isMutable() &&
3503 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3504 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3505 Info.Note(Field->getLocation(), diag::note_declared_at);
3506 return true;
3509 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3510 return true;
3513 for (auto &BaseSpec : RD->bases())
3514 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3515 return true;
3517 // All mutable fields were empty, and thus not actually read.
3518 return false;
3521 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3522 APValue::LValueBase Base,
3523 bool MutableSubobject = false) {
3524 // A temporary or transient heap allocation we created.
3525 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3526 return true;
3528 switch (Info.IsEvaluatingDecl) {
3529 case EvalInfo::EvaluatingDeclKind::None:
3530 return false;
3532 case EvalInfo::EvaluatingDeclKind::Ctor:
3533 // The variable whose initializer we're evaluating.
3534 if (Info.EvaluatingDecl == Base)
3535 return true;
3537 // A temporary lifetime-extended by the variable whose initializer we're
3538 // evaluating.
3539 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3540 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3541 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3542 return false;
3544 case EvalInfo::EvaluatingDeclKind::Dtor:
3545 // C++2a [expr.const]p6:
3546 // [during constant destruction] the lifetime of a and its non-mutable
3547 // subobjects (but not its mutable subobjects) [are] considered to start
3548 // within e.
3549 if (MutableSubobject || Base != Info.EvaluatingDecl)
3550 return false;
3551 // FIXME: We can meaningfully extend this to cover non-const objects, but
3552 // we will need special handling: we should be able to access only
3553 // subobjects of such objects that are themselves declared const.
3554 QualType T = getType(Base);
3555 return T.isConstQualified() || T->isReferenceType();
3558 llvm_unreachable("unknown evaluating decl kind");
3561 namespace {
3562 /// A handle to a complete object (an object that is not a subobject of
3563 /// another object).
3564 struct CompleteObject {
3565 /// The identity of the object.
3566 APValue::LValueBase Base;
3567 /// The value of the complete object.
3568 APValue *Value;
3569 /// The type of the complete object.
3570 QualType Type;
3572 CompleteObject() : Value(nullptr) {}
3573 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3574 : Base(Base), Value(Value), Type(Type) {}
3576 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3577 // If this isn't a "real" access (eg, if it's just accessing the type
3578 // info), allow it. We assume the type doesn't change dynamically for
3579 // subobjects of constexpr objects (even though we'd hit UB here if it
3580 // did). FIXME: Is this right?
3581 if (!isAnyAccess(AK))
3582 return true;
3584 // In C++14 onwards, it is permitted to read a mutable member whose
3585 // lifetime began within the evaluation.
3586 // FIXME: Should we also allow this in C++11?
3587 if (!Info.getLangOpts().CPlusPlus14)
3588 return false;
3589 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3592 explicit operator bool() const { return !Type.isNull(); }
3594 } // end anonymous namespace
3596 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3597 bool IsMutable = false) {
3598 // C++ [basic.type.qualifier]p1:
3599 // - A const object is an object of type const T or a non-mutable subobject
3600 // of a const object.
3601 if (ObjType.isConstQualified() && !IsMutable)
3602 SubobjType.addConst();
3603 // - A volatile object is an object of type const T or a subobject of a
3604 // volatile object.
3605 if (ObjType.isVolatileQualified())
3606 SubobjType.addVolatile();
3607 return SubobjType;
3610 /// Find the designated sub-object of an rvalue.
3611 template<typename SubobjectHandler>
3612 typename SubobjectHandler::result_type
3613 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3614 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3615 if (Sub.Invalid)
3616 // A diagnostic will have already been produced.
3617 return handler.failed();
3618 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3619 if (Info.getLangOpts().CPlusPlus11)
3620 Info.FFDiag(E, Sub.isOnePastTheEnd()
3621 ? diag::note_constexpr_access_past_end
3622 : diag::note_constexpr_access_unsized_array)
3623 << handler.AccessKind;
3624 else
3625 Info.FFDiag(E);
3626 return handler.failed();
3629 APValue *O = Obj.Value;
3630 QualType ObjType = Obj.Type;
3631 const FieldDecl *LastField = nullptr;
3632 const FieldDecl *VolatileField = nullptr;
3634 // Walk the designator's path to find the subobject.
3635 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3636 // Reading an indeterminate value is undefined, but assigning over one is OK.
3637 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3638 (O->isIndeterminate() &&
3639 !isValidIndeterminateAccess(handler.AccessKind))) {
3640 if (!Info.checkingPotentialConstantExpression())
3641 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3642 << handler.AccessKind << O->isIndeterminate();
3643 return handler.failed();
3646 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3647 // const and volatile semantics are not applied on an object under
3648 // {con,de}struction.
3649 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3650 ObjType->isRecordType() &&
3651 Info.isEvaluatingCtorDtor(
3652 Obj.Base,
3653 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3654 ConstructionPhase::None) {
3655 ObjType = Info.Ctx.getCanonicalType(ObjType);
3656 ObjType.removeLocalConst();
3657 ObjType.removeLocalVolatile();
3660 // If this is our last pass, check that the final object type is OK.
3661 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3662 // Accesses to volatile objects are prohibited.
3663 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3664 if (Info.getLangOpts().CPlusPlus) {
3665 int DiagKind;
3666 SourceLocation Loc;
3667 const NamedDecl *Decl = nullptr;
3668 if (VolatileField) {
3669 DiagKind = 2;
3670 Loc = VolatileField->getLocation();
3671 Decl = VolatileField;
3672 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3673 DiagKind = 1;
3674 Loc = VD->getLocation();
3675 Decl = VD;
3676 } else {
3677 DiagKind = 0;
3678 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3679 Loc = E->getExprLoc();
3681 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3682 << handler.AccessKind << DiagKind << Decl;
3683 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3684 } else {
3685 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3687 return handler.failed();
3690 // If we are reading an object of class type, there may still be more
3691 // things we need to check: if there are any mutable subobjects, we
3692 // cannot perform this read. (This only happens when performing a trivial
3693 // copy or assignment.)
3694 if (ObjType->isRecordType() &&
3695 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3696 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3697 return handler.failed();
3700 if (I == N) {
3701 if (!handler.found(*O, ObjType))
3702 return false;
3704 // If we modified a bit-field, truncate it to the right width.
3705 if (isModification(handler.AccessKind) &&
3706 LastField && LastField->isBitField() &&
3707 !truncateBitfieldValue(Info, E, *O, LastField))
3708 return false;
3710 return true;
3713 LastField = nullptr;
3714 if (ObjType->isArrayType()) {
3715 // Next subobject is an array element.
3716 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3717 assert(CAT && "vla in literal type?");
3718 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3719 if (CAT->getSize().ule(Index)) {
3720 // Note, it should not be possible to form a pointer with a valid
3721 // designator which points more than one past the end of the array.
3722 if (Info.getLangOpts().CPlusPlus11)
3723 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3724 << handler.AccessKind;
3725 else
3726 Info.FFDiag(E);
3727 return handler.failed();
3730 ObjType = CAT->getElementType();
3732 if (O->getArrayInitializedElts() > Index)
3733 O = &O->getArrayInitializedElt(Index);
3734 else if (!isRead(handler.AccessKind)) {
3735 expandArray(*O, Index);
3736 O = &O->getArrayInitializedElt(Index);
3737 } else
3738 O = &O->getArrayFiller();
3739 } else if (ObjType->isAnyComplexType()) {
3740 // Next subobject is a complex number.
3741 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3742 if (Index > 1) {
3743 if (Info.getLangOpts().CPlusPlus11)
3744 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3745 << handler.AccessKind;
3746 else
3747 Info.FFDiag(E);
3748 return handler.failed();
3751 ObjType = getSubobjectType(
3752 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3754 assert(I == N - 1 && "extracting subobject of scalar?");
3755 if (O->isComplexInt()) {
3756 return handler.found(Index ? O->getComplexIntImag()
3757 : O->getComplexIntReal(), ObjType);
3758 } else {
3759 assert(O->isComplexFloat());
3760 return handler.found(Index ? O->getComplexFloatImag()
3761 : O->getComplexFloatReal(), ObjType);
3763 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3764 if (Field->isMutable() &&
3765 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3766 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3767 << handler.AccessKind << Field;
3768 Info.Note(Field->getLocation(), diag::note_declared_at);
3769 return handler.failed();
3772 // Next subobject is a class, struct or union field.
3773 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3774 if (RD->isUnion()) {
3775 const FieldDecl *UnionField = O->getUnionField();
3776 if (!UnionField ||
3777 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3778 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3779 // Placement new onto an inactive union member makes it active.
3780 O->setUnion(Field, APValue());
3781 } else {
3782 // FIXME: If O->getUnionValue() is absent, report that there's no
3783 // active union member rather than reporting the prior active union
3784 // member. We'll need to fix nullptr_t to not use APValue() as its
3785 // representation first.
3786 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3787 << handler.AccessKind << Field << !UnionField << UnionField;
3788 return handler.failed();
3791 O = &O->getUnionValue();
3792 } else
3793 O = &O->getStructField(Field->getFieldIndex());
3795 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3796 LastField = Field;
3797 if (Field->getType().isVolatileQualified())
3798 VolatileField = Field;
3799 } else {
3800 // Next subobject is a base class.
3801 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3802 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3803 O = &O->getStructBase(getBaseIndex(Derived, Base));
3805 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3810 namespace {
3811 struct ExtractSubobjectHandler {
3812 EvalInfo &Info;
3813 const Expr *E;
3814 APValue &Result;
3815 const AccessKinds AccessKind;
3817 typedef bool result_type;
3818 bool failed() { return false; }
3819 bool found(APValue &Subobj, QualType SubobjType) {
3820 Result = Subobj;
3821 if (AccessKind == AK_ReadObjectRepresentation)
3822 return true;
3823 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3825 bool found(APSInt &Value, QualType SubobjType) {
3826 Result = APValue(Value);
3827 return true;
3829 bool found(APFloat &Value, QualType SubobjType) {
3830 Result = APValue(Value);
3831 return true;
3834 } // end anonymous namespace
3836 /// Extract the designated sub-object of an rvalue.
3837 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3838 const CompleteObject &Obj,
3839 const SubobjectDesignator &Sub, APValue &Result,
3840 AccessKinds AK = AK_Read) {
3841 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3842 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3843 return findSubobject(Info, E, Obj, Sub, Handler);
3846 namespace {
3847 struct ModifySubobjectHandler {
3848 EvalInfo &Info;
3849 APValue &NewVal;
3850 const Expr *E;
3852 typedef bool result_type;
3853 static const AccessKinds AccessKind = AK_Assign;
3855 bool checkConst(QualType QT) {
3856 // Assigning to a const object has undefined behavior.
3857 if (QT.isConstQualified()) {
3858 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3859 return false;
3861 return true;
3864 bool failed() { return false; }
3865 bool found(APValue &Subobj, QualType SubobjType) {
3866 if (!checkConst(SubobjType))
3867 return false;
3868 // We've been given ownership of NewVal, so just swap it in.
3869 Subobj.swap(NewVal);
3870 return true;
3872 bool found(APSInt &Value, QualType SubobjType) {
3873 if (!checkConst(SubobjType))
3874 return false;
3875 if (!NewVal.isInt()) {
3876 // Maybe trying to write a cast pointer value into a complex?
3877 Info.FFDiag(E);
3878 return false;
3880 Value = NewVal.getInt();
3881 return true;
3883 bool found(APFloat &Value, QualType SubobjType) {
3884 if (!checkConst(SubobjType))
3885 return false;
3886 Value = NewVal.getFloat();
3887 return true;
3890 } // end anonymous namespace
3892 const AccessKinds ModifySubobjectHandler::AccessKind;
3894 /// Update the designated sub-object of an rvalue to the given value.
3895 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3896 const CompleteObject &Obj,
3897 const SubobjectDesignator &Sub,
3898 APValue &NewVal) {
3899 ModifySubobjectHandler Handler = { Info, NewVal, E };
3900 return findSubobject(Info, E, Obj, Sub, Handler);
3903 /// Find the position where two subobject designators diverge, or equivalently
3904 /// the length of the common initial subsequence.
3905 static unsigned FindDesignatorMismatch(QualType ObjType,
3906 const SubobjectDesignator &A,
3907 const SubobjectDesignator &B,
3908 bool &WasArrayIndex) {
3909 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3910 for (/**/; I != N; ++I) {
3911 if (!ObjType.isNull() &&
3912 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3913 // Next subobject is an array element.
3914 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3915 WasArrayIndex = true;
3916 return I;
3918 if (ObjType->isAnyComplexType())
3919 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3920 else
3921 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3922 } else {
3923 if (A.Entries[I].getAsBaseOrMember() !=
3924 B.Entries[I].getAsBaseOrMember()) {
3925 WasArrayIndex = false;
3926 return I;
3928 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3929 // Next subobject is a field.
3930 ObjType = FD->getType();
3931 else
3932 // Next subobject is a base class.
3933 ObjType = QualType();
3936 WasArrayIndex = false;
3937 return I;
3940 /// Determine whether the given subobject designators refer to elements of the
3941 /// same array object.
3942 static bool AreElementsOfSameArray(QualType ObjType,
3943 const SubobjectDesignator &A,
3944 const SubobjectDesignator &B) {
3945 if (A.Entries.size() != B.Entries.size())
3946 return false;
3948 bool IsArray = A.MostDerivedIsArrayElement;
3949 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3950 // A is a subobject of the array element.
3951 return false;
3953 // If A (and B) designates an array element, the last entry will be the array
3954 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3955 // of length 1' case, and the entire path must match.
3956 bool WasArrayIndex;
3957 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3958 return CommonLength >= A.Entries.size() - IsArray;
3961 /// Find the complete object to which an LValue refers.
3962 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3963 AccessKinds AK, const LValue &LVal,
3964 QualType LValType) {
3965 if (LVal.InvalidBase) {
3966 Info.FFDiag(E);
3967 return CompleteObject();
3970 if (!LVal.Base) {
3971 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3972 return CompleteObject();
3975 CallStackFrame *Frame = nullptr;
3976 unsigned Depth = 0;
3977 if (LVal.getLValueCallIndex()) {
3978 std::tie(Frame, Depth) =
3979 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3980 if (!Frame) {
3981 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3982 << AK << LVal.Base.is<const ValueDecl*>();
3983 NoteLValueLocation(Info, LVal.Base);
3984 return CompleteObject();
3988 bool IsAccess = isAnyAccess(AK);
3990 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3991 // is not a constant expression (even if the object is non-volatile). We also
3992 // apply this rule to C++98, in order to conform to the expected 'volatile'
3993 // semantics.
3994 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3995 if (Info.getLangOpts().CPlusPlus)
3996 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3997 << AK << LValType;
3998 else
3999 Info.FFDiag(E);
4000 return CompleteObject();
4003 // Compute value storage location and type of base object.
4004 APValue *BaseVal = nullptr;
4005 QualType BaseType = getType(LVal.Base);
4007 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4008 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4009 // This is the object whose initializer we're evaluating, so its lifetime
4010 // started in the current evaluation.
4011 BaseVal = Info.EvaluatingDeclValue;
4012 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4013 // Allow reading from a GUID declaration.
4014 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4015 if (isModification(AK)) {
4016 // All the remaining cases do not permit modification of the object.
4017 Info.FFDiag(E, diag::note_constexpr_modify_global);
4018 return CompleteObject();
4020 APValue &V = GD->getAsAPValue();
4021 if (V.isAbsent()) {
4022 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4023 << GD->getType();
4024 return CompleteObject();
4026 return CompleteObject(LVal.Base, &V, GD->getType());
4029 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4030 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4031 if (isModification(AK)) {
4032 Info.FFDiag(E, diag::note_constexpr_modify_global);
4033 return CompleteObject();
4035 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4036 GCD->getType());
4039 // Allow reading from template parameter objects.
4040 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4041 if (isModification(AK)) {
4042 Info.FFDiag(E, diag::note_constexpr_modify_global);
4043 return CompleteObject();
4045 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4046 TPO->getType());
4049 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4050 // In C++11, constexpr, non-volatile variables initialized with constant
4051 // expressions are constant expressions too. Inside constexpr functions,
4052 // parameters are constant expressions even if they're non-const.
4053 // In C++1y, objects local to a constant expression (those with a Frame) are
4054 // both readable and writable inside constant expressions.
4055 // In C, such things can also be folded, although they are not ICEs.
4056 const VarDecl *VD = dyn_cast<VarDecl>(D);
4057 if (VD) {
4058 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4059 VD = VDef;
4061 if (!VD || VD->isInvalidDecl()) {
4062 Info.FFDiag(E);
4063 return CompleteObject();
4066 bool IsConstant = BaseType.isConstant(Info.Ctx);
4068 // Unless we're looking at a local variable or argument in a constexpr call,
4069 // the variable we're reading must be const.
4070 if (!Frame) {
4071 if (IsAccess && isa<ParmVarDecl>(VD)) {
4072 // Access of a parameter that's not associated with a frame isn't going
4073 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4074 // suitable diagnostic.
4075 } else if (Info.getLangOpts().CPlusPlus14 &&
4076 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4077 // OK, we can read and modify an object if we're in the process of
4078 // evaluating its initializer, because its lifetime began in this
4079 // evaluation.
4080 } else if (isModification(AK)) {
4081 // All the remaining cases do not permit modification of the object.
4082 Info.FFDiag(E, diag::note_constexpr_modify_global);
4083 return CompleteObject();
4084 } else if (VD->isConstexpr()) {
4085 // OK, we can read this variable.
4086 } else if (BaseType->isIntegralOrEnumerationType()) {
4087 if (!IsConstant) {
4088 if (!IsAccess)
4089 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4090 if (Info.getLangOpts().CPlusPlus) {
4091 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4092 Info.Note(VD->getLocation(), diag::note_declared_at);
4093 } else {
4094 Info.FFDiag(E);
4096 return CompleteObject();
4098 } else if (!IsAccess) {
4099 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4100 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4101 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4102 // This variable might end up being constexpr. Don't diagnose it yet.
4103 } else if (IsConstant) {
4104 // Keep evaluating to see what we can do. In particular, we support
4105 // folding of const floating-point types, in order to make static const
4106 // data members of such types (supported as an extension) more useful.
4107 if (Info.getLangOpts().CPlusPlus) {
4108 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4109 ? diag::note_constexpr_ltor_non_constexpr
4110 : diag::note_constexpr_ltor_non_integral, 1)
4111 << VD << BaseType;
4112 Info.Note(VD->getLocation(), diag::note_declared_at);
4113 } else {
4114 Info.CCEDiag(E);
4116 } else {
4117 // Never allow reading a non-const value.
4118 if (Info.getLangOpts().CPlusPlus) {
4119 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4120 ? diag::note_constexpr_ltor_non_constexpr
4121 : diag::note_constexpr_ltor_non_integral, 1)
4122 << VD << BaseType;
4123 Info.Note(VD->getLocation(), diag::note_declared_at);
4124 } else {
4125 Info.FFDiag(E);
4127 return CompleteObject();
4131 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4132 return CompleteObject();
4133 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4134 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4135 if (!Alloc) {
4136 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4137 return CompleteObject();
4139 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4140 LVal.Base.getDynamicAllocType());
4141 } else {
4142 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4144 if (!Frame) {
4145 if (const MaterializeTemporaryExpr *MTE =
4146 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4147 assert(MTE->getStorageDuration() == SD_Static &&
4148 "should have a frame for a non-global materialized temporary");
4150 // C++20 [expr.const]p4: [DR2126]
4151 // An object or reference is usable in constant expressions if it is
4152 // - a temporary object of non-volatile const-qualified literal type
4153 // whose lifetime is extended to that of a variable that is usable
4154 // in constant expressions
4156 // C++20 [expr.const]p5:
4157 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4158 // - a non-volatile glvalue that refers to an object that is usable
4159 // in constant expressions, or
4160 // - a non-volatile glvalue of literal type that refers to a
4161 // non-volatile object whose lifetime began within the evaluation
4162 // of E;
4164 // C++11 misses the 'began within the evaluation of e' check and
4165 // instead allows all temporaries, including things like:
4166 // int &&r = 1;
4167 // int x = ++r;
4168 // constexpr int k = r;
4169 // Therefore we use the C++14-onwards rules in C++11 too.
4171 // Note that temporaries whose lifetimes began while evaluating a
4172 // variable's constructor are not usable while evaluating the
4173 // corresponding destructor, not even if they're of const-qualified
4174 // types.
4175 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4176 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4177 if (!IsAccess)
4178 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4179 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4180 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4181 return CompleteObject();
4184 BaseVal = MTE->getOrCreateValue(false);
4185 assert(BaseVal && "got reference to unevaluated temporary");
4186 } else {
4187 if (!IsAccess)
4188 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4189 APValue Val;
4190 LVal.moveInto(Val);
4191 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4192 << AK
4193 << Val.getAsString(Info.Ctx,
4194 Info.Ctx.getLValueReferenceType(LValType));
4195 NoteLValueLocation(Info, LVal.Base);
4196 return CompleteObject();
4198 } else {
4199 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4200 assert(BaseVal && "missing value for temporary");
4204 // In C++14, we can't safely access any mutable state when we might be
4205 // evaluating after an unmodeled side effect. Parameters are modeled as state
4206 // in the caller, but aren't visible once the call returns, so they can be
4207 // modified in a speculatively-evaluated call.
4209 // FIXME: Not all local state is mutable. Allow local constant subobjects
4210 // to be read here (but take care with 'mutable' fields).
4211 unsigned VisibleDepth = Depth;
4212 if (llvm::isa_and_nonnull<ParmVarDecl>(
4213 LVal.Base.dyn_cast<const ValueDecl *>()))
4214 ++VisibleDepth;
4215 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4216 Info.EvalStatus.HasSideEffects) ||
4217 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4218 return CompleteObject();
4220 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4223 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4224 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4225 /// glvalue referred to by an entity of reference type.
4227 /// \param Info - Information about the ongoing evaluation.
4228 /// \param Conv - The expression for which we are performing the conversion.
4229 /// Used for diagnostics.
4230 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4231 /// case of a non-class type).
4232 /// \param LVal - The glvalue on which we are attempting to perform this action.
4233 /// \param RVal - The produced value will be placed here.
4234 /// \param WantObjectRepresentation - If true, we're looking for the object
4235 /// representation rather than the value, and in particular,
4236 /// there is no requirement that the result be fully initialized.
4237 static bool
4238 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4239 const LValue &LVal, APValue &RVal,
4240 bool WantObjectRepresentation = false) {
4241 if (LVal.Designator.Invalid)
4242 return false;
4244 // Check for special cases where there is no existing APValue to look at.
4245 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4247 AccessKinds AK =
4248 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4250 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4251 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4252 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4253 // initializer until now for such expressions. Such an expression can't be
4254 // an ICE in C, so this only matters for fold.
4255 if (Type.isVolatileQualified()) {
4256 Info.FFDiag(Conv);
4257 return false;
4260 APValue Lit;
4261 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4262 return false;
4264 // According to GCC info page:
4266 // 6.28 Compound Literals
4268 // As an optimization, G++ sometimes gives array compound literals longer
4269 // lifetimes: when the array either appears outside a function or has a
4270 // const-qualified type. If foo and its initializer had elements of type
4271 // char *const rather than char *, or if foo were a global variable, the
4272 // array would have static storage duration. But it is probably safest
4273 // just to avoid the use of array compound literals in C++ code.
4275 // Obey that rule by checking constness for converted array types.
4277 QualType CLETy = CLE->getType();
4278 if (CLETy->isArrayType() && !Type->isArrayType()) {
4279 if (!CLETy.isConstant(Info.Ctx)) {
4280 Info.FFDiag(Conv);
4281 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4282 return false;
4286 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4287 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4288 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4289 // Special-case character extraction so we don't have to construct an
4290 // APValue for the whole string.
4291 assert(LVal.Designator.Entries.size() <= 1 &&
4292 "Can only read characters from string literals");
4293 if (LVal.Designator.Entries.empty()) {
4294 // Fail for now for LValue to RValue conversion of an array.
4295 // (This shouldn't show up in C/C++, but it could be triggered by a
4296 // weird EvaluateAsRValue call from a tool.)
4297 Info.FFDiag(Conv);
4298 return false;
4300 if (LVal.Designator.isOnePastTheEnd()) {
4301 if (Info.getLangOpts().CPlusPlus11)
4302 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4303 else
4304 Info.FFDiag(Conv);
4305 return false;
4307 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4308 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4309 return true;
4313 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4314 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4317 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4318 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4319 QualType LValType, APValue &Val) {
4320 if (LVal.Designator.Invalid)
4321 return false;
4323 if (!Info.getLangOpts().CPlusPlus14) {
4324 Info.FFDiag(E);
4325 return false;
4328 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4329 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4332 namespace {
4333 struct CompoundAssignSubobjectHandler {
4334 EvalInfo &Info;
4335 const CompoundAssignOperator *E;
4336 QualType PromotedLHSType;
4337 BinaryOperatorKind Opcode;
4338 const APValue &RHS;
4340 static const AccessKinds AccessKind = AK_Assign;
4342 typedef bool result_type;
4344 bool checkConst(QualType QT) {
4345 // Assigning to a const object has undefined behavior.
4346 if (QT.isConstQualified()) {
4347 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4348 return false;
4350 return true;
4353 bool failed() { return false; }
4354 bool found(APValue &Subobj, QualType SubobjType) {
4355 switch (Subobj.getKind()) {
4356 case APValue::Int:
4357 return found(Subobj.getInt(), SubobjType);
4358 case APValue::Float:
4359 return found(Subobj.getFloat(), SubobjType);
4360 case APValue::ComplexInt:
4361 case APValue::ComplexFloat:
4362 // FIXME: Implement complex compound assignment.
4363 Info.FFDiag(E);
4364 return false;
4365 case APValue::LValue:
4366 return foundPointer(Subobj, SubobjType);
4367 case APValue::Vector:
4368 return foundVector(Subobj, SubobjType);
4369 default:
4370 // FIXME: can this happen?
4371 Info.FFDiag(E);
4372 return false;
4376 bool foundVector(APValue &Value, QualType SubobjType) {
4377 if (!checkConst(SubobjType))
4378 return false;
4380 if (!SubobjType->isVectorType()) {
4381 Info.FFDiag(E);
4382 return false;
4384 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4387 bool found(APSInt &Value, QualType SubobjType) {
4388 if (!checkConst(SubobjType))
4389 return false;
4391 if (!SubobjType->isIntegerType()) {
4392 // We don't support compound assignment on integer-cast-to-pointer
4393 // values.
4394 Info.FFDiag(E);
4395 return false;
4398 if (RHS.isInt()) {
4399 APSInt LHS =
4400 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4401 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4402 return false;
4403 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4404 return true;
4405 } else if (RHS.isFloat()) {
4406 const FPOptions FPO = E->getFPFeaturesInEffect(
4407 Info.Ctx.getLangOpts());
4408 APFloat FValue(0.0);
4409 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4410 PromotedLHSType, FValue) &&
4411 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4412 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4413 Value);
4416 Info.FFDiag(E);
4417 return false;
4419 bool found(APFloat &Value, QualType SubobjType) {
4420 return checkConst(SubobjType) &&
4421 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4422 Value) &&
4423 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4424 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4426 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4427 if (!checkConst(SubobjType))
4428 return false;
4430 QualType PointeeType;
4431 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4432 PointeeType = PT->getPointeeType();
4434 if (PointeeType.isNull() || !RHS.isInt() ||
4435 (Opcode != BO_Add && Opcode != BO_Sub)) {
4436 Info.FFDiag(E);
4437 return false;
4440 APSInt Offset = RHS.getInt();
4441 if (Opcode == BO_Sub)
4442 negateAsSigned(Offset);
4444 LValue LVal;
4445 LVal.setFrom(Info.Ctx, Subobj);
4446 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4447 return false;
4448 LVal.moveInto(Subobj);
4449 return true;
4452 } // end anonymous namespace
4454 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4456 /// Perform a compound assignment of LVal <op>= RVal.
4457 static bool handleCompoundAssignment(EvalInfo &Info,
4458 const CompoundAssignOperator *E,
4459 const LValue &LVal, QualType LValType,
4460 QualType PromotedLValType,
4461 BinaryOperatorKind Opcode,
4462 const APValue &RVal) {
4463 if (LVal.Designator.Invalid)
4464 return false;
4466 if (!Info.getLangOpts().CPlusPlus14) {
4467 Info.FFDiag(E);
4468 return false;
4471 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4472 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4473 RVal };
4474 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4477 namespace {
4478 struct IncDecSubobjectHandler {
4479 EvalInfo &Info;
4480 const UnaryOperator *E;
4481 AccessKinds AccessKind;
4482 APValue *Old;
4484 typedef bool result_type;
4486 bool checkConst(QualType QT) {
4487 // Assigning to a const object has undefined behavior.
4488 if (QT.isConstQualified()) {
4489 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4490 return false;
4492 return true;
4495 bool failed() { return false; }
4496 bool found(APValue &Subobj, QualType SubobjType) {
4497 // Stash the old value. Also clear Old, so we don't clobber it later
4498 // if we're post-incrementing a complex.
4499 if (Old) {
4500 *Old = Subobj;
4501 Old = nullptr;
4504 switch (Subobj.getKind()) {
4505 case APValue::Int:
4506 return found(Subobj.getInt(), SubobjType);
4507 case APValue::Float:
4508 return found(Subobj.getFloat(), SubobjType);
4509 case APValue::ComplexInt:
4510 return found(Subobj.getComplexIntReal(),
4511 SubobjType->castAs<ComplexType>()->getElementType()
4512 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4513 case APValue::ComplexFloat:
4514 return found(Subobj.getComplexFloatReal(),
4515 SubobjType->castAs<ComplexType>()->getElementType()
4516 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4517 case APValue::LValue:
4518 return foundPointer(Subobj, SubobjType);
4519 default:
4520 // FIXME: can this happen?
4521 Info.FFDiag(E);
4522 return false;
4525 bool found(APSInt &Value, QualType SubobjType) {
4526 if (!checkConst(SubobjType))
4527 return false;
4529 if (!SubobjType->isIntegerType()) {
4530 // We don't support increment / decrement on integer-cast-to-pointer
4531 // values.
4532 Info.FFDiag(E);
4533 return false;
4536 if (Old) *Old = APValue(Value);
4538 // bool arithmetic promotes to int, and the conversion back to bool
4539 // doesn't reduce mod 2^n, so special-case it.
4540 if (SubobjType->isBooleanType()) {
4541 if (AccessKind == AK_Increment)
4542 Value = 1;
4543 else
4544 Value = !Value;
4545 return true;
4548 bool WasNegative = Value.isNegative();
4549 if (AccessKind == AK_Increment) {
4550 ++Value;
4552 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4553 APSInt ActualValue(Value, /*IsUnsigned*/true);
4554 return HandleOverflow(Info, E, ActualValue, SubobjType);
4556 } else {
4557 --Value;
4559 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4560 unsigned BitWidth = Value.getBitWidth();
4561 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4562 ActualValue.setBit(BitWidth);
4563 return HandleOverflow(Info, E, ActualValue, SubobjType);
4566 return true;
4568 bool found(APFloat &Value, QualType SubobjType) {
4569 if (!checkConst(SubobjType))
4570 return false;
4572 if (Old) *Old = APValue(Value);
4574 APFloat One(Value.getSemantics(), 1);
4575 if (AccessKind == AK_Increment)
4576 Value.add(One, APFloat::rmNearestTiesToEven);
4577 else
4578 Value.subtract(One, APFloat::rmNearestTiesToEven);
4579 return true;
4581 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4582 if (!checkConst(SubobjType))
4583 return false;
4585 QualType PointeeType;
4586 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4587 PointeeType = PT->getPointeeType();
4588 else {
4589 Info.FFDiag(E);
4590 return false;
4593 LValue LVal;
4594 LVal.setFrom(Info.Ctx, Subobj);
4595 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4596 AccessKind == AK_Increment ? 1 : -1))
4597 return false;
4598 LVal.moveInto(Subobj);
4599 return true;
4602 } // end anonymous namespace
4604 /// Perform an increment or decrement on LVal.
4605 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4606 QualType LValType, bool IsIncrement, APValue *Old) {
4607 if (LVal.Designator.Invalid)
4608 return false;
4610 if (!Info.getLangOpts().CPlusPlus14) {
4611 Info.FFDiag(E);
4612 return false;
4615 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4616 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4617 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4618 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4621 /// Build an lvalue for the object argument of a member function call.
4622 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4623 LValue &This) {
4624 if (Object->getType()->isPointerType() && Object->isPRValue())
4625 return EvaluatePointer(Object, This, Info);
4627 if (Object->isGLValue())
4628 return EvaluateLValue(Object, This, Info);
4630 if (Object->getType()->isLiteralType(Info.Ctx))
4631 return EvaluateTemporary(Object, This, Info);
4633 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4634 return false;
4637 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4638 /// lvalue referring to the result.
4640 /// \param Info - Information about the ongoing evaluation.
4641 /// \param LV - An lvalue referring to the base of the member pointer.
4642 /// \param RHS - The member pointer expression.
4643 /// \param IncludeMember - Specifies whether the member itself is included in
4644 /// the resulting LValue subobject designator. This is not possible when
4645 /// creating a bound member function.
4646 /// \return The field or method declaration to which the member pointer refers,
4647 /// or 0 if evaluation fails.
4648 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4649 QualType LVType,
4650 LValue &LV,
4651 const Expr *RHS,
4652 bool IncludeMember = true) {
4653 MemberPtr MemPtr;
4654 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4655 return nullptr;
4657 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4658 // member value, the behavior is undefined.
4659 if (!MemPtr.getDecl()) {
4660 // FIXME: Specific diagnostic.
4661 Info.FFDiag(RHS);
4662 return nullptr;
4665 if (MemPtr.isDerivedMember()) {
4666 // This is a member of some derived class. Truncate LV appropriately.
4667 // The end of the derived-to-base path for the base object must match the
4668 // derived-to-base path for the member pointer.
4669 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4670 LV.Designator.Entries.size()) {
4671 Info.FFDiag(RHS);
4672 return nullptr;
4674 unsigned PathLengthToMember =
4675 LV.Designator.Entries.size() - MemPtr.Path.size();
4676 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4677 const CXXRecordDecl *LVDecl = getAsBaseClass(
4678 LV.Designator.Entries[PathLengthToMember + I]);
4679 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4680 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4681 Info.FFDiag(RHS);
4682 return nullptr;
4686 // Truncate the lvalue to the appropriate derived class.
4687 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4688 PathLengthToMember))
4689 return nullptr;
4690 } else if (!MemPtr.Path.empty()) {
4691 // Extend the LValue path with the member pointer's path.
4692 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4693 MemPtr.Path.size() + IncludeMember);
4695 // Walk down to the appropriate base class.
4696 if (const PointerType *PT = LVType->getAs<PointerType>())
4697 LVType = PT->getPointeeType();
4698 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4699 assert(RD && "member pointer access on non-class-type expression");
4700 // The first class in the path is that of the lvalue.
4701 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4702 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4703 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4704 return nullptr;
4705 RD = Base;
4707 // Finally cast to the class containing the member.
4708 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4709 MemPtr.getContainingRecord()))
4710 return nullptr;
4713 // Add the member. Note that we cannot build bound member functions here.
4714 if (IncludeMember) {
4715 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4716 if (!HandleLValueMember(Info, RHS, LV, FD))
4717 return nullptr;
4718 } else if (const IndirectFieldDecl *IFD =
4719 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4720 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4721 return nullptr;
4722 } else {
4723 llvm_unreachable("can't construct reference to bound member function");
4727 return MemPtr.getDecl();
4730 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4731 const BinaryOperator *BO,
4732 LValue &LV,
4733 bool IncludeMember = true) {
4734 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4736 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4737 if (Info.noteFailure()) {
4738 MemberPtr MemPtr;
4739 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4741 return nullptr;
4744 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4745 BO->getRHS(), IncludeMember);
4748 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4749 /// the provided lvalue, which currently refers to the base object.
4750 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4751 LValue &Result) {
4752 SubobjectDesignator &D = Result.Designator;
4753 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4754 return false;
4756 QualType TargetQT = E->getType();
4757 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4758 TargetQT = PT->getPointeeType();
4760 // Check this cast lands within the final derived-to-base subobject path.
4761 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4762 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4763 << D.MostDerivedType << TargetQT;
4764 return false;
4767 // Check the type of the final cast. We don't need to check the path,
4768 // since a cast can only be formed if the path is unique.
4769 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4770 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4771 const CXXRecordDecl *FinalType;
4772 if (NewEntriesSize == D.MostDerivedPathLength)
4773 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4774 else
4775 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4776 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4777 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4778 << D.MostDerivedType << TargetQT;
4779 return false;
4782 // Truncate the lvalue to the appropriate derived class.
4783 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4786 /// Get the value to use for a default-initialized object of type T.
4787 /// Return false if it encounters something invalid.
4788 static bool getDefaultInitValue(QualType T, APValue &Result) {
4789 bool Success = true;
4790 if (auto *RD = T->getAsCXXRecordDecl()) {
4791 if (RD->isInvalidDecl()) {
4792 Result = APValue();
4793 return false;
4795 if (RD->isUnion()) {
4796 Result = APValue((const FieldDecl *)nullptr);
4797 return true;
4799 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4800 std::distance(RD->field_begin(), RD->field_end()));
4802 unsigned Index = 0;
4803 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4804 End = RD->bases_end();
4805 I != End; ++I, ++Index)
4806 Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4808 for (const auto *I : RD->fields()) {
4809 if (I->isUnnamedBitfield())
4810 continue;
4811 Success &= getDefaultInitValue(I->getType(),
4812 Result.getStructField(I->getFieldIndex()));
4814 return Success;
4817 if (auto *AT =
4818 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4819 Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4820 if (Result.hasArrayFiller())
4821 Success &=
4822 getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4824 return Success;
4827 Result = APValue::IndeterminateValue();
4828 return true;
4831 namespace {
4832 enum EvalStmtResult {
4833 /// Evaluation failed.
4834 ESR_Failed,
4835 /// Hit a 'return' statement.
4836 ESR_Returned,
4837 /// Evaluation succeeded.
4838 ESR_Succeeded,
4839 /// Hit a 'continue' statement.
4840 ESR_Continue,
4841 /// Hit a 'break' statement.
4842 ESR_Break,
4843 /// Still scanning for 'case' or 'default' statement.
4844 ESR_CaseNotFound
4848 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4849 if (VD->isInvalidDecl())
4850 return false;
4851 // We don't need to evaluate the initializer for a static local.
4852 if (!VD->hasLocalStorage())
4853 return true;
4855 LValue Result;
4856 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4857 ScopeKind::Block, Result);
4859 const Expr *InitE = VD->getInit();
4860 if (!InitE) {
4861 if (VD->getType()->isDependentType())
4862 return Info.noteSideEffect();
4863 return getDefaultInitValue(VD->getType(), Val);
4865 if (InitE->isValueDependent())
4866 return false;
4868 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4869 // Wipe out any partially-computed value, to allow tracking that this
4870 // evaluation failed.
4871 Val = APValue();
4872 return false;
4875 return true;
4878 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4879 bool OK = true;
4881 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4882 OK &= EvaluateVarDecl(Info, VD);
4884 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4885 for (auto *BD : DD->bindings())
4886 if (auto *VD = BD->getHoldingVar())
4887 OK &= EvaluateDecl(Info, VD);
4889 return OK;
4892 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4893 assert(E->isValueDependent());
4894 if (Info.noteSideEffect())
4895 return true;
4896 assert(E->containsErrors() && "valid value-dependent expression should never "
4897 "reach invalid code path.");
4898 return false;
4901 /// Evaluate a condition (either a variable declaration or an expression).
4902 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4903 const Expr *Cond, bool &Result) {
4904 if (Cond->isValueDependent())
4905 return false;
4906 FullExpressionRAII Scope(Info);
4907 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4908 return false;
4909 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4910 return false;
4911 return Scope.destroy();
4914 namespace {
4915 /// A location where the result (returned value) of evaluating a
4916 /// statement should be stored.
4917 struct StmtResult {
4918 /// The APValue that should be filled in with the returned value.
4919 APValue &Value;
4920 /// The location containing the result, if any (used to support RVO).
4921 const LValue *Slot;
4924 struct TempVersionRAII {
4925 CallStackFrame &Frame;
4927 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4928 Frame.pushTempVersion();
4931 ~TempVersionRAII() {
4932 Frame.popTempVersion();
4938 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4939 const Stmt *S,
4940 const SwitchCase *SC = nullptr);
4942 /// Evaluate the body of a loop, and translate the result as appropriate.
4943 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4944 const Stmt *Body,
4945 const SwitchCase *Case = nullptr) {
4946 BlockScopeRAII Scope(Info);
4948 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4949 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4950 ESR = ESR_Failed;
4952 switch (ESR) {
4953 case ESR_Break:
4954 return ESR_Succeeded;
4955 case ESR_Succeeded:
4956 case ESR_Continue:
4957 return ESR_Continue;
4958 case ESR_Failed:
4959 case ESR_Returned:
4960 case ESR_CaseNotFound:
4961 return ESR;
4963 llvm_unreachable("Invalid EvalStmtResult!");
4966 /// Evaluate a switch statement.
4967 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4968 const SwitchStmt *SS) {
4969 BlockScopeRAII Scope(Info);
4971 // Evaluate the switch condition.
4972 APSInt Value;
4974 if (const Stmt *Init = SS->getInit()) {
4975 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4976 if (ESR != ESR_Succeeded) {
4977 if (ESR != ESR_Failed && !Scope.destroy())
4978 ESR = ESR_Failed;
4979 return ESR;
4983 FullExpressionRAII CondScope(Info);
4984 if (SS->getConditionVariable() &&
4985 !EvaluateDecl(Info, SS->getConditionVariable()))
4986 return ESR_Failed;
4987 if (SS->getCond()->isValueDependent()) {
4988 if (!EvaluateDependentExpr(SS->getCond(), Info))
4989 return ESR_Failed;
4990 } else {
4991 if (!EvaluateInteger(SS->getCond(), Value, Info))
4992 return ESR_Failed;
4994 if (!CondScope.destroy())
4995 return ESR_Failed;
4998 // Find the switch case corresponding to the value of the condition.
4999 // FIXME: Cache this lookup.
5000 const SwitchCase *Found = nullptr;
5001 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5002 SC = SC->getNextSwitchCase()) {
5003 if (isa<DefaultStmt>(SC)) {
5004 Found = SC;
5005 continue;
5008 const CaseStmt *CS = cast<CaseStmt>(SC);
5009 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5010 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5011 : LHS;
5012 if (LHS <= Value && Value <= RHS) {
5013 Found = SC;
5014 break;
5018 if (!Found)
5019 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5021 // Search the switch body for the switch case and evaluate it from there.
5022 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5023 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5024 return ESR_Failed;
5026 switch (ESR) {
5027 case ESR_Break:
5028 return ESR_Succeeded;
5029 case ESR_Succeeded:
5030 case ESR_Continue:
5031 case ESR_Failed:
5032 case ESR_Returned:
5033 return ESR;
5034 case ESR_CaseNotFound:
5035 // This can only happen if the switch case is nested within a statement
5036 // expression. We have no intention of supporting that.
5037 Info.FFDiag(Found->getBeginLoc(),
5038 diag::note_constexpr_stmt_expr_unsupported);
5039 return ESR_Failed;
5041 llvm_unreachable("Invalid EvalStmtResult!");
5044 static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5045 // An expression E is a core constant expression unless the evaluation of E
5046 // would evaluate one of the following: [C++2b] - a control flow that passes
5047 // through a declaration of a variable with static or thread storage duration
5048 // unless that variable is usable in constant expressions.
5049 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5050 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5051 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5052 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5053 return false;
5055 return true;
5058 // Evaluate a statement.
5059 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5060 const Stmt *S, const SwitchCase *Case) {
5061 if (!Info.nextStep(S))
5062 return ESR_Failed;
5064 // If we're hunting down a 'case' or 'default' label, recurse through
5065 // substatements until we hit the label.
5066 if (Case) {
5067 switch (S->getStmtClass()) {
5068 case Stmt::CompoundStmtClass:
5069 // FIXME: Precompute which substatement of a compound statement we
5070 // would jump to, and go straight there rather than performing a
5071 // linear scan each time.
5072 case Stmt::LabelStmtClass:
5073 case Stmt::AttributedStmtClass:
5074 case Stmt::DoStmtClass:
5075 break;
5077 case Stmt::CaseStmtClass:
5078 case Stmt::DefaultStmtClass:
5079 if (Case == S)
5080 Case = nullptr;
5081 break;
5083 case Stmt::IfStmtClass: {
5084 // FIXME: Precompute which side of an 'if' we would jump to, and go
5085 // straight there rather than scanning both sides.
5086 const IfStmt *IS = cast<IfStmt>(S);
5088 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5089 // preceded by our switch label.
5090 BlockScopeRAII Scope(Info);
5092 // Step into the init statement in case it brings an (uninitialized)
5093 // variable into scope.
5094 if (const Stmt *Init = IS->getInit()) {
5095 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5096 if (ESR != ESR_CaseNotFound) {
5097 assert(ESR != ESR_Succeeded);
5098 return ESR;
5102 // Condition variable must be initialized if it exists.
5103 // FIXME: We can skip evaluating the body if there's a condition
5104 // variable, as there can't be any case labels within it.
5105 // (The same is true for 'for' statements.)
5107 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5108 if (ESR == ESR_Failed)
5109 return ESR;
5110 if (ESR != ESR_CaseNotFound)
5111 return Scope.destroy() ? ESR : ESR_Failed;
5112 if (!IS->getElse())
5113 return ESR_CaseNotFound;
5115 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5116 if (ESR == ESR_Failed)
5117 return ESR;
5118 if (ESR != ESR_CaseNotFound)
5119 return Scope.destroy() ? ESR : ESR_Failed;
5120 return ESR_CaseNotFound;
5123 case Stmt::WhileStmtClass: {
5124 EvalStmtResult ESR =
5125 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5126 if (ESR != ESR_Continue)
5127 return ESR;
5128 break;
5131 case Stmt::ForStmtClass: {
5132 const ForStmt *FS = cast<ForStmt>(S);
5133 BlockScopeRAII Scope(Info);
5135 // Step into the init statement in case it brings an (uninitialized)
5136 // variable into scope.
5137 if (const Stmt *Init = FS->getInit()) {
5138 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5139 if (ESR != ESR_CaseNotFound) {
5140 assert(ESR != ESR_Succeeded);
5141 return ESR;
5145 EvalStmtResult ESR =
5146 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5147 if (ESR != ESR_Continue)
5148 return ESR;
5149 if (const auto *Inc = FS->getInc()) {
5150 if (Inc->isValueDependent()) {
5151 if (!EvaluateDependentExpr(Inc, Info))
5152 return ESR_Failed;
5153 } else {
5154 FullExpressionRAII IncScope(Info);
5155 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5156 return ESR_Failed;
5159 break;
5162 case Stmt::DeclStmtClass: {
5163 // Start the lifetime of any uninitialized variables we encounter. They
5164 // might be used by the selected branch of the switch.
5165 const DeclStmt *DS = cast<DeclStmt>(S);
5166 for (const auto *D : DS->decls()) {
5167 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5168 if (!CheckLocalVariableDeclaration(Info, VD))
5169 return ESR_Failed;
5170 if (VD->hasLocalStorage() && !VD->getInit())
5171 if (!EvaluateVarDecl(Info, VD))
5172 return ESR_Failed;
5173 // FIXME: If the variable has initialization that can't be jumped
5174 // over, bail out of any immediately-surrounding compound-statement
5175 // too. There can't be any case labels here.
5178 return ESR_CaseNotFound;
5181 default:
5182 return ESR_CaseNotFound;
5186 switch (S->getStmtClass()) {
5187 default:
5188 if (const Expr *E = dyn_cast<Expr>(S)) {
5189 if (E->isValueDependent()) {
5190 if (!EvaluateDependentExpr(E, Info))
5191 return ESR_Failed;
5192 } else {
5193 // Don't bother evaluating beyond an expression-statement which couldn't
5194 // be evaluated.
5195 // FIXME: Do we need the FullExpressionRAII object here?
5196 // VisitExprWithCleanups should create one when necessary.
5197 FullExpressionRAII Scope(Info);
5198 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5199 return ESR_Failed;
5201 return ESR_Succeeded;
5204 Info.FFDiag(S->getBeginLoc());
5205 return ESR_Failed;
5207 case Stmt::NullStmtClass:
5208 return ESR_Succeeded;
5210 case Stmt::DeclStmtClass: {
5211 const DeclStmt *DS = cast<DeclStmt>(S);
5212 for (const auto *D : DS->decls()) {
5213 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5214 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5215 return ESR_Failed;
5216 // Each declaration initialization is its own full-expression.
5217 FullExpressionRAII Scope(Info);
5218 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5219 return ESR_Failed;
5220 if (!Scope.destroy())
5221 return ESR_Failed;
5223 return ESR_Succeeded;
5226 case Stmt::ReturnStmtClass: {
5227 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5228 FullExpressionRAII Scope(Info);
5229 if (RetExpr && RetExpr->isValueDependent()) {
5230 EvaluateDependentExpr(RetExpr, Info);
5231 // We know we returned, but we don't know what the value is.
5232 return ESR_Failed;
5234 if (RetExpr &&
5235 !(Result.Slot
5236 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5237 : Evaluate(Result.Value, Info, RetExpr)))
5238 return ESR_Failed;
5239 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5242 case Stmt::CompoundStmtClass: {
5243 BlockScopeRAII Scope(Info);
5245 const CompoundStmt *CS = cast<CompoundStmt>(S);
5246 for (const auto *BI : CS->body()) {
5247 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5248 if (ESR == ESR_Succeeded)
5249 Case = nullptr;
5250 else if (ESR != ESR_CaseNotFound) {
5251 if (ESR != ESR_Failed && !Scope.destroy())
5252 return ESR_Failed;
5253 return ESR;
5256 if (Case)
5257 return ESR_CaseNotFound;
5258 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5261 case Stmt::IfStmtClass: {
5262 const IfStmt *IS = cast<IfStmt>(S);
5264 // Evaluate the condition, as either a var decl or as an expression.
5265 BlockScopeRAII Scope(Info);
5266 if (const Stmt *Init = IS->getInit()) {
5267 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5268 if (ESR != ESR_Succeeded) {
5269 if (ESR != ESR_Failed && !Scope.destroy())
5270 return ESR_Failed;
5271 return ESR;
5274 bool Cond;
5275 if (IS->isConsteval()) {
5276 Cond = IS->isNonNegatedConsteval();
5277 // If we are not in a constant context, if consteval should not evaluate
5278 // to true.
5279 if (!Info.InConstantContext)
5280 Cond = !Cond;
5281 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5282 Cond))
5283 return ESR_Failed;
5285 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5286 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5287 if (ESR != ESR_Succeeded) {
5288 if (ESR != ESR_Failed && !Scope.destroy())
5289 return ESR_Failed;
5290 return ESR;
5293 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5296 case Stmt::WhileStmtClass: {
5297 const WhileStmt *WS = cast<WhileStmt>(S);
5298 while (true) {
5299 BlockScopeRAII Scope(Info);
5300 bool Continue;
5301 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5302 Continue))
5303 return ESR_Failed;
5304 if (!Continue)
5305 break;
5307 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5308 if (ESR != ESR_Continue) {
5309 if (ESR != ESR_Failed && !Scope.destroy())
5310 return ESR_Failed;
5311 return ESR;
5313 if (!Scope.destroy())
5314 return ESR_Failed;
5316 return ESR_Succeeded;
5319 case Stmt::DoStmtClass: {
5320 const DoStmt *DS = cast<DoStmt>(S);
5321 bool Continue;
5322 do {
5323 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5324 if (ESR != ESR_Continue)
5325 return ESR;
5326 Case = nullptr;
5328 if (DS->getCond()->isValueDependent()) {
5329 EvaluateDependentExpr(DS->getCond(), Info);
5330 // Bailout as we don't know whether to keep going or terminate the loop.
5331 return ESR_Failed;
5333 FullExpressionRAII CondScope(Info);
5334 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5335 !CondScope.destroy())
5336 return ESR_Failed;
5337 } while (Continue);
5338 return ESR_Succeeded;
5341 case Stmt::ForStmtClass: {
5342 const ForStmt *FS = cast<ForStmt>(S);
5343 BlockScopeRAII ForScope(Info);
5344 if (FS->getInit()) {
5345 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5346 if (ESR != ESR_Succeeded) {
5347 if (ESR != ESR_Failed && !ForScope.destroy())
5348 return ESR_Failed;
5349 return ESR;
5352 while (true) {
5353 BlockScopeRAII IterScope(Info);
5354 bool Continue = true;
5355 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5356 FS->getCond(), Continue))
5357 return ESR_Failed;
5358 if (!Continue)
5359 break;
5361 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5362 if (ESR != ESR_Continue) {
5363 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5364 return ESR_Failed;
5365 return ESR;
5368 if (const auto *Inc = FS->getInc()) {
5369 if (Inc->isValueDependent()) {
5370 if (!EvaluateDependentExpr(Inc, Info))
5371 return ESR_Failed;
5372 } else {
5373 FullExpressionRAII IncScope(Info);
5374 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5375 return ESR_Failed;
5379 if (!IterScope.destroy())
5380 return ESR_Failed;
5382 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5385 case Stmt::CXXForRangeStmtClass: {
5386 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5387 BlockScopeRAII Scope(Info);
5389 // Evaluate the init-statement if present.
5390 if (FS->getInit()) {
5391 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5392 if (ESR != ESR_Succeeded) {
5393 if (ESR != ESR_Failed && !Scope.destroy())
5394 return ESR_Failed;
5395 return ESR;
5399 // Initialize the __range variable.
5400 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5401 if (ESR != ESR_Succeeded) {
5402 if (ESR != ESR_Failed && !Scope.destroy())
5403 return ESR_Failed;
5404 return ESR;
5407 // In error-recovery cases it's possible to get here even if we failed to
5408 // synthesize the __begin and __end variables.
5409 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5410 return ESR_Failed;
5412 // Create the __begin and __end iterators.
5413 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5414 if (ESR != ESR_Succeeded) {
5415 if (ESR != ESR_Failed && !Scope.destroy())
5416 return ESR_Failed;
5417 return ESR;
5419 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5420 if (ESR != ESR_Succeeded) {
5421 if (ESR != ESR_Failed && !Scope.destroy())
5422 return ESR_Failed;
5423 return ESR;
5426 while (true) {
5427 // Condition: __begin != __end.
5429 if (FS->getCond()->isValueDependent()) {
5430 EvaluateDependentExpr(FS->getCond(), Info);
5431 // We don't know whether to keep going or terminate the loop.
5432 return ESR_Failed;
5434 bool Continue = true;
5435 FullExpressionRAII CondExpr(Info);
5436 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5437 return ESR_Failed;
5438 if (!Continue)
5439 break;
5442 // User's variable declaration, initialized by *__begin.
5443 BlockScopeRAII InnerScope(Info);
5444 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5445 if (ESR != ESR_Succeeded) {
5446 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5447 return ESR_Failed;
5448 return ESR;
5451 // Loop body.
5452 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5453 if (ESR != ESR_Continue) {
5454 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5455 return ESR_Failed;
5456 return ESR;
5458 if (FS->getInc()->isValueDependent()) {
5459 if (!EvaluateDependentExpr(FS->getInc(), Info))
5460 return ESR_Failed;
5461 } else {
5462 // Increment: ++__begin
5463 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5464 return ESR_Failed;
5467 if (!InnerScope.destroy())
5468 return ESR_Failed;
5471 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5474 case Stmt::SwitchStmtClass:
5475 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5477 case Stmt::ContinueStmtClass:
5478 return ESR_Continue;
5480 case Stmt::BreakStmtClass:
5481 return ESR_Break;
5483 case Stmt::LabelStmtClass:
5484 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5486 case Stmt::AttributedStmtClass:
5487 // As a general principle, C++11 attributes can be ignored without
5488 // any semantic impact.
5489 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5490 Case);
5492 case Stmt::CaseStmtClass:
5493 case Stmt::DefaultStmtClass:
5494 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5495 case Stmt::CXXTryStmtClass:
5496 // Evaluate try blocks by evaluating all sub statements.
5497 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5501 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5502 /// default constructor. If so, we'll fold it whether or not it's marked as
5503 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5504 /// so we need special handling.
5505 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5506 const CXXConstructorDecl *CD,
5507 bool IsValueInitialization) {
5508 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5509 return false;
5511 // Value-initialization does not call a trivial default constructor, so such a
5512 // call is a core constant expression whether or not the constructor is
5513 // constexpr.
5514 if (!CD->isConstexpr() && !IsValueInitialization) {
5515 if (Info.getLangOpts().CPlusPlus11) {
5516 // FIXME: If DiagDecl is an implicitly-declared special member function,
5517 // we should be much more explicit about why it's not constexpr.
5518 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5519 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5520 Info.Note(CD->getLocation(), diag::note_declared_at);
5521 } else {
5522 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5525 return true;
5528 /// CheckConstexprFunction - Check that a function can be called in a constant
5529 /// expression.
5530 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5531 const FunctionDecl *Declaration,
5532 const FunctionDecl *Definition,
5533 const Stmt *Body) {
5534 // Potential constant expressions can contain calls to declared, but not yet
5535 // defined, constexpr functions.
5536 if (Info.checkingPotentialConstantExpression() && !Definition &&
5537 Declaration->isConstexpr())
5538 return false;
5540 // Bail out if the function declaration itself is invalid. We will
5541 // have produced a relevant diagnostic while parsing it, so just
5542 // note the problematic sub-expression.
5543 if (Declaration->isInvalidDecl()) {
5544 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5545 return false;
5548 // DR1872: An instantiated virtual constexpr function can't be called in a
5549 // constant expression (prior to C++20). We can still constant-fold such a
5550 // call.
5551 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5552 cast<CXXMethodDecl>(Declaration)->isVirtual())
5553 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5555 if (Definition && Definition->isInvalidDecl()) {
5556 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5557 return false;
5560 // Can we evaluate this function call?
5561 if (Definition && Definition->isConstexpr() && Body)
5562 return true;
5564 if (Info.getLangOpts().CPlusPlus11) {
5565 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5567 // If this function is not constexpr because it is an inherited
5568 // non-constexpr constructor, diagnose that directly.
5569 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5570 if (CD && CD->isInheritingConstructor()) {
5571 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5572 if (!Inherited->isConstexpr())
5573 DiagDecl = CD = Inherited;
5576 // FIXME: If DiagDecl is an implicitly-declared special member function
5577 // or an inheriting constructor, we should be much more explicit about why
5578 // it's not constexpr.
5579 if (CD && CD->isInheritingConstructor())
5580 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5581 << CD->getInheritedConstructor().getConstructor()->getParent();
5582 else
5583 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5584 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5585 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5586 } else {
5587 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5589 return false;
5592 namespace {
5593 struct CheckDynamicTypeHandler {
5594 AccessKinds AccessKind;
5595 typedef bool result_type;
5596 bool failed() { return false; }
5597 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5598 bool found(APSInt &Value, QualType SubobjType) { return true; }
5599 bool found(APFloat &Value, QualType SubobjType) { return true; }
5601 } // end anonymous namespace
5603 /// Check that we can access the notional vptr of an object / determine its
5604 /// dynamic type.
5605 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5606 AccessKinds AK, bool Polymorphic) {
5607 if (This.Designator.Invalid)
5608 return false;
5610 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5612 if (!Obj)
5613 return false;
5615 if (!Obj.Value) {
5616 // The object is not usable in constant expressions, so we can't inspect
5617 // its value to see if it's in-lifetime or what the active union members
5618 // are. We can still check for a one-past-the-end lvalue.
5619 if (This.Designator.isOnePastTheEnd() ||
5620 This.Designator.isMostDerivedAnUnsizedArray()) {
5621 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5622 ? diag::note_constexpr_access_past_end
5623 : diag::note_constexpr_access_unsized_array)
5624 << AK;
5625 return false;
5626 } else if (Polymorphic) {
5627 // Conservatively refuse to perform a polymorphic operation if we would
5628 // not be able to read a notional 'vptr' value.
5629 APValue Val;
5630 This.moveInto(Val);
5631 QualType StarThisType =
5632 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5633 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5634 << AK << Val.getAsString(Info.Ctx, StarThisType);
5635 return false;
5637 return true;
5640 CheckDynamicTypeHandler Handler{AK};
5641 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5644 /// Check that the pointee of the 'this' pointer in a member function call is
5645 /// either within its lifetime or in its period of construction or destruction.
5646 static bool
5647 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5648 const LValue &This,
5649 const CXXMethodDecl *NamedMember) {
5650 return checkDynamicType(
5651 Info, E, This,
5652 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5655 struct DynamicType {
5656 /// The dynamic class type of the object.
5657 const CXXRecordDecl *Type;
5658 /// The corresponding path length in the lvalue.
5659 unsigned PathLength;
5662 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5663 unsigned PathLength) {
5664 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5665 Designator.Entries.size() && "invalid path length");
5666 return (PathLength == Designator.MostDerivedPathLength)
5667 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5668 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5671 /// Determine the dynamic type of an object.
5672 static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
5673 const Expr *E,
5674 LValue &This,
5675 AccessKinds AK) {
5676 // If we don't have an lvalue denoting an object of class type, there is no
5677 // meaningful dynamic type. (We consider objects of non-class type to have no
5678 // dynamic type.)
5679 if (!checkDynamicType(Info, E, This, AK, true))
5680 return std::nullopt;
5682 // Refuse to compute a dynamic type in the presence of virtual bases. This
5683 // shouldn't happen other than in constant-folding situations, since literal
5684 // types can't have virtual bases.
5686 // Note that consumers of DynamicType assume that the type has no virtual
5687 // bases, and will need modifications if this restriction is relaxed.
5688 const CXXRecordDecl *Class =
5689 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5690 if (!Class || Class->getNumVBases()) {
5691 Info.FFDiag(E);
5692 return std::nullopt;
5695 // FIXME: For very deep class hierarchies, it might be beneficial to use a
5696 // binary search here instead. But the overwhelmingly common case is that
5697 // we're not in the middle of a constructor, so it probably doesn't matter
5698 // in practice.
5699 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5700 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5701 PathLength <= Path.size(); ++PathLength) {
5702 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5703 Path.slice(0, PathLength))) {
5704 case ConstructionPhase::Bases:
5705 case ConstructionPhase::DestroyingBases:
5706 // We're constructing or destroying a base class. This is not the dynamic
5707 // type.
5708 break;
5710 case ConstructionPhase::None:
5711 case ConstructionPhase::AfterBases:
5712 case ConstructionPhase::AfterFields:
5713 case ConstructionPhase::Destroying:
5714 // We've finished constructing the base classes and not yet started
5715 // destroying them again, so this is the dynamic type.
5716 return DynamicType{getBaseClassType(This.Designator, PathLength),
5717 PathLength};
5721 // CWG issue 1517: we're constructing a base class of the object described by
5722 // 'This', so that object has not yet begun its period of construction and
5723 // any polymorphic operation on it results in undefined behavior.
5724 Info.FFDiag(E);
5725 return std::nullopt;
5728 /// Perform virtual dispatch.
5729 static const CXXMethodDecl *HandleVirtualDispatch(
5730 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5731 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5732 std::optional<DynamicType> DynType = ComputeDynamicType(
5733 Info, E, This,
5734 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5735 if (!DynType)
5736 return nullptr;
5738 // Find the final overrider. It must be declared in one of the classes on the
5739 // path from the dynamic type to the static type.
5740 // FIXME: If we ever allow literal types to have virtual base classes, that
5741 // won't be true.
5742 const CXXMethodDecl *Callee = Found;
5743 unsigned PathLength = DynType->PathLength;
5744 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5745 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5746 const CXXMethodDecl *Overrider =
5747 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5748 if (Overrider) {
5749 Callee = Overrider;
5750 break;
5754 // C++2a [class.abstract]p6:
5755 // the effect of making a virtual call to a pure virtual function [...] is
5756 // undefined
5757 if (Callee->isPure()) {
5758 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5759 Info.Note(Callee->getLocation(), diag::note_declared_at);
5760 return nullptr;
5763 // If necessary, walk the rest of the path to determine the sequence of
5764 // covariant adjustment steps to apply.
5765 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5766 Found->getReturnType())) {
5767 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5768 for (unsigned CovariantPathLength = PathLength + 1;
5769 CovariantPathLength != This.Designator.Entries.size();
5770 ++CovariantPathLength) {
5771 const CXXRecordDecl *NextClass =
5772 getBaseClassType(This.Designator, CovariantPathLength);
5773 const CXXMethodDecl *Next =
5774 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5775 if (Next && !Info.Ctx.hasSameUnqualifiedType(
5776 Next->getReturnType(), CovariantAdjustmentPath.back()))
5777 CovariantAdjustmentPath.push_back(Next->getReturnType());
5779 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5780 CovariantAdjustmentPath.back()))
5781 CovariantAdjustmentPath.push_back(Found->getReturnType());
5784 // Perform 'this' adjustment.
5785 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5786 return nullptr;
5788 return Callee;
5791 /// Perform the adjustment from a value returned by a virtual function to
5792 /// a value of the statically expected type, which may be a pointer or
5793 /// reference to a base class of the returned type.
5794 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5795 APValue &Result,
5796 ArrayRef<QualType> Path) {
5797 assert(Result.isLValue() &&
5798 "unexpected kind of APValue for covariant return");
5799 if (Result.isNullPointer())
5800 return true;
5802 LValue LVal;
5803 LVal.setFrom(Info.Ctx, Result);
5805 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5806 for (unsigned I = 1; I != Path.size(); ++I) {
5807 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5808 assert(OldClass && NewClass && "unexpected kind of covariant return");
5809 if (OldClass != NewClass &&
5810 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5811 return false;
5812 OldClass = NewClass;
5815 LVal.moveInto(Result);
5816 return true;
5819 /// Determine whether \p Base, which is known to be a direct base class of
5820 /// \p Derived, is a public base class.
5821 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5822 const CXXRecordDecl *Base) {
5823 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5824 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5825 if (BaseClass && declaresSameEntity(BaseClass, Base))
5826 return BaseSpec.getAccessSpecifier() == AS_public;
5828 llvm_unreachable("Base is not a direct base of Derived");
5831 /// Apply the given dynamic cast operation on the provided lvalue.
5833 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5834 /// to find a suitable target subobject.
5835 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5836 LValue &Ptr) {
5837 // We can't do anything with a non-symbolic pointer value.
5838 SubobjectDesignator &D = Ptr.Designator;
5839 if (D.Invalid)
5840 return false;
5842 // C++ [expr.dynamic.cast]p6:
5843 // If v is a null pointer value, the result is a null pointer value.
5844 if (Ptr.isNullPointer() && !E->isGLValue())
5845 return true;
5847 // For all the other cases, we need the pointer to point to an object within
5848 // its lifetime / period of construction / destruction, and we need to know
5849 // its dynamic type.
5850 std::optional<DynamicType> DynType =
5851 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5852 if (!DynType)
5853 return false;
5855 // C++ [expr.dynamic.cast]p7:
5856 // If T is "pointer to cv void", then the result is a pointer to the most
5857 // derived object
5858 if (E->getType()->isVoidPointerType())
5859 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5861 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5862 assert(C && "dynamic_cast target is not void pointer nor class");
5863 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5865 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5866 // C++ [expr.dynamic.cast]p9:
5867 if (!E->isGLValue()) {
5868 // The value of a failed cast to pointer type is the null pointer value
5869 // of the required result type.
5870 Ptr.setNull(Info.Ctx, E->getType());
5871 return true;
5874 // A failed cast to reference type throws [...] std::bad_cast.
5875 unsigned DiagKind;
5876 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5877 DynType->Type->isDerivedFrom(C)))
5878 DiagKind = 0;
5879 else if (!Paths || Paths->begin() == Paths->end())
5880 DiagKind = 1;
5881 else if (Paths->isAmbiguous(CQT))
5882 DiagKind = 2;
5883 else {
5884 assert(Paths->front().Access != AS_public && "why did the cast fail?");
5885 DiagKind = 3;
5887 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5888 << DiagKind << Ptr.Designator.getType(Info.Ctx)
5889 << Info.Ctx.getRecordType(DynType->Type)
5890 << E->getType().getUnqualifiedType();
5891 return false;
5894 // Runtime check, phase 1:
5895 // Walk from the base subobject towards the derived object looking for the
5896 // target type.
5897 for (int PathLength = Ptr.Designator.Entries.size();
5898 PathLength >= (int)DynType->PathLength; --PathLength) {
5899 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5900 if (declaresSameEntity(Class, C))
5901 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5902 // We can only walk across public inheritance edges.
5903 if (PathLength > (int)DynType->PathLength &&
5904 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5905 Class))
5906 return RuntimeCheckFailed(nullptr);
5909 // Runtime check, phase 2:
5910 // Search the dynamic type for an unambiguous public base of type C.
5911 CXXBasePaths Paths(/*FindAmbiguities=*/true,
5912 /*RecordPaths=*/true, /*DetectVirtual=*/false);
5913 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5914 Paths.front().Access == AS_public) {
5915 // Downcast to the dynamic type...
5916 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5917 return false;
5918 // ... then upcast to the chosen base class subobject.
5919 for (CXXBasePathElement &Elem : Paths.front())
5920 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5921 return false;
5922 return true;
5925 // Otherwise, the runtime check fails.
5926 return RuntimeCheckFailed(&Paths);
5929 namespace {
5930 struct StartLifetimeOfUnionMemberHandler {
5931 EvalInfo &Info;
5932 const Expr *LHSExpr;
5933 const FieldDecl *Field;
5934 bool DuringInit;
5935 bool Failed = false;
5936 static const AccessKinds AccessKind = AK_Assign;
5938 typedef bool result_type;
5939 bool failed() { return Failed; }
5940 bool found(APValue &Subobj, QualType SubobjType) {
5941 // We are supposed to perform no initialization but begin the lifetime of
5942 // the object. We interpret that as meaning to do what default
5943 // initialization of the object would do if all constructors involved were
5944 // trivial:
5945 // * All base, non-variant member, and array element subobjects' lifetimes
5946 // begin
5947 // * No variant members' lifetimes begin
5948 // * All scalar subobjects whose lifetimes begin have indeterminate values
5949 assert(SubobjType->isUnionType());
5950 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5951 // This union member is already active. If it's also in-lifetime, there's
5952 // nothing to do.
5953 if (Subobj.getUnionValue().hasValue())
5954 return true;
5955 } else if (DuringInit) {
5956 // We're currently in the process of initializing a different union
5957 // member. If we carried on, that initialization would attempt to
5958 // store to an inactive union member, resulting in undefined behavior.
5959 Info.FFDiag(LHSExpr,
5960 diag::note_constexpr_union_member_change_during_init);
5961 return false;
5963 APValue Result;
5964 Failed = !getDefaultInitValue(Field->getType(), Result);
5965 Subobj.setUnion(Field, Result);
5966 return true;
5968 bool found(APSInt &Value, QualType SubobjType) {
5969 llvm_unreachable("wrong value kind for union object");
5971 bool found(APFloat &Value, QualType SubobjType) {
5972 llvm_unreachable("wrong value kind for union object");
5975 } // end anonymous namespace
5977 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5979 /// Handle a builtin simple-assignment or a call to a trivial assignment
5980 /// operator whose left-hand side might involve a union member access. If it
5981 /// does, implicitly start the lifetime of any accessed union elements per
5982 /// C++20 [class.union]5.
5983 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5984 const LValue &LHS) {
5985 if (LHS.InvalidBase || LHS.Designator.Invalid)
5986 return false;
5988 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5989 // C++ [class.union]p5:
5990 // define the set S(E) of subexpressions of E as follows:
5991 unsigned PathLength = LHS.Designator.Entries.size();
5992 for (const Expr *E = LHSExpr; E != nullptr;) {
5993 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5994 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5995 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5996 // Note that we can't implicitly start the lifetime of a reference,
5997 // so we don't need to proceed any further if we reach one.
5998 if (!FD || FD->getType()->isReferenceType())
5999 break;
6001 // ... and also contains A.B if B names a union member ...
6002 if (FD->getParent()->isUnion()) {
6003 // ... of a non-class, non-array type, or of a class type with a
6004 // trivial default constructor that is not deleted, or an array of
6005 // such types.
6006 auto *RD =
6007 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6008 if (!RD || RD->hasTrivialDefaultConstructor())
6009 UnionPathLengths.push_back({PathLength - 1, FD});
6012 E = ME->getBase();
6013 --PathLength;
6014 assert(declaresSameEntity(FD,
6015 LHS.Designator.Entries[PathLength]
6016 .getAsBaseOrMember().getPointer()));
6018 // -- If E is of the form A[B] and is interpreted as a built-in array
6019 // subscripting operator, S(E) is [S(the array operand, if any)].
6020 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6021 // Step over an ArrayToPointerDecay implicit cast.
6022 auto *Base = ASE->getBase()->IgnoreImplicit();
6023 if (!Base->getType()->isArrayType())
6024 break;
6026 E = Base;
6027 --PathLength;
6029 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6030 // Step over a derived-to-base conversion.
6031 E = ICE->getSubExpr();
6032 if (ICE->getCastKind() == CK_NoOp)
6033 continue;
6034 if (ICE->getCastKind() != CK_DerivedToBase &&
6035 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6036 break;
6037 // Walk path backwards as we walk up from the base to the derived class.
6038 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6039 --PathLength;
6040 (void)Elt;
6041 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6042 LHS.Designator.Entries[PathLength]
6043 .getAsBaseOrMember().getPointer()));
6046 // -- Otherwise, S(E) is empty.
6047 } else {
6048 break;
6052 // Common case: no unions' lifetimes are started.
6053 if (UnionPathLengths.empty())
6054 return true;
6056 // if modification of X [would access an inactive union member], an object
6057 // of the type of X is implicitly created
6058 CompleteObject Obj =
6059 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6060 if (!Obj)
6061 return false;
6062 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6063 llvm::reverse(UnionPathLengths)) {
6064 // Form a designator for the union object.
6065 SubobjectDesignator D = LHS.Designator;
6066 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6068 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6069 ConstructionPhase::AfterBases;
6070 StartLifetimeOfUnionMemberHandler StartLifetime{
6071 Info, LHSExpr, LengthAndField.second, DuringInit};
6072 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6073 return false;
6076 return true;
6079 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6080 CallRef Call, EvalInfo &Info,
6081 bool NonNull = false) {
6082 LValue LV;
6083 // Create the parameter slot and register its destruction. For a vararg
6084 // argument, create a temporary.
6085 // FIXME: For calling conventions that destroy parameters in the callee,
6086 // should we consider performing destruction when the function returns
6087 // instead?
6088 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6089 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6090 ScopeKind::Call, LV);
6091 if (!EvaluateInPlace(V, Info, LV, Arg))
6092 return false;
6094 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6095 // undefined behavior, so is non-constant.
6096 if (NonNull && V.isLValue() && V.isNullPointer()) {
6097 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6098 return false;
6101 return true;
6104 /// Evaluate the arguments to a function call.
6105 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6106 EvalInfo &Info, const FunctionDecl *Callee,
6107 bool RightToLeft = false) {
6108 bool Success = true;
6109 llvm::SmallBitVector ForbiddenNullArgs;
6110 if (Callee->hasAttr<NonNullAttr>()) {
6111 ForbiddenNullArgs.resize(Args.size());
6112 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6113 if (!Attr->args_size()) {
6114 ForbiddenNullArgs.set();
6115 break;
6116 } else
6117 for (auto Idx : Attr->args()) {
6118 unsigned ASTIdx = Idx.getASTIndex();
6119 if (ASTIdx >= Args.size())
6120 continue;
6121 ForbiddenNullArgs[ASTIdx] = true;
6125 for (unsigned I = 0; I < Args.size(); I++) {
6126 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6127 const ParmVarDecl *PVD =
6128 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6129 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6130 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6131 // If we're checking for a potential constant expression, evaluate all
6132 // initializers even if some of them fail.
6133 if (!Info.noteFailure())
6134 return false;
6135 Success = false;
6138 return Success;
6141 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6142 /// constructor or assignment operator.
6143 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6144 const Expr *E, APValue &Result,
6145 bool CopyObjectRepresentation) {
6146 // Find the reference argument.
6147 CallStackFrame *Frame = Info.CurrentCall;
6148 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6149 if (!RefValue) {
6150 Info.FFDiag(E);
6151 return false;
6154 // Copy out the contents of the RHS object.
6155 LValue RefLValue;
6156 RefLValue.setFrom(Info.Ctx, *RefValue);
6157 return handleLValueToRValueConversion(
6158 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6159 CopyObjectRepresentation);
6162 /// Evaluate a function call.
6163 static bool HandleFunctionCall(SourceLocation CallLoc,
6164 const FunctionDecl *Callee, const LValue *This,
6165 ArrayRef<const Expr *> Args, CallRef Call,
6166 const Stmt *Body, EvalInfo &Info,
6167 APValue &Result, const LValue *ResultSlot) {
6168 if (!Info.CheckCallLimit(CallLoc))
6169 return false;
6171 CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6173 // For a trivial copy or move assignment, perform an APValue copy. This is
6174 // essential for unions, where the operations performed by the assignment
6175 // operator cannot be represented as statements.
6177 // Skip this for non-union classes with no fields; in that case, the defaulted
6178 // copy/move does not actually read the object.
6179 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6180 if (MD && MD->isDefaulted() &&
6181 (MD->getParent()->isUnion() ||
6182 (MD->isTrivial() &&
6183 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6184 assert(This &&
6185 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6186 APValue RHSValue;
6187 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6188 MD->getParent()->isUnion()))
6189 return false;
6190 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6191 RHSValue))
6192 return false;
6193 This->moveInto(Result);
6194 return true;
6195 } else if (MD && isLambdaCallOperator(MD)) {
6196 // We're in a lambda; determine the lambda capture field maps unless we're
6197 // just constexpr checking a lambda's call operator. constexpr checking is
6198 // done before the captures have been added to the closure object (unless
6199 // we're inferring constexpr-ness), so we don't have access to them in this
6200 // case. But since we don't need the captures to constexpr check, we can
6201 // just ignore them.
6202 if (!Info.checkingPotentialConstantExpression())
6203 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6204 Frame.LambdaThisCaptureField);
6207 StmtResult Ret = {Result, ResultSlot};
6208 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6209 if (ESR == ESR_Succeeded) {
6210 if (Callee->getReturnType()->isVoidType())
6211 return true;
6212 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6214 return ESR == ESR_Returned;
6217 /// Evaluate a constructor call.
6218 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6219 CallRef Call,
6220 const CXXConstructorDecl *Definition,
6221 EvalInfo &Info, APValue &Result) {
6222 SourceLocation CallLoc = E->getExprLoc();
6223 if (!Info.CheckCallLimit(CallLoc))
6224 return false;
6226 const CXXRecordDecl *RD = Definition->getParent();
6227 if (RD->getNumVBases()) {
6228 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6229 return false;
6232 EvalInfo::EvaluatingConstructorRAII EvalObj(
6233 Info,
6234 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6235 RD->getNumBases());
6236 CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6238 // FIXME: Creating an APValue just to hold a nonexistent return value is
6239 // wasteful.
6240 APValue RetVal;
6241 StmtResult Ret = {RetVal, nullptr};
6243 // If it's a delegating constructor, delegate.
6244 if (Definition->isDelegatingConstructor()) {
6245 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6246 if ((*I)->getInit()->isValueDependent()) {
6247 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6248 return false;
6249 } else {
6250 FullExpressionRAII InitScope(Info);
6251 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6252 !InitScope.destroy())
6253 return false;
6255 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6258 // For a trivial copy or move constructor, perform an APValue copy. This is
6259 // essential for unions (or classes with anonymous union members), where the
6260 // operations performed by the constructor cannot be represented by
6261 // ctor-initializers.
6263 // Skip this for empty non-union classes; we should not perform an
6264 // lvalue-to-rvalue conversion on them because their copy constructor does not
6265 // actually read them.
6266 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6267 (Definition->getParent()->isUnion() ||
6268 (Definition->isTrivial() &&
6269 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6270 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6271 Definition->getParent()->isUnion());
6274 // Reserve space for the struct members.
6275 if (!Result.hasValue()) {
6276 if (!RD->isUnion())
6277 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6278 std::distance(RD->field_begin(), RD->field_end()));
6279 else
6280 // A union starts with no active member.
6281 Result = APValue((const FieldDecl*)nullptr);
6284 if (RD->isInvalidDecl()) return false;
6285 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6287 // A scope for temporaries lifetime-extended by reference members.
6288 BlockScopeRAII LifetimeExtendedScope(Info);
6290 bool Success = true;
6291 unsigned BasesSeen = 0;
6292 #ifndef NDEBUG
6293 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6294 #endif
6295 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6296 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6297 // We might be initializing the same field again if this is an indirect
6298 // field initialization.
6299 if (FieldIt == RD->field_end() ||
6300 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6301 assert(Indirect && "fields out of order?");
6302 return;
6305 // Default-initialize any fields with no explicit initializer.
6306 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6307 assert(FieldIt != RD->field_end() && "missing field?");
6308 if (!FieldIt->isUnnamedBitfield())
6309 Success &= getDefaultInitValue(
6310 FieldIt->getType(),
6311 Result.getStructField(FieldIt->getFieldIndex()));
6313 ++FieldIt;
6315 for (const auto *I : Definition->inits()) {
6316 LValue Subobject = This;
6317 LValue SubobjectParent = This;
6318 APValue *Value = &Result;
6320 // Determine the subobject to initialize.
6321 FieldDecl *FD = nullptr;
6322 if (I->isBaseInitializer()) {
6323 QualType BaseType(I->getBaseClass(), 0);
6324 #ifndef NDEBUG
6325 // Non-virtual base classes are initialized in the order in the class
6326 // definition. We have already checked for virtual base classes.
6327 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6328 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6329 "base class initializers not in expected order");
6330 ++BaseIt;
6331 #endif
6332 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6333 BaseType->getAsCXXRecordDecl(), &Layout))
6334 return false;
6335 Value = &Result.getStructBase(BasesSeen++);
6336 } else if ((FD = I->getMember())) {
6337 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6338 return false;
6339 if (RD->isUnion()) {
6340 Result = APValue(FD);
6341 Value = &Result.getUnionValue();
6342 } else {
6343 SkipToField(FD, false);
6344 Value = &Result.getStructField(FD->getFieldIndex());
6346 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6347 // Walk the indirect field decl's chain to find the object to initialize,
6348 // and make sure we've initialized every step along it.
6349 auto IndirectFieldChain = IFD->chain();
6350 for (auto *C : IndirectFieldChain) {
6351 FD = cast<FieldDecl>(C);
6352 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6353 // Switch the union field if it differs. This happens if we had
6354 // preceding zero-initialization, and we're now initializing a union
6355 // subobject other than the first.
6356 // FIXME: In this case, the values of the other subobjects are
6357 // specified, since zero-initialization sets all padding bits to zero.
6358 if (!Value->hasValue() ||
6359 (Value->isUnion() && Value->getUnionField() != FD)) {
6360 if (CD->isUnion())
6361 *Value = APValue(FD);
6362 else
6363 // FIXME: This immediately starts the lifetime of all members of
6364 // an anonymous struct. It would be preferable to strictly start
6365 // member lifetime in initialization order.
6366 Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6368 // Store Subobject as its parent before updating it for the last element
6369 // in the chain.
6370 if (C == IndirectFieldChain.back())
6371 SubobjectParent = Subobject;
6372 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6373 return false;
6374 if (CD->isUnion())
6375 Value = &Value->getUnionValue();
6376 else {
6377 if (C == IndirectFieldChain.front() && !RD->isUnion())
6378 SkipToField(FD, true);
6379 Value = &Value->getStructField(FD->getFieldIndex());
6382 } else {
6383 llvm_unreachable("unknown base initializer kind");
6386 // Need to override This for implicit field initializers as in this case
6387 // This refers to innermost anonymous struct/union containing initializer,
6388 // not to currently constructed class.
6389 const Expr *Init = I->getInit();
6390 if (Init->isValueDependent()) {
6391 if (!EvaluateDependentExpr(Init, Info))
6392 return false;
6393 } else {
6394 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6395 isa<CXXDefaultInitExpr>(Init));
6396 FullExpressionRAII InitScope(Info);
6397 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6398 (FD && FD->isBitField() &&
6399 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6400 // If we're checking for a potential constant expression, evaluate all
6401 // initializers even if some of them fail.
6402 if (!Info.noteFailure())
6403 return false;
6404 Success = false;
6408 // This is the point at which the dynamic type of the object becomes this
6409 // class type.
6410 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6411 EvalObj.finishedConstructingBases();
6414 // Default-initialize any remaining fields.
6415 if (!RD->isUnion()) {
6416 for (; FieldIt != RD->field_end(); ++FieldIt) {
6417 if (!FieldIt->isUnnamedBitfield())
6418 Success &= getDefaultInitValue(
6419 FieldIt->getType(),
6420 Result.getStructField(FieldIt->getFieldIndex()));
6424 EvalObj.finishedConstructingFields();
6426 return Success &&
6427 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6428 LifetimeExtendedScope.destroy();
6431 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6432 ArrayRef<const Expr*> Args,
6433 const CXXConstructorDecl *Definition,
6434 EvalInfo &Info, APValue &Result) {
6435 CallScopeRAII CallScope(Info);
6436 CallRef Call = Info.CurrentCall->createCall(Definition);
6437 if (!EvaluateArgs(Args, Call, Info, Definition))
6438 return false;
6440 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6441 CallScope.destroy();
6444 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6445 const LValue &This, APValue &Value,
6446 QualType T) {
6447 // Objects can only be destroyed while they're within their lifetimes.
6448 // FIXME: We have no representation for whether an object of type nullptr_t
6449 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6450 // as indeterminate instead?
6451 if (Value.isAbsent() && !T->isNullPtrType()) {
6452 APValue Printable;
6453 This.moveInto(Printable);
6454 Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6455 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6456 return false;
6459 // Invent an expression for location purposes.
6460 // FIXME: We shouldn't need to do this.
6461 OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6463 // For arrays, destroy elements right-to-left.
6464 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6465 uint64_t Size = CAT->getSize().getZExtValue();
6466 QualType ElemT = CAT->getElementType();
6468 LValue ElemLV = This;
6469 ElemLV.addArray(Info, &LocE, CAT);
6470 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6471 return false;
6473 // Ensure that we have actual array elements available to destroy; the
6474 // destructors might mutate the value, so we can't run them on the array
6475 // filler.
6476 if (Size && Size > Value.getArrayInitializedElts())
6477 expandArray(Value, Value.getArraySize() - 1);
6479 for (; Size != 0; --Size) {
6480 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6481 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6482 !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6483 return false;
6486 // End the lifetime of this array now.
6487 Value = APValue();
6488 return true;
6491 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6492 if (!RD) {
6493 if (T.isDestructedType()) {
6494 Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6495 return false;
6498 Value = APValue();
6499 return true;
6502 if (RD->getNumVBases()) {
6503 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6504 return false;
6507 const CXXDestructorDecl *DD = RD->getDestructor();
6508 if (!DD && !RD->hasTrivialDestructor()) {
6509 Info.FFDiag(CallLoc);
6510 return false;
6513 if (!DD || DD->isTrivial() ||
6514 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6515 // A trivial destructor just ends the lifetime of the object. Check for
6516 // this case before checking for a body, because we might not bother
6517 // building a body for a trivial destructor. Note that it doesn't matter
6518 // whether the destructor is constexpr in this case; all trivial
6519 // destructors are constexpr.
6521 // If an anonymous union would be destroyed, some enclosing destructor must
6522 // have been explicitly defined, and the anonymous union destruction should
6523 // have no effect.
6524 Value = APValue();
6525 return true;
6528 if (!Info.CheckCallLimit(CallLoc))
6529 return false;
6531 const FunctionDecl *Definition = nullptr;
6532 const Stmt *Body = DD->getBody(Definition);
6534 if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6535 return false;
6537 CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6539 // We're now in the period of destruction of this object.
6540 unsigned BasesLeft = RD->getNumBases();
6541 EvalInfo::EvaluatingDestructorRAII EvalObj(
6542 Info,
6543 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6544 if (!EvalObj.DidInsert) {
6545 // C++2a [class.dtor]p19:
6546 // the behavior is undefined if the destructor is invoked for an object
6547 // whose lifetime has ended
6548 // (Note that formally the lifetime ends when the period of destruction
6549 // begins, even though certain uses of the object remain valid until the
6550 // period of destruction ends.)
6551 Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6552 return false;
6555 // FIXME: Creating an APValue just to hold a nonexistent return value is
6556 // wasteful.
6557 APValue RetVal;
6558 StmtResult Ret = {RetVal, nullptr};
6559 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6560 return false;
6562 // A union destructor does not implicitly destroy its members.
6563 if (RD->isUnion())
6564 return true;
6566 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6568 // We don't have a good way to iterate fields in reverse, so collect all the
6569 // fields first and then walk them backwards.
6570 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6571 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6572 if (FD->isUnnamedBitfield())
6573 continue;
6575 LValue Subobject = This;
6576 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6577 return false;
6579 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6580 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6581 FD->getType()))
6582 return false;
6585 if (BasesLeft != 0)
6586 EvalObj.startedDestroyingBases();
6588 // Destroy base classes in reverse order.
6589 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6590 --BasesLeft;
6592 QualType BaseType = Base.getType();
6593 LValue Subobject = This;
6594 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6595 BaseType->getAsCXXRecordDecl(), &Layout))
6596 return false;
6598 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6599 if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6600 BaseType))
6601 return false;
6603 assert(BasesLeft == 0 && "NumBases was wrong?");
6605 // The period of destruction ends now. The object is gone.
6606 Value = APValue();
6607 return true;
6610 namespace {
6611 struct DestroyObjectHandler {
6612 EvalInfo &Info;
6613 const Expr *E;
6614 const LValue &This;
6615 const AccessKinds AccessKind;
6617 typedef bool result_type;
6618 bool failed() { return false; }
6619 bool found(APValue &Subobj, QualType SubobjType) {
6620 return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6621 SubobjType);
6623 bool found(APSInt &Value, QualType SubobjType) {
6624 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6625 return false;
6627 bool found(APFloat &Value, QualType SubobjType) {
6628 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6629 return false;
6634 /// Perform a destructor or pseudo-destructor call on the given object, which
6635 /// might in general not be a complete object.
6636 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6637 const LValue &This, QualType ThisType) {
6638 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6639 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6640 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6643 /// Destroy and end the lifetime of the given complete object.
6644 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6645 APValue::LValueBase LVBase, APValue &Value,
6646 QualType T) {
6647 // If we've had an unmodeled side-effect, we can't rely on mutable state
6648 // (such as the object we're about to destroy) being correct.
6649 if (Info.EvalStatus.HasSideEffects)
6650 return false;
6652 LValue LV;
6653 LV.set({LVBase});
6654 return HandleDestructionImpl(Info, Loc, LV, Value, T);
6657 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6658 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6659 LValue &Result) {
6660 if (Info.checkingPotentialConstantExpression() ||
6661 Info.SpeculativeEvaluationDepth)
6662 return false;
6664 // This is permitted only within a call to std::allocator<T>::allocate.
6665 auto Caller = Info.getStdAllocatorCaller("allocate");
6666 if (!Caller) {
6667 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6668 ? diag::note_constexpr_new_untyped
6669 : diag::note_constexpr_new);
6670 return false;
6673 QualType ElemType = Caller.ElemType;
6674 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6675 Info.FFDiag(E->getExprLoc(),
6676 diag::note_constexpr_new_not_complete_object_type)
6677 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6678 return false;
6681 APSInt ByteSize;
6682 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6683 return false;
6684 bool IsNothrow = false;
6685 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6686 EvaluateIgnoredValue(Info, E->getArg(I));
6687 IsNothrow |= E->getType()->isNothrowT();
6690 CharUnits ElemSize;
6691 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6692 return false;
6693 APInt Size, Remainder;
6694 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6695 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6696 if (Remainder != 0) {
6697 // This likely indicates a bug in the implementation of 'std::allocator'.
6698 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6699 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6700 return false;
6703 if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6704 if (IsNothrow) {
6705 Result.setNull(Info.Ctx, E->getType());
6706 return true;
6709 Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6710 return false;
6713 QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6714 ArrayType::Normal, 0);
6715 APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6716 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6717 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6718 return true;
6721 static bool hasVirtualDestructor(QualType T) {
6722 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6723 if (CXXDestructorDecl *DD = RD->getDestructor())
6724 return DD->isVirtual();
6725 return false;
6728 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6729 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6730 if (CXXDestructorDecl *DD = RD->getDestructor())
6731 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6732 return nullptr;
6735 /// Check that the given object is a suitable pointer to a heap allocation that
6736 /// still exists and is of the right kind for the purpose of a deletion.
6738 /// On success, returns the heap allocation to deallocate. On failure, produces
6739 /// a diagnostic and returns std::nullopt.
6740 static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6741 const LValue &Pointer,
6742 DynAlloc::Kind DeallocKind) {
6743 auto PointerAsString = [&] {
6744 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6747 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6748 if (!DA) {
6749 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6750 << PointerAsString();
6751 if (Pointer.Base)
6752 NoteLValueLocation(Info, Pointer.Base);
6753 return std::nullopt;
6756 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6757 if (!Alloc) {
6758 Info.FFDiag(E, diag::note_constexpr_double_delete);
6759 return std::nullopt;
6762 QualType AllocType = Pointer.Base.getDynamicAllocType();
6763 if (DeallocKind != (*Alloc)->getKind()) {
6764 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6765 << DeallocKind << (*Alloc)->getKind() << AllocType;
6766 NoteLValueLocation(Info, Pointer.Base);
6767 return std::nullopt;
6770 bool Subobject = false;
6771 if (DeallocKind == DynAlloc::New) {
6772 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6773 Pointer.Designator.isOnePastTheEnd();
6774 } else {
6775 Subobject = Pointer.Designator.Entries.size() != 1 ||
6776 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6778 if (Subobject) {
6779 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6780 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6781 return std::nullopt;
6784 return Alloc;
6787 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6788 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6789 if (Info.checkingPotentialConstantExpression() ||
6790 Info.SpeculativeEvaluationDepth)
6791 return false;
6793 // This is permitted only within a call to std::allocator<T>::deallocate.
6794 if (!Info.getStdAllocatorCaller("deallocate")) {
6795 Info.FFDiag(E->getExprLoc());
6796 return true;
6799 LValue Pointer;
6800 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6801 return false;
6802 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6803 EvaluateIgnoredValue(Info, E->getArg(I));
6805 if (Pointer.Designator.Invalid)
6806 return false;
6808 // Deleting a null pointer would have no effect, but it's not permitted by
6809 // std::allocator<T>::deallocate's contract.
6810 if (Pointer.isNullPointer()) {
6811 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6812 return true;
6815 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6816 return false;
6818 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6819 return true;
6822 //===----------------------------------------------------------------------===//
6823 // Generic Evaluation
6824 //===----------------------------------------------------------------------===//
6825 namespace {
6827 class BitCastBuffer {
6828 // FIXME: We're going to need bit-level granularity when we support
6829 // bit-fields.
6830 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6831 // we don't support a host or target where that is the case. Still, we should
6832 // use a more generic type in case we ever do.
6833 SmallVector<std::optional<unsigned char>, 32> Bytes;
6835 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6836 "Need at least 8 bit unsigned char");
6838 bool TargetIsLittleEndian;
6840 public:
6841 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6842 : Bytes(Width.getQuantity()),
6843 TargetIsLittleEndian(TargetIsLittleEndian) {}
6845 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
6846 SmallVectorImpl<unsigned char> &Output) const {
6847 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6848 // If a byte of an integer is uninitialized, then the whole integer is
6849 // uninitialized.
6850 if (!Bytes[I.getQuantity()])
6851 return false;
6852 Output.push_back(*Bytes[I.getQuantity()]);
6854 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6855 std::reverse(Output.begin(), Output.end());
6856 return true;
6859 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6860 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6861 std::reverse(Input.begin(), Input.end());
6863 size_t Index = 0;
6864 for (unsigned char Byte : Input) {
6865 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6866 Bytes[Offset.getQuantity() + Index] = Byte;
6867 ++Index;
6871 size_t size() { return Bytes.size(); }
6874 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6875 /// target would represent the value at runtime.
6876 class APValueToBufferConverter {
6877 EvalInfo &Info;
6878 BitCastBuffer Buffer;
6879 const CastExpr *BCE;
6881 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6882 const CastExpr *BCE)
6883 : Info(Info),
6884 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6885 BCE(BCE) {}
6887 bool visit(const APValue &Val, QualType Ty) {
6888 return visit(Val, Ty, CharUnits::fromQuantity(0));
6891 // Write out Val with type Ty into Buffer starting at Offset.
6892 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6893 assert((size_t)Offset.getQuantity() <= Buffer.size());
6895 // As a special case, nullptr_t has an indeterminate value.
6896 if (Ty->isNullPtrType())
6897 return true;
6899 // Dig through Src to find the byte at SrcOffset.
6900 switch (Val.getKind()) {
6901 case APValue::Indeterminate:
6902 case APValue::None:
6903 return true;
6905 case APValue::Int:
6906 return visitInt(Val.getInt(), Ty, Offset);
6907 case APValue::Float:
6908 return visitFloat(Val.getFloat(), Ty, Offset);
6909 case APValue::Array:
6910 return visitArray(Val, Ty, Offset);
6911 case APValue::Struct:
6912 return visitRecord(Val, Ty, Offset);
6914 case APValue::ComplexInt:
6915 case APValue::ComplexFloat:
6916 case APValue::Vector:
6917 case APValue::FixedPoint:
6918 // FIXME: We should support these.
6920 case APValue::Union:
6921 case APValue::MemberPointer:
6922 case APValue::AddrLabelDiff: {
6923 Info.FFDiag(BCE->getBeginLoc(),
6924 diag::note_constexpr_bit_cast_unsupported_type)
6925 << Ty;
6926 return false;
6929 case APValue::LValue:
6930 llvm_unreachable("LValue subobject in bit_cast?");
6932 llvm_unreachable("Unhandled APValue::ValueKind");
6935 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6936 const RecordDecl *RD = Ty->getAsRecordDecl();
6937 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6939 // Visit the base classes.
6940 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6941 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6942 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6943 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6945 if (!visitRecord(Val.getStructBase(I), BS.getType(),
6946 Layout.getBaseClassOffset(BaseDecl) + Offset))
6947 return false;
6951 // Visit the fields.
6952 unsigned FieldIdx = 0;
6953 for (FieldDecl *FD : RD->fields()) {
6954 if (FD->isBitField()) {
6955 Info.FFDiag(BCE->getBeginLoc(),
6956 diag::note_constexpr_bit_cast_unsupported_bitfield);
6957 return false;
6960 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6962 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6963 "only bit-fields can have sub-char alignment");
6964 CharUnits FieldOffset =
6965 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6966 QualType FieldTy = FD->getType();
6967 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6968 return false;
6969 ++FieldIdx;
6972 return true;
6975 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6976 const auto *CAT =
6977 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6978 if (!CAT)
6979 return false;
6981 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6982 unsigned NumInitializedElts = Val.getArrayInitializedElts();
6983 unsigned ArraySize = Val.getArraySize();
6984 // First, initialize the initialized elements.
6985 for (unsigned I = 0; I != NumInitializedElts; ++I) {
6986 const APValue &SubObj = Val.getArrayInitializedElt(I);
6987 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6988 return false;
6991 // Next, initialize the rest of the array using the filler.
6992 if (Val.hasArrayFiller()) {
6993 const APValue &Filler = Val.getArrayFiller();
6994 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6995 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6996 return false;
7000 return true;
7003 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7004 APSInt AdjustedVal = Val;
7005 unsigned Width = AdjustedVal.getBitWidth();
7006 if (Ty->isBooleanType()) {
7007 Width = Info.Ctx.getTypeSize(Ty);
7008 AdjustedVal = AdjustedVal.extend(Width);
7011 SmallVector<unsigned char, 8> Bytes(Width / 8);
7012 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7013 Buffer.writeObject(Offset, Bytes);
7014 return true;
7017 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7018 APSInt AsInt(Val.bitcastToAPInt());
7019 return visitInt(AsInt, Ty, Offset);
7022 public:
7023 static std::optional<BitCastBuffer>
7024 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7025 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7026 APValueToBufferConverter Converter(Info, DstSize, BCE);
7027 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7028 return std::nullopt;
7029 return Converter.Buffer;
7033 /// Write an BitCastBuffer into an APValue.
7034 class BufferToAPValueConverter {
7035 EvalInfo &Info;
7036 const BitCastBuffer &Buffer;
7037 const CastExpr *BCE;
7039 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7040 const CastExpr *BCE)
7041 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7043 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7044 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7045 // Ideally this will be unreachable.
7046 std::nullopt_t unsupportedType(QualType Ty) {
7047 Info.FFDiag(BCE->getBeginLoc(),
7048 diag::note_constexpr_bit_cast_unsupported_type)
7049 << Ty;
7050 return std::nullopt;
7053 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7054 Info.FFDiag(BCE->getBeginLoc(),
7055 diag::note_constexpr_bit_cast_unrepresentable_value)
7056 << Ty << toString(Val, /*Radix=*/10);
7057 return std::nullopt;
7060 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7061 const EnumType *EnumSugar = nullptr) {
7062 if (T->isNullPtrType()) {
7063 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7064 return APValue((Expr *)nullptr,
7065 /*Offset=*/CharUnits::fromQuantity(NullValue),
7066 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7069 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7071 // Work around floating point types that contain unused padding bytes. This
7072 // is really just `long double` on x86, which is the only fundamental type
7073 // with padding bytes.
7074 if (T->isRealFloatingType()) {
7075 const llvm::fltSemantics &Semantics =
7076 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7077 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7078 assert(NumBits % 8 == 0);
7079 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7080 if (NumBytes != SizeOf)
7081 SizeOf = NumBytes;
7084 SmallVector<uint8_t, 8> Bytes;
7085 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7086 // If this is std::byte or unsigned char, then its okay to store an
7087 // indeterminate value.
7088 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7089 bool IsUChar =
7090 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7091 T->isSpecificBuiltinType(BuiltinType::Char_U));
7092 if (!IsStdByte && !IsUChar) {
7093 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7094 Info.FFDiag(BCE->getExprLoc(),
7095 diag::note_constexpr_bit_cast_indet_dest)
7096 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7097 return std::nullopt;
7100 return APValue::IndeterminateValue();
7103 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7104 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7106 if (T->isIntegralOrEnumerationType()) {
7107 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7109 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7110 if (IntWidth != Val.getBitWidth()) {
7111 APSInt Truncated = Val.trunc(IntWidth);
7112 if (Truncated.extend(Val.getBitWidth()) != Val)
7113 return unrepresentableValue(QualType(T, 0), Val);
7114 Val = Truncated;
7117 return APValue(Val);
7120 if (T->isRealFloatingType()) {
7121 const llvm::fltSemantics &Semantics =
7122 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7123 return APValue(APFloat(Semantics, Val));
7126 return unsupportedType(QualType(T, 0));
7129 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7130 const RecordDecl *RD = RTy->getAsRecordDecl();
7131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7133 unsigned NumBases = 0;
7134 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7135 NumBases = CXXRD->getNumBases();
7137 APValue ResultVal(APValue::UninitStruct(), NumBases,
7138 std::distance(RD->field_begin(), RD->field_end()));
7140 // Visit the base classes.
7141 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7142 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7143 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7144 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7145 if (BaseDecl->isEmpty() ||
7146 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7147 continue;
7149 std::optional<APValue> SubObj = visitType(
7150 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7151 if (!SubObj)
7152 return std::nullopt;
7153 ResultVal.getStructBase(I) = *SubObj;
7157 // Visit the fields.
7158 unsigned FieldIdx = 0;
7159 for (FieldDecl *FD : RD->fields()) {
7160 // FIXME: We don't currently support bit-fields. A lot of the logic for
7161 // this is in CodeGen, so we need to factor it around.
7162 if (FD->isBitField()) {
7163 Info.FFDiag(BCE->getBeginLoc(),
7164 diag::note_constexpr_bit_cast_unsupported_bitfield);
7165 return std::nullopt;
7168 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7169 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7171 CharUnits FieldOffset =
7172 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7173 Offset;
7174 QualType FieldTy = FD->getType();
7175 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7176 if (!SubObj)
7177 return std::nullopt;
7178 ResultVal.getStructField(FieldIdx) = *SubObj;
7179 ++FieldIdx;
7182 return ResultVal;
7185 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7186 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7187 assert(!RepresentationType.isNull() &&
7188 "enum forward decl should be caught by Sema");
7189 const auto *AsBuiltin =
7190 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7191 // Recurse into the underlying type. Treat std::byte transparently as
7192 // unsigned char.
7193 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7196 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7197 size_t Size = Ty->getSize().getLimitedValue();
7198 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7200 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7201 for (size_t I = 0; I != Size; ++I) {
7202 std::optional<APValue> ElementValue =
7203 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7204 if (!ElementValue)
7205 return std::nullopt;
7206 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7209 return ArrayValue;
7212 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7213 return unsupportedType(QualType(Ty, 0));
7216 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7217 QualType Can = Ty.getCanonicalType();
7219 switch (Can->getTypeClass()) {
7220 #define TYPE(Class, Base) \
7221 case Type::Class: \
7222 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7223 #define ABSTRACT_TYPE(Class, Base)
7224 #define NON_CANONICAL_TYPE(Class, Base) \
7225 case Type::Class: \
7226 llvm_unreachable("non-canonical type should be impossible!");
7227 #define DEPENDENT_TYPE(Class, Base) \
7228 case Type::Class: \
7229 llvm_unreachable( \
7230 "dependent types aren't supported in the constant evaluator!");
7231 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7232 case Type::Class: \
7233 llvm_unreachable("either dependent or not canonical!");
7234 #include "clang/AST/TypeNodes.inc"
7236 llvm_unreachable("Unhandled Type::TypeClass");
7239 public:
7240 // Pull out a full value of type DstType.
7241 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7242 const CastExpr *BCE) {
7243 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7244 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7248 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7249 QualType Ty, EvalInfo *Info,
7250 const ASTContext &Ctx,
7251 bool CheckingDest) {
7252 Ty = Ty.getCanonicalType();
7254 auto diag = [&](int Reason) {
7255 if (Info)
7256 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7257 << CheckingDest << (Reason == 4) << Reason;
7258 return false;
7260 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7261 if (Info)
7262 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7263 << NoteTy << Construct << Ty;
7264 return false;
7267 if (Ty->isUnionType())
7268 return diag(0);
7269 if (Ty->isPointerType())
7270 return diag(1);
7271 if (Ty->isMemberPointerType())
7272 return diag(2);
7273 if (Ty.isVolatileQualified())
7274 return diag(3);
7276 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7277 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7278 for (CXXBaseSpecifier &BS : CXXRD->bases())
7279 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7280 CheckingDest))
7281 return note(1, BS.getType(), BS.getBeginLoc());
7283 for (FieldDecl *FD : Record->fields()) {
7284 if (FD->getType()->isReferenceType())
7285 return diag(4);
7286 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7287 CheckingDest))
7288 return note(0, FD->getType(), FD->getBeginLoc());
7292 if (Ty->isArrayType() &&
7293 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7294 Info, Ctx, CheckingDest))
7295 return false;
7297 return true;
7300 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7301 const ASTContext &Ctx,
7302 const CastExpr *BCE) {
7303 bool DestOK = checkBitCastConstexprEligibilityType(
7304 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7305 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7306 BCE->getBeginLoc(),
7307 BCE->getSubExpr()->getType(), Info, Ctx, false);
7308 return SourceOK;
7311 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7312 APValue &SourceValue,
7313 const CastExpr *BCE) {
7314 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7315 "no host or target supports non 8-bit chars");
7316 assert(SourceValue.isLValue() &&
7317 "LValueToRValueBitcast requires an lvalue operand!");
7319 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7320 return false;
7322 LValue SourceLValue;
7323 APValue SourceRValue;
7324 SourceLValue.setFrom(Info.Ctx, SourceValue);
7325 if (!handleLValueToRValueConversion(
7326 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7327 SourceRValue, /*WantObjectRepresentation=*/true))
7328 return false;
7330 // Read out SourceValue into a char buffer.
7331 std::optional<BitCastBuffer> Buffer =
7332 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7333 if (!Buffer)
7334 return false;
7336 // Write out the buffer into a new APValue.
7337 std::optional<APValue> MaybeDestValue =
7338 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7339 if (!MaybeDestValue)
7340 return false;
7342 DestValue = std::move(*MaybeDestValue);
7343 return true;
7346 template <class Derived>
7347 class ExprEvaluatorBase
7348 : public ConstStmtVisitor<Derived, bool> {
7349 private:
7350 Derived &getDerived() { return static_cast<Derived&>(*this); }
7351 bool DerivedSuccess(const APValue &V, const Expr *E) {
7352 return getDerived().Success(V, E);
7354 bool DerivedZeroInitialization(const Expr *E) {
7355 return getDerived().ZeroInitialization(E);
7358 // Check whether a conditional operator with a non-constant condition is a
7359 // potential constant expression. If neither arm is a potential constant
7360 // expression, then the conditional operator is not either.
7361 template<typename ConditionalOperator>
7362 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7363 assert(Info.checkingPotentialConstantExpression());
7365 // Speculatively evaluate both arms.
7366 SmallVector<PartialDiagnosticAt, 8> Diag;
7368 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7369 StmtVisitorTy::Visit(E->getFalseExpr());
7370 if (Diag.empty())
7371 return;
7375 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7376 Diag.clear();
7377 StmtVisitorTy::Visit(E->getTrueExpr());
7378 if (Diag.empty())
7379 return;
7382 Error(E, diag::note_constexpr_conditional_never_const);
7386 template<typename ConditionalOperator>
7387 bool HandleConditionalOperator(const ConditionalOperator *E) {
7388 bool BoolResult;
7389 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7390 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7391 CheckPotentialConstantConditional(E);
7392 return false;
7394 if (Info.noteFailure()) {
7395 StmtVisitorTy::Visit(E->getTrueExpr());
7396 StmtVisitorTy::Visit(E->getFalseExpr());
7398 return false;
7401 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7402 return StmtVisitorTy::Visit(EvalExpr);
7405 protected:
7406 EvalInfo &Info;
7407 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7408 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7410 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7411 return Info.CCEDiag(E, D);
7414 bool ZeroInitialization(const Expr *E) { return Error(E); }
7416 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7417 unsigned BuiltinOp = E->getBuiltinCallee();
7418 return BuiltinOp != 0 &&
7419 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7422 public:
7423 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7425 EvalInfo &getEvalInfo() { return Info; }
7427 /// Report an evaluation error. This should only be called when an error is
7428 /// first discovered. When propagating an error, just return false.
7429 bool Error(const Expr *E, diag::kind D) {
7430 Info.FFDiag(E, D);
7431 return false;
7433 bool Error(const Expr *E) {
7434 return Error(E, diag::note_invalid_subexpr_in_const_expr);
7437 bool VisitStmt(const Stmt *) {
7438 llvm_unreachable("Expression evaluator should not be called on stmts");
7440 bool VisitExpr(const Expr *E) {
7441 return Error(E);
7444 bool VisitConstantExpr(const ConstantExpr *E) {
7445 if (E->hasAPValueResult())
7446 return DerivedSuccess(E->getAPValueResult(), E);
7448 return StmtVisitorTy::Visit(E->getSubExpr());
7451 bool VisitParenExpr(const ParenExpr *E)
7452 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7453 bool VisitUnaryExtension(const UnaryOperator *E)
7454 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7455 bool VisitUnaryPlus(const UnaryOperator *E)
7456 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7457 bool VisitChooseExpr(const ChooseExpr *E)
7458 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7459 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7460 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7461 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7462 { return StmtVisitorTy::Visit(E->getReplacement()); }
7463 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7464 TempVersionRAII RAII(*Info.CurrentCall);
7465 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7466 return StmtVisitorTy::Visit(E->getExpr());
7468 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7469 TempVersionRAII RAII(*Info.CurrentCall);
7470 // The initializer may not have been parsed yet, or might be erroneous.
7471 if (!E->getExpr())
7472 return Error(E);
7473 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7474 return StmtVisitorTy::Visit(E->getExpr());
7477 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7478 FullExpressionRAII Scope(Info);
7479 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7482 // Temporaries are registered when created, so we don't care about
7483 // CXXBindTemporaryExpr.
7484 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7485 return StmtVisitorTy::Visit(E->getSubExpr());
7488 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7489 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7490 return static_cast<Derived*>(this)->VisitCastExpr(E);
7492 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7493 if (!Info.Ctx.getLangOpts().CPlusPlus20)
7494 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7495 return static_cast<Derived*>(this)->VisitCastExpr(E);
7497 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7498 return static_cast<Derived*>(this)->VisitCastExpr(E);
7501 bool VisitBinaryOperator(const BinaryOperator *E) {
7502 switch (E->getOpcode()) {
7503 default:
7504 return Error(E);
7506 case BO_Comma:
7507 VisitIgnoredValue(E->getLHS());
7508 return StmtVisitorTy::Visit(E->getRHS());
7510 case BO_PtrMemD:
7511 case BO_PtrMemI: {
7512 LValue Obj;
7513 if (!HandleMemberPointerAccess(Info, E, Obj))
7514 return false;
7515 APValue Result;
7516 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7517 return false;
7518 return DerivedSuccess(Result, E);
7523 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7524 return StmtVisitorTy::Visit(E->getSemanticForm());
7527 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7528 // Evaluate and cache the common expression. We treat it as a temporary,
7529 // even though it's not quite the same thing.
7530 LValue CommonLV;
7531 if (!Evaluate(Info.CurrentCall->createTemporary(
7532 E->getOpaqueValue(),
7533 getStorageType(Info.Ctx, E->getOpaqueValue()),
7534 ScopeKind::FullExpression, CommonLV),
7535 Info, E->getCommon()))
7536 return false;
7538 return HandleConditionalOperator(E);
7541 bool VisitConditionalOperator(const ConditionalOperator *E) {
7542 bool IsBcpCall = false;
7543 // If the condition (ignoring parens) is a __builtin_constant_p call,
7544 // the result is a constant expression if it can be folded without
7545 // side-effects. This is an important GNU extension. See GCC PR38377
7546 // for discussion.
7547 if (const CallExpr *CallCE =
7548 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7549 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7550 IsBcpCall = true;
7552 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7553 // constant expression; we can't check whether it's potentially foldable.
7554 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7555 // it would return 'false' in this mode.
7556 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7557 return false;
7559 FoldConstant Fold(Info, IsBcpCall);
7560 if (!HandleConditionalOperator(E)) {
7561 Fold.keepDiagnostics();
7562 return false;
7565 return true;
7568 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7569 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7570 return DerivedSuccess(*Value, E);
7572 const Expr *Source = E->getSourceExpr();
7573 if (!Source)
7574 return Error(E);
7575 if (Source == E) {
7576 assert(0 && "OpaqueValueExpr recursively refers to itself");
7577 return Error(E);
7579 return StmtVisitorTy::Visit(Source);
7582 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7583 for (const Expr *SemE : E->semantics()) {
7584 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7585 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7586 // result expression: there could be two different LValues that would
7587 // refer to the same object in that case, and we can't model that.
7588 if (SemE == E->getResultExpr())
7589 return Error(E);
7591 // Unique OVEs get evaluated if and when we encounter them when
7592 // emitting the rest of the semantic form, rather than eagerly.
7593 if (OVE->isUnique())
7594 continue;
7596 LValue LV;
7597 if (!Evaluate(Info.CurrentCall->createTemporary(
7598 OVE, getStorageType(Info.Ctx, OVE),
7599 ScopeKind::FullExpression, LV),
7600 Info, OVE->getSourceExpr()))
7601 return false;
7602 } else if (SemE == E->getResultExpr()) {
7603 if (!StmtVisitorTy::Visit(SemE))
7604 return false;
7605 } else {
7606 if (!EvaluateIgnoredValue(Info, SemE))
7607 return false;
7610 return true;
7613 bool VisitCallExpr(const CallExpr *E) {
7614 APValue Result;
7615 if (!handleCallExpr(E, Result, nullptr))
7616 return false;
7617 return DerivedSuccess(Result, E);
7620 bool handleCallExpr(const CallExpr *E, APValue &Result,
7621 const LValue *ResultSlot) {
7622 CallScopeRAII CallScope(Info);
7624 const Expr *Callee = E->getCallee()->IgnoreParens();
7625 QualType CalleeType = Callee->getType();
7627 const FunctionDecl *FD = nullptr;
7628 LValue *This = nullptr, ThisVal;
7629 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7630 bool HasQualifier = false;
7632 CallRef Call;
7634 // Extract function decl and 'this' pointer from the callee.
7635 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7636 const CXXMethodDecl *Member = nullptr;
7637 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7638 // Explicit bound member calls, such as x.f() or p->g();
7639 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7640 return false;
7641 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7642 if (!Member)
7643 return Error(Callee);
7644 This = &ThisVal;
7645 HasQualifier = ME->hasQualifier();
7646 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7647 // Indirect bound member calls ('.*' or '->*').
7648 const ValueDecl *D =
7649 HandleMemberPointerAccess(Info, BE, ThisVal, false);
7650 if (!D)
7651 return false;
7652 Member = dyn_cast<CXXMethodDecl>(D);
7653 if (!Member)
7654 return Error(Callee);
7655 This = &ThisVal;
7656 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7657 if (!Info.getLangOpts().CPlusPlus20)
7658 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7659 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7660 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7661 } else
7662 return Error(Callee);
7663 FD = Member;
7664 } else if (CalleeType->isFunctionPointerType()) {
7665 LValue CalleeLV;
7666 if (!EvaluatePointer(Callee, CalleeLV, Info))
7667 return false;
7669 if (!CalleeLV.getLValueOffset().isZero())
7670 return Error(Callee);
7671 FD = dyn_cast_or_null<FunctionDecl>(
7672 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7673 if (!FD)
7674 return Error(Callee);
7675 // Don't call function pointers which have been cast to some other type.
7676 // Per DR (no number yet), the caller and callee can differ in noexcept.
7677 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7678 CalleeType->getPointeeType(), FD->getType())) {
7679 return Error(E);
7682 // For an (overloaded) assignment expression, evaluate the RHS before the
7683 // LHS.
7684 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7685 if (OCE && OCE->isAssignmentOp()) {
7686 assert(Args.size() == 2 && "wrong number of arguments in assignment");
7687 Call = Info.CurrentCall->createCall(FD);
7688 if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7689 Info, FD, /*RightToLeft=*/true))
7690 return false;
7693 // Overloaded operator calls to member functions are represented as normal
7694 // calls with '*this' as the first argument.
7695 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7696 if (MD && !MD->isStatic()) {
7697 // FIXME: When selecting an implicit conversion for an overloaded
7698 // operator delete, we sometimes try to evaluate calls to conversion
7699 // operators without a 'this' parameter!
7700 if (Args.empty())
7701 return Error(E);
7703 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7704 return false;
7705 This = &ThisVal;
7707 // If this is syntactically a simple assignment using a trivial
7708 // assignment operator, start the lifetimes of union members as needed,
7709 // per C++20 [class.union]5.
7710 if (Info.getLangOpts().CPlusPlus20 && OCE &&
7711 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
7712 !HandleUnionActiveMemberChange(Info, Args[0], ThisVal))
7713 return false;
7715 Args = Args.slice(1);
7716 } else if (MD && MD->isLambdaStaticInvoker()) {
7717 // Map the static invoker for the lambda back to the call operator.
7718 // Conveniently, we don't have to slice out the 'this' argument (as is
7719 // being done for the non-static case), since a static member function
7720 // doesn't have an implicit argument passed in.
7721 const CXXRecordDecl *ClosureClass = MD->getParent();
7722 assert(
7723 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7724 "Number of captures must be zero for conversion to function-ptr");
7726 const CXXMethodDecl *LambdaCallOp =
7727 ClosureClass->getLambdaCallOperator();
7729 // Set 'FD', the function that will be called below, to the call
7730 // operator. If the closure object represents a generic lambda, find
7731 // the corresponding specialization of the call operator.
7733 if (ClosureClass->isGenericLambda()) {
7734 assert(MD->isFunctionTemplateSpecialization() &&
7735 "A generic lambda's static-invoker function must be a "
7736 "template specialization");
7737 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7738 FunctionTemplateDecl *CallOpTemplate =
7739 LambdaCallOp->getDescribedFunctionTemplate();
7740 void *InsertPos = nullptr;
7741 FunctionDecl *CorrespondingCallOpSpecialization =
7742 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7743 assert(CorrespondingCallOpSpecialization &&
7744 "We must always have a function call operator specialization "
7745 "that corresponds to our static invoker specialization");
7746 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7747 } else
7748 FD = LambdaCallOp;
7749 } else if (FD->isReplaceableGlobalAllocationFunction()) {
7750 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7751 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7752 LValue Ptr;
7753 if (!HandleOperatorNewCall(Info, E, Ptr))
7754 return false;
7755 Ptr.moveInto(Result);
7756 return CallScope.destroy();
7757 } else {
7758 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7761 } else
7762 return Error(E);
7764 // Evaluate the arguments now if we've not already done so.
7765 if (!Call) {
7766 Call = Info.CurrentCall->createCall(FD);
7767 if (!EvaluateArgs(Args, Call, Info, FD))
7768 return false;
7771 SmallVector<QualType, 4> CovariantAdjustmentPath;
7772 if (This) {
7773 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7774 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7775 // Perform virtual dispatch, if necessary.
7776 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7777 CovariantAdjustmentPath);
7778 if (!FD)
7779 return false;
7780 } else {
7781 // Check that the 'this' pointer points to an object of the right type.
7782 // FIXME: If this is an assignment operator call, we may need to change
7783 // the active union member before we check this.
7784 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7785 return false;
7789 // Destructor calls are different enough that they have their own codepath.
7790 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7791 assert(This && "no 'this' pointer for destructor call");
7792 return HandleDestruction(Info, E, *This,
7793 Info.Ctx.getRecordType(DD->getParent())) &&
7794 CallScope.destroy();
7797 const FunctionDecl *Definition = nullptr;
7798 Stmt *Body = FD->getBody(Definition);
7800 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7801 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7802 Body, Info, Result, ResultSlot))
7803 return false;
7805 if (!CovariantAdjustmentPath.empty() &&
7806 !HandleCovariantReturnAdjustment(Info, E, Result,
7807 CovariantAdjustmentPath))
7808 return false;
7810 return CallScope.destroy();
7813 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7814 return StmtVisitorTy::Visit(E->getInitializer());
7816 bool VisitInitListExpr(const InitListExpr *E) {
7817 if (E->getNumInits() == 0)
7818 return DerivedZeroInitialization(E);
7819 if (E->getNumInits() == 1)
7820 return StmtVisitorTy::Visit(E->getInit(0));
7821 return Error(E);
7823 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7824 return DerivedZeroInitialization(E);
7826 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7827 return DerivedZeroInitialization(E);
7829 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7830 return DerivedZeroInitialization(E);
7833 /// A member expression where the object is a prvalue is itself a prvalue.
7834 bool VisitMemberExpr(const MemberExpr *E) {
7835 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7836 "missing temporary materialization conversion");
7837 assert(!E->isArrow() && "missing call to bound member function?");
7839 APValue Val;
7840 if (!Evaluate(Val, Info, E->getBase()))
7841 return false;
7843 QualType BaseTy = E->getBase()->getType();
7845 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7846 if (!FD) return Error(E);
7847 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7848 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7849 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7851 // Note: there is no lvalue base here. But this case should only ever
7852 // happen in C or in C++98, where we cannot be evaluating a constexpr
7853 // constructor, which is the only case the base matters.
7854 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7855 SubobjectDesignator Designator(BaseTy);
7856 Designator.addDeclUnchecked(FD);
7858 APValue Result;
7859 return extractSubobject(Info, E, Obj, Designator, Result) &&
7860 DerivedSuccess(Result, E);
7863 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7864 APValue Val;
7865 if (!Evaluate(Val, Info, E->getBase()))
7866 return false;
7868 if (Val.isVector()) {
7869 SmallVector<uint32_t, 4> Indices;
7870 E->getEncodedElementAccess(Indices);
7871 if (Indices.size() == 1) {
7872 // Return scalar.
7873 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7874 } else {
7875 // Construct new APValue vector.
7876 SmallVector<APValue, 4> Elts;
7877 for (unsigned I = 0; I < Indices.size(); ++I) {
7878 Elts.push_back(Val.getVectorElt(Indices[I]));
7880 APValue VecResult(Elts.data(), Indices.size());
7881 return DerivedSuccess(VecResult, E);
7885 return false;
7888 bool VisitCastExpr(const CastExpr *E) {
7889 switch (E->getCastKind()) {
7890 default:
7891 break;
7893 case CK_AtomicToNonAtomic: {
7894 APValue AtomicVal;
7895 // This does not need to be done in place even for class/array types:
7896 // atomic-to-non-atomic conversion implies copying the object
7897 // representation.
7898 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7899 return false;
7900 return DerivedSuccess(AtomicVal, E);
7903 case CK_NoOp:
7904 case CK_UserDefinedConversion:
7905 return StmtVisitorTy::Visit(E->getSubExpr());
7907 case CK_LValueToRValue: {
7908 LValue LVal;
7909 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7910 return false;
7911 APValue RVal;
7912 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7913 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7914 LVal, RVal))
7915 return false;
7916 return DerivedSuccess(RVal, E);
7918 case CK_LValueToRValueBitCast: {
7919 APValue DestValue, SourceValue;
7920 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7921 return false;
7922 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7923 return false;
7924 return DerivedSuccess(DestValue, E);
7927 case CK_AddressSpaceConversion: {
7928 APValue Value;
7929 if (!Evaluate(Value, Info, E->getSubExpr()))
7930 return false;
7931 return DerivedSuccess(Value, E);
7935 return Error(E);
7938 bool VisitUnaryPostInc(const UnaryOperator *UO) {
7939 return VisitUnaryPostIncDec(UO);
7941 bool VisitUnaryPostDec(const UnaryOperator *UO) {
7942 return VisitUnaryPostIncDec(UO);
7944 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7945 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7946 return Error(UO);
7948 LValue LVal;
7949 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7950 return false;
7951 APValue RVal;
7952 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7953 UO->isIncrementOp(), &RVal))
7954 return false;
7955 return DerivedSuccess(RVal, UO);
7958 bool VisitStmtExpr(const StmtExpr *E) {
7959 // We will have checked the full-expressions inside the statement expression
7960 // when they were completed, and don't need to check them again now.
7961 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
7962 false);
7964 const CompoundStmt *CS = E->getSubStmt();
7965 if (CS->body_empty())
7966 return true;
7968 BlockScopeRAII Scope(Info);
7969 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7970 BE = CS->body_end();
7971 /**/; ++BI) {
7972 if (BI + 1 == BE) {
7973 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7974 if (!FinalExpr) {
7975 Info.FFDiag((*BI)->getBeginLoc(),
7976 diag::note_constexpr_stmt_expr_unsupported);
7977 return false;
7979 return this->Visit(FinalExpr) && Scope.destroy();
7982 APValue ReturnValue;
7983 StmtResult Result = { ReturnValue, nullptr };
7984 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7985 if (ESR != ESR_Succeeded) {
7986 // FIXME: If the statement-expression terminated due to 'return',
7987 // 'break', or 'continue', it would be nice to propagate that to
7988 // the outer statement evaluation rather than bailing out.
7989 if (ESR != ESR_Failed)
7990 Info.FFDiag((*BI)->getBeginLoc(),
7991 diag::note_constexpr_stmt_expr_unsupported);
7992 return false;
7996 llvm_unreachable("Return from function from the loop above.");
7999 /// Visit a value which is evaluated, but whose value is ignored.
8000 void VisitIgnoredValue(const Expr *E) {
8001 EvaluateIgnoredValue(Info, E);
8004 /// Potentially visit a MemberExpr's base expression.
8005 void VisitIgnoredBaseExpression(const Expr *E) {
8006 // While MSVC doesn't evaluate the base expression, it does diagnose the
8007 // presence of side-effecting behavior.
8008 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8009 return;
8010 VisitIgnoredValue(E);
8014 } // namespace
8016 //===----------------------------------------------------------------------===//
8017 // Common base class for lvalue and temporary evaluation.
8018 //===----------------------------------------------------------------------===//
8019 namespace {
8020 template<class Derived>
8021 class LValueExprEvaluatorBase
8022 : public ExprEvaluatorBase<Derived> {
8023 protected:
8024 LValue &Result;
8025 bool InvalidBaseOK;
8026 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8027 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8029 bool Success(APValue::LValueBase B) {
8030 Result.set(B);
8031 return true;
8034 bool evaluatePointer(const Expr *E, LValue &Result) {
8035 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8038 public:
8039 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8040 : ExprEvaluatorBaseTy(Info), Result(Result),
8041 InvalidBaseOK(InvalidBaseOK) {}
8043 bool Success(const APValue &V, const Expr *E) {
8044 Result.setFrom(this->Info.Ctx, V);
8045 return true;
8048 bool VisitMemberExpr(const MemberExpr *E) {
8049 // Handle non-static data members.
8050 QualType BaseTy;
8051 bool EvalOK;
8052 if (E->isArrow()) {
8053 EvalOK = evaluatePointer(E->getBase(), Result);
8054 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8055 } else if (E->getBase()->isPRValue()) {
8056 assert(E->getBase()->getType()->isRecordType());
8057 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8058 BaseTy = E->getBase()->getType();
8059 } else {
8060 EvalOK = this->Visit(E->getBase());
8061 BaseTy = E->getBase()->getType();
8063 if (!EvalOK) {
8064 if (!InvalidBaseOK)
8065 return false;
8066 Result.setInvalid(E);
8067 return true;
8070 const ValueDecl *MD = E->getMemberDecl();
8071 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8072 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8073 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8074 (void)BaseTy;
8075 if (!HandleLValueMember(this->Info, E, Result, FD))
8076 return false;
8077 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8078 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8079 return false;
8080 } else
8081 return this->Error(E);
8083 if (MD->getType()->isReferenceType()) {
8084 APValue RefValue;
8085 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8086 RefValue))
8087 return false;
8088 return Success(RefValue, E);
8090 return true;
8093 bool VisitBinaryOperator(const BinaryOperator *E) {
8094 switch (E->getOpcode()) {
8095 default:
8096 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8098 case BO_PtrMemD:
8099 case BO_PtrMemI:
8100 return HandleMemberPointerAccess(this->Info, E, Result);
8104 bool VisitCastExpr(const CastExpr *E) {
8105 switch (E->getCastKind()) {
8106 default:
8107 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8109 case CK_DerivedToBase:
8110 case CK_UncheckedDerivedToBase:
8111 if (!this->Visit(E->getSubExpr()))
8112 return false;
8114 // Now figure out the necessary offset to add to the base LV to get from
8115 // the derived class to the base class.
8116 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8117 Result);
8123 //===----------------------------------------------------------------------===//
8124 // LValue Evaluation
8126 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8127 // function designators (in C), decl references to void objects (in C), and
8128 // temporaries (if building with -Wno-address-of-temporary).
8130 // LValue evaluation produces values comprising a base expression of one of the
8131 // following types:
8132 // - Declarations
8133 // * VarDecl
8134 // * FunctionDecl
8135 // - Literals
8136 // * CompoundLiteralExpr in C (and in global scope in C++)
8137 // * StringLiteral
8138 // * PredefinedExpr
8139 // * ObjCStringLiteralExpr
8140 // * ObjCEncodeExpr
8141 // * AddrLabelExpr
8142 // * BlockExpr
8143 // * CallExpr for a MakeStringConstant builtin
8144 // - typeid(T) expressions, as TypeInfoLValues
8145 // - Locals and temporaries
8146 // * MaterializeTemporaryExpr
8147 // * Any Expr, with a CallIndex indicating the function in which the temporary
8148 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
8149 // from the AST (FIXME).
8150 // * A MaterializeTemporaryExpr that has static storage duration, with no
8151 // CallIndex, for a lifetime-extended temporary.
8152 // * The ConstantExpr that is currently being evaluated during evaluation of an
8153 // immediate invocation.
8154 // plus an offset in bytes.
8155 //===----------------------------------------------------------------------===//
8156 namespace {
8157 class LValueExprEvaluator
8158 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8159 public:
8160 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8161 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8163 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8164 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8166 bool VisitCallExpr(const CallExpr *E);
8167 bool VisitDeclRefExpr(const DeclRefExpr *E);
8168 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8169 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8170 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8171 bool VisitMemberExpr(const MemberExpr *E);
8172 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8173 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8174 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8175 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8176 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8177 bool VisitUnaryDeref(const UnaryOperator *E);
8178 bool VisitUnaryReal(const UnaryOperator *E);
8179 bool VisitUnaryImag(const UnaryOperator *E);
8180 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8181 return VisitUnaryPreIncDec(UO);
8183 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8184 return VisitUnaryPreIncDec(UO);
8186 bool VisitBinAssign(const BinaryOperator *BO);
8187 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8189 bool VisitCastExpr(const CastExpr *E) {
8190 switch (E->getCastKind()) {
8191 default:
8192 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8194 case CK_LValueBitCast:
8195 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8196 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8197 if (!Visit(E->getSubExpr()))
8198 return false;
8199 Result.Designator.setInvalid();
8200 return true;
8202 case CK_BaseToDerived:
8203 if (!Visit(E->getSubExpr()))
8204 return false;
8205 return HandleBaseToDerivedCast(Info, E, Result);
8207 case CK_Dynamic:
8208 if (!Visit(E->getSubExpr()))
8209 return false;
8210 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8214 } // end anonymous namespace
8216 /// Evaluate an expression as an lvalue. This can be legitimately called on
8217 /// expressions which are not glvalues, in three cases:
8218 /// * function designators in C, and
8219 /// * "extern void" objects
8220 /// * @selector() expressions in Objective-C
8221 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8222 bool InvalidBaseOK) {
8223 assert(!E->isValueDependent());
8224 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8225 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8226 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8229 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8230 const NamedDecl *D = E->getDecl();
8231 if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
8232 UnnamedGlobalConstantDecl>(D))
8233 return Success(cast<ValueDecl>(D));
8234 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8235 return VisitVarDecl(E, VD);
8236 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8237 return Visit(BD->getBinding());
8238 return Error(E);
8242 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8244 // If we are within a lambda's call operator, check whether the 'VD' referred
8245 // to within 'E' actually represents a lambda-capture that maps to a
8246 // data-member/field within the closure object, and if so, evaluate to the
8247 // field or what the field refers to.
8248 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8249 isa<DeclRefExpr>(E) &&
8250 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8251 // We don't always have a complete capture-map when checking or inferring if
8252 // the function call operator meets the requirements of a constexpr function
8253 // - but we don't need to evaluate the captures to determine constexprness
8254 // (dcl.constexpr C++17).
8255 if (Info.checkingPotentialConstantExpression())
8256 return false;
8258 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8259 // Start with 'Result' referring to the complete closure object...
8260 Result = *Info.CurrentCall->This;
8261 // ... then update it to refer to the field of the closure object
8262 // that represents the capture.
8263 if (!HandleLValueMember(Info, E, Result, FD))
8264 return false;
8265 // And if the field is of reference type, update 'Result' to refer to what
8266 // the field refers to.
8267 if (FD->getType()->isReferenceType()) {
8268 APValue RVal;
8269 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8270 RVal))
8271 return false;
8272 Result.setFrom(Info.Ctx, RVal);
8274 return true;
8278 CallStackFrame *Frame = nullptr;
8279 unsigned Version = 0;
8280 if (VD->hasLocalStorage()) {
8281 // Only if a local variable was declared in the function currently being
8282 // evaluated, do we expect to be able to find its value in the current
8283 // frame. (Otherwise it was likely declared in an enclosing context and
8284 // could either have a valid evaluatable value (for e.g. a constexpr
8285 // variable) or be ill-formed (and trigger an appropriate evaluation
8286 // diagnostic)).
8287 CallStackFrame *CurrFrame = Info.CurrentCall;
8288 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8289 // Function parameters are stored in some caller's frame. (Usually the
8290 // immediate caller, but for an inherited constructor they may be more
8291 // distant.)
8292 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8293 if (CurrFrame->Arguments) {
8294 VD = CurrFrame->Arguments.getOrigParam(PVD);
8295 Frame =
8296 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8297 Version = CurrFrame->Arguments.Version;
8299 } else {
8300 Frame = CurrFrame;
8301 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8306 if (!VD->getType()->isReferenceType()) {
8307 if (Frame) {
8308 Result.set({VD, Frame->Index, Version});
8309 return true;
8311 return Success(VD);
8314 if (!Info.getLangOpts().CPlusPlus11) {
8315 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8316 << VD << VD->getType();
8317 Info.Note(VD->getLocation(), diag::note_declared_at);
8320 APValue *V;
8321 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8322 return false;
8323 if (!V->hasValue()) {
8324 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8325 // adjust the diagnostic to say that.
8326 if (!Info.checkingPotentialConstantExpression())
8327 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8328 return false;
8330 return Success(*V, E);
8333 bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8334 if (!IsConstantEvaluatedBuiltinCall(E))
8335 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8337 switch (E->getBuiltinCallee()) {
8338 default:
8339 return false;
8340 case Builtin::BIas_const:
8341 case Builtin::BIforward:
8342 case Builtin::BIforward_like:
8343 case Builtin::BImove:
8344 case Builtin::BImove_if_noexcept:
8345 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8346 return Visit(E->getArg(0));
8347 break;
8350 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8353 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8354 const MaterializeTemporaryExpr *E) {
8355 // Walk through the expression to find the materialized temporary itself.
8356 SmallVector<const Expr *, 2> CommaLHSs;
8357 SmallVector<SubobjectAdjustment, 2> Adjustments;
8358 const Expr *Inner =
8359 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8361 // If we passed any comma operators, evaluate their LHSs.
8362 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8363 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8364 return false;
8366 // A materialized temporary with static storage duration can appear within the
8367 // result of a constant expression evaluation, so we need to preserve its
8368 // value for use outside this evaluation.
8369 APValue *Value;
8370 if (E->getStorageDuration() == SD_Static) {
8371 // FIXME: What about SD_Thread?
8372 Value = E->getOrCreateValue(true);
8373 *Value = APValue();
8374 Result.set(E);
8375 } else {
8376 Value = &Info.CurrentCall->createTemporary(
8377 E, E->getType(),
8378 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8379 : ScopeKind::Block,
8380 Result);
8383 QualType Type = Inner->getType();
8385 // Materialize the temporary itself.
8386 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8387 *Value = APValue();
8388 return false;
8391 // Adjust our lvalue to refer to the desired subobject.
8392 for (unsigned I = Adjustments.size(); I != 0; /**/) {
8393 --I;
8394 switch (Adjustments[I].Kind) {
8395 case SubobjectAdjustment::DerivedToBaseAdjustment:
8396 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8397 Type, Result))
8398 return false;
8399 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8400 break;
8402 case SubobjectAdjustment::FieldAdjustment:
8403 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8404 return false;
8405 Type = Adjustments[I].Field->getType();
8406 break;
8408 case SubobjectAdjustment::MemberPointerAdjustment:
8409 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8410 Adjustments[I].Ptr.RHS))
8411 return false;
8412 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8413 break;
8417 return true;
8420 bool
8421 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8422 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8423 "lvalue compound literal in c++?");
8424 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8425 // only see this when folding in C, so there's no standard to follow here.
8426 return Success(E);
8429 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8430 TypeInfoLValue TypeInfo;
8432 if (!E->isPotentiallyEvaluated()) {
8433 if (E->isTypeOperand())
8434 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8435 else
8436 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8437 } else {
8438 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8439 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8440 << E->getExprOperand()->getType()
8441 << E->getExprOperand()->getSourceRange();
8444 if (!Visit(E->getExprOperand()))
8445 return false;
8447 std::optional<DynamicType> DynType =
8448 ComputeDynamicType(Info, E, Result, AK_TypeId);
8449 if (!DynType)
8450 return false;
8452 TypeInfo =
8453 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8456 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8459 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8460 return Success(E->getGuidDecl());
8463 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8464 // Handle static data members.
8465 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8466 VisitIgnoredBaseExpression(E->getBase());
8467 return VisitVarDecl(E, VD);
8470 // Handle static member functions.
8471 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8472 if (MD->isStatic()) {
8473 VisitIgnoredBaseExpression(E->getBase());
8474 return Success(MD);
8478 // Handle non-static data members.
8479 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8482 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8483 // FIXME: Deal with vectors as array subscript bases.
8484 if (E->getBase()->getType()->isVectorType() ||
8485 E->getBase()->getType()->isVLSTBuiltinType())
8486 return Error(E);
8488 APSInt Index;
8489 bool Success = true;
8491 // C++17's rules require us to evaluate the LHS first, regardless of which
8492 // side is the base.
8493 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8494 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8495 : !EvaluateInteger(SubExpr, Index, Info)) {
8496 if (!Info.noteFailure())
8497 return false;
8498 Success = false;
8502 return Success &&
8503 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8506 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8507 return evaluatePointer(E->getSubExpr(), Result);
8510 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8511 if (!Visit(E->getSubExpr()))
8512 return false;
8513 // __real is a no-op on scalar lvalues.
8514 if (E->getSubExpr()->getType()->isAnyComplexType())
8515 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8516 return true;
8519 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8520 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8521 "lvalue __imag__ on scalar?");
8522 if (!Visit(E->getSubExpr()))
8523 return false;
8524 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8525 return true;
8528 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8529 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8530 return Error(UO);
8532 if (!this->Visit(UO->getSubExpr()))
8533 return false;
8535 return handleIncDec(
8536 this->Info, UO, Result, UO->getSubExpr()->getType(),
8537 UO->isIncrementOp(), nullptr);
8540 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8541 const CompoundAssignOperator *CAO) {
8542 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8543 return Error(CAO);
8545 bool Success = true;
8547 // C++17 onwards require that we evaluate the RHS first.
8548 APValue RHS;
8549 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8550 if (!Info.noteFailure())
8551 return false;
8552 Success = false;
8555 // The overall lvalue result is the result of evaluating the LHS.
8556 if (!this->Visit(CAO->getLHS()) || !Success)
8557 return false;
8559 return handleCompoundAssignment(
8560 this->Info, CAO,
8561 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8562 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8565 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8566 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8567 return Error(E);
8569 bool Success = true;
8571 // C++17 onwards require that we evaluate the RHS first.
8572 APValue NewVal;
8573 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8574 if (!Info.noteFailure())
8575 return false;
8576 Success = false;
8579 if (!this->Visit(E->getLHS()) || !Success)
8580 return false;
8582 if (Info.getLangOpts().CPlusPlus20 &&
8583 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8584 return false;
8586 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8587 NewVal);
8590 //===----------------------------------------------------------------------===//
8591 // Pointer Evaluation
8592 //===----------------------------------------------------------------------===//
8594 /// Attempts to compute the number of bytes available at the pointer
8595 /// returned by a function with the alloc_size attribute. Returns true if we
8596 /// were successful. Places an unsigned number into `Result`.
8598 /// This expects the given CallExpr to be a call to a function with an
8599 /// alloc_size attribute.
8600 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8601 const CallExpr *Call,
8602 llvm::APInt &Result) {
8603 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8605 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8606 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8607 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8608 if (Call->getNumArgs() <= SizeArgNo)
8609 return false;
8611 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8612 Expr::EvalResult ExprResult;
8613 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8614 return false;
8615 Into = ExprResult.Val.getInt();
8616 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8617 return false;
8618 Into = Into.zext(BitsInSizeT);
8619 return true;
8622 APSInt SizeOfElem;
8623 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8624 return false;
8626 if (!AllocSize->getNumElemsParam().isValid()) {
8627 Result = std::move(SizeOfElem);
8628 return true;
8631 APSInt NumberOfElems;
8632 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8633 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8634 return false;
8636 bool Overflow;
8637 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8638 if (Overflow)
8639 return false;
8641 Result = std::move(BytesAvailable);
8642 return true;
8645 /// Convenience function. LVal's base must be a call to an alloc_size
8646 /// function.
8647 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8648 const LValue &LVal,
8649 llvm::APInt &Result) {
8650 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8651 "Can't get the size of a non alloc_size function");
8652 const auto *Base = LVal.getLValueBase().get<const Expr *>();
8653 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8654 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8657 /// Attempts to evaluate the given LValueBase as the result of a call to
8658 /// a function with the alloc_size attribute. If it was possible to do so, this
8659 /// function will return true, make Result's Base point to said function call,
8660 /// and mark Result's Base as invalid.
8661 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8662 LValue &Result) {
8663 if (Base.isNull())
8664 return false;
8666 // Because we do no form of static analysis, we only support const variables.
8668 // Additionally, we can't support parameters, nor can we support static
8669 // variables (in the latter case, use-before-assign isn't UB; in the former,
8670 // we have no clue what they'll be assigned to).
8671 const auto *VD =
8672 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8673 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8674 return false;
8676 const Expr *Init = VD->getAnyInitializer();
8677 if (!Init || Init->getType().isNull())
8678 return false;
8680 const Expr *E = Init->IgnoreParens();
8681 if (!tryUnwrapAllocSizeCall(E))
8682 return false;
8684 // Store E instead of E unwrapped so that the type of the LValue's base is
8685 // what the user wanted.
8686 Result.setInvalid(E);
8688 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8689 Result.addUnsizedArray(Info, E, Pointee);
8690 return true;
8693 namespace {
8694 class PointerExprEvaluator
8695 : public ExprEvaluatorBase<PointerExprEvaluator> {
8696 LValue &Result;
8697 bool InvalidBaseOK;
8699 bool Success(const Expr *E) {
8700 Result.set(E);
8701 return true;
8704 bool evaluateLValue(const Expr *E, LValue &Result) {
8705 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8708 bool evaluatePointer(const Expr *E, LValue &Result) {
8709 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8712 bool visitNonBuiltinCallExpr(const CallExpr *E);
8713 public:
8715 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8716 : ExprEvaluatorBaseTy(info), Result(Result),
8717 InvalidBaseOK(InvalidBaseOK) {}
8719 bool Success(const APValue &V, const Expr *E) {
8720 Result.setFrom(Info.Ctx, V);
8721 return true;
8723 bool ZeroInitialization(const Expr *E) {
8724 Result.setNull(Info.Ctx, E->getType());
8725 return true;
8728 bool VisitBinaryOperator(const BinaryOperator *E);
8729 bool VisitCastExpr(const CastExpr* E);
8730 bool VisitUnaryAddrOf(const UnaryOperator *E);
8731 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8732 { return Success(E); }
8733 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8734 if (E->isExpressibleAsConstantInitializer())
8735 return Success(E);
8736 if (Info.noteFailure())
8737 EvaluateIgnoredValue(Info, E->getSubExpr());
8738 return Error(E);
8740 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8741 { return Success(E); }
8742 bool VisitCallExpr(const CallExpr *E);
8743 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8744 bool VisitBlockExpr(const BlockExpr *E) {
8745 if (!E->getBlockDecl()->hasCaptures())
8746 return Success(E);
8747 return Error(E);
8749 bool VisitCXXThisExpr(const CXXThisExpr *E) {
8750 // Can't look at 'this' when checking a potential constant expression.
8751 if (Info.checkingPotentialConstantExpression())
8752 return false;
8753 if (!Info.CurrentCall->This) {
8754 if (Info.getLangOpts().CPlusPlus11)
8755 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8756 else
8757 Info.FFDiag(E);
8758 return false;
8760 Result = *Info.CurrentCall->This;
8761 // If we are inside a lambda's call operator, the 'this' expression refers
8762 // to the enclosing '*this' object (either by value or reference) which is
8763 // either copied into the closure object's field that represents the '*this'
8764 // or refers to '*this'.
8765 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8766 // Ensure we actually have captured 'this'. (an error will have
8767 // been previously reported if not).
8768 if (!Info.CurrentCall->LambdaThisCaptureField)
8769 return false;
8771 // Update 'Result' to refer to the data member/field of the closure object
8772 // that represents the '*this' capture.
8773 if (!HandleLValueMember(Info, E, Result,
8774 Info.CurrentCall->LambdaThisCaptureField))
8775 return false;
8776 // If we captured '*this' by reference, replace the field with its referent.
8777 if (Info.CurrentCall->LambdaThisCaptureField->getType()
8778 ->isPointerType()) {
8779 APValue RVal;
8780 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8781 RVal))
8782 return false;
8784 Result.setFrom(Info.Ctx, RVal);
8787 return true;
8790 bool VisitCXXNewExpr(const CXXNewExpr *E);
8792 bool VisitSourceLocExpr(const SourceLocExpr *E) {
8793 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
8794 APValue LValResult = E->EvaluateInContext(
8795 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8796 Result.setFrom(Info.Ctx, LValResult);
8797 return true;
8800 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8801 std::string ResultStr = E->ComputeName(Info.Ctx);
8803 QualType CharTy = Info.Ctx.CharTy.withConst();
8804 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8805 ResultStr.size() + 1);
8806 QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8807 ArrayType::Normal, 0);
8809 StringLiteral *SL =
8810 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ordinary,
8811 /*Pascal*/ false, ArrayTy, E->getLocation());
8813 evaluateLValue(SL, Result);
8814 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8815 return true;
8818 // FIXME: Missing: @protocol, @selector
8820 } // end anonymous namespace
8822 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8823 bool InvalidBaseOK) {
8824 assert(!E->isValueDependent());
8825 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8826 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8829 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8830 if (E->getOpcode() != BO_Add &&
8831 E->getOpcode() != BO_Sub)
8832 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8834 const Expr *PExp = E->getLHS();
8835 const Expr *IExp = E->getRHS();
8836 if (IExp->getType()->isPointerType())
8837 std::swap(PExp, IExp);
8839 bool EvalPtrOK = evaluatePointer(PExp, Result);
8840 if (!EvalPtrOK && !Info.noteFailure())
8841 return false;
8843 llvm::APSInt Offset;
8844 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8845 return false;
8847 if (E->getOpcode() == BO_Sub)
8848 negateAsSigned(Offset);
8850 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8851 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8854 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8855 return evaluateLValue(E->getSubExpr(), Result);
8858 // Is the provided decl 'std::source_location::current'?
8859 static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD) {
8860 if (!FD)
8861 return false;
8862 const IdentifierInfo *FnII = FD->getIdentifier();
8863 if (!FnII || !FnII->isStr("current"))
8864 return false;
8866 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
8867 if (!RD)
8868 return false;
8870 const IdentifierInfo *ClassII = RD->getIdentifier();
8871 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
8874 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8875 const Expr *SubExpr = E->getSubExpr();
8877 switch (E->getCastKind()) {
8878 default:
8879 break;
8880 case CK_BitCast:
8881 case CK_CPointerToObjCPointerCast:
8882 case CK_BlockPointerToObjCPointerCast:
8883 case CK_AnyPointerToBlockPointerCast:
8884 case CK_AddressSpaceConversion:
8885 if (!Visit(SubExpr))
8886 return false;
8887 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8888 // permitted in constant expressions in C++11. Bitcasts from cv void* are
8889 // also static_casts, but we disallow them as a resolution to DR1312.
8890 if (!E->getType()->isVoidPointerType()) {
8891 // In some circumstances, we permit casting from void* to cv1 T*, when the
8892 // actual pointee object is actually a cv2 T.
8893 bool VoidPtrCastMaybeOK =
8894 !Result.InvalidBase && !Result.Designator.Invalid &&
8895 !Result.IsNullPtr &&
8896 Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8897 E->getType()->getPointeeType());
8898 // 1. We'll allow it in std::allocator::allocate, and anything which that
8899 // calls.
8900 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
8901 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
8902 // We'll allow it in the body of std::source_location::current. GCC's
8903 // implementation had a parameter of type `void*`, and casts from
8904 // that back to `const __impl*` in its body.
8905 if (VoidPtrCastMaybeOK &&
8906 (Info.getStdAllocatorCaller("allocate") ||
8907 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee))) {
8908 // Permitted.
8909 } else {
8910 Result.Designator.setInvalid();
8911 if (SubExpr->getType()->isVoidPointerType())
8912 CCEDiag(E, diag::note_constexpr_invalid_cast)
8913 << 3 << SubExpr->getType();
8914 else
8915 CCEDiag(E, diag::note_constexpr_invalid_cast)
8916 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8919 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8920 ZeroInitialization(E);
8921 return true;
8923 case CK_DerivedToBase:
8924 case CK_UncheckedDerivedToBase:
8925 if (!evaluatePointer(E->getSubExpr(), Result))
8926 return false;
8927 if (!Result.Base && Result.Offset.isZero())
8928 return true;
8930 // Now figure out the necessary offset to add to the base LV to get from
8931 // the derived class to the base class.
8932 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8933 castAs<PointerType>()->getPointeeType(),
8934 Result);
8936 case CK_BaseToDerived:
8937 if (!Visit(E->getSubExpr()))
8938 return false;
8939 if (!Result.Base && Result.Offset.isZero())
8940 return true;
8941 return HandleBaseToDerivedCast(Info, E, Result);
8943 case CK_Dynamic:
8944 if (!Visit(E->getSubExpr()))
8945 return false;
8946 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8948 case CK_NullToPointer:
8949 VisitIgnoredValue(E->getSubExpr());
8950 return ZeroInitialization(E);
8952 case CK_IntegralToPointer: {
8953 CCEDiag(E, diag::note_constexpr_invalid_cast)
8954 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8956 APValue Value;
8957 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8958 break;
8960 if (Value.isInt()) {
8961 unsigned Size = Info.Ctx.getTypeSize(E->getType());
8962 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8963 Result.Base = (Expr*)nullptr;
8964 Result.InvalidBase = false;
8965 Result.Offset = CharUnits::fromQuantity(N);
8966 Result.Designator.setInvalid();
8967 Result.IsNullPtr = false;
8968 return true;
8969 } else {
8970 // Cast is of an lvalue, no need to change value.
8971 Result.setFrom(Info.Ctx, Value);
8972 return true;
8976 case CK_ArrayToPointerDecay: {
8977 if (SubExpr->isGLValue()) {
8978 if (!evaluateLValue(SubExpr, Result))
8979 return false;
8980 } else {
8981 APValue &Value = Info.CurrentCall->createTemporary(
8982 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8983 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8984 return false;
8986 // The result is a pointer to the first element of the array.
8987 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8988 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8989 Result.addArray(Info, E, CAT);
8990 else
8991 Result.addUnsizedArray(Info, E, AT->getElementType());
8992 return true;
8995 case CK_FunctionToPointerDecay:
8996 return evaluateLValue(SubExpr, Result);
8998 case CK_LValueToRValue: {
8999 LValue LVal;
9000 if (!evaluateLValue(E->getSubExpr(), LVal))
9001 return false;
9003 APValue RVal;
9004 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9005 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9006 LVal, RVal))
9007 return InvalidBaseOK &&
9008 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9009 return Success(RVal, E);
9013 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9016 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
9017 UnaryExprOrTypeTrait ExprKind) {
9018 // C++ [expr.alignof]p3:
9019 // When alignof is applied to a reference type, the result is the
9020 // alignment of the referenced type.
9021 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
9022 T = Ref->getPointeeType();
9024 if (T.getQualifiers().hasUnaligned())
9025 return CharUnits::One();
9027 const bool AlignOfReturnsPreferred =
9028 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9030 // __alignof is defined to return the preferred alignment.
9031 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9032 // as well.
9033 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9034 return Info.Ctx.toCharUnitsFromBits(
9035 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
9036 // alignof and _Alignof are defined to return the ABI alignment.
9037 else if (ExprKind == UETT_AlignOf)
9038 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
9039 else
9040 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9043 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
9044 UnaryExprOrTypeTrait ExprKind) {
9045 E = E->IgnoreParens();
9047 // The kinds of expressions that we have special-case logic here for
9048 // should be kept up to date with the special checks for those
9049 // expressions in Sema.
9051 // alignof decl is always accepted, even if it doesn't make sense: we default
9052 // to 1 in those cases.
9053 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9054 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9055 /*RefAsPointee*/true);
9057 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9058 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9059 /*RefAsPointee*/true);
9061 return GetAlignOfType(Info, E->getType(), ExprKind);
9064 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9065 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9066 return Info.Ctx.getDeclAlign(VD);
9067 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9068 return GetAlignOfExpr(Info, E, UETT_AlignOf);
9069 return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
9072 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9073 /// __builtin_is_aligned and __builtin_assume_aligned.
9074 static bool getAlignmentArgument(const Expr *E, QualType ForType,
9075 EvalInfo &Info, APSInt &Alignment) {
9076 if (!EvaluateInteger(E, Alignment, Info))
9077 return false;
9078 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9079 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9080 return false;
9082 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9083 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9084 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9085 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9086 << MaxValue << ForType << Alignment;
9087 return false;
9089 // Ensure both alignment and source value have the same bit width so that we
9090 // don't assert when computing the resulting value.
9091 APSInt ExtAlignment =
9092 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9093 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9094 "Alignment should not be changed by ext/trunc");
9095 Alignment = ExtAlignment;
9096 assert(Alignment.getBitWidth() == SrcWidth);
9097 return true;
9100 // To be clear: this happily visits unsupported builtins. Better name welcomed.
9101 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9102 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9103 return true;
9105 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9106 return false;
9108 Result.setInvalid(E);
9109 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9110 Result.addUnsizedArray(Info, E, PointeeTy);
9111 return true;
9114 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9115 if (!IsConstantEvaluatedBuiltinCall(E))
9116 return visitNonBuiltinCallExpr(E);
9117 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9120 // Determine if T is a character type for which we guarantee that
9121 // sizeof(T) == 1.
9122 static bool isOneByteCharacterType(QualType T) {
9123 return T->isCharType() || T->isChar8Type();
9126 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9127 unsigned BuiltinOp) {
9128 if (IsNoOpCall(E))
9129 return Success(E);
9131 switch (BuiltinOp) {
9132 case Builtin::BIaddressof:
9133 case Builtin::BI__addressof:
9134 case Builtin::BI__builtin_addressof:
9135 return evaluateLValue(E->getArg(0), Result);
9136 case Builtin::BI__builtin_assume_aligned: {
9137 // We need to be very careful here because: if the pointer does not have the
9138 // asserted alignment, then the behavior is undefined, and undefined
9139 // behavior is non-constant.
9140 if (!evaluatePointer(E->getArg(0), Result))
9141 return false;
9143 LValue OffsetResult(Result);
9144 APSInt Alignment;
9145 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9146 Alignment))
9147 return false;
9148 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9150 if (E->getNumArgs() > 2) {
9151 APSInt Offset;
9152 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9153 return false;
9155 int64_t AdditionalOffset = -Offset.getZExtValue();
9156 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9159 // If there is a base object, then it must have the correct alignment.
9160 if (OffsetResult.Base) {
9161 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9163 if (BaseAlignment < Align) {
9164 Result.Designator.setInvalid();
9165 // FIXME: Add support to Diagnostic for long / long long.
9166 CCEDiag(E->getArg(0),
9167 diag::note_constexpr_baa_insufficient_alignment) << 0
9168 << (unsigned)BaseAlignment.getQuantity()
9169 << (unsigned)Align.getQuantity();
9170 return false;
9174 // The offset must also have the correct alignment.
9175 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9176 Result.Designator.setInvalid();
9178 (OffsetResult.Base
9179 ? CCEDiag(E->getArg(0),
9180 diag::note_constexpr_baa_insufficient_alignment) << 1
9181 : CCEDiag(E->getArg(0),
9182 diag::note_constexpr_baa_value_insufficient_alignment))
9183 << (int)OffsetResult.Offset.getQuantity()
9184 << (unsigned)Align.getQuantity();
9185 return false;
9188 return true;
9190 case Builtin::BI__builtin_align_up:
9191 case Builtin::BI__builtin_align_down: {
9192 if (!evaluatePointer(E->getArg(0), Result))
9193 return false;
9194 APSInt Alignment;
9195 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9196 Alignment))
9197 return false;
9198 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9199 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9200 // For align_up/align_down, we can return the same value if the alignment
9201 // is known to be greater or equal to the requested value.
9202 if (PtrAlign.getQuantity() >= Alignment)
9203 return true;
9205 // The alignment could be greater than the minimum at run-time, so we cannot
9206 // infer much about the resulting pointer value. One case is possible:
9207 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9208 // can infer the correct index if the requested alignment is smaller than
9209 // the base alignment so we can perform the computation on the offset.
9210 if (BaseAlignment.getQuantity() >= Alignment) {
9211 assert(Alignment.getBitWidth() <= 64 &&
9212 "Cannot handle > 64-bit address-space");
9213 uint64_t Alignment64 = Alignment.getZExtValue();
9214 CharUnits NewOffset = CharUnits::fromQuantity(
9215 BuiltinOp == Builtin::BI__builtin_align_down
9216 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9217 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9218 Result.adjustOffset(NewOffset - Result.Offset);
9219 // TODO: diagnose out-of-bounds values/only allow for arrays?
9220 return true;
9222 // Otherwise, we cannot constant-evaluate the result.
9223 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9224 << Alignment;
9225 return false;
9227 case Builtin::BI__builtin_operator_new:
9228 return HandleOperatorNewCall(Info, E, Result);
9229 case Builtin::BI__builtin_launder:
9230 return evaluatePointer(E->getArg(0), Result);
9231 case Builtin::BIstrchr:
9232 case Builtin::BIwcschr:
9233 case Builtin::BImemchr:
9234 case Builtin::BIwmemchr:
9235 if (Info.getLangOpts().CPlusPlus11)
9236 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9237 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9238 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9239 else
9240 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9241 [[fallthrough]];
9242 case Builtin::BI__builtin_strchr:
9243 case Builtin::BI__builtin_wcschr:
9244 case Builtin::BI__builtin_memchr:
9245 case Builtin::BI__builtin_char_memchr:
9246 case Builtin::BI__builtin_wmemchr: {
9247 if (!Visit(E->getArg(0)))
9248 return false;
9249 APSInt Desired;
9250 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9251 return false;
9252 uint64_t MaxLength = uint64_t(-1);
9253 if (BuiltinOp != Builtin::BIstrchr &&
9254 BuiltinOp != Builtin::BIwcschr &&
9255 BuiltinOp != Builtin::BI__builtin_strchr &&
9256 BuiltinOp != Builtin::BI__builtin_wcschr) {
9257 APSInt N;
9258 if (!EvaluateInteger(E->getArg(2), N, Info))
9259 return false;
9260 MaxLength = N.getExtValue();
9262 // We cannot find the value if there are no candidates to match against.
9263 if (MaxLength == 0u)
9264 return ZeroInitialization(E);
9265 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9266 Result.Designator.Invalid)
9267 return false;
9268 QualType CharTy = Result.Designator.getType(Info.Ctx);
9269 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9270 BuiltinOp == Builtin::BI__builtin_memchr;
9271 assert(IsRawByte ||
9272 Info.Ctx.hasSameUnqualifiedType(
9273 CharTy, E->getArg(0)->getType()->getPointeeType()));
9274 // Pointers to const void may point to objects of incomplete type.
9275 if (IsRawByte && CharTy->isIncompleteType()) {
9276 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9277 return false;
9279 // Give up on byte-oriented matching against multibyte elements.
9280 // FIXME: We can compare the bytes in the correct order.
9281 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9282 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9283 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
9284 << CharTy;
9285 return false;
9287 // Figure out what value we're actually looking for (after converting to
9288 // the corresponding unsigned type if necessary).
9289 uint64_t DesiredVal;
9290 bool StopAtNull = false;
9291 switch (BuiltinOp) {
9292 case Builtin::BIstrchr:
9293 case Builtin::BI__builtin_strchr:
9294 // strchr compares directly to the passed integer, and therefore
9295 // always fails if given an int that is not a char.
9296 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9297 E->getArg(1)->getType(),
9298 Desired),
9299 Desired))
9300 return ZeroInitialization(E);
9301 StopAtNull = true;
9302 [[fallthrough]];
9303 case Builtin::BImemchr:
9304 case Builtin::BI__builtin_memchr:
9305 case Builtin::BI__builtin_char_memchr:
9306 // memchr compares by converting both sides to unsigned char. That's also
9307 // correct for strchr if we get this far (to cope with plain char being
9308 // unsigned in the strchr case).
9309 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9310 break;
9312 case Builtin::BIwcschr:
9313 case Builtin::BI__builtin_wcschr:
9314 StopAtNull = true;
9315 [[fallthrough]];
9316 case Builtin::BIwmemchr:
9317 case Builtin::BI__builtin_wmemchr:
9318 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9319 DesiredVal = Desired.getZExtValue();
9320 break;
9323 for (; MaxLength; --MaxLength) {
9324 APValue Char;
9325 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9326 !Char.isInt())
9327 return false;
9328 if (Char.getInt().getZExtValue() == DesiredVal)
9329 return true;
9330 if (StopAtNull && !Char.getInt())
9331 break;
9332 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9333 return false;
9335 // Not found: return nullptr.
9336 return ZeroInitialization(E);
9339 case Builtin::BImemcpy:
9340 case Builtin::BImemmove:
9341 case Builtin::BIwmemcpy:
9342 case Builtin::BIwmemmove:
9343 if (Info.getLangOpts().CPlusPlus11)
9344 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9345 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9346 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
9347 else
9348 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9349 [[fallthrough]];
9350 case Builtin::BI__builtin_memcpy:
9351 case Builtin::BI__builtin_memmove:
9352 case Builtin::BI__builtin_wmemcpy:
9353 case Builtin::BI__builtin_wmemmove: {
9354 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9355 BuiltinOp == Builtin::BIwmemmove ||
9356 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9357 BuiltinOp == Builtin::BI__builtin_wmemmove;
9358 bool Move = BuiltinOp == Builtin::BImemmove ||
9359 BuiltinOp == Builtin::BIwmemmove ||
9360 BuiltinOp == Builtin::BI__builtin_memmove ||
9361 BuiltinOp == Builtin::BI__builtin_wmemmove;
9363 // The result of mem* is the first argument.
9364 if (!Visit(E->getArg(0)))
9365 return false;
9366 LValue Dest = Result;
9368 LValue Src;
9369 if (!EvaluatePointer(E->getArg(1), Src, Info))
9370 return false;
9372 APSInt N;
9373 if (!EvaluateInteger(E->getArg(2), N, Info))
9374 return false;
9375 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9377 // If the size is zero, we treat this as always being a valid no-op.
9378 // (Even if one of the src and dest pointers is null.)
9379 if (!N)
9380 return true;
9382 // Otherwise, if either of the operands is null, we can't proceed. Don't
9383 // try to determine the type of the copied objects, because there aren't
9384 // any.
9385 if (!Src.Base || !Dest.Base) {
9386 APValue Val;
9387 (!Src.Base ? Src : Dest).moveInto(Val);
9388 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9389 << Move << WChar << !!Src.Base
9390 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9391 return false;
9393 if (Src.Designator.Invalid || Dest.Designator.Invalid)
9394 return false;
9396 // We require that Src and Dest are both pointers to arrays of
9397 // trivially-copyable type. (For the wide version, the designator will be
9398 // invalid if the designated object is not a wchar_t.)
9399 QualType T = Dest.Designator.getType(Info.Ctx);
9400 QualType SrcT = Src.Designator.getType(Info.Ctx);
9401 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9402 // FIXME: Consider using our bit_cast implementation to support this.
9403 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9404 return false;
9406 if (T->isIncompleteType()) {
9407 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9408 return false;
9410 if (!T.isTriviallyCopyableType(Info.Ctx)) {
9411 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9412 return false;
9415 // Figure out how many T's we're copying.
9416 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9417 if (!WChar) {
9418 uint64_t Remainder;
9419 llvm::APInt OrigN = N;
9420 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9421 if (Remainder) {
9422 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9423 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9424 << (unsigned)TSize;
9425 return false;
9429 // Check that the copying will remain within the arrays, just so that we
9430 // can give a more meaningful diagnostic. This implicitly also checks that
9431 // N fits into 64 bits.
9432 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9433 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9434 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9435 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9436 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9437 << toString(N, 10, /*Signed*/false);
9438 return false;
9440 uint64_t NElems = N.getZExtValue();
9441 uint64_t NBytes = NElems * TSize;
9443 // Check for overlap.
9444 int Direction = 1;
9445 if (HasSameBase(Src, Dest)) {
9446 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9447 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9448 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9449 // Dest is inside the source region.
9450 if (!Move) {
9451 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9452 return false;
9454 // For memmove and friends, copy backwards.
9455 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9456 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9457 return false;
9458 Direction = -1;
9459 } else if (!Move && SrcOffset >= DestOffset &&
9460 SrcOffset - DestOffset < NBytes) {
9461 // Src is inside the destination region for memcpy: invalid.
9462 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9463 return false;
9467 while (true) {
9468 APValue Val;
9469 // FIXME: Set WantObjectRepresentation to true if we're copying a
9470 // char-like type?
9471 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9472 !handleAssignment(Info, E, Dest, T, Val))
9473 return false;
9474 // Do not iterate past the last element; if we're copying backwards, that
9475 // might take us off the start of the array.
9476 if (--NElems == 0)
9477 return true;
9478 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9479 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9480 return false;
9484 default:
9485 return false;
9489 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9490 APValue &Result, const InitListExpr *ILE,
9491 QualType AllocType);
9492 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9493 APValue &Result,
9494 const CXXConstructExpr *CCE,
9495 QualType AllocType);
9497 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9498 if (!Info.getLangOpts().CPlusPlus20)
9499 Info.CCEDiag(E, diag::note_constexpr_new);
9501 // We cannot speculatively evaluate a delete expression.
9502 if (Info.SpeculativeEvaluationDepth)
9503 return false;
9505 FunctionDecl *OperatorNew = E->getOperatorNew();
9507 bool IsNothrow = false;
9508 bool IsPlacement = false;
9509 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9510 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9511 // FIXME Support array placement new.
9512 assert(E->getNumPlacementArgs() == 1);
9513 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9514 return false;
9515 if (Result.Designator.Invalid)
9516 return false;
9517 IsPlacement = true;
9518 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9519 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9520 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9521 return false;
9522 } else if (E->getNumPlacementArgs()) {
9523 // The only new-placement list we support is of the form (std::nothrow).
9525 // FIXME: There is no restriction on this, but it's not clear that any
9526 // other form makes any sense. We get here for cases such as:
9528 // new (std::align_val_t{N}) X(int)
9530 // (which should presumably be valid only if N is a multiple of
9531 // alignof(int), and in any case can't be deallocated unless N is
9532 // alignof(X) and X has new-extended alignment).
9533 if (E->getNumPlacementArgs() != 1 ||
9534 !E->getPlacementArg(0)->getType()->isNothrowT())
9535 return Error(E, diag::note_constexpr_new_placement);
9537 LValue Nothrow;
9538 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9539 return false;
9540 IsNothrow = true;
9543 const Expr *Init = E->getInitializer();
9544 const InitListExpr *ResizedArrayILE = nullptr;
9545 const CXXConstructExpr *ResizedArrayCCE = nullptr;
9546 bool ValueInit = false;
9548 QualType AllocType = E->getAllocatedType();
9549 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9550 const Expr *Stripped = *ArraySize;
9551 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9552 Stripped = ICE->getSubExpr())
9553 if (ICE->getCastKind() != CK_NoOp &&
9554 ICE->getCastKind() != CK_IntegralCast)
9555 break;
9557 llvm::APSInt ArrayBound;
9558 if (!EvaluateInteger(Stripped, ArrayBound, Info))
9559 return false;
9561 // C++ [expr.new]p9:
9562 // The expression is erroneous if:
9563 // -- [...] its value before converting to size_t [or] applying the
9564 // second standard conversion sequence is less than zero
9565 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9566 if (IsNothrow)
9567 return ZeroInitialization(E);
9569 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9570 << ArrayBound << (*ArraySize)->getSourceRange();
9571 return false;
9574 // -- its value is such that the size of the allocated object would
9575 // exceed the implementation-defined limit
9576 if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9577 ArrayBound) >
9578 ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9579 if (IsNothrow)
9580 return ZeroInitialization(E);
9582 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9583 << ArrayBound << (*ArraySize)->getSourceRange();
9584 return false;
9587 // -- the new-initializer is a braced-init-list and the number of
9588 // array elements for which initializers are provided [...]
9589 // exceeds the number of elements to initialize
9590 if (!Init) {
9591 // No initialization is performed.
9592 } else if (isa<CXXScalarValueInitExpr>(Init) ||
9593 isa<ImplicitValueInitExpr>(Init)) {
9594 ValueInit = true;
9595 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9596 ResizedArrayCCE = CCE;
9597 } else {
9598 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9599 assert(CAT && "unexpected type for array initializer");
9601 unsigned Bits =
9602 std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9603 llvm::APInt InitBound = CAT->getSize().zext(Bits);
9604 llvm::APInt AllocBound = ArrayBound.zext(Bits);
9605 if (InitBound.ugt(AllocBound)) {
9606 if (IsNothrow)
9607 return ZeroInitialization(E);
9609 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9610 << toString(AllocBound, 10, /*Signed=*/false)
9611 << toString(InitBound, 10, /*Signed=*/false)
9612 << (*ArraySize)->getSourceRange();
9613 return false;
9616 // If the sizes differ, we must have an initializer list, and we need
9617 // special handling for this case when we initialize.
9618 if (InitBound != AllocBound)
9619 ResizedArrayILE = cast<InitListExpr>(Init);
9622 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9623 ArrayType::Normal, 0);
9624 } else {
9625 assert(!AllocType->isArrayType() &&
9626 "array allocation with non-array new");
9629 APValue *Val;
9630 if (IsPlacement) {
9631 AccessKinds AK = AK_Construct;
9632 struct FindObjectHandler {
9633 EvalInfo &Info;
9634 const Expr *E;
9635 QualType AllocType;
9636 const AccessKinds AccessKind;
9637 APValue *Value;
9639 typedef bool result_type;
9640 bool failed() { return false; }
9641 bool found(APValue &Subobj, QualType SubobjType) {
9642 // FIXME: Reject the cases where [basic.life]p8 would not permit the
9643 // old name of the object to be used to name the new object.
9644 if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9645 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9646 SubobjType << AllocType;
9647 return false;
9649 Value = &Subobj;
9650 return true;
9652 bool found(APSInt &Value, QualType SubobjType) {
9653 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9654 return false;
9656 bool found(APFloat &Value, QualType SubobjType) {
9657 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9658 return false;
9660 } Handler = {Info, E, AllocType, AK, nullptr};
9662 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9663 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9664 return false;
9666 Val = Handler.Value;
9668 // [basic.life]p1:
9669 // The lifetime of an object o of type T ends when [...] the storage
9670 // which the object occupies is [...] reused by an object that is not
9671 // nested within o (6.6.2).
9672 *Val = APValue();
9673 } else {
9674 // Perform the allocation and obtain a pointer to the resulting object.
9675 Val = Info.createHeapAlloc(E, AllocType, Result);
9676 if (!Val)
9677 return false;
9680 if (ValueInit) {
9681 ImplicitValueInitExpr VIE(AllocType);
9682 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9683 return false;
9684 } else if (ResizedArrayILE) {
9685 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9686 AllocType))
9687 return false;
9688 } else if (ResizedArrayCCE) {
9689 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9690 AllocType))
9691 return false;
9692 } else if (Init) {
9693 if (!EvaluateInPlace(*Val, Info, Result, Init))
9694 return false;
9695 } else if (!getDefaultInitValue(AllocType, *Val)) {
9696 return false;
9699 // Array new returns a pointer to the first element, not a pointer to the
9700 // array.
9701 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9702 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9704 return true;
9706 //===----------------------------------------------------------------------===//
9707 // Member Pointer Evaluation
9708 //===----------------------------------------------------------------------===//
9710 namespace {
9711 class MemberPointerExprEvaluator
9712 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9713 MemberPtr &Result;
9715 bool Success(const ValueDecl *D) {
9716 Result = MemberPtr(D);
9717 return true;
9719 public:
9721 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9722 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9724 bool Success(const APValue &V, const Expr *E) {
9725 Result.setFrom(V);
9726 return true;
9728 bool ZeroInitialization(const Expr *E) {
9729 return Success((const ValueDecl*)nullptr);
9732 bool VisitCastExpr(const CastExpr *E);
9733 bool VisitUnaryAddrOf(const UnaryOperator *E);
9735 } // end anonymous namespace
9737 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9738 EvalInfo &Info) {
9739 assert(!E->isValueDependent());
9740 assert(E->isPRValue() && E->getType()->isMemberPointerType());
9741 return MemberPointerExprEvaluator(Info, Result).Visit(E);
9744 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9745 switch (E->getCastKind()) {
9746 default:
9747 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9749 case CK_NullToMemberPointer:
9750 VisitIgnoredValue(E->getSubExpr());
9751 return ZeroInitialization(E);
9753 case CK_BaseToDerivedMemberPointer: {
9754 if (!Visit(E->getSubExpr()))
9755 return false;
9756 if (E->path_empty())
9757 return true;
9758 // Base-to-derived member pointer casts store the path in derived-to-base
9759 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9760 // the wrong end of the derived->base arc, so stagger the path by one class.
9761 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9762 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9763 PathI != PathE; ++PathI) {
9764 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9765 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9766 if (!Result.castToDerived(Derived))
9767 return Error(E);
9769 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9770 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9771 return Error(E);
9772 return true;
9775 case CK_DerivedToBaseMemberPointer:
9776 if (!Visit(E->getSubExpr()))
9777 return false;
9778 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9779 PathE = E->path_end(); PathI != PathE; ++PathI) {
9780 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9781 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9782 if (!Result.castToBase(Base))
9783 return Error(E);
9785 return true;
9789 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9790 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9791 // member can be formed.
9792 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9795 //===----------------------------------------------------------------------===//
9796 // Record Evaluation
9797 //===----------------------------------------------------------------------===//
9799 namespace {
9800 class RecordExprEvaluator
9801 : public ExprEvaluatorBase<RecordExprEvaluator> {
9802 const LValue &This;
9803 APValue &Result;
9804 public:
9806 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9807 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9809 bool Success(const APValue &V, const Expr *E) {
9810 Result = V;
9811 return true;
9813 bool ZeroInitialization(const Expr *E) {
9814 return ZeroInitialization(E, E->getType());
9816 bool ZeroInitialization(const Expr *E, QualType T);
9818 bool VisitCallExpr(const CallExpr *E) {
9819 return handleCallExpr(E, Result, &This);
9821 bool VisitCastExpr(const CastExpr *E);
9822 bool VisitInitListExpr(const InitListExpr *E);
9823 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9824 return VisitCXXConstructExpr(E, E->getType());
9826 bool VisitLambdaExpr(const LambdaExpr *E);
9827 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9828 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9829 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9830 bool VisitBinCmp(const BinaryOperator *E);
9831 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
9832 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
9833 ArrayRef<Expr *> Args);
9837 /// Perform zero-initialization on an object of non-union class type.
9838 /// C++11 [dcl.init]p5:
9839 /// To zero-initialize an object or reference of type T means:
9840 /// [...]
9841 /// -- if T is a (possibly cv-qualified) non-union class type,
9842 /// each non-static data member and each base-class subobject is
9843 /// zero-initialized
9844 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9845 const RecordDecl *RD,
9846 const LValue &This, APValue &Result) {
9847 assert(!RD->isUnion() && "Expected non-union class type");
9848 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9849 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9850 std::distance(RD->field_begin(), RD->field_end()));
9852 if (RD->isInvalidDecl()) return false;
9853 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9855 if (CD) {
9856 unsigned Index = 0;
9857 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9858 End = CD->bases_end(); I != End; ++I, ++Index) {
9859 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9860 LValue Subobject = This;
9861 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9862 return false;
9863 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9864 Result.getStructBase(Index)))
9865 return false;
9869 for (const auto *I : RD->fields()) {
9870 // -- if T is a reference type, no initialization is performed.
9871 if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9872 continue;
9874 LValue Subobject = This;
9875 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9876 return false;
9878 ImplicitValueInitExpr VIE(I->getType());
9879 if (!EvaluateInPlace(
9880 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9881 return false;
9884 return true;
9887 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9888 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9889 if (RD->isInvalidDecl()) return false;
9890 if (RD->isUnion()) {
9891 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9892 // object's first non-static named data member is zero-initialized
9893 RecordDecl::field_iterator I = RD->field_begin();
9894 while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9895 ++I;
9896 if (I == RD->field_end()) {
9897 Result = APValue((const FieldDecl*)nullptr);
9898 return true;
9901 LValue Subobject = This;
9902 if (!HandleLValueMember(Info, E, Subobject, *I))
9903 return false;
9904 Result = APValue(*I);
9905 ImplicitValueInitExpr VIE(I->getType());
9906 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9909 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9910 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9911 return false;
9914 return HandleClassZeroInitialization(Info, E, RD, This, Result);
9917 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9918 switch (E->getCastKind()) {
9919 default:
9920 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9922 case CK_ConstructorConversion:
9923 return Visit(E->getSubExpr());
9925 case CK_DerivedToBase:
9926 case CK_UncheckedDerivedToBase: {
9927 APValue DerivedObject;
9928 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9929 return false;
9930 if (!DerivedObject.isStruct())
9931 return Error(E->getSubExpr());
9933 // Derived-to-base rvalue conversion: just slice off the derived part.
9934 APValue *Value = &DerivedObject;
9935 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9936 for (CastExpr::path_const_iterator PathI = E->path_begin(),
9937 PathE = E->path_end(); PathI != PathE; ++PathI) {
9938 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9939 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9940 Value = &Value->getStructBase(getBaseIndex(RD, Base));
9941 RD = Base;
9943 Result = *Value;
9944 return true;
9949 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9950 if (E->isTransparent())
9951 return Visit(E->getInit(0));
9952 return VisitCXXParenListOrInitListExpr(E, E->inits());
9955 bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
9956 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
9957 const RecordDecl *RD =
9958 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
9959 if (RD->isInvalidDecl()) return false;
9960 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9961 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9963 EvalInfo::EvaluatingConstructorRAII EvalObj(
9964 Info,
9965 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9966 CXXRD && CXXRD->getNumBases());
9968 if (RD->isUnion()) {
9969 const FieldDecl *Field;
9970 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
9971 Field = ILE->getInitializedFieldInUnion();
9972 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
9973 Field = PLIE->getInitializedFieldInUnion();
9974 } else {
9975 llvm_unreachable(
9976 "Expression is neither an init list nor a C++ paren list");
9979 Result = APValue(Field);
9980 if (!Field)
9981 return true;
9983 // If the initializer list for a union does not contain any elements, the
9984 // first element of the union is value-initialized.
9985 // FIXME: The element should be initialized from an initializer list.
9986 // Is this difference ever observable for initializer lists which
9987 // we don't build?
9988 ImplicitValueInitExpr VIE(Field->getType());
9989 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
9991 LValue Subobject = This;
9992 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9993 return false;
9995 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9996 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9997 isa<CXXDefaultInitExpr>(InitExpr));
9999 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10000 if (Field->isBitField())
10001 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10002 Field);
10003 return true;
10006 return false;
10009 if (!Result.hasValue())
10010 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10011 std::distance(RD->field_begin(), RD->field_end()));
10012 unsigned ElementNo = 0;
10013 bool Success = true;
10015 // Initialize base classes.
10016 if (CXXRD && CXXRD->getNumBases()) {
10017 for (const auto &Base : CXXRD->bases()) {
10018 assert(ElementNo < Args.size() && "missing init for base class");
10019 const Expr *Init = Args[ElementNo];
10021 LValue Subobject = This;
10022 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10023 return false;
10025 APValue &FieldVal = Result.getStructBase(ElementNo);
10026 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10027 if (!Info.noteFailure())
10028 return false;
10029 Success = false;
10031 ++ElementNo;
10034 EvalObj.finishedConstructingBases();
10037 // Initialize members.
10038 for (const auto *Field : RD->fields()) {
10039 // Anonymous bit-fields are not considered members of the class for
10040 // purposes of aggregate initialization.
10041 if (Field->isUnnamedBitfield())
10042 continue;
10044 LValue Subobject = This;
10046 bool HaveInit = ElementNo < Args.size();
10048 // FIXME: Diagnostics here should point to the end of the initializer
10049 // list, not the start.
10050 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10051 Subobject, Field, &Layout))
10052 return false;
10054 // Perform an implicit value-initialization for members beyond the end of
10055 // the initializer list.
10056 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10057 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10059 if (Field->getType()->isIncompleteArrayType()) {
10060 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10061 if (!CAT->getSize().isZero()) {
10062 // Bail out for now. This might sort of "work", but the rest of the
10063 // code isn't really prepared to handle it.
10064 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10065 return false;
10070 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10071 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10072 isa<CXXDefaultInitExpr>(Init));
10074 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10075 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10076 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10077 FieldVal, Field))) {
10078 if (!Info.noteFailure())
10079 return false;
10080 Success = false;
10084 EvalObj.finishedConstructingFields();
10086 return Success;
10089 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10090 QualType T) {
10091 // Note that E's type is not necessarily the type of our class here; we might
10092 // be initializing an array element instead.
10093 const CXXConstructorDecl *FD = E->getConstructor();
10094 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10096 bool ZeroInit = E->requiresZeroInitialization();
10097 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10098 // If we've already performed zero-initialization, we're already done.
10099 if (Result.hasValue())
10100 return true;
10102 if (ZeroInit)
10103 return ZeroInitialization(E, T);
10105 return getDefaultInitValue(T, Result);
10108 const FunctionDecl *Definition = nullptr;
10109 auto Body = FD->getBody(Definition);
10111 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10112 return false;
10114 // Avoid materializing a temporary for an elidable copy/move constructor.
10115 if (E->isElidable() && !ZeroInit) {
10116 // FIXME: This only handles the simplest case, where the source object
10117 // is passed directly as the first argument to the constructor.
10118 // This should also handle stepping though implicit casts and
10119 // and conversion sequences which involve two steps, with a
10120 // conversion operator followed by a converting constructor.
10121 const Expr *SrcObj = E->getArg(0);
10122 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10123 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10124 if (const MaterializeTemporaryExpr *ME =
10125 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10126 return Visit(ME->getSubExpr());
10129 if (ZeroInit && !ZeroInitialization(E, T))
10130 return false;
10132 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10133 return HandleConstructorCall(E, This, Args,
10134 cast<CXXConstructorDecl>(Definition), Info,
10135 Result);
10138 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10139 const CXXInheritedCtorInitExpr *E) {
10140 if (!Info.CurrentCall) {
10141 assert(Info.checkingPotentialConstantExpression());
10142 return false;
10145 const CXXConstructorDecl *FD = E->getConstructor();
10146 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10147 return false;
10149 const FunctionDecl *Definition = nullptr;
10150 auto Body = FD->getBody(Definition);
10152 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10153 return false;
10155 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10156 cast<CXXConstructorDecl>(Definition), Info,
10157 Result);
10160 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10161 const CXXStdInitializerListExpr *E) {
10162 const ConstantArrayType *ArrayType =
10163 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10165 LValue Array;
10166 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10167 return false;
10169 // Get a pointer to the first element of the array.
10170 Array.addArray(Info, E, ArrayType);
10172 auto InvalidType = [&] {
10173 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
10174 << E->getType();
10175 return false;
10178 // FIXME: Perform the checks on the field types in SemaInit.
10179 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10180 RecordDecl::field_iterator Field = Record->field_begin();
10181 if (Field == Record->field_end())
10182 return InvalidType();
10184 // Start pointer.
10185 if (!Field->getType()->isPointerType() ||
10186 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10187 ArrayType->getElementType()))
10188 return InvalidType();
10190 // FIXME: What if the initializer_list type has base classes, etc?
10191 Result = APValue(APValue::UninitStruct(), 0, 2);
10192 Array.moveInto(Result.getStructField(0));
10194 if (++Field == Record->field_end())
10195 return InvalidType();
10197 if (Field->getType()->isPointerType() &&
10198 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10199 ArrayType->getElementType())) {
10200 // End pointer.
10201 if (!HandleLValueArrayAdjustment(Info, E, Array,
10202 ArrayType->getElementType(),
10203 ArrayType->getSize().getZExtValue()))
10204 return false;
10205 Array.moveInto(Result.getStructField(1));
10206 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10207 // Length.
10208 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10209 else
10210 return InvalidType();
10212 if (++Field != Record->field_end())
10213 return InvalidType();
10215 return true;
10218 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10219 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10220 if (ClosureClass->isInvalidDecl())
10221 return false;
10223 const size_t NumFields =
10224 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10226 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10227 E->capture_init_end()) &&
10228 "The number of lambda capture initializers should equal the number of "
10229 "fields within the closure type");
10231 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10232 // Iterate through all the lambda's closure object's fields and initialize
10233 // them.
10234 auto *CaptureInitIt = E->capture_init_begin();
10235 bool Success = true;
10236 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10237 for (const auto *Field : ClosureClass->fields()) {
10238 assert(CaptureInitIt != E->capture_init_end());
10239 // Get the initializer for this field
10240 Expr *const CurFieldInit = *CaptureInitIt++;
10242 // If there is no initializer, either this is a VLA or an error has
10243 // occurred.
10244 if (!CurFieldInit)
10245 return Error(E);
10247 LValue Subobject = This;
10249 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10250 return false;
10252 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10253 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10254 if (!Info.keepEvaluatingAfterFailure())
10255 return false;
10256 Success = false;
10259 return Success;
10262 static bool EvaluateRecord(const Expr *E, const LValue &This,
10263 APValue &Result, EvalInfo &Info) {
10264 assert(!E->isValueDependent());
10265 assert(E->isPRValue() && E->getType()->isRecordType() &&
10266 "can't evaluate expression as a record rvalue");
10267 return RecordExprEvaluator(Info, This, Result).Visit(E);
10270 //===----------------------------------------------------------------------===//
10271 // Temporary Evaluation
10273 // Temporaries are represented in the AST as rvalues, but generally behave like
10274 // lvalues. The full-object of which the temporary is a subobject is implicitly
10275 // materialized so that a reference can bind to it.
10276 //===----------------------------------------------------------------------===//
10277 namespace {
10278 class TemporaryExprEvaluator
10279 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10280 public:
10281 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10282 LValueExprEvaluatorBaseTy(Info, Result, false) {}
10284 /// Visit an expression which constructs the value of this temporary.
10285 bool VisitConstructExpr(const Expr *E) {
10286 APValue &Value = Info.CurrentCall->createTemporary(
10287 E, E->getType(), ScopeKind::FullExpression, Result);
10288 return EvaluateInPlace(Value, Info, Result, E);
10291 bool VisitCastExpr(const CastExpr *E) {
10292 switch (E->getCastKind()) {
10293 default:
10294 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10296 case CK_ConstructorConversion:
10297 return VisitConstructExpr(E->getSubExpr());
10300 bool VisitInitListExpr(const InitListExpr *E) {
10301 return VisitConstructExpr(E);
10303 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10304 return VisitConstructExpr(E);
10306 bool VisitCallExpr(const CallExpr *E) {
10307 return VisitConstructExpr(E);
10309 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10310 return VisitConstructExpr(E);
10312 bool VisitLambdaExpr(const LambdaExpr *E) {
10313 return VisitConstructExpr(E);
10316 } // end anonymous namespace
10318 /// Evaluate an expression of record type as a temporary.
10319 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10320 assert(!E->isValueDependent());
10321 assert(E->isPRValue() && E->getType()->isRecordType());
10322 return TemporaryExprEvaluator(Info, Result).Visit(E);
10325 //===----------------------------------------------------------------------===//
10326 // Vector Evaluation
10327 //===----------------------------------------------------------------------===//
10329 namespace {
10330 class VectorExprEvaluator
10331 : public ExprEvaluatorBase<VectorExprEvaluator> {
10332 APValue &Result;
10333 public:
10335 VectorExprEvaluator(EvalInfo &info, APValue &Result)
10336 : ExprEvaluatorBaseTy(info), Result(Result) {}
10338 bool Success(ArrayRef<APValue> V, const Expr *E) {
10339 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10340 // FIXME: remove this APValue copy.
10341 Result = APValue(V.data(), V.size());
10342 return true;
10344 bool Success(const APValue &V, const Expr *E) {
10345 assert(V.isVector());
10346 Result = V;
10347 return true;
10349 bool ZeroInitialization(const Expr *E);
10351 bool VisitUnaryReal(const UnaryOperator *E)
10352 { return Visit(E->getSubExpr()); }
10353 bool VisitCastExpr(const CastExpr* E);
10354 bool VisitInitListExpr(const InitListExpr *E);
10355 bool VisitUnaryImag(const UnaryOperator *E);
10356 bool VisitBinaryOperator(const BinaryOperator *E);
10357 bool VisitUnaryOperator(const UnaryOperator *E);
10358 // FIXME: Missing: conditional operator (for GNU
10359 // conditional select), shufflevector, ExtVectorElementExpr
10361 } // end anonymous namespace
10363 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10364 assert(E->isPRValue() && E->getType()->isVectorType() &&
10365 "not a vector prvalue");
10366 return VectorExprEvaluator(Info, Result).Visit(E);
10369 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10370 const VectorType *VTy = E->getType()->castAs<VectorType>();
10371 unsigned NElts = VTy->getNumElements();
10373 const Expr *SE = E->getSubExpr();
10374 QualType SETy = SE->getType();
10376 switch (E->getCastKind()) {
10377 case CK_VectorSplat: {
10378 APValue Val = APValue();
10379 if (SETy->isIntegerType()) {
10380 APSInt IntResult;
10381 if (!EvaluateInteger(SE, IntResult, Info))
10382 return false;
10383 Val = APValue(std::move(IntResult));
10384 } else if (SETy->isRealFloatingType()) {
10385 APFloat FloatResult(0.0);
10386 if (!EvaluateFloat(SE, FloatResult, Info))
10387 return false;
10388 Val = APValue(std::move(FloatResult));
10389 } else {
10390 return Error(E);
10393 // Splat and create vector APValue.
10394 SmallVector<APValue, 4> Elts(NElts, Val);
10395 return Success(Elts, E);
10397 case CK_BitCast: {
10398 // Evaluate the operand into an APInt we can extract from.
10399 llvm::APInt SValInt;
10400 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10401 return false;
10402 // Extract the elements
10403 QualType EltTy = VTy->getElementType();
10404 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10405 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10406 SmallVector<APValue, 4> Elts;
10407 if (EltTy->isRealFloatingType()) {
10408 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10409 unsigned FloatEltSize = EltSize;
10410 if (&Sem == &APFloat::x87DoubleExtended())
10411 FloatEltSize = 80;
10412 for (unsigned i = 0; i < NElts; i++) {
10413 llvm::APInt Elt;
10414 if (BigEndian)
10415 Elt = SValInt.rotl(i * EltSize + FloatEltSize).trunc(FloatEltSize);
10416 else
10417 Elt = SValInt.rotr(i * EltSize).trunc(FloatEltSize);
10418 Elts.push_back(APValue(APFloat(Sem, Elt)));
10420 } else if (EltTy->isIntegerType()) {
10421 for (unsigned i = 0; i < NElts; i++) {
10422 llvm::APInt Elt;
10423 if (BigEndian)
10424 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10425 else
10426 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10427 Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10429 } else {
10430 return Error(E);
10432 return Success(Elts, E);
10434 default:
10435 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10439 bool
10440 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10441 const VectorType *VT = E->getType()->castAs<VectorType>();
10442 unsigned NumInits = E->getNumInits();
10443 unsigned NumElements = VT->getNumElements();
10445 QualType EltTy = VT->getElementType();
10446 SmallVector<APValue, 4> Elements;
10448 // The number of initializers can be less than the number of
10449 // vector elements. For OpenCL, this can be due to nested vector
10450 // initialization. For GCC compatibility, missing trailing elements
10451 // should be initialized with zeroes.
10452 unsigned CountInits = 0, CountElts = 0;
10453 while (CountElts < NumElements) {
10454 // Handle nested vector initialization.
10455 if (CountInits < NumInits
10456 && E->getInit(CountInits)->getType()->isVectorType()) {
10457 APValue v;
10458 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10459 return Error(E);
10460 unsigned vlen = v.getVectorLength();
10461 for (unsigned j = 0; j < vlen; j++)
10462 Elements.push_back(v.getVectorElt(j));
10463 CountElts += vlen;
10464 } else if (EltTy->isIntegerType()) {
10465 llvm::APSInt sInt(32);
10466 if (CountInits < NumInits) {
10467 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10468 return false;
10469 } else // trailing integer zero.
10470 sInt = Info.Ctx.MakeIntValue(0, EltTy);
10471 Elements.push_back(APValue(sInt));
10472 CountElts++;
10473 } else {
10474 llvm::APFloat f(0.0);
10475 if (CountInits < NumInits) {
10476 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10477 return false;
10478 } else // trailing float zero.
10479 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10480 Elements.push_back(APValue(f));
10481 CountElts++;
10483 CountInits++;
10485 return Success(Elements, E);
10488 bool
10489 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10490 const auto *VT = E->getType()->castAs<VectorType>();
10491 QualType EltTy = VT->getElementType();
10492 APValue ZeroElement;
10493 if (EltTy->isIntegerType())
10494 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10495 else
10496 ZeroElement =
10497 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10499 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10500 return Success(Elements, E);
10503 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10504 VisitIgnoredValue(E->getSubExpr());
10505 return ZeroInitialization(E);
10508 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10509 BinaryOperatorKind Op = E->getOpcode();
10510 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10511 "Operation not supported on vector types");
10513 if (Op == BO_Comma)
10514 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10516 Expr *LHS = E->getLHS();
10517 Expr *RHS = E->getRHS();
10519 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10520 "Must both be vector types");
10521 // Checking JUST the types are the same would be fine, except shifts don't
10522 // need to have their types be the same (since you always shift by an int).
10523 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10524 E->getType()->castAs<VectorType>()->getNumElements() &&
10525 RHS->getType()->castAs<VectorType>()->getNumElements() ==
10526 E->getType()->castAs<VectorType>()->getNumElements() &&
10527 "All operands must be the same size.");
10529 APValue LHSValue;
10530 APValue RHSValue;
10531 bool LHSOK = Evaluate(LHSValue, Info, LHS);
10532 if (!LHSOK && !Info.noteFailure())
10533 return false;
10534 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10535 return false;
10537 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10538 return false;
10540 return Success(LHSValue, E);
10543 static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
10544 QualType ResultTy,
10545 UnaryOperatorKind Op,
10546 APValue Elt) {
10547 switch (Op) {
10548 case UO_Plus:
10549 // Nothing to do here.
10550 return Elt;
10551 case UO_Minus:
10552 if (Elt.getKind() == APValue::Int) {
10553 Elt.getInt().negate();
10554 } else {
10555 assert(Elt.getKind() == APValue::Float &&
10556 "Vector can only be int or float type");
10557 Elt.getFloat().changeSign();
10559 return Elt;
10560 case UO_Not:
10561 // This is only valid for integral types anyway, so we don't have to handle
10562 // float here.
10563 assert(Elt.getKind() == APValue::Int &&
10564 "Vector operator ~ can only be int");
10565 Elt.getInt().flipAllBits();
10566 return Elt;
10567 case UO_LNot: {
10568 if (Elt.getKind() == APValue::Int) {
10569 Elt.getInt() = !Elt.getInt();
10570 // operator ! on vectors returns -1 for 'truth', so negate it.
10571 Elt.getInt().negate();
10572 return Elt;
10574 assert(Elt.getKind() == APValue::Float &&
10575 "Vector can only be int or float type");
10576 // Float types result in an int of the same size, but -1 for true, or 0 for
10577 // false.
10578 APSInt EltResult{Ctx.getIntWidth(ResultTy),
10579 ResultTy->isUnsignedIntegerType()};
10580 if (Elt.getFloat().isZero())
10581 EltResult.setAllBits();
10582 else
10583 EltResult.clearAllBits();
10585 return APValue{EltResult};
10587 default:
10588 // FIXME: Implement the rest of the unary operators.
10589 return std::nullopt;
10593 bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10594 Expr *SubExpr = E->getSubExpr();
10595 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10596 // This result element type differs in the case of negating a floating point
10597 // vector, since the result type is the a vector of the equivilant sized
10598 // integer.
10599 const QualType ResultEltTy = VD->getElementType();
10600 UnaryOperatorKind Op = E->getOpcode();
10602 APValue SubExprValue;
10603 if (!Evaluate(SubExprValue, Info, SubExpr))
10604 return false;
10606 // FIXME: This vector evaluator someday needs to be changed to be LValue
10607 // aware/keep LValue information around, rather than dealing with just vector
10608 // types directly. Until then, we cannot handle cases where the operand to
10609 // these unary operators is an LValue. The only case I've been able to see
10610 // cause this is operator++ assigning to a member expression (only valid in
10611 // altivec compilations) in C mode, so this shouldn't limit us too much.
10612 if (SubExprValue.isLValue())
10613 return false;
10615 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10616 "Vector length doesn't match type?");
10618 SmallVector<APValue, 4> ResultElements;
10619 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
10620 std::optional<APValue> Elt = handleVectorUnaryOperator(
10621 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
10622 if (!Elt)
10623 return false;
10624 ResultElements.push_back(*Elt);
10626 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
10629 //===----------------------------------------------------------------------===//
10630 // Array Evaluation
10631 //===----------------------------------------------------------------------===//
10633 namespace {
10634 class ArrayExprEvaluator
10635 : public ExprEvaluatorBase<ArrayExprEvaluator> {
10636 const LValue &This;
10637 APValue &Result;
10638 public:
10640 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10641 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10643 bool Success(const APValue &V, const Expr *E) {
10644 assert(V.isArray() && "expected array");
10645 Result = V;
10646 return true;
10649 bool ZeroInitialization(const Expr *E) {
10650 const ConstantArrayType *CAT =
10651 Info.Ctx.getAsConstantArrayType(E->getType());
10652 if (!CAT) {
10653 if (E->getType()->isIncompleteArrayType()) {
10654 // We can be asked to zero-initialize a flexible array member; this
10655 // is represented as an ImplicitValueInitExpr of incomplete array
10656 // type. In this case, the array has zero elements.
10657 Result = APValue(APValue::UninitArray(), 0, 0);
10658 return true;
10660 // FIXME: We could handle VLAs here.
10661 return Error(E);
10664 Result = APValue(APValue::UninitArray(), 0,
10665 CAT->getSize().getZExtValue());
10666 if (!Result.hasArrayFiller())
10667 return true;
10669 // Zero-initialize all elements.
10670 LValue Subobject = This;
10671 Subobject.addArray(Info, E, CAT);
10672 ImplicitValueInitExpr VIE(CAT->getElementType());
10673 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10676 bool VisitCallExpr(const CallExpr *E) {
10677 return handleCallExpr(E, Result, &This);
10679 bool VisitInitListExpr(const InitListExpr *E,
10680 QualType AllocType = QualType());
10681 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10682 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10683 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10684 const LValue &Subobject,
10685 APValue *Value, QualType Type);
10686 bool VisitStringLiteral(const StringLiteral *E,
10687 QualType AllocType = QualType()) {
10688 expandStringLiteral(Info, E, Result, AllocType);
10689 return true;
10691 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10692 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10693 ArrayRef<Expr *> Args,
10694 const Expr *ArrayFiller,
10695 QualType AllocType = QualType());
10697 } // end anonymous namespace
10699 static bool EvaluateArray(const Expr *E, const LValue &This,
10700 APValue &Result, EvalInfo &Info) {
10701 assert(!E->isValueDependent());
10702 assert(E->isPRValue() && E->getType()->isArrayType() &&
10703 "not an array prvalue");
10704 return ArrayExprEvaluator(Info, This, Result).Visit(E);
10707 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10708 APValue &Result, const InitListExpr *ILE,
10709 QualType AllocType) {
10710 assert(!ILE->isValueDependent());
10711 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10712 "not an array prvalue");
10713 return ArrayExprEvaluator(Info, This, Result)
10714 .VisitInitListExpr(ILE, AllocType);
10717 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10718 APValue &Result,
10719 const CXXConstructExpr *CCE,
10720 QualType AllocType) {
10721 assert(!CCE->isValueDependent());
10722 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10723 "not an array prvalue");
10724 return ArrayExprEvaluator(Info, This, Result)
10725 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10728 // Return true iff the given array filler may depend on the element index.
10729 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10730 // For now, just allow non-class value-initialization and initialization
10731 // lists comprised of them.
10732 if (isa<ImplicitValueInitExpr>(FillerExpr))
10733 return false;
10734 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10735 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10736 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10737 return true;
10740 if (ILE->hasArrayFiller() &&
10741 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
10742 return true;
10744 return false;
10746 return true;
10749 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10750 QualType AllocType) {
10751 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10752 AllocType.isNull() ? E->getType() : AllocType);
10753 if (!CAT)
10754 return Error(E);
10756 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10757 // an appropriately-typed string literal enclosed in braces.
10758 if (E->isStringLiteralInit()) {
10759 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10760 // FIXME: Support ObjCEncodeExpr here once we support it in
10761 // ArrayExprEvaluator generally.
10762 if (!SL)
10763 return Error(E);
10764 return VisitStringLiteral(SL, AllocType);
10766 // Any other transparent list init will need proper handling of the
10767 // AllocType; we can't just recurse to the inner initializer.
10768 assert(!E->isTransparent() &&
10769 "transparent array list initialization is not string literal init?");
10771 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
10772 AllocType);
10775 bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
10776 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
10777 QualType AllocType) {
10778 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10779 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
10781 bool Success = true;
10783 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10784 "zero-initialized array shouldn't have any initialized elts");
10785 APValue Filler;
10786 if (Result.isArray() && Result.hasArrayFiller())
10787 Filler = Result.getArrayFiller();
10789 unsigned NumEltsToInit = Args.size();
10790 unsigned NumElts = CAT->getSize().getZExtValue();
10792 // If the initializer might depend on the array index, run it for each
10793 // array element.
10794 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(ArrayFiller))
10795 NumEltsToInit = NumElts;
10797 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10798 << NumEltsToInit << ".\n");
10800 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10802 // If the array was previously zero-initialized, preserve the
10803 // zero-initialized values.
10804 if (Filler.hasValue()) {
10805 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10806 Result.getArrayInitializedElt(I) = Filler;
10807 if (Result.hasArrayFiller())
10808 Result.getArrayFiller() = Filler;
10811 LValue Subobject = This;
10812 Subobject.addArray(Info, ExprToVisit, CAT);
10813 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10814 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
10815 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10816 Info, Subobject, Init) ||
10817 !HandleLValueArrayAdjustment(Info, Init, Subobject,
10818 CAT->getElementType(), 1)) {
10819 if (!Info.noteFailure())
10820 return false;
10821 Success = false;
10825 if (!Result.hasArrayFiller())
10826 return Success;
10828 // If we get here, we have a trivial filler, which we can just evaluate
10829 // once and splat over the rest of the array elements.
10830 assert(ArrayFiller && "no array filler for incomplete init list");
10831 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10832 ArrayFiller) &&
10833 Success;
10836 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10837 LValue CommonLV;
10838 if (E->getCommonExpr() &&
10839 !Evaluate(Info.CurrentCall->createTemporary(
10840 E->getCommonExpr(),
10841 getStorageType(Info.Ctx, E->getCommonExpr()),
10842 ScopeKind::FullExpression, CommonLV),
10843 Info, E->getCommonExpr()->getSourceExpr()))
10844 return false;
10846 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10848 uint64_t Elements = CAT->getSize().getZExtValue();
10849 Result = APValue(APValue::UninitArray(), Elements, Elements);
10851 LValue Subobject = This;
10852 Subobject.addArray(Info, E, CAT);
10854 bool Success = true;
10855 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10856 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10857 Info, Subobject, E->getSubExpr()) ||
10858 !HandleLValueArrayAdjustment(Info, E, Subobject,
10859 CAT->getElementType(), 1)) {
10860 if (!Info.noteFailure())
10861 return false;
10862 Success = false;
10866 return Success;
10869 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10870 return VisitCXXConstructExpr(E, This, &Result, E->getType());
10873 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10874 const LValue &Subobject,
10875 APValue *Value,
10876 QualType Type) {
10877 bool HadZeroInit = Value->hasValue();
10879 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10880 unsigned FinalSize = CAT->getSize().getZExtValue();
10882 // Preserve the array filler if we had prior zero-initialization.
10883 APValue Filler =
10884 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10885 : APValue();
10887 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
10888 if (FinalSize == 0)
10889 return true;
10891 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
10892 Info, E->getExprLoc(), E->getConstructor(),
10893 E->requiresZeroInitialization());
10894 LValue ArrayElt = Subobject;
10895 ArrayElt.addArray(Info, E, CAT);
10896 // We do the whole initialization in two passes, first for just one element,
10897 // then for the whole array. It's possible we may find out we can't do const
10898 // init in the first pass, in which case we avoid allocating a potentially
10899 // large array. We don't do more passes because expanding array requires
10900 // copying the data, which is wasteful.
10901 for (const unsigned N : {1u, FinalSize}) {
10902 unsigned OldElts = Value->getArrayInitializedElts();
10903 if (OldElts == N)
10904 break;
10906 // Expand the array to appropriate size.
10907 APValue NewValue(APValue::UninitArray(), N, FinalSize);
10908 for (unsigned I = 0; I < OldElts; ++I)
10909 NewValue.getArrayInitializedElt(I).swap(
10910 Value->getArrayInitializedElt(I));
10911 Value->swap(NewValue);
10913 if (HadZeroInit)
10914 for (unsigned I = OldElts; I < N; ++I)
10915 Value->getArrayInitializedElt(I) = Filler;
10917 if (HasTrivialConstructor && N == FinalSize) {
10918 // If we have a trivial constructor, only evaluate it once and copy
10919 // the result into all the array elements.
10920 APValue &FirstResult = Value->getArrayInitializedElt(0);
10921 for (unsigned I = OldElts; I < FinalSize; ++I)
10922 Value->getArrayInitializedElt(I) = FirstResult;
10923 } else {
10924 for (unsigned I = OldElts; I < N; ++I) {
10925 if (!VisitCXXConstructExpr(E, ArrayElt,
10926 &Value->getArrayInitializedElt(I),
10927 CAT->getElementType()) ||
10928 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10929 CAT->getElementType(), 1))
10930 return false;
10931 // When checking for const initilization any diagnostic is considered
10932 // an error.
10933 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
10934 !Info.keepEvaluatingAfterFailure())
10935 return false;
10940 return true;
10943 if (!Type->isRecordType())
10944 return Error(E);
10946 return RecordExprEvaluator(Info, Subobject, *Value)
10947 .VisitCXXConstructExpr(E, Type);
10950 bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
10951 const CXXParenListInitExpr *E) {
10952 assert(dyn_cast<ConstantArrayType>(E->getType()) &&
10953 "Expression result is not a constant array type");
10955 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
10956 E->getArrayFiller());
10959 //===----------------------------------------------------------------------===//
10960 // Integer Evaluation
10962 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10963 // types and back in constant folding. Integer values are thus represented
10964 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10965 //===----------------------------------------------------------------------===//
10967 namespace {
10968 class IntExprEvaluator
10969 : public ExprEvaluatorBase<IntExprEvaluator> {
10970 APValue &Result;
10971 public:
10972 IntExprEvaluator(EvalInfo &info, APValue &result)
10973 : ExprEvaluatorBaseTy(info), Result(result) {}
10975 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10976 assert(E->getType()->isIntegralOrEnumerationType() &&
10977 "Invalid evaluation result.");
10978 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10979 "Invalid evaluation result.");
10980 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10981 "Invalid evaluation result.");
10982 Result = APValue(SI);
10983 return true;
10985 bool Success(const llvm::APSInt &SI, const Expr *E) {
10986 return Success(SI, E, Result);
10989 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10990 assert(E->getType()->isIntegralOrEnumerationType() &&
10991 "Invalid evaluation result.");
10992 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10993 "Invalid evaluation result.");
10994 Result = APValue(APSInt(I));
10995 Result.getInt().setIsUnsigned(
10996 E->getType()->isUnsignedIntegerOrEnumerationType());
10997 return true;
10999 bool Success(const llvm::APInt &I, const Expr *E) {
11000 return Success(I, E, Result);
11003 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11004 assert(E->getType()->isIntegralOrEnumerationType() &&
11005 "Invalid evaluation result.");
11006 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11007 return true;
11009 bool Success(uint64_t Value, const Expr *E) {
11010 return Success(Value, E, Result);
11013 bool Success(CharUnits Size, const Expr *E) {
11014 return Success(Size.getQuantity(), E);
11017 bool Success(const APValue &V, const Expr *E) {
11018 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
11019 Result = V;
11020 return true;
11022 return Success(V.getInt(), E);
11025 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11027 //===--------------------------------------------------------------------===//
11028 // Visitor Methods
11029 //===--------------------------------------------------------------------===//
11031 bool VisitIntegerLiteral(const IntegerLiteral *E) {
11032 return Success(E->getValue(), E);
11034 bool VisitCharacterLiteral(const CharacterLiteral *E) {
11035 return Success(E->getValue(), E);
11038 bool CheckReferencedDecl(const Expr *E, const Decl *D);
11039 bool VisitDeclRefExpr(const DeclRefExpr *E) {
11040 if (CheckReferencedDecl(E, E->getDecl()))
11041 return true;
11043 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
11045 bool VisitMemberExpr(const MemberExpr *E) {
11046 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11047 VisitIgnoredBaseExpression(E->getBase());
11048 return true;
11051 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
11054 bool VisitCallExpr(const CallExpr *E);
11055 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
11056 bool VisitBinaryOperator(const BinaryOperator *E);
11057 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
11058 bool VisitUnaryOperator(const UnaryOperator *E);
11060 bool VisitCastExpr(const CastExpr* E);
11061 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
11063 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
11064 return Success(E->getValue(), E);
11067 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
11068 return Success(E->getValue(), E);
11071 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
11072 if (Info.ArrayInitIndex == uint64_t(-1)) {
11073 // We were asked to evaluate this subexpression independent of the
11074 // enclosing ArrayInitLoopExpr. We can't do that.
11075 Info.FFDiag(E);
11076 return false;
11078 return Success(Info.ArrayInitIndex, E);
11081 // Note, GNU defines __null as an integer, not a pointer.
11082 bool VisitGNUNullExpr(const GNUNullExpr *E) {
11083 return ZeroInitialization(E);
11086 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
11087 return Success(E->getValue(), E);
11090 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
11091 return Success(E->getValue(), E);
11094 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
11095 return Success(E->getValue(), E);
11098 bool VisitUnaryReal(const UnaryOperator *E);
11099 bool VisitUnaryImag(const UnaryOperator *E);
11101 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
11102 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
11103 bool VisitSourceLocExpr(const SourceLocExpr *E);
11104 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
11105 bool VisitRequiresExpr(const RequiresExpr *E);
11106 // FIXME: Missing: array subscript of vector, member of vector
11109 class FixedPointExprEvaluator
11110 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
11111 APValue &Result;
11113 public:
11114 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
11115 : ExprEvaluatorBaseTy(info), Result(result) {}
11117 bool Success(const llvm::APInt &I, const Expr *E) {
11118 return Success(
11119 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11122 bool Success(uint64_t Value, const Expr *E) {
11123 return Success(
11124 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11127 bool Success(const APValue &V, const Expr *E) {
11128 return Success(V.getFixedPoint(), E);
11131 bool Success(const APFixedPoint &V, const Expr *E) {
11132 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11133 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11134 "Invalid evaluation result.");
11135 Result = APValue(V);
11136 return true;
11139 //===--------------------------------------------------------------------===//
11140 // Visitor Methods
11141 //===--------------------------------------------------------------------===//
11143 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
11144 return Success(E->getValue(), E);
11147 bool VisitCastExpr(const CastExpr *E);
11148 bool VisitUnaryOperator(const UnaryOperator *E);
11149 bool VisitBinaryOperator(const BinaryOperator *E);
11151 } // end anonymous namespace
11153 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11154 /// produce either the integer value or a pointer.
11156 /// GCC has a heinous extension which folds casts between pointer types and
11157 /// pointer-sized integral types. We support this by allowing the evaluation of
11158 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
11159 /// Some simple arithmetic on such values is supported (they are treated much
11160 /// like char*).
11161 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
11162 EvalInfo &Info) {
11163 assert(!E->isValueDependent());
11164 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11165 return IntExprEvaluator(Info, Result).Visit(E);
11168 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
11169 assert(!E->isValueDependent());
11170 APValue Val;
11171 if (!EvaluateIntegerOrLValue(E, Val, Info))
11172 return false;
11173 if (!Val.isInt()) {
11174 // FIXME: It would be better to produce the diagnostic for casting
11175 // a pointer to an integer.
11176 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11177 return false;
11179 Result = Val.getInt();
11180 return true;
11183 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
11184 APValue Evaluated = E->EvaluateInContext(
11185 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11186 return Success(Evaluated, E);
11189 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
11190 EvalInfo &Info) {
11191 assert(!E->isValueDependent());
11192 if (E->getType()->isFixedPointType()) {
11193 APValue Val;
11194 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
11195 return false;
11196 if (!Val.isFixedPoint())
11197 return false;
11199 Result = Val.getFixedPoint();
11200 return true;
11202 return false;
11205 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
11206 EvalInfo &Info) {
11207 assert(!E->isValueDependent());
11208 if (E->getType()->isIntegerType()) {
11209 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11210 APSInt Val;
11211 if (!EvaluateInteger(E, Val, Info))
11212 return false;
11213 Result = APFixedPoint(Val, FXSema);
11214 return true;
11215 } else if (E->getType()->isFixedPointType()) {
11216 return EvaluateFixedPoint(E, Result, Info);
11218 return false;
11221 /// Check whether the given declaration can be directly converted to an integral
11222 /// rvalue. If not, no diagnostic is produced; there are other things we can
11223 /// try.
11224 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
11225 // Enums are integer constant exprs.
11226 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
11227 // Check for signedness/width mismatches between E type and ECD value.
11228 bool SameSign = (ECD->getInitVal().isSigned()
11229 == E->getType()->isSignedIntegerOrEnumerationType());
11230 bool SameWidth = (ECD->getInitVal().getBitWidth()
11231 == Info.Ctx.getIntWidth(E->getType()));
11232 if (SameSign && SameWidth)
11233 return Success(ECD->getInitVal(), E);
11234 else {
11235 // Get rid of mismatch (otherwise Success assertions will fail)
11236 // by computing a new value matching the type of E.
11237 llvm::APSInt Val = ECD->getInitVal();
11238 if (!SameSign)
11239 Val.setIsSigned(!ECD->getInitVal().isSigned());
11240 if (!SameWidth)
11241 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11242 return Success(Val, E);
11245 return false;
11248 /// Values returned by __builtin_classify_type, chosen to match the values
11249 /// produced by GCC's builtin.
11250 enum class GCCTypeClass {
11251 None = -1,
11252 Void = 0,
11253 Integer = 1,
11254 // GCC reserves 2 for character types, but instead classifies them as
11255 // integers.
11256 Enum = 3,
11257 Bool = 4,
11258 Pointer = 5,
11259 // GCC reserves 6 for references, but appears to never use it (because
11260 // expressions never have reference type, presumably).
11261 PointerToDataMember = 7,
11262 RealFloat = 8,
11263 Complex = 9,
11264 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
11265 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
11266 // GCC claims to reserve 11 for pointers to member functions, but *actually*
11267 // uses 12 for that purpose, same as for a class or struct. Maybe it
11268 // internally implements a pointer to member as a struct? Who knows.
11269 PointerToMemberFunction = 12, // Not a bug, see above.
11270 ClassOrStruct = 12,
11271 Union = 13,
11272 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
11273 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
11274 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
11275 // literals.
11278 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11279 /// as GCC.
11280 static GCCTypeClass
11281 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
11282 assert(!T->isDependentType() && "unexpected dependent type");
11284 QualType CanTy = T.getCanonicalType();
11285 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
11287 switch (CanTy->getTypeClass()) {
11288 #define TYPE(ID, BASE)
11289 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
11290 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
11291 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
11292 #include "clang/AST/TypeNodes.inc"
11293 case Type::Auto:
11294 case Type::DeducedTemplateSpecialization:
11295 llvm_unreachable("unexpected non-canonical or dependent type");
11297 case Type::Builtin:
11298 switch (BT->getKind()) {
11299 #define BUILTIN_TYPE(ID, SINGLETON_ID)
11300 #define SIGNED_TYPE(ID, SINGLETON_ID) \
11301 case BuiltinType::ID: return GCCTypeClass::Integer;
11302 #define FLOATING_TYPE(ID, SINGLETON_ID) \
11303 case BuiltinType::ID: return GCCTypeClass::RealFloat;
11304 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
11305 case BuiltinType::ID: break;
11306 #include "clang/AST/BuiltinTypes.def"
11307 case BuiltinType::Void:
11308 return GCCTypeClass::Void;
11310 case BuiltinType::Bool:
11311 return GCCTypeClass::Bool;
11313 case BuiltinType::Char_U:
11314 case BuiltinType::UChar:
11315 case BuiltinType::WChar_U:
11316 case BuiltinType::Char8:
11317 case BuiltinType::Char16:
11318 case BuiltinType::Char32:
11319 case BuiltinType::UShort:
11320 case BuiltinType::UInt:
11321 case BuiltinType::ULong:
11322 case BuiltinType::ULongLong:
11323 case BuiltinType::UInt128:
11324 return GCCTypeClass::Integer;
11326 case BuiltinType::UShortAccum:
11327 case BuiltinType::UAccum:
11328 case BuiltinType::ULongAccum:
11329 case BuiltinType::UShortFract:
11330 case BuiltinType::UFract:
11331 case BuiltinType::ULongFract:
11332 case BuiltinType::SatUShortAccum:
11333 case BuiltinType::SatUAccum:
11334 case BuiltinType::SatULongAccum:
11335 case BuiltinType::SatUShortFract:
11336 case BuiltinType::SatUFract:
11337 case BuiltinType::SatULongFract:
11338 return GCCTypeClass::None;
11340 case BuiltinType::NullPtr:
11342 case BuiltinType::ObjCId:
11343 case BuiltinType::ObjCClass:
11344 case BuiltinType::ObjCSel:
11345 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11346 case BuiltinType::Id:
11347 #include "clang/Basic/OpenCLImageTypes.def"
11348 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11349 case BuiltinType::Id:
11350 #include "clang/Basic/OpenCLExtensionTypes.def"
11351 case BuiltinType::OCLSampler:
11352 case BuiltinType::OCLEvent:
11353 case BuiltinType::OCLClkEvent:
11354 case BuiltinType::OCLQueue:
11355 case BuiltinType::OCLReserveID:
11356 #define SVE_TYPE(Name, Id, SingletonId) \
11357 case BuiltinType::Id:
11358 #include "clang/Basic/AArch64SVEACLETypes.def"
11359 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11360 case BuiltinType::Id:
11361 #include "clang/Basic/PPCTypes.def"
11362 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11363 #include "clang/Basic/RISCVVTypes.def"
11364 return GCCTypeClass::None;
11366 case BuiltinType::Dependent:
11367 llvm_unreachable("unexpected dependent type");
11369 llvm_unreachable("unexpected placeholder type");
11371 case Type::Enum:
11372 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11374 case Type::Pointer:
11375 case Type::ConstantArray:
11376 case Type::VariableArray:
11377 case Type::IncompleteArray:
11378 case Type::FunctionNoProto:
11379 case Type::FunctionProto:
11380 return GCCTypeClass::Pointer;
11382 case Type::MemberPointer:
11383 return CanTy->isMemberDataPointerType()
11384 ? GCCTypeClass::PointerToDataMember
11385 : GCCTypeClass::PointerToMemberFunction;
11387 case Type::Complex:
11388 return GCCTypeClass::Complex;
11390 case Type::Record:
11391 return CanTy->isUnionType() ? GCCTypeClass::Union
11392 : GCCTypeClass::ClassOrStruct;
11394 case Type::Atomic:
11395 // GCC classifies _Atomic T the same as T.
11396 return EvaluateBuiltinClassifyType(
11397 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11399 case Type::BlockPointer:
11400 case Type::Vector:
11401 case Type::ExtVector:
11402 case Type::ConstantMatrix:
11403 case Type::ObjCObject:
11404 case Type::ObjCInterface:
11405 case Type::ObjCObjectPointer:
11406 case Type::Pipe:
11407 case Type::BitInt:
11408 // GCC classifies vectors as None. We follow its lead and classify all
11409 // other types that don't fit into the regular classification the same way.
11410 return GCCTypeClass::None;
11412 case Type::LValueReference:
11413 case Type::RValueReference:
11414 llvm_unreachable("invalid type for expression");
11417 llvm_unreachable("unexpected type class");
11420 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11421 /// as GCC.
11422 static GCCTypeClass
11423 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11424 // If no argument was supplied, default to None. This isn't
11425 // ideal, however it is what gcc does.
11426 if (E->getNumArgs() == 0)
11427 return GCCTypeClass::None;
11429 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11430 // being an ICE, but still folds it to a constant using the type of the first
11431 // argument.
11432 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11435 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11436 /// __builtin_constant_p when applied to the given pointer.
11438 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11439 /// or it points to the first character of a string literal.
11440 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11441 APValue::LValueBase Base = LV.getLValueBase();
11442 if (Base.isNull()) {
11443 // A null base is acceptable.
11444 return true;
11445 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11446 if (!isa<StringLiteral>(E))
11447 return false;
11448 return LV.getLValueOffset().isZero();
11449 } else if (Base.is<TypeInfoLValue>()) {
11450 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11451 // evaluate to true.
11452 return true;
11453 } else {
11454 // Any other base is not constant enough for GCC.
11455 return false;
11459 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11460 /// GCC as we can manage.
11461 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11462 // This evaluation is not permitted to have side-effects, so evaluate it in
11463 // a speculative evaluation context.
11464 SpeculativeEvaluationRAII SpeculativeEval(Info);
11466 // Constant-folding is always enabled for the operand of __builtin_constant_p
11467 // (even when the enclosing evaluation context otherwise requires a strict
11468 // language-specific constant expression).
11469 FoldConstant Fold(Info, true);
11471 QualType ArgType = Arg->getType();
11473 // __builtin_constant_p always has one operand. The rules which gcc follows
11474 // are not precisely documented, but are as follows:
11476 // - If the operand is of integral, floating, complex or enumeration type,
11477 // and can be folded to a known value of that type, it returns 1.
11478 // - If the operand can be folded to a pointer to the first character
11479 // of a string literal (or such a pointer cast to an integral type)
11480 // or to a null pointer or an integer cast to a pointer, it returns 1.
11482 // Otherwise, it returns 0.
11484 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11485 // its support for this did not work prior to GCC 9 and is not yet well
11486 // understood.
11487 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11488 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11489 ArgType->isNullPtrType()) {
11490 APValue V;
11491 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11492 Fold.keepDiagnostics();
11493 return false;
11496 // For a pointer (possibly cast to integer), there are special rules.
11497 if (V.getKind() == APValue::LValue)
11498 return EvaluateBuiltinConstantPForLValue(V);
11500 // Otherwise, any constant value is good enough.
11501 return V.hasValue();
11504 // Anything else isn't considered to be sufficiently constant.
11505 return false;
11508 /// Retrieves the "underlying object type" of the given expression,
11509 /// as used by __builtin_object_size.
11510 static QualType getObjectType(APValue::LValueBase B) {
11511 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11512 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11513 return VD->getType();
11514 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11515 if (isa<CompoundLiteralExpr>(E))
11516 return E->getType();
11517 } else if (B.is<TypeInfoLValue>()) {
11518 return B.getTypeInfoType();
11519 } else if (B.is<DynamicAllocLValue>()) {
11520 return B.getDynamicAllocType();
11523 return QualType();
11526 /// A more selective version of E->IgnoreParenCasts for
11527 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11528 /// to change the type of E.
11529 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11531 /// Always returns an RValue with a pointer representation.
11532 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11533 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11535 auto *NoParens = E->IgnoreParens();
11536 auto *Cast = dyn_cast<CastExpr>(NoParens);
11537 if (Cast == nullptr)
11538 return NoParens;
11540 // We only conservatively allow a few kinds of casts, because this code is
11541 // inherently a simple solution that seeks to support the common case.
11542 auto CastKind = Cast->getCastKind();
11543 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11544 CastKind != CK_AddressSpaceConversion)
11545 return NoParens;
11547 auto *SubExpr = Cast->getSubExpr();
11548 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11549 return NoParens;
11550 return ignorePointerCastsAndParens(SubExpr);
11553 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11554 /// record layout. e.g.
11555 /// struct { struct { int a, b; } fst, snd; } obj;
11556 /// obj.fst // no
11557 /// obj.snd // yes
11558 /// obj.fst.a // no
11559 /// obj.fst.b // no
11560 /// obj.snd.a // no
11561 /// obj.snd.b // yes
11563 /// Please note: this function is specialized for how __builtin_object_size
11564 /// views "objects".
11566 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11567 /// correct result, it will always return true.
11568 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11569 assert(!LVal.Designator.Invalid);
11571 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11572 const RecordDecl *Parent = FD->getParent();
11573 Invalid = Parent->isInvalidDecl();
11574 if (Invalid || Parent->isUnion())
11575 return true;
11576 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11577 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11580 auto &Base = LVal.getLValueBase();
11581 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11582 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11583 bool Invalid;
11584 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11585 return Invalid;
11586 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11587 for (auto *FD : IFD->chain()) {
11588 bool Invalid;
11589 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11590 return Invalid;
11595 unsigned I = 0;
11596 QualType BaseType = getType(Base);
11597 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11598 // If we don't know the array bound, conservatively assume we're looking at
11599 // the final array element.
11600 ++I;
11601 if (BaseType->isIncompleteArrayType())
11602 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11603 else
11604 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11607 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11608 const auto &Entry = LVal.Designator.Entries[I];
11609 if (BaseType->isArrayType()) {
11610 // Because __builtin_object_size treats arrays as objects, we can ignore
11611 // the index iff this is the last array in the Designator.
11612 if (I + 1 == E)
11613 return true;
11614 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11615 uint64_t Index = Entry.getAsArrayIndex();
11616 if (Index + 1 != CAT->getSize())
11617 return false;
11618 BaseType = CAT->getElementType();
11619 } else if (BaseType->isAnyComplexType()) {
11620 const auto *CT = BaseType->castAs<ComplexType>();
11621 uint64_t Index = Entry.getAsArrayIndex();
11622 if (Index != 1)
11623 return false;
11624 BaseType = CT->getElementType();
11625 } else if (auto *FD = getAsField(Entry)) {
11626 bool Invalid;
11627 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11628 return Invalid;
11629 BaseType = FD->getType();
11630 } else {
11631 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11632 return false;
11635 return true;
11638 /// Tests to see if the LValue has a user-specified designator (that isn't
11639 /// necessarily valid). Note that this always returns 'true' if the LValue has
11640 /// an unsized array as its first designator entry, because there's currently no
11641 /// way to tell if the user typed *foo or foo[0].
11642 static bool refersToCompleteObject(const LValue &LVal) {
11643 if (LVal.Designator.Invalid)
11644 return false;
11646 if (!LVal.Designator.Entries.empty())
11647 return LVal.Designator.isMostDerivedAnUnsizedArray();
11649 if (!LVal.InvalidBase)
11650 return true;
11652 // If `E` is a MemberExpr, then the first part of the designator is hiding in
11653 // the LValueBase.
11654 const auto *E = LVal.Base.dyn_cast<const Expr *>();
11655 return !E || !isa<MemberExpr>(E);
11658 /// Attempts to detect a user writing into a piece of memory that's impossible
11659 /// to figure out the size of by just using types.
11660 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11661 const SubobjectDesignator &Designator = LVal.Designator;
11662 // Notes:
11663 // - Users can only write off of the end when we have an invalid base. Invalid
11664 // bases imply we don't know where the memory came from.
11665 // - We used to be a bit more aggressive here; we'd only be conservative if
11666 // the array at the end was flexible, or if it had 0 or 1 elements. This
11667 // broke some common standard library extensions (PR30346), but was
11668 // otherwise seemingly fine. It may be useful to reintroduce this behavior
11669 // with some sort of list. OTOH, it seems that GCC is always
11670 // conservative with the last element in structs (if it's an array), so our
11671 // current behavior is more compatible than an explicit list approach would
11672 // be.
11673 auto isFlexibleArrayMember = [&] {
11674 using FAMKind = LangOptions::StrictFlexArraysLevelKind;
11675 FAMKind StrictFlexArraysLevel =
11676 Ctx.getLangOpts().getStrictFlexArraysLevel();
11678 if (Designator.isMostDerivedAnUnsizedArray())
11679 return true;
11681 if (StrictFlexArraysLevel == FAMKind::Default)
11682 return true;
11684 if (Designator.getMostDerivedArraySize() == 0 &&
11685 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
11686 return true;
11688 if (Designator.getMostDerivedArraySize() == 1 &&
11689 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
11690 return true;
11692 return false;
11695 return LVal.InvalidBase &&
11696 Designator.Entries.size() == Designator.MostDerivedPathLength &&
11697 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
11698 isDesignatorAtObjectEnd(Ctx, LVal);
11701 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11702 /// Fails if the conversion would cause loss of precision.
11703 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11704 CharUnits &Result) {
11705 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11706 if (Int.ugt(CharUnitsMax))
11707 return false;
11708 Result = CharUnits::fromQuantity(Int.getZExtValue());
11709 return true;
11712 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11713 /// determine how many bytes exist from the beginning of the object to either
11714 /// the end of the current subobject, or the end of the object itself, depending
11715 /// on what the LValue looks like + the value of Type.
11717 /// If this returns false, the value of Result is undefined.
11718 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11719 unsigned Type, const LValue &LVal,
11720 CharUnits &EndOffset) {
11721 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11723 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11724 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11725 return false;
11726 return HandleSizeof(Info, ExprLoc, Ty, Result);
11729 // We want to evaluate the size of the entire object. This is a valid fallback
11730 // for when Type=1 and the designator is invalid, because we're asked for an
11731 // upper-bound.
11732 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11733 // Type=3 wants a lower bound, so we can't fall back to this.
11734 if (Type == 3 && !DetermineForCompleteObject)
11735 return false;
11737 llvm::APInt APEndOffset;
11738 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11739 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11740 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11742 if (LVal.InvalidBase)
11743 return false;
11745 QualType BaseTy = getObjectType(LVal.getLValueBase());
11746 return CheckedHandleSizeof(BaseTy, EndOffset);
11749 // We want to evaluate the size of a subobject.
11750 const SubobjectDesignator &Designator = LVal.Designator;
11752 // The following is a moderately common idiom in C:
11754 // struct Foo { int a; char c[1]; };
11755 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11756 // strcpy(&F->c[0], Bar);
11758 // In order to not break too much legacy code, we need to support it.
11759 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11760 // If we can resolve this to an alloc_size call, we can hand that back,
11761 // because we know for certain how many bytes there are to write to.
11762 llvm::APInt APEndOffset;
11763 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11764 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11765 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11767 // If we cannot determine the size of the initial allocation, then we can't
11768 // given an accurate upper-bound. However, we are still able to give
11769 // conservative lower-bounds for Type=3.
11770 if (Type == 1)
11771 return false;
11774 CharUnits BytesPerElem;
11775 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11776 return false;
11778 // According to the GCC documentation, we want the size of the subobject
11779 // denoted by the pointer. But that's not quite right -- what we actually
11780 // want is the size of the immediately-enclosing array, if there is one.
11781 int64_t ElemsRemaining;
11782 if (Designator.MostDerivedIsArrayElement &&
11783 Designator.Entries.size() == Designator.MostDerivedPathLength) {
11784 uint64_t ArraySize = Designator.getMostDerivedArraySize();
11785 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11786 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11787 } else {
11788 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11791 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11792 return true;
11795 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11796 /// returns true and stores the result in @p Size.
11798 /// If @p WasError is non-null, this will report whether the failure to evaluate
11799 /// is to be treated as an Error in IntExprEvaluator.
11800 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11801 EvalInfo &Info, uint64_t &Size) {
11802 // Determine the denoted object.
11803 LValue LVal;
11805 // The operand of __builtin_object_size is never evaluated for side-effects.
11806 // If there are any, but we can determine the pointed-to object anyway, then
11807 // ignore the side-effects.
11808 SpeculativeEvaluationRAII SpeculativeEval(Info);
11809 IgnoreSideEffectsRAII Fold(Info);
11811 if (E->isGLValue()) {
11812 // It's possible for us to be given GLValues if we're called via
11813 // Expr::tryEvaluateObjectSize.
11814 APValue RVal;
11815 if (!EvaluateAsRValue(Info, E, RVal))
11816 return false;
11817 LVal.setFrom(Info.Ctx, RVal);
11818 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11819 /*InvalidBaseOK=*/true))
11820 return false;
11823 // If we point to before the start of the object, there are no accessible
11824 // bytes.
11825 if (LVal.getLValueOffset().isNegative()) {
11826 Size = 0;
11827 return true;
11830 CharUnits EndOffset;
11831 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11832 return false;
11834 // If we've fallen outside of the end offset, just pretend there's nothing to
11835 // write to/read from.
11836 if (EndOffset <= LVal.getLValueOffset())
11837 Size = 0;
11838 else
11839 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11840 return true;
11843 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11844 if (!IsConstantEvaluatedBuiltinCall(E))
11845 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11846 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
11849 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11850 APValue &Val, APSInt &Alignment) {
11851 QualType SrcTy = E->getArg(0)->getType();
11852 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11853 return false;
11854 // Even though we are evaluating integer expressions we could get a pointer
11855 // argument for the __builtin_is_aligned() case.
11856 if (SrcTy->isPointerType()) {
11857 LValue Ptr;
11858 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11859 return false;
11860 Ptr.moveInto(Val);
11861 } else if (!SrcTy->isIntegralOrEnumerationType()) {
11862 Info.FFDiag(E->getArg(0));
11863 return false;
11864 } else {
11865 APSInt SrcInt;
11866 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11867 return false;
11868 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11869 "Bit widths must be the same");
11870 Val = APValue(SrcInt);
11872 assert(Val.hasValue());
11873 return true;
11876 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11877 unsigned BuiltinOp) {
11878 switch (BuiltinOp) {
11879 default:
11880 return false;
11882 case Builtin::BI__builtin_dynamic_object_size:
11883 case Builtin::BI__builtin_object_size: {
11884 // The type was checked when we built the expression.
11885 unsigned Type =
11886 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11887 assert(Type <= 3 && "unexpected type");
11889 uint64_t Size;
11890 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11891 return Success(Size, E);
11893 if (E->getArg(0)->HasSideEffects(Info.Ctx))
11894 return Success((Type & 2) ? 0 : -1, E);
11896 // Expression had no side effects, but we couldn't statically determine the
11897 // size of the referenced object.
11898 switch (Info.EvalMode) {
11899 case EvalInfo::EM_ConstantExpression:
11900 case EvalInfo::EM_ConstantFold:
11901 case EvalInfo::EM_IgnoreSideEffects:
11902 // Leave it to IR generation.
11903 return Error(E);
11904 case EvalInfo::EM_ConstantExpressionUnevaluated:
11905 // Reduce it to a constant now.
11906 return Success((Type & 2) ? 0 : -1, E);
11909 llvm_unreachable("unexpected EvalMode");
11912 case Builtin::BI__builtin_os_log_format_buffer_size: {
11913 analyze_os_log::OSLogBufferLayout Layout;
11914 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11915 return Success(Layout.size().getQuantity(), E);
11918 case Builtin::BI__builtin_is_aligned: {
11919 APValue Src;
11920 APSInt Alignment;
11921 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11922 return false;
11923 if (Src.isLValue()) {
11924 // If we evaluated a pointer, check the minimum known alignment.
11925 LValue Ptr;
11926 Ptr.setFrom(Info.Ctx, Src);
11927 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11928 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11929 // We can return true if the known alignment at the computed offset is
11930 // greater than the requested alignment.
11931 assert(PtrAlign.isPowerOfTwo());
11932 assert(Alignment.isPowerOf2());
11933 if (PtrAlign.getQuantity() >= Alignment)
11934 return Success(1, E);
11935 // If the alignment is not known to be sufficient, some cases could still
11936 // be aligned at run time. However, if the requested alignment is less or
11937 // equal to the base alignment and the offset is not aligned, we know that
11938 // the run-time value can never be aligned.
11939 if (BaseAlignment.getQuantity() >= Alignment &&
11940 PtrAlign.getQuantity() < Alignment)
11941 return Success(0, E);
11942 // Otherwise we can't infer whether the value is sufficiently aligned.
11943 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11944 // in cases where we can't fully evaluate the pointer.
11945 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11946 << Alignment;
11947 return false;
11949 assert(Src.isInt());
11950 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11952 case Builtin::BI__builtin_align_up: {
11953 APValue Src;
11954 APSInt Alignment;
11955 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11956 return false;
11957 if (!Src.isInt())
11958 return Error(E);
11959 APSInt AlignedVal =
11960 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11961 Src.getInt().isUnsigned());
11962 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11963 return Success(AlignedVal, E);
11965 case Builtin::BI__builtin_align_down: {
11966 APValue Src;
11967 APSInt Alignment;
11968 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11969 return false;
11970 if (!Src.isInt())
11971 return Error(E);
11972 APSInt AlignedVal =
11973 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11974 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11975 return Success(AlignedVal, E);
11978 case Builtin::BI__builtin_bitreverse8:
11979 case Builtin::BI__builtin_bitreverse16:
11980 case Builtin::BI__builtin_bitreverse32:
11981 case Builtin::BI__builtin_bitreverse64: {
11982 APSInt Val;
11983 if (!EvaluateInteger(E->getArg(0), Val, Info))
11984 return false;
11986 return Success(Val.reverseBits(), E);
11989 case Builtin::BI__builtin_bswap16:
11990 case Builtin::BI__builtin_bswap32:
11991 case Builtin::BI__builtin_bswap64: {
11992 APSInt Val;
11993 if (!EvaluateInteger(E->getArg(0), Val, Info))
11994 return false;
11996 return Success(Val.byteSwap(), E);
11999 case Builtin::BI__builtin_classify_type:
12000 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12002 case Builtin::BI__builtin_clrsb:
12003 case Builtin::BI__builtin_clrsbl:
12004 case Builtin::BI__builtin_clrsbll: {
12005 APSInt Val;
12006 if (!EvaluateInteger(E->getArg(0), Val, Info))
12007 return false;
12009 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
12012 case Builtin::BI__builtin_clz:
12013 case Builtin::BI__builtin_clzl:
12014 case Builtin::BI__builtin_clzll:
12015 case Builtin::BI__builtin_clzs: {
12016 APSInt Val;
12017 if (!EvaluateInteger(E->getArg(0), Val, Info))
12018 return false;
12019 if (!Val)
12020 return Error(E);
12022 return Success(Val.countLeadingZeros(), E);
12025 case Builtin::BI__builtin_constant_p: {
12026 const Expr *Arg = E->getArg(0);
12027 if (EvaluateBuiltinConstantP(Info, Arg))
12028 return Success(true, E);
12029 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12030 // Outside a constant context, eagerly evaluate to false in the presence
12031 // of side-effects in order to avoid -Wunsequenced false-positives in
12032 // a branch on __builtin_constant_p(expr).
12033 return Success(false, E);
12035 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12036 return false;
12039 case Builtin::BI__builtin_is_constant_evaluated: {
12040 const auto *Callee = Info.CurrentCall->getCallee();
12041 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
12042 (Info.CallStackDepth == 1 ||
12043 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12044 Callee->getIdentifier() &&
12045 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12046 // FIXME: Find a better way to avoid duplicated diagnostics.
12047 if (Info.EvalStatus.Diag)
12048 Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
12049 : Info.CurrentCall->CallLoc,
12050 diag::warn_is_constant_evaluated_always_true_constexpr)
12051 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
12052 : "std::is_constant_evaluated");
12055 return Success(Info.InConstantContext, E);
12058 case Builtin::BI__builtin_ctz:
12059 case Builtin::BI__builtin_ctzl:
12060 case Builtin::BI__builtin_ctzll:
12061 case Builtin::BI__builtin_ctzs: {
12062 APSInt Val;
12063 if (!EvaluateInteger(E->getArg(0), Val, Info))
12064 return false;
12065 if (!Val)
12066 return Error(E);
12068 return Success(Val.countTrailingZeros(), E);
12071 case Builtin::BI__builtin_eh_return_data_regno: {
12072 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12073 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
12074 return Success(Operand, E);
12077 case Builtin::BI__builtin_expect:
12078 case Builtin::BI__builtin_expect_with_probability:
12079 return Visit(E->getArg(0));
12081 case Builtin::BI__builtin_ffs:
12082 case Builtin::BI__builtin_ffsl:
12083 case Builtin::BI__builtin_ffsll: {
12084 APSInt Val;
12085 if (!EvaluateInteger(E->getArg(0), Val, Info))
12086 return false;
12088 unsigned N = Val.countTrailingZeros();
12089 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
12092 case Builtin::BI__builtin_fpclassify: {
12093 APFloat Val(0.0);
12094 if (!EvaluateFloat(E->getArg(5), Val, Info))
12095 return false;
12096 unsigned Arg;
12097 switch (Val.getCategory()) {
12098 case APFloat::fcNaN: Arg = 0; break;
12099 case APFloat::fcInfinity: Arg = 1; break;
12100 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
12101 case APFloat::fcZero: Arg = 4; break;
12103 return Visit(E->getArg(Arg));
12106 case Builtin::BI__builtin_isinf_sign: {
12107 APFloat Val(0.0);
12108 return EvaluateFloat(E->getArg(0), Val, Info) &&
12109 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12112 case Builtin::BI__builtin_isinf: {
12113 APFloat Val(0.0);
12114 return EvaluateFloat(E->getArg(0), Val, Info) &&
12115 Success(Val.isInfinity() ? 1 : 0, E);
12118 case Builtin::BI__builtin_isfinite: {
12119 APFloat Val(0.0);
12120 return EvaluateFloat(E->getArg(0), Val, Info) &&
12121 Success(Val.isFinite() ? 1 : 0, E);
12124 case Builtin::BI__builtin_isnan: {
12125 APFloat Val(0.0);
12126 return EvaluateFloat(E->getArg(0), Val, Info) &&
12127 Success(Val.isNaN() ? 1 : 0, E);
12130 case Builtin::BI__builtin_isnormal: {
12131 APFloat Val(0.0);
12132 return EvaluateFloat(E->getArg(0), Val, Info) &&
12133 Success(Val.isNormal() ? 1 : 0, E);
12136 case Builtin::BI__builtin_parity:
12137 case Builtin::BI__builtin_parityl:
12138 case Builtin::BI__builtin_parityll: {
12139 APSInt Val;
12140 if (!EvaluateInteger(E->getArg(0), Val, Info))
12141 return false;
12143 return Success(Val.countPopulation() % 2, E);
12146 case Builtin::BI__builtin_popcount:
12147 case Builtin::BI__builtin_popcountl:
12148 case Builtin::BI__builtin_popcountll: {
12149 APSInt Val;
12150 if (!EvaluateInteger(E->getArg(0), Val, Info))
12151 return false;
12153 return Success(Val.countPopulation(), E);
12156 case Builtin::BI__builtin_rotateleft8:
12157 case Builtin::BI__builtin_rotateleft16:
12158 case Builtin::BI__builtin_rotateleft32:
12159 case Builtin::BI__builtin_rotateleft64:
12160 case Builtin::BI_rotl8: // Microsoft variants of rotate right
12161 case Builtin::BI_rotl16:
12162 case Builtin::BI_rotl:
12163 case Builtin::BI_lrotl:
12164 case Builtin::BI_rotl64: {
12165 APSInt Val, Amt;
12166 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12167 !EvaluateInteger(E->getArg(1), Amt, Info))
12168 return false;
12170 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
12173 case Builtin::BI__builtin_rotateright8:
12174 case Builtin::BI__builtin_rotateright16:
12175 case Builtin::BI__builtin_rotateright32:
12176 case Builtin::BI__builtin_rotateright64:
12177 case Builtin::BI_rotr8: // Microsoft variants of rotate right
12178 case Builtin::BI_rotr16:
12179 case Builtin::BI_rotr:
12180 case Builtin::BI_lrotr:
12181 case Builtin::BI_rotr64: {
12182 APSInt Val, Amt;
12183 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12184 !EvaluateInteger(E->getArg(1), Amt, Info))
12185 return false;
12187 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
12190 case Builtin::BIstrlen:
12191 case Builtin::BIwcslen:
12192 // A call to strlen is not a constant expression.
12193 if (Info.getLangOpts().CPlusPlus11)
12194 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12195 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12196 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12197 else
12198 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12199 [[fallthrough]];
12200 case Builtin::BI__builtin_strlen:
12201 case Builtin::BI__builtin_wcslen: {
12202 // As an extension, we support __builtin_strlen() as a constant expression,
12203 // and support folding strlen() to a constant.
12204 uint64_t StrLen;
12205 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12206 return Success(StrLen, E);
12207 return false;
12210 case Builtin::BIstrcmp:
12211 case Builtin::BIwcscmp:
12212 case Builtin::BIstrncmp:
12213 case Builtin::BIwcsncmp:
12214 case Builtin::BImemcmp:
12215 case Builtin::BIbcmp:
12216 case Builtin::BIwmemcmp:
12217 // A call to strlen is not a constant expression.
12218 if (Info.getLangOpts().CPlusPlus11)
12219 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
12220 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
12221 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str();
12222 else
12223 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12224 [[fallthrough]];
12225 case Builtin::BI__builtin_strcmp:
12226 case Builtin::BI__builtin_wcscmp:
12227 case Builtin::BI__builtin_strncmp:
12228 case Builtin::BI__builtin_wcsncmp:
12229 case Builtin::BI__builtin_memcmp:
12230 case Builtin::BI__builtin_bcmp:
12231 case Builtin::BI__builtin_wmemcmp: {
12232 LValue String1, String2;
12233 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12234 !EvaluatePointer(E->getArg(1), String2, Info))
12235 return false;
12237 uint64_t MaxLength = uint64_t(-1);
12238 if (BuiltinOp != Builtin::BIstrcmp &&
12239 BuiltinOp != Builtin::BIwcscmp &&
12240 BuiltinOp != Builtin::BI__builtin_strcmp &&
12241 BuiltinOp != Builtin::BI__builtin_wcscmp) {
12242 APSInt N;
12243 if (!EvaluateInteger(E->getArg(2), N, Info))
12244 return false;
12245 MaxLength = N.getExtValue();
12248 // Empty substrings compare equal by definition.
12249 if (MaxLength == 0u)
12250 return Success(0, E);
12252 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12253 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
12254 String1.Designator.Invalid || String2.Designator.Invalid)
12255 return false;
12257 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
12258 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
12260 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
12261 BuiltinOp == Builtin::BIbcmp ||
12262 BuiltinOp == Builtin::BI__builtin_memcmp ||
12263 BuiltinOp == Builtin::BI__builtin_bcmp;
12265 assert(IsRawByte ||
12266 (Info.Ctx.hasSameUnqualifiedType(
12267 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12268 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
12270 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
12271 // 'char8_t', but no other types.
12272 if (IsRawByte &&
12273 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
12274 // FIXME: Consider using our bit_cast implementation to support this.
12275 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
12276 << ("'" + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'").str()
12277 << CharTy1 << CharTy2;
12278 return false;
12281 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
12282 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
12283 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
12284 Char1.isInt() && Char2.isInt();
12286 const auto &AdvanceElems = [&] {
12287 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
12288 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
12291 bool StopAtNull =
12292 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
12293 BuiltinOp != Builtin::BIwmemcmp &&
12294 BuiltinOp != Builtin::BI__builtin_memcmp &&
12295 BuiltinOp != Builtin::BI__builtin_bcmp &&
12296 BuiltinOp != Builtin::BI__builtin_wmemcmp);
12297 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
12298 BuiltinOp == Builtin::BIwcsncmp ||
12299 BuiltinOp == Builtin::BIwmemcmp ||
12300 BuiltinOp == Builtin::BI__builtin_wcscmp ||
12301 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
12302 BuiltinOp == Builtin::BI__builtin_wmemcmp;
12304 for (; MaxLength; --MaxLength) {
12305 APValue Char1, Char2;
12306 if (!ReadCurElems(Char1, Char2))
12307 return false;
12308 if (Char1.getInt().ne(Char2.getInt())) {
12309 if (IsWide) // wmemcmp compares with wchar_t signedness.
12310 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12311 // memcmp always compares unsigned chars.
12312 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12314 if (StopAtNull && !Char1.getInt())
12315 return Success(0, E);
12316 assert(!(StopAtNull && !Char2.getInt()));
12317 if (!AdvanceElems())
12318 return false;
12320 // We hit the strncmp / memcmp limit.
12321 return Success(0, E);
12324 case Builtin::BI__atomic_always_lock_free:
12325 case Builtin::BI__atomic_is_lock_free:
12326 case Builtin::BI__c11_atomic_is_lock_free: {
12327 APSInt SizeVal;
12328 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12329 return false;
12331 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
12332 // of two less than or equal to the maximum inline atomic width, we know it
12333 // is lock-free. If the size isn't a power of two, or greater than the
12334 // maximum alignment where we promote atomics, we know it is not lock-free
12335 // (at least not in the sense of atomic_is_lock_free). Otherwise,
12336 // the answer can only be determined at runtime; for example, 16-byte
12337 // atomics have lock-free implementations on some, but not all,
12338 // x86-64 processors.
12340 // Check power-of-two.
12341 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
12342 if (Size.isPowerOfTwo()) {
12343 // Check against inlining width.
12344 unsigned InlineWidthBits =
12345 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
12346 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
12347 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
12348 Size == CharUnits::One() ||
12349 E->getArg(1)->isNullPointerConstant(Info.Ctx,
12350 Expr::NPC_NeverValueDependent))
12351 // OK, we will inline appropriately-aligned operations of this size,
12352 // and _Atomic(T) is appropriately-aligned.
12353 return Success(1, E);
12355 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12356 castAs<PointerType>()->getPointeeType();
12357 if (!PointeeType->isIncompleteType() &&
12358 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12359 // OK, we will inline operations on this object.
12360 return Success(1, E);
12365 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12366 Success(0, E) : Error(E);
12368 case Builtin::BI__builtin_add_overflow:
12369 case Builtin::BI__builtin_sub_overflow:
12370 case Builtin::BI__builtin_mul_overflow:
12371 case Builtin::BI__builtin_sadd_overflow:
12372 case Builtin::BI__builtin_uadd_overflow:
12373 case Builtin::BI__builtin_uaddl_overflow:
12374 case Builtin::BI__builtin_uaddll_overflow:
12375 case Builtin::BI__builtin_usub_overflow:
12376 case Builtin::BI__builtin_usubl_overflow:
12377 case Builtin::BI__builtin_usubll_overflow:
12378 case Builtin::BI__builtin_umul_overflow:
12379 case Builtin::BI__builtin_umull_overflow:
12380 case Builtin::BI__builtin_umulll_overflow:
12381 case Builtin::BI__builtin_saddl_overflow:
12382 case Builtin::BI__builtin_saddll_overflow:
12383 case Builtin::BI__builtin_ssub_overflow:
12384 case Builtin::BI__builtin_ssubl_overflow:
12385 case Builtin::BI__builtin_ssubll_overflow:
12386 case Builtin::BI__builtin_smul_overflow:
12387 case Builtin::BI__builtin_smull_overflow:
12388 case Builtin::BI__builtin_smulll_overflow: {
12389 LValue ResultLValue;
12390 APSInt LHS, RHS;
12392 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12393 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12394 !EvaluateInteger(E->getArg(1), RHS, Info) ||
12395 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12396 return false;
12398 APSInt Result;
12399 bool DidOverflow = false;
12401 // If the types don't have to match, enlarge all 3 to the largest of them.
12402 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12403 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12404 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12405 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12406 ResultType->isSignedIntegerOrEnumerationType();
12407 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12408 ResultType->isSignedIntegerOrEnumerationType();
12409 uint64_t LHSSize = LHS.getBitWidth();
12410 uint64_t RHSSize = RHS.getBitWidth();
12411 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12412 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12414 // Add an additional bit if the signedness isn't uniformly agreed to. We
12415 // could do this ONLY if there is a signed and an unsigned that both have
12416 // MaxBits, but the code to check that is pretty nasty. The issue will be
12417 // caught in the shrink-to-result later anyway.
12418 if (IsSigned && !AllSigned)
12419 ++MaxBits;
12421 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12422 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12423 Result = APSInt(MaxBits, !IsSigned);
12426 // Find largest int.
12427 switch (BuiltinOp) {
12428 default:
12429 llvm_unreachable("Invalid value for BuiltinOp");
12430 case Builtin::BI__builtin_add_overflow:
12431 case Builtin::BI__builtin_sadd_overflow:
12432 case Builtin::BI__builtin_saddl_overflow:
12433 case Builtin::BI__builtin_saddll_overflow:
12434 case Builtin::BI__builtin_uadd_overflow:
12435 case Builtin::BI__builtin_uaddl_overflow:
12436 case Builtin::BI__builtin_uaddll_overflow:
12437 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12438 : LHS.uadd_ov(RHS, DidOverflow);
12439 break;
12440 case Builtin::BI__builtin_sub_overflow:
12441 case Builtin::BI__builtin_ssub_overflow:
12442 case Builtin::BI__builtin_ssubl_overflow:
12443 case Builtin::BI__builtin_ssubll_overflow:
12444 case Builtin::BI__builtin_usub_overflow:
12445 case Builtin::BI__builtin_usubl_overflow:
12446 case Builtin::BI__builtin_usubll_overflow:
12447 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12448 : LHS.usub_ov(RHS, DidOverflow);
12449 break;
12450 case Builtin::BI__builtin_mul_overflow:
12451 case Builtin::BI__builtin_smul_overflow:
12452 case Builtin::BI__builtin_smull_overflow:
12453 case Builtin::BI__builtin_smulll_overflow:
12454 case Builtin::BI__builtin_umul_overflow:
12455 case Builtin::BI__builtin_umull_overflow:
12456 case Builtin::BI__builtin_umulll_overflow:
12457 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12458 : LHS.umul_ov(RHS, DidOverflow);
12459 break;
12462 // In the case where multiple sizes are allowed, truncate and see if
12463 // the values are the same.
12464 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12465 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12466 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12467 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12468 // since it will give us the behavior of a TruncOrSelf in the case where
12469 // its parameter <= its size. We previously set Result to be at least the
12470 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12471 // will work exactly like TruncOrSelf.
12472 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12473 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12475 if (!APSInt::isSameValue(Temp, Result))
12476 DidOverflow = true;
12477 Result = Temp;
12480 APValue APV{Result};
12481 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12482 return false;
12483 return Success(DidOverflow, E);
12488 /// Determine whether this is a pointer past the end of the complete
12489 /// object referred to by the lvalue.
12490 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12491 const LValue &LV) {
12492 // A null pointer can be viewed as being "past the end" but we don't
12493 // choose to look at it that way here.
12494 if (!LV.getLValueBase())
12495 return false;
12497 // If the designator is valid and refers to a subobject, we're not pointing
12498 // past the end.
12499 if (!LV.getLValueDesignator().Invalid &&
12500 !LV.getLValueDesignator().isOnePastTheEnd())
12501 return false;
12503 // A pointer to an incomplete type might be past-the-end if the type's size is
12504 // zero. We cannot tell because the type is incomplete.
12505 QualType Ty = getType(LV.getLValueBase());
12506 if (Ty->isIncompleteType())
12507 return true;
12509 // We're a past-the-end pointer if we point to the byte after the object,
12510 // no matter what our type or path is.
12511 auto Size = Ctx.getTypeSizeInChars(Ty);
12512 return LV.getLValueOffset() == Size;
12515 namespace {
12517 /// Data recursive integer evaluator of certain binary operators.
12519 /// We use a data recursive algorithm for binary operators so that we are able
12520 /// to handle extreme cases of chained binary operators without causing stack
12521 /// overflow.
12522 class DataRecursiveIntBinOpEvaluator {
12523 struct EvalResult {
12524 APValue Val;
12525 bool Failed;
12527 EvalResult() : Failed(false) { }
12529 void swap(EvalResult &RHS) {
12530 Val.swap(RHS.Val);
12531 Failed = RHS.Failed;
12532 RHS.Failed = false;
12536 struct Job {
12537 const Expr *E;
12538 EvalResult LHSResult; // meaningful only for binary operator expression.
12539 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12541 Job() = default;
12542 Job(Job &&) = default;
12544 void startSpeculativeEval(EvalInfo &Info) {
12545 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12548 private:
12549 SpeculativeEvaluationRAII SpecEvalRAII;
12552 SmallVector<Job, 16> Queue;
12554 IntExprEvaluator &IntEval;
12555 EvalInfo &Info;
12556 APValue &FinalResult;
12558 public:
12559 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12560 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12562 /// True if \param E is a binary operator that we are going to handle
12563 /// data recursively.
12564 /// We handle binary operators that are comma, logical, or that have operands
12565 /// with integral or enumeration type.
12566 static bool shouldEnqueue(const BinaryOperator *E) {
12567 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12568 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12569 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12570 E->getRHS()->getType()->isIntegralOrEnumerationType());
12573 bool Traverse(const BinaryOperator *E) {
12574 enqueue(E);
12575 EvalResult PrevResult;
12576 while (!Queue.empty())
12577 process(PrevResult);
12579 if (PrevResult.Failed) return false;
12581 FinalResult.swap(PrevResult.Val);
12582 return true;
12585 private:
12586 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12587 return IntEval.Success(Value, E, Result);
12589 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12590 return IntEval.Success(Value, E, Result);
12592 bool Error(const Expr *E) {
12593 return IntEval.Error(E);
12595 bool Error(const Expr *E, diag::kind D) {
12596 return IntEval.Error(E, D);
12599 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12600 return Info.CCEDiag(E, D);
12603 // Returns true if visiting the RHS is necessary, false otherwise.
12604 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12605 bool &SuppressRHSDiags);
12607 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12608 const BinaryOperator *E, APValue &Result);
12610 void EvaluateExpr(const Expr *E, EvalResult &Result) {
12611 Result.Failed = !Evaluate(Result.Val, Info, E);
12612 if (Result.Failed)
12613 Result.Val = APValue();
12616 void process(EvalResult &Result);
12618 void enqueue(const Expr *E) {
12619 E = E->IgnoreParens();
12620 Queue.resize(Queue.size()+1);
12621 Queue.back().E = E;
12622 Queue.back().Kind = Job::AnyExprKind;
12628 bool DataRecursiveIntBinOpEvaluator::
12629 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12630 bool &SuppressRHSDiags) {
12631 if (E->getOpcode() == BO_Comma) {
12632 // Ignore LHS but note if we could not evaluate it.
12633 if (LHSResult.Failed)
12634 return Info.noteSideEffect();
12635 return true;
12638 if (E->isLogicalOp()) {
12639 bool LHSAsBool;
12640 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12641 // We were able to evaluate the LHS, see if we can get away with not
12642 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12643 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12644 Success(LHSAsBool, E, LHSResult.Val);
12645 return false; // Ignore RHS
12647 } else {
12648 LHSResult.Failed = true;
12650 // Since we weren't able to evaluate the left hand side, it
12651 // might have had side effects.
12652 if (!Info.noteSideEffect())
12653 return false;
12655 // We can't evaluate the LHS; however, sometimes the result
12656 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12657 // Don't ignore RHS and suppress diagnostics from this arm.
12658 SuppressRHSDiags = true;
12661 return true;
12664 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12665 E->getRHS()->getType()->isIntegralOrEnumerationType());
12667 if (LHSResult.Failed && !Info.noteFailure())
12668 return false; // Ignore RHS;
12670 return true;
12673 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12674 bool IsSub) {
12675 // Compute the new offset in the appropriate width, wrapping at 64 bits.
12676 // FIXME: When compiling for a 32-bit target, we should use 32-bit
12677 // offsets.
12678 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12679 CharUnits &Offset = LVal.getLValueOffset();
12680 uint64_t Offset64 = Offset.getQuantity();
12681 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12682 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12683 : Offset64 + Index64);
12686 bool DataRecursiveIntBinOpEvaluator::
12687 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12688 const BinaryOperator *E, APValue &Result) {
12689 if (E->getOpcode() == BO_Comma) {
12690 if (RHSResult.Failed)
12691 return false;
12692 Result = RHSResult.Val;
12693 return true;
12696 if (E->isLogicalOp()) {
12697 bool lhsResult, rhsResult;
12698 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12699 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12701 if (LHSIsOK) {
12702 if (RHSIsOK) {
12703 if (E->getOpcode() == BO_LOr)
12704 return Success(lhsResult || rhsResult, E, Result);
12705 else
12706 return Success(lhsResult && rhsResult, E, Result);
12708 } else {
12709 if (RHSIsOK) {
12710 // We can't evaluate the LHS; however, sometimes the result
12711 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12712 if (rhsResult == (E->getOpcode() == BO_LOr))
12713 return Success(rhsResult, E, Result);
12717 return false;
12720 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12721 E->getRHS()->getType()->isIntegralOrEnumerationType());
12723 if (LHSResult.Failed || RHSResult.Failed)
12724 return false;
12726 const APValue &LHSVal = LHSResult.Val;
12727 const APValue &RHSVal = RHSResult.Val;
12729 // Handle cases like (unsigned long)&a + 4.
12730 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12731 Result = LHSVal;
12732 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12733 return true;
12736 // Handle cases like 4 + (unsigned long)&a
12737 if (E->getOpcode() == BO_Add &&
12738 RHSVal.isLValue() && LHSVal.isInt()) {
12739 Result = RHSVal;
12740 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12741 return true;
12744 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12745 // Handle (intptr_t)&&A - (intptr_t)&&B.
12746 if (!LHSVal.getLValueOffset().isZero() ||
12747 !RHSVal.getLValueOffset().isZero())
12748 return false;
12749 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12750 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12751 if (!LHSExpr || !RHSExpr)
12752 return false;
12753 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12754 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12755 if (!LHSAddrExpr || !RHSAddrExpr)
12756 return false;
12757 // Make sure both labels come from the same function.
12758 if (LHSAddrExpr->getLabel()->getDeclContext() !=
12759 RHSAddrExpr->getLabel()->getDeclContext())
12760 return false;
12761 Result = APValue(LHSAddrExpr, RHSAddrExpr);
12762 return true;
12765 // All the remaining cases expect both operands to be an integer
12766 if (!LHSVal.isInt() || !RHSVal.isInt())
12767 return Error(E);
12769 // Set up the width and signedness manually, in case it can't be deduced
12770 // from the operation we're performing.
12771 // FIXME: Don't do this in the cases where we can deduce it.
12772 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12773 E->getType()->isUnsignedIntegerOrEnumerationType());
12774 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12775 RHSVal.getInt(), Value))
12776 return false;
12777 return Success(Value, E, Result);
12780 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12781 Job &job = Queue.back();
12783 switch (job.Kind) {
12784 case Job::AnyExprKind: {
12785 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12786 if (shouldEnqueue(Bop)) {
12787 job.Kind = Job::BinOpKind;
12788 enqueue(Bop->getLHS());
12789 return;
12793 EvaluateExpr(job.E, Result);
12794 Queue.pop_back();
12795 return;
12798 case Job::BinOpKind: {
12799 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12800 bool SuppressRHSDiags = false;
12801 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12802 Queue.pop_back();
12803 return;
12805 if (SuppressRHSDiags)
12806 job.startSpeculativeEval(Info);
12807 job.LHSResult.swap(Result);
12808 job.Kind = Job::BinOpVisitedLHSKind;
12809 enqueue(Bop->getRHS());
12810 return;
12813 case Job::BinOpVisitedLHSKind: {
12814 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12815 EvalResult RHS;
12816 RHS.swap(Result);
12817 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12818 Queue.pop_back();
12819 return;
12823 llvm_unreachable("Invalid Job::Kind!");
12826 namespace {
12827 enum class CmpResult {
12828 Unequal,
12829 Less,
12830 Equal,
12831 Greater,
12832 Unordered,
12836 template <class SuccessCB, class AfterCB>
12837 static bool
12838 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12839 SuccessCB &&Success, AfterCB &&DoAfter) {
12840 assert(!E->isValueDependent());
12841 assert(E->isComparisonOp() && "expected comparison operator");
12842 assert((E->getOpcode() == BO_Cmp ||
12843 E->getType()->isIntegralOrEnumerationType()) &&
12844 "unsupported binary expression evaluation");
12845 auto Error = [&](const Expr *E) {
12846 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12847 return false;
12850 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12851 bool IsEquality = E->isEqualityOp();
12853 QualType LHSTy = E->getLHS()->getType();
12854 QualType RHSTy = E->getRHS()->getType();
12856 if (LHSTy->isIntegralOrEnumerationType() &&
12857 RHSTy->isIntegralOrEnumerationType()) {
12858 APSInt LHS, RHS;
12859 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12860 if (!LHSOK && !Info.noteFailure())
12861 return false;
12862 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12863 return false;
12864 if (LHS < RHS)
12865 return Success(CmpResult::Less, E);
12866 if (LHS > RHS)
12867 return Success(CmpResult::Greater, E);
12868 return Success(CmpResult::Equal, E);
12871 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12872 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12873 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12875 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12876 if (!LHSOK && !Info.noteFailure())
12877 return false;
12878 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12879 return false;
12880 if (LHSFX < RHSFX)
12881 return Success(CmpResult::Less, E);
12882 if (LHSFX > RHSFX)
12883 return Success(CmpResult::Greater, E);
12884 return Success(CmpResult::Equal, E);
12887 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12888 ComplexValue LHS, RHS;
12889 bool LHSOK;
12890 if (E->isAssignmentOp()) {
12891 LValue LV;
12892 EvaluateLValue(E->getLHS(), LV, Info);
12893 LHSOK = false;
12894 } else if (LHSTy->isRealFloatingType()) {
12895 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12896 if (LHSOK) {
12897 LHS.makeComplexFloat();
12898 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12900 } else {
12901 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12903 if (!LHSOK && !Info.noteFailure())
12904 return false;
12906 if (E->getRHS()->getType()->isRealFloatingType()) {
12907 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12908 return false;
12909 RHS.makeComplexFloat();
12910 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12911 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12912 return false;
12914 if (LHS.isComplexFloat()) {
12915 APFloat::cmpResult CR_r =
12916 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12917 APFloat::cmpResult CR_i =
12918 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12919 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12920 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12921 } else {
12922 assert(IsEquality && "invalid complex comparison");
12923 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12924 LHS.getComplexIntImag() == RHS.getComplexIntImag();
12925 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12929 if (LHSTy->isRealFloatingType() &&
12930 RHSTy->isRealFloatingType()) {
12931 APFloat RHS(0.0), LHS(0.0);
12933 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12934 if (!LHSOK && !Info.noteFailure())
12935 return false;
12937 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12938 return false;
12940 assert(E->isComparisonOp() && "Invalid binary operator!");
12941 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12942 if (!Info.InConstantContext &&
12943 APFloatCmpResult == APFloat::cmpUnordered &&
12944 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12945 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12946 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12947 return false;
12949 auto GetCmpRes = [&]() {
12950 switch (APFloatCmpResult) {
12951 case APFloat::cmpEqual:
12952 return CmpResult::Equal;
12953 case APFloat::cmpLessThan:
12954 return CmpResult::Less;
12955 case APFloat::cmpGreaterThan:
12956 return CmpResult::Greater;
12957 case APFloat::cmpUnordered:
12958 return CmpResult::Unordered;
12960 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12962 return Success(GetCmpRes(), E);
12965 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12966 LValue LHSValue, RHSValue;
12968 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12969 if (!LHSOK && !Info.noteFailure())
12970 return false;
12972 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12973 return false;
12975 // Reject differing bases from the normal codepath; we special-case
12976 // comparisons to null.
12977 if (!HasSameBase(LHSValue, RHSValue)) {
12978 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
12979 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
12980 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
12981 Info.FFDiag(E, DiagID)
12982 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
12983 return false;
12985 // Inequalities and subtractions between unrelated pointers have
12986 // unspecified or undefined behavior.
12987 if (!IsEquality)
12988 return DiagComparison(
12989 diag::note_constexpr_pointer_comparison_unspecified);
12990 // A constant address may compare equal to the address of a symbol.
12991 // The one exception is that address of an object cannot compare equal
12992 // to a null pointer constant.
12993 // TODO: Should we restrict this to actual null pointers, and exclude the
12994 // case of zero cast to pointer type?
12995 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12996 (!RHSValue.Base && !RHSValue.Offset.isZero()))
12997 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
12998 !RHSValue.Base);
12999 // It's implementation-defined whether distinct literals will have
13000 // distinct addresses. In clang, the result of such a comparison is
13001 // unspecified, so it is not a constant expression. However, we do know
13002 // that the address of a literal will be non-null.
13003 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
13004 LHSValue.Base && RHSValue.Base)
13005 return DiagComparison(diag::note_constexpr_literal_comparison);
13006 // We can't tell whether weak symbols will end up pointing to the same
13007 // object.
13008 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
13009 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
13010 !IsWeakLValue(LHSValue));
13011 // We can't compare the address of the start of one object with the
13012 // past-the-end address of another object, per C++ DR1652.
13013 if (LHSValue.Base && LHSValue.Offset.isZero() &&
13014 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
13015 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13016 true);
13017 if (RHSValue.Base && RHSValue.Offset.isZero() &&
13018 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
13019 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
13020 false);
13021 // We can't tell whether an object is at the same address as another
13022 // zero sized object.
13023 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
13024 (LHSValue.Base && isZeroSized(RHSValue)))
13025 return DiagComparison(
13026 diag::note_constexpr_pointer_comparison_zero_sized);
13027 return Success(CmpResult::Unequal, E);
13030 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13031 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13033 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13034 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13036 // C++11 [expr.rel]p3:
13037 // Pointers to void (after pointer conversions) can be compared, with a
13038 // result defined as follows: If both pointers represent the same
13039 // address or are both the null pointer value, the result is true if the
13040 // operator is <= or >= and false otherwise; otherwise the result is
13041 // unspecified.
13042 // We interpret this as applying to pointers to *cv* void.
13043 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13044 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
13046 // C++11 [expr.rel]p2:
13047 // - If two pointers point to non-static data members of the same object,
13048 // or to subobjects or array elements fo such members, recursively, the
13049 // pointer to the later declared member compares greater provided the
13050 // two members have the same access control and provided their class is
13051 // not a union.
13052 // [...]
13053 // - Otherwise pointer comparisons are unspecified.
13054 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
13055 bool WasArrayIndex;
13056 unsigned Mismatch = FindDesignatorMismatch(
13057 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
13058 // At the point where the designators diverge, the comparison has a
13059 // specified value if:
13060 // - we are comparing array indices
13061 // - we are comparing fields of a union, or fields with the same access
13062 // Otherwise, the result is unspecified and thus the comparison is not a
13063 // constant expression.
13064 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
13065 Mismatch < RHSDesignator.Entries.size()) {
13066 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
13067 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
13068 if (!LF && !RF)
13069 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
13070 else if (!LF)
13071 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13072 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
13073 << RF->getParent() << RF;
13074 else if (!RF)
13075 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
13076 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
13077 << LF->getParent() << LF;
13078 else if (!LF->getParent()->isUnion() &&
13079 LF->getAccess() != RF->getAccess())
13080 Info.CCEDiag(E,
13081 diag::note_constexpr_pointer_comparison_differing_access)
13082 << LF << LF->getAccess() << RF << RF->getAccess()
13083 << LF->getParent();
13087 // The comparison here must be unsigned, and performed with the same
13088 // width as the pointer.
13089 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
13090 uint64_t CompareLHS = LHSOffset.getQuantity();
13091 uint64_t CompareRHS = RHSOffset.getQuantity();
13092 assert(PtrSize <= 64 && "Unexpected pointer width");
13093 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13094 CompareLHS &= Mask;
13095 CompareRHS &= Mask;
13097 // If there is a base and this is a relational operator, we can only
13098 // compare pointers within the object in question; otherwise, the result
13099 // depends on where the object is located in memory.
13100 if (!LHSValue.Base.isNull() && IsRelational) {
13101 QualType BaseTy = getType(LHSValue.Base);
13102 if (BaseTy->isIncompleteType())
13103 return Error(E);
13104 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
13105 uint64_t OffsetLimit = Size.getQuantity();
13106 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
13107 return Error(E);
13110 if (CompareLHS < CompareRHS)
13111 return Success(CmpResult::Less, E);
13112 if (CompareLHS > CompareRHS)
13113 return Success(CmpResult::Greater, E);
13114 return Success(CmpResult::Equal, E);
13117 if (LHSTy->isMemberPointerType()) {
13118 assert(IsEquality && "unexpected member pointer operation");
13119 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13121 MemberPtr LHSValue, RHSValue;
13123 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13124 if (!LHSOK && !Info.noteFailure())
13125 return false;
13127 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13128 return false;
13130 // If either operand is a pointer to a weak function, the comparison is not
13131 // constant.
13132 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13133 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13134 << LHSValue.getDecl();
13135 return true;
13137 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13138 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
13139 << RHSValue.getDecl();
13140 return true;
13143 // C++11 [expr.eq]p2:
13144 // If both operands are null, they compare equal. Otherwise if only one is
13145 // null, they compare unequal.
13146 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
13147 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
13148 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13151 // Otherwise if either is a pointer to a virtual member function, the
13152 // result is unspecified.
13153 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
13154 if (MD->isVirtual())
13155 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13156 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
13157 if (MD->isVirtual())
13158 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
13160 // Otherwise they compare equal if and only if they would refer to the
13161 // same member of the same most derived object or the same subobject if
13162 // they were dereferenced with a hypothetical object of the associated
13163 // class type.
13164 bool Equal = LHSValue == RHSValue;
13165 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
13168 if (LHSTy->isNullPtrType()) {
13169 assert(E->isComparisonOp() && "unexpected nullptr operation");
13170 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13171 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
13172 // are compared, the result is true of the operator is <=, >= or ==, and
13173 // false otherwise.
13174 return Success(CmpResult::Equal, E);
13177 return DoAfter();
13180 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
13181 if (!CheckLiteralType(Info, E))
13182 return false;
13184 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13185 ComparisonCategoryResult CCR;
13186 switch (CR) {
13187 case CmpResult::Unequal:
13188 llvm_unreachable("should never produce Unequal for three-way comparison");
13189 case CmpResult::Less:
13190 CCR = ComparisonCategoryResult::Less;
13191 break;
13192 case CmpResult::Equal:
13193 CCR = ComparisonCategoryResult::Equal;
13194 break;
13195 case CmpResult::Greater:
13196 CCR = ComparisonCategoryResult::Greater;
13197 break;
13198 case CmpResult::Unordered:
13199 CCR = ComparisonCategoryResult::Unordered;
13200 break;
13202 // Evaluation succeeded. Lookup the information for the comparison category
13203 // type and fetch the VarDecl for the result.
13204 const ComparisonCategoryInfo &CmpInfo =
13205 Info.Ctx.CompCategories.getInfoForType(E->getType());
13206 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13207 // Check and evaluate the result as a constant expression.
13208 LValue LV;
13209 LV.set(VD);
13210 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13211 return false;
13212 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13213 ConstantExprKind::Normal);
13215 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13216 return ExprEvaluatorBaseTy::VisitBinCmp(E);
13220 bool RecordExprEvaluator::VisitCXXParenListInitExpr(
13221 const CXXParenListInitExpr *E) {
13222 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13225 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13226 // We don't support assignment in C. C++ assignments don't get here because
13227 // assignment is an lvalue in C++.
13228 if (E->isAssignmentOp()) {
13229 Error(E);
13230 if (!Info.noteFailure())
13231 return false;
13234 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
13235 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
13237 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13238 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13239 "DataRecursiveIntBinOpEvaluator should have handled integral types");
13241 if (E->isComparisonOp()) {
13242 // Evaluate builtin binary comparisons by evaluating them as three-way
13243 // comparisons and then translating the result.
13244 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
13245 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13246 "should only produce Unequal for equality comparisons");
13247 bool IsEqual = CR == CmpResult::Equal,
13248 IsLess = CR == CmpResult::Less,
13249 IsGreater = CR == CmpResult::Greater;
13250 auto Op = E->getOpcode();
13251 switch (Op) {
13252 default:
13253 llvm_unreachable("unsupported binary operator");
13254 case BO_EQ:
13255 case BO_NE:
13256 return Success(IsEqual == (Op == BO_EQ), E);
13257 case BO_LT:
13258 return Success(IsLess, E);
13259 case BO_GT:
13260 return Success(IsGreater, E);
13261 case BO_LE:
13262 return Success(IsEqual || IsLess, E);
13263 case BO_GE:
13264 return Success(IsEqual || IsGreater, E);
13267 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
13268 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13272 QualType LHSTy = E->getLHS()->getType();
13273 QualType RHSTy = E->getRHS()->getType();
13275 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13276 E->getOpcode() == BO_Sub) {
13277 LValue LHSValue, RHSValue;
13279 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13280 if (!LHSOK && !Info.noteFailure())
13281 return false;
13283 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13284 return false;
13286 // Reject differing bases from the normal codepath; we special-case
13287 // comparisons to null.
13288 if (!HasSameBase(LHSValue, RHSValue)) {
13289 // Handle &&A - &&B.
13290 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
13291 return Error(E);
13292 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
13293 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
13294 if (!LHSExpr || !RHSExpr)
13295 return Error(E);
13296 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
13297 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
13298 if (!LHSAddrExpr || !RHSAddrExpr)
13299 return Error(E);
13300 // Make sure both labels come from the same function.
13301 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13302 RHSAddrExpr->getLabel()->getDeclContext())
13303 return Error(E);
13304 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
13306 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
13307 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
13309 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
13310 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
13312 // C++11 [expr.add]p6:
13313 // Unless both pointers point to elements of the same array object, or
13314 // one past the last element of the array object, the behavior is
13315 // undefined.
13316 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
13317 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
13318 RHSDesignator))
13319 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
13321 QualType Type = E->getLHS()->getType();
13322 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
13324 CharUnits ElementSize;
13325 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
13326 return false;
13328 // As an extension, a type may have zero size (empty struct or union in
13329 // C, array of zero length). Pointer subtraction in such cases has
13330 // undefined behavior, so is not constant.
13331 if (ElementSize.isZero()) {
13332 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
13333 << ElementType;
13334 return false;
13337 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
13338 // and produce incorrect results when it overflows. Such behavior
13339 // appears to be non-conforming, but is common, so perhaps we should
13340 // assume the standard intended for such cases to be undefined behavior
13341 // and check for them.
13343 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
13344 // overflow in the final conversion to ptrdiff_t.
13345 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
13346 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
13347 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
13348 false);
13349 APSInt TrueResult = (LHS - RHS) / ElemSize;
13350 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
13352 if (Result.extend(65) != TrueResult &&
13353 !HandleOverflow(Info, E, TrueResult, E->getType()))
13354 return false;
13355 return Success(Result, E);
13358 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13361 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
13362 /// a result as the expression's type.
13363 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
13364 const UnaryExprOrTypeTraitExpr *E) {
13365 switch(E->getKind()) {
13366 case UETT_PreferredAlignOf:
13367 case UETT_AlignOf: {
13368 if (E->isArgumentType())
13369 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
13371 else
13372 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
13376 case UETT_VecStep: {
13377 QualType Ty = E->getTypeOfArgument();
13379 if (Ty->isVectorType()) {
13380 unsigned n = Ty->castAs<VectorType>()->getNumElements();
13382 // The vec_step built-in functions that take a 3-component
13383 // vector return 4. (OpenCL 1.1 spec 6.11.12)
13384 if (n == 3)
13385 n = 4;
13387 return Success(n, E);
13388 } else
13389 return Success(1, E);
13392 case UETT_SizeOf: {
13393 QualType SrcTy = E->getTypeOfArgument();
13394 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13395 // the result is the size of the referenced type."
13396 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13397 SrcTy = Ref->getPointeeType();
13399 CharUnits Sizeof;
13400 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13401 return false;
13402 return Success(Sizeof, E);
13404 case UETT_OpenMPRequiredSimdAlign:
13405 assert(E->isArgumentType());
13406 return Success(
13407 Info.Ctx.toCharUnitsFromBits(
13408 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13409 .getQuantity(),
13413 llvm_unreachable("unknown expr/type trait");
13416 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13417 CharUnits Result;
13418 unsigned n = OOE->getNumComponents();
13419 if (n == 0)
13420 return Error(OOE);
13421 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13422 for (unsigned i = 0; i != n; ++i) {
13423 OffsetOfNode ON = OOE->getComponent(i);
13424 switch (ON.getKind()) {
13425 case OffsetOfNode::Array: {
13426 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13427 APSInt IdxResult;
13428 if (!EvaluateInteger(Idx, IdxResult, Info))
13429 return false;
13430 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13431 if (!AT)
13432 return Error(OOE);
13433 CurrentType = AT->getElementType();
13434 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13435 Result += IdxResult.getSExtValue() * ElementSize;
13436 break;
13439 case OffsetOfNode::Field: {
13440 FieldDecl *MemberDecl = ON.getField();
13441 const RecordType *RT = CurrentType->getAs<RecordType>();
13442 if (!RT)
13443 return Error(OOE);
13444 RecordDecl *RD = RT->getDecl();
13445 if (RD->isInvalidDecl()) return false;
13446 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13447 unsigned i = MemberDecl->getFieldIndex();
13448 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13449 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13450 CurrentType = MemberDecl->getType().getNonReferenceType();
13451 break;
13454 case OffsetOfNode::Identifier:
13455 llvm_unreachable("dependent __builtin_offsetof");
13457 case OffsetOfNode::Base: {
13458 CXXBaseSpecifier *BaseSpec = ON.getBase();
13459 if (BaseSpec->isVirtual())
13460 return Error(OOE);
13462 // Find the layout of the class whose base we are looking into.
13463 const RecordType *RT = CurrentType->getAs<RecordType>();
13464 if (!RT)
13465 return Error(OOE);
13466 RecordDecl *RD = RT->getDecl();
13467 if (RD->isInvalidDecl()) return false;
13468 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13470 // Find the base class itself.
13471 CurrentType = BaseSpec->getType();
13472 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13473 if (!BaseRT)
13474 return Error(OOE);
13476 // Add the offset to the base.
13477 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13478 break;
13482 return Success(Result, OOE);
13485 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13486 switch (E->getOpcode()) {
13487 default:
13488 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13489 // See C99 6.6p3.
13490 return Error(E);
13491 case UO_Extension:
13492 // FIXME: Should extension allow i-c-e extension expressions in its scope?
13493 // If so, we could clear the diagnostic ID.
13494 return Visit(E->getSubExpr());
13495 case UO_Plus:
13496 // The result is just the value.
13497 return Visit(E->getSubExpr());
13498 case UO_Minus: {
13499 if (!Visit(E->getSubExpr()))
13500 return false;
13501 if (!Result.isInt()) return Error(E);
13502 const APSInt &Value = Result.getInt();
13503 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
13504 if (Info.checkingForUndefinedBehavior())
13505 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13506 diag::warn_integer_constant_overflow)
13507 << toString(Value, 10) << E->getType();
13509 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13510 E->getType()))
13511 return false;
13513 return Success(-Value, E);
13515 case UO_Not: {
13516 if (!Visit(E->getSubExpr()))
13517 return false;
13518 if (!Result.isInt()) return Error(E);
13519 return Success(~Result.getInt(), E);
13521 case UO_LNot: {
13522 bool bres;
13523 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13524 return false;
13525 return Success(!bres, E);
13530 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13531 /// result type is integer.
13532 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13533 const Expr *SubExpr = E->getSubExpr();
13534 QualType DestType = E->getType();
13535 QualType SrcType = SubExpr->getType();
13537 switch (E->getCastKind()) {
13538 case CK_BaseToDerived:
13539 case CK_DerivedToBase:
13540 case CK_UncheckedDerivedToBase:
13541 case CK_Dynamic:
13542 case CK_ToUnion:
13543 case CK_ArrayToPointerDecay:
13544 case CK_FunctionToPointerDecay:
13545 case CK_NullToPointer:
13546 case CK_NullToMemberPointer:
13547 case CK_BaseToDerivedMemberPointer:
13548 case CK_DerivedToBaseMemberPointer:
13549 case CK_ReinterpretMemberPointer:
13550 case CK_ConstructorConversion:
13551 case CK_IntegralToPointer:
13552 case CK_ToVoid:
13553 case CK_VectorSplat:
13554 case CK_IntegralToFloating:
13555 case CK_FloatingCast:
13556 case CK_CPointerToObjCPointerCast:
13557 case CK_BlockPointerToObjCPointerCast:
13558 case CK_AnyPointerToBlockPointerCast:
13559 case CK_ObjCObjectLValueCast:
13560 case CK_FloatingRealToComplex:
13561 case CK_FloatingComplexToReal:
13562 case CK_FloatingComplexCast:
13563 case CK_FloatingComplexToIntegralComplex:
13564 case CK_IntegralRealToComplex:
13565 case CK_IntegralComplexCast:
13566 case CK_IntegralComplexToFloatingComplex:
13567 case CK_BuiltinFnToFnPtr:
13568 case CK_ZeroToOCLOpaqueType:
13569 case CK_NonAtomicToAtomic:
13570 case CK_AddressSpaceConversion:
13571 case CK_IntToOCLSampler:
13572 case CK_FloatingToFixedPoint:
13573 case CK_FixedPointToFloating:
13574 case CK_FixedPointCast:
13575 case CK_IntegralToFixedPoint:
13576 case CK_MatrixCast:
13577 llvm_unreachable("invalid cast kind for integral value");
13579 case CK_BitCast:
13580 case CK_Dependent:
13581 case CK_LValueBitCast:
13582 case CK_ARCProduceObject:
13583 case CK_ARCConsumeObject:
13584 case CK_ARCReclaimReturnedObject:
13585 case CK_ARCExtendBlockObject:
13586 case CK_CopyAndAutoreleaseBlockObject:
13587 return Error(E);
13589 case CK_UserDefinedConversion:
13590 case CK_LValueToRValue:
13591 case CK_AtomicToNonAtomic:
13592 case CK_NoOp:
13593 case CK_LValueToRValueBitCast:
13594 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13596 case CK_MemberPointerToBoolean:
13597 case CK_PointerToBoolean:
13598 case CK_IntegralToBoolean:
13599 case CK_FloatingToBoolean:
13600 case CK_BooleanToSignedIntegral:
13601 case CK_FloatingComplexToBoolean:
13602 case CK_IntegralComplexToBoolean: {
13603 bool BoolResult;
13604 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13605 return false;
13606 uint64_t IntResult = BoolResult;
13607 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13608 IntResult = (uint64_t)-1;
13609 return Success(IntResult, E);
13612 case CK_FixedPointToIntegral: {
13613 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13614 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13615 return false;
13616 bool Overflowed;
13617 llvm::APSInt Result = Src.convertToInt(
13618 Info.Ctx.getIntWidth(DestType),
13619 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13620 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13621 return false;
13622 return Success(Result, E);
13625 case CK_FixedPointToBoolean: {
13626 // Unsigned padding does not affect this.
13627 APValue Val;
13628 if (!Evaluate(Val, Info, SubExpr))
13629 return false;
13630 return Success(Val.getFixedPoint().getBoolValue(), E);
13633 case CK_IntegralCast: {
13634 if (!Visit(SubExpr))
13635 return false;
13637 if (!Result.isInt()) {
13638 // Allow casts of address-of-label differences if they are no-ops
13639 // or narrowing. (The narrowing case isn't actually guaranteed to
13640 // be constant-evaluatable except in some narrow cases which are hard
13641 // to detect here. We let it through on the assumption the user knows
13642 // what they are doing.)
13643 if (Result.isAddrLabelDiff())
13644 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13645 // Only allow casts of lvalues if they are lossless.
13646 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13649 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
13650 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
13651 DestType->isEnumeralType()) {
13653 bool ConstexprVar = true;
13655 // We know if we are here that we are in a context that we might require
13656 // a constant expression or a context that requires a constant
13657 // value. But if we are initializing a value we don't know if it is a
13658 // constexpr variable or not. We can check the EvaluatingDecl to determine
13659 // if it constexpr or not. If not then we don't want to emit a diagnostic.
13660 if (const auto *VD = dyn_cast_or_null<VarDecl>(
13661 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
13662 ConstexprVar = VD->isConstexpr();
13664 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
13665 const EnumDecl *ED = ET->getDecl();
13666 // Check that the value is within the range of the enumeration values.
13668 // This corressponds to [expr.static.cast]p10 which says:
13669 // A value of integral or enumeration type can be explicitly converted
13670 // to a complete enumeration type ... If the enumeration type does not
13671 // have a fixed underlying type, the value is unchanged if the original
13672 // value is within the range of the enumeration values ([dcl.enum]), and
13673 // otherwise, the behavior is undefined.
13675 // This was resolved as part of DR2338 which has CD5 status.
13676 if (!ED->isFixed()) {
13677 llvm::APInt Min;
13678 llvm::APInt Max;
13680 ED->getValueRange(Max, Min);
13681 --Max;
13683 if (ED->getNumNegativeBits() && ConstexprVar &&
13684 (Max.slt(Result.getInt().getSExtValue()) ||
13685 Min.sgt(Result.getInt().getSExtValue())))
13686 Info.Ctx.getDiagnostics().Report(
13687 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
13688 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
13689 << Max.getSExtValue();
13690 else if (!ED->getNumNegativeBits() && ConstexprVar &&
13691 Max.ult(Result.getInt().getZExtValue()))
13692 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13693 diag::warn_constexpr_unscoped_enum_out_of_range)
13694 << llvm::toString(Result.getInt(),10) << Min.getZExtValue() << Max.getZExtValue();
13698 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13699 Result.getInt()), E);
13702 case CK_PointerToIntegral: {
13703 CCEDiag(E, diag::note_constexpr_invalid_cast)
13704 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
13706 LValue LV;
13707 if (!EvaluatePointer(SubExpr, LV, Info))
13708 return false;
13710 if (LV.getLValueBase()) {
13711 // Only allow based lvalue casts if they are lossless.
13712 // FIXME: Allow a larger integer size than the pointer size, and allow
13713 // narrowing back down to pointer width in subsequent integral casts.
13714 // FIXME: Check integer type's active bits, not its type size.
13715 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13716 return Error(E);
13718 LV.Designator.setInvalid();
13719 LV.moveInto(Result);
13720 return true;
13723 APSInt AsInt;
13724 APValue V;
13725 LV.moveInto(V);
13726 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13727 llvm_unreachable("Can't cast this!");
13729 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13732 case CK_IntegralComplexToReal: {
13733 ComplexValue C;
13734 if (!EvaluateComplex(SubExpr, C, Info))
13735 return false;
13736 return Success(C.getComplexIntReal(), E);
13739 case CK_FloatingToIntegral: {
13740 APFloat F(0.0);
13741 if (!EvaluateFloat(SubExpr, F, Info))
13742 return false;
13744 APSInt Value;
13745 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13746 return false;
13747 return Success(Value, E);
13751 llvm_unreachable("unknown cast resulting in integral value");
13754 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13755 if (E->getSubExpr()->getType()->isAnyComplexType()) {
13756 ComplexValue LV;
13757 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13758 return false;
13759 if (!LV.isComplexInt())
13760 return Error(E);
13761 return Success(LV.getComplexIntReal(), E);
13764 return Visit(E->getSubExpr());
13767 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13768 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13769 ComplexValue LV;
13770 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13771 return false;
13772 if (!LV.isComplexInt())
13773 return Error(E);
13774 return Success(LV.getComplexIntImag(), E);
13777 VisitIgnoredValue(E->getSubExpr());
13778 return Success(0, E);
13781 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13782 return Success(E->getPackLength(), E);
13785 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13786 return Success(E->getValue(), E);
13789 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13790 const ConceptSpecializationExpr *E) {
13791 return Success(E->isSatisfied(), E);
13794 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13795 return Success(E->isSatisfied(), E);
13798 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13799 switch (E->getOpcode()) {
13800 default:
13801 // Invalid unary operators
13802 return Error(E);
13803 case UO_Plus:
13804 // The result is just the value.
13805 return Visit(E->getSubExpr());
13806 case UO_Minus: {
13807 if (!Visit(E->getSubExpr())) return false;
13808 if (!Result.isFixedPoint())
13809 return Error(E);
13810 bool Overflowed;
13811 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13812 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13813 return false;
13814 return Success(Negated, E);
13816 case UO_LNot: {
13817 bool bres;
13818 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13819 return false;
13820 return Success(!bres, E);
13825 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13826 const Expr *SubExpr = E->getSubExpr();
13827 QualType DestType = E->getType();
13828 assert(DestType->isFixedPointType() &&
13829 "Expected destination type to be a fixed point type");
13830 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13832 switch (E->getCastKind()) {
13833 case CK_FixedPointCast: {
13834 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13835 if (!EvaluateFixedPoint(SubExpr, Src, Info))
13836 return false;
13837 bool Overflowed;
13838 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13839 if (Overflowed) {
13840 if (Info.checkingForUndefinedBehavior())
13841 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13842 diag::warn_fixedpoint_constant_overflow)
13843 << Result.toString() << E->getType();
13844 if (!HandleOverflow(Info, E, Result, E->getType()))
13845 return false;
13847 return Success(Result, E);
13849 case CK_IntegralToFixedPoint: {
13850 APSInt Src;
13851 if (!EvaluateInteger(SubExpr, Src, Info))
13852 return false;
13854 bool Overflowed;
13855 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13856 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13858 if (Overflowed) {
13859 if (Info.checkingForUndefinedBehavior())
13860 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13861 diag::warn_fixedpoint_constant_overflow)
13862 << IntResult.toString() << E->getType();
13863 if (!HandleOverflow(Info, E, IntResult, E->getType()))
13864 return false;
13867 return Success(IntResult, E);
13869 case CK_FloatingToFixedPoint: {
13870 APFloat Src(0.0);
13871 if (!EvaluateFloat(SubExpr, Src, Info))
13872 return false;
13874 bool Overflowed;
13875 APFixedPoint Result = APFixedPoint::getFromFloatValue(
13876 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13878 if (Overflowed) {
13879 if (Info.checkingForUndefinedBehavior())
13880 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13881 diag::warn_fixedpoint_constant_overflow)
13882 << Result.toString() << E->getType();
13883 if (!HandleOverflow(Info, E, Result, E->getType()))
13884 return false;
13887 return Success(Result, E);
13889 case CK_NoOp:
13890 case CK_LValueToRValue:
13891 return ExprEvaluatorBaseTy::VisitCastExpr(E);
13892 default:
13893 return Error(E);
13897 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13898 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13899 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13901 const Expr *LHS = E->getLHS();
13902 const Expr *RHS = E->getRHS();
13903 FixedPointSemantics ResultFXSema =
13904 Info.Ctx.getFixedPointSemantics(E->getType());
13906 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13907 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13908 return false;
13909 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13910 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13911 return false;
13913 bool OpOverflow = false, ConversionOverflow = false;
13914 APFixedPoint Result(LHSFX.getSemantics());
13915 switch (E->getOpcode()) {
13916 case BO_Add: {
13917 Result = LHSFX.add(RHSFX, &OpOverflow)
13918 .convert(ResultFXSema, &ConversionOverflow);
13919 break;
13921 case BO_Sub: {
13922 Result = LHSFX.sub(RHSFX, &OpOverflow)
13923 .convert(ResultFXSema, &ConversionOverflow);
13924 break;
13926 case BO_Mul: {
13927 Result = LHSFX.mul(RHSFX, &OpOverflow)
13928 .convert(ResultFXSema, &ConversionOverflow);
13929 break;
13931 case BO_Div: {
13932 if (RHSFX.getValue() == 0) {
13933 Info.FFDiag(E, diag::note_expr_divide_by_zero);
13934 return false;
13936 Result = LHSFX.div(RHSFX, &OpOverflow)
13937 .convert(ResultFXSema, &ConversionOverflow);
13938 break;
13940 case BO_Shl:
13941 case BO_Shr: {
13942 FixedPointSemantics LHSSema = LHSFX.getSemantics();
13943 llvm::APSInt RHSVal = RHSFX.getValue();
13945 unsigned ShiftBW =
13946 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13947 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13948 // Embedded-C 4.1.6.2.2:
13949 // The right operand must be nonnegative and less than the total number
13950 // of (nonpadding) bits of the fixed-point operand ...
13951 if (RHSVal.isNegative())
13952 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13953 else if (Amt != RHSVal)
13954 Info.CCEDiag(E, diag::note_constexpr_large_shift)
13955 << RHSVal << E->getType() << ShiftBW;
13957 if (E->getOpcode() == BO_Shl)
13958 Result = LHSFX.shl(Amt, &OpOverflow);
13959 else
13960 Result = LHSFX.shr(Amt, &OpOverflow);
13961 break;
13963 default:
13964 return false;
13966 if (OpOverflow || ConversionOverflow) {
13967 if (Info.checkingForUndefinedBehavior())
13968 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13969 diag::warn_fixedpoint_constant_overflow)
13970 << Result.toString() << E->getType();
13971 if (!HandleOverflow(Info, E, Result, E->getType()))
13972 return false;
13974 return Success(Result, E);
13977 //===----------------------------------------------------------------------===//
13978 // Float Evaluation
13979 //===----------------------------------------------------------------------===//
13981 namespace {
13982 class FloatExprEvaluator
13983 : public ExprEvaluatorBase<FloatExprEvaluator> {
13984 APFloat &Result;
13985 public:
13986 FloatExprEvaluator(EvalInfo &info, APFloat &result)
13987 : ExprEvaluatorBaseTy(info), Result(result) {}
13989 bool Success(const APValue &V, const Expr *e) {
13990 Result = V.getFloat();
13991 return true;
13994 bool ZeroInitialization(const Expr *E) {
13995 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13996 return true;
13999 bool VisitCallExpr(const CallExpr *E);
14001 bool VisitUnaryOperator(const UnaryOperator *E);
14002 bool VisitBinaryOperator(const BinaryOperator *E);
14003 bool VisitFloatingLiteral(const FloatingLiteral *E);
14004 bool VisitCastExpr(const CastExpr *E);
14006 bool VisitUnaryReal(const UnaryOperator *E);
14007 bool VisitUnaryImag(const UnaryOperator *E);
14009 // FIXME: Missing: array subscript of vector, member of vector
14011 } // end anonymous namespace
14013 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
14014 assert(!E->isValueDependent());
14015 assert(E->isPRValue() && E->getType()->isRealFloatingType());
14016 return FloatExprEvaluator(Info, Result).Visit(E);
14019 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
14020 QualType ResultTy,
14021 const Expr *Arg,
14022 bool SNaN,
14023 llvm::APFloat &Result) {
14024 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14025 if (!S) return false;
14027 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
14029 llvm::APInt fill;
14031 // Treat empty strings as if they were zero.
14032 if (S->getString().empty())
14033 fill = llvm::APInt(32, 0);
14034 else if (S->getString().getAsInteger(0, fill))
14035 return false;
14037 if (Context.getTargetInfo().isNan2008()) {
14038 if (SNaN)
14039 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14040 else
14041 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14042 } else {
14043 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14044 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
14045 // a different encoding to what became a standard in 2008, and for pre-
14046 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14047 // sNaN. This is now known as "legacy NaN" encoding.
14048 if (SNaN)
14049 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
14050 else
14051 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
14054 return true;
14057 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
14058 if (!IsConstantEvaluatedBuiltinCall(E))
14059 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14061 switch (E->getBuiltinCallee()) {
14062 default:
14063 return false;
14065 case Builtin::BI__builtin_huge_val:
14066 case Builtin::BI__builtin_huge_valf:
14067 case Builtin::BI__builtin_huge_vall:
14068 case Builtin::BI__builtin_huge_valf16:
14069 case Builtin::BI__builtin_huge_valf128:
14070 case Builtin::BI__builtin_inf:
14071 case Builtin::BI__builtin_inff:
14072 case Builtin::BI__builtin_infl:
14073 case Builtin::BI__builtin_inff16:
14074 case Builtin::BI__builtin_inff128: {
14075 const llvm::fltSemantics &Sem =
14076 Info.Ctx.getFloatTypeSemantics(E->getType());
14077 Result = llvm::APFloat::getInf(Sem);
14078 return true;
14081 case Builtin::BI__builtin_nans:
14082 case Builtin::BI__builtin_nansf:
14083 case Builtin::BI__builtin_nansl:
14084 case Builtin::BI__builtin_nansf16:
14085 case Builtin::BI__builtin_nansf128:
14086 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14087 true, Result))
14088 return Error(E);
14089 return true;
14091 case Builtin::BI__builtin_nan:
14092 case Builtin::BI__builtin_nanf:
14093 case Builtin::BI__builtin_nanl:
14094 case Builtin::BI__builtin_nanf16:
14095 case Builtin::BI__builtin_nanf128:
14096 // If this is __builtin_nan() turn this into a nan, otherwise we
14097 // can't constant fold it.
14098 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14099 false, Result))
14100 return Error(E);
14101 return true;
14103 case Builtin::BI__builtin_fabs:
14104 case Builtin::BI__builtin_fabsf:
14105 case Builtin::BI__builtin_fabsl:
14106 case Builtin::BI__builtin_fabsf128:
14107 // The C standard says "fabs raises no floating-point exceptions,
14108 // even if x is a signaling NaN. The returned value is independent of
14109 // the current rounding direction mode." Therefore constant folding can
14110 // proceed without regard to the floating point settings.
14111 // Reference, WG14 N2478 F.10.4.3
14112 if (!EvaluateFloat(E->getArg(0), Result, Info))
14113 return false;
14115 if (Result.isNegative())
14116 Result.changeSign();
14117 return true;
14119 case Builtin::BI__arithmetic_fence:
14120 return EvaluateFloat(E->getArg(0), Result, Info);
14122 // FIXME: Builtin::BI__builtin_powi
14123 // FIXME: Builtin::BI__builtin_powif
14124 // FIXME: Builtin::BI__builtin_powil
14126 case Builtin::BI__builtin_copysign:
14127 case Builtin::BI__builtin_copysignf:
14128 case Builtin::BI__builtin_copysignl:
14129 case Builtin::BI__builtin_copysignf128: {
14130 APFloat RHS(0.);
14131 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14132 !EvaluateFloat(E->getArg(1), RHS, Info))
14133 return false;
14134 Result.copySign(RHS);
14135 return true;
14138 case Builtin::BI__builtin_fmax:
14139 case Builtin::BI__builtin_fmaxf:
14140 case Builtin::BI__builtin_fmaxl:
14141 case Builtin::BI__builtin_fmaxf16:
14142 case Builtin::BI__builtin_fmaxf128: {
14143 // TODO: Handle sNaN.
14144 APFloat RHS(0.);
14145 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14146 !EvaluateFloat(E->getArg(1), RHS, Info))
14147 return false;
14148 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
14149 if (Result.isZero() && RHS.isZero() && Result.isNegative())
14150 Result = RHS;
14151 else if (Result.isNaN() || RHS > Result)
14152 Result = RHS;
14153 return true;
14156 case Builtin::BI__builtin_fmin:
14157 case Builtin::BI__builtin_fminf:
14158 case Builtin::BI__builtin_fminl:
14159 case Builtin::BI__builtin_fminf16:
14160 case Builtin::BI__builtin_fminf128: {
14161 // TODO: Handle sNaN.
14162 APFloat RHS(0.);
14163 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14164 !EvaluateFloat(E->getArg(1), RHS, Info))
14165 return false;
14166 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14167 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
14168 Result = RHS;
14169 else if (Result.isNaN() || RHS < Result)
14170 Result = RHS;
14171 return true;
14176 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
14177 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14178 ComplexValue CV;
14179 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14180 return false;
14181 Result = CV.FloatReal;
14182 return true;
14185 return Visit(E->getSubExpr());
14188 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
14189 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14190 ComplexValue CV;
14191 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14192 return false;
14193 Result = CV.FloatImag;
14194 return true;
14197 VisitIgnoredValue(E->getSubExpr());
14198 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14199 Result = llvm::APFloat::getZero(Sem);
14200 return true;
14203 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14204 switch (E->getOpcode()) {
14205 default: return Error(E);
14206 case UO_Plus:
14207 return EvaluateFloat(E->getSubExpr(), Result, Info);
14208 case UO_Minus:
14209 // In C standard, WG14 N2478 F.3 p4
14210 // "the unary - raises no floating point exceptions,
14211 // even if the operand is signalling."
14212 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14213 return false;
14214 Result.changeSign();
14215 return true;
14219 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14220 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14221 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14223 APFloat RHS(0.0);
14224 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14225 if (!LHSOK && !Info.noteFailure())
14226 return false;
14227 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14228 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14231 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
14232 Result = E->getValue();
14233 return true;
14236 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
14237 const Expr* SubExpr = E->getSubExpr();
14239 switch (E->getCastKind()) {
14240 default:
14241 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14243 case CK_IntegralToFloating: {
14244 APSInt IntResult;
14245 const FPOptions FPO = E->getFPFeaturesInEffect(
14246 Info.Ctx.getLangOpts());
14247 return EvaluateInteger(SubExpr, IntResult, Info) &&
14248 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14249 IntResult, E->getType(), Result);
14252 case CK_FixedPointToFloating: {
14253 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14254 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
14255 return false;
14256 Result =
14257 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14258 return true;
14261 case CK_FloatingCast: {
14262 if (!Visit(SubExpr))
14263 return false;
14264 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14265 Result);
14268 case CK_FloatingComplexToReal: {
14269 ComplexValue V;
14270 if (!EvaluateComplex(SubExpr, V, Info))
14271 return false;
14272 Result = V.getComplexFloatReal();
14273 return true;
14278 //===----------------------------------------------------------------------===//
14279 // Complex Evaluation (for float and integer)
14280 //===----------------------------------------------------------------------===//
14282 namespace {
14283 class ComplexExprEvaluator
14284 : public ExprEvaluatorBase<ComplexExprEvaluator> {
14285 ComplexValue &Result;
14287 public:
14288 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
14289 : ExprEvaluatorBaseTy(info), Result(Result) {}
14291 bool Success(const APValue &V, const Expr *e) {
14292 Result.setFrom(V);
14293 return true;
14296 bool ZeroInitialization(const Expr *E);
14298 //===--------------------------------------------------------------------===//
14299 // Visitor Methods
14300 //===--------------------------------------------------------------------===//
14302 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
14303 bool VisitCastExpr(const CastExpr *E);
14304 bool VisitBinaryOperator(const BinaryOperator *E);
14305 bool VisitUnaryOperator(const UnaryOperator *E);
14306 bool VisitInitListExpr(const InitListExpr *E);
14307 bool VisitCallExpr(const CallExpr *E);
14309 } // end anonymous namespace
14311 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
14312 EvalInfo &Info) {
14313 assert(!E->isValueDependent());
14314 assert(E->isPRValue() && E->getType()->isAnyComplexType());
14315 return ComplexExprEvaluator(Info, Result).Visit(E);
14318 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
14319 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
14320 if (ElemTy->isRealFloatingType()) {
14321 Result.makeComplexFloat();
14322 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
14323 Result.FloatReal = Zero;
14324 Result.FloatImag = Zero;
14325 } else {
14326 Result.makeComplexInt();
14327 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
14328 Result.IntReal = Zero;
14329 Result.IntImag = Zero;
14331 return true;
14334 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
14335 const Expr* SubExpr = E->getSubExpr();
14337 if (SubExpr->getType()->isRealFloatingType()) {
14338 Result.makeComplexFloat();
14339 APFloat &Imag = Result.FloatImag;
14340 if (!EvaluateFloat(SubExpr, Imag, Info))
14341 return false;
14343 Result.FloatReal = APFloat(Imag.getSemantics());
14344 return true;
14345 } else {
14346 assert(SubExpr->getType()->isIntegerType() &&
14347 "Unexpected imaginary literal.");
14349 Result.makeComplexInt();
14350 APSInt &Imag = Result.IntImag;
14351 if (!EvaluateInteger(SubExpr, Imag, Info))
14352 return false;
14354 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
14355 return true;
14359 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
14361 switch (E->getCastKind()) {
14362 case CK_BitCast:
14363 case CK_BaseToDerived:
14364 case CK_DerivedToBase:
14365 case CK_UncheckedDerivedToBase:
14366 case CK_Dynamic:
14367 case CK_ToUnion:
14368 case CK_ArrayToPointerDecay:
14369 case CK_FunctionToPointerDecay:
14370 case CK_NullToPointer:
14371 case CK_NullToMemberPointer:
14372 case CK_BaseToDerivedMemberPointer:
14373 case CK_DerivedToBaseMemberPointer:
14374 case CK_MemberPointerToBoolean:
14375 case CK_ReinterpretMemberPointer:
14376 case CK_ConstructorConversion:
14377 case CK_IntegralToPointer:
14378 case CK_PointerToIntegral:
14379 case CK_PointerToBoolean:
14380 case CK_ToVoid:
14381 case CK_VectorSplat:
14382 case CK_IntegralCast:
14383 case CK_BooleanToSignedIntegral:
14384 case CK_IntegralToBoolean:
14385 case CK_IntegralToFloating:
14386 case CK_FloatingToIntegral:
14387 case CK_FloatingToBoolean:
14388 case CK_FloatingCast:
14389 case CK_CPointerToObjCPointerCast:
14390 case CK_BlockPointerToObjCPointerCast:
14391 case CK_AnyPointerToBlockPointerCast:
14392 case CK_ObjCObjectLValueCast:
14393 case CK_FloatingComplexToReal:
14394 case CK_FloatingComplexToBoolean:
14395 case CK_IntegralComplexToReal:
14396 case CK_IntegralComplexToBoolean:
14397 case CK_ARCProduceObject:
14398 case CK_ARCConsumeObject:
14399 case CK_ARCReclaimReturnedObject:
14400 case CK_ARCExtendBlockObject:
14401 case CK_CopyAndAutoreleaseBlockObject:
14402 case CK_BuiltinFnToFnPtr:
14403 case CK_ZeroToOCLOpaqueType:
14404 case CK_NonAtomicToAtomic:
14405 case CK_AddressSpaceConversion:
14406 case CK_IntToOCLSampler:
14407 case CK_FloatingToFixedPoint:
14408 case CK_FixedPointToFloating:
14409 case CK_FixedPointCast:
14410 case CK_FixedPointToBoolean:
14411 case CK_FixedPointToIntegral:
14412 case CK_IntegralToFixedPoint:
14413 case CK_MatrixCast:
14414 llvm_unreachable("invalid cast kind for complex value");
14416 case CK_LValueToRValue:
14417 case CK_AtomicToNonAtomic:
14418 case CK_NoOp:
14419 case CK_LValueToRValueBitCast:
14420 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14422 case CK_Dependent:
14423 case CK_LValueBitCast:
14424 case CK_UserDefinedConversion:
14425 return Error(E);
14427 case CK_FloatingRealToComplex: {
14428 APFloat &Real = Result.FloatReal;
14429 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
14430 return false;
14432 Result.makeComplexFloat();
14433 Result.FloatImag = APFloat(Real.getSemantics());
14434 return true;
14437 case CK_FloatingComplexCast: {
14438 if (!Visit(E->getSubExpr()))
14439 return false;
14441 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14442 QualType From
14443 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14445 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
14446 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
14449 case CK_FloatingComplexToIntegralComplex: {
14450 if (!Visit(E->getSubExpr()))
14451 return false;
14453 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14454 QualType From
14455 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14456 Result.makeComplexInt();
14457 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
14458 To, Result.IntReal) &&
14459 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
14460 To, Result.IntImag);
14463 case CK_IntegralRealToComplex: {
14464 APSInt &Real = Result.IntReal;
14465 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
14466 return false;
14468 Result.makeComplexInt();
14469 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
14470 return true;
14473 case CK_IntegralComplexCast: {
14474 if (!Visit(E->getSubExpr()))
14475 return false;
14477 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14478 QualType From
14479 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14481 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14482 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14483 return true;
14486 case CK_IntegralComplexToFloatingComplex: {
14487 if (!Visit(E->getSubExpr()))
14488 return false;
14490 const FPOptions FPO = E->getFPFeaturesInEffect(
14491 Info.Ctx.getLangOpts());
14492 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14493 QualType From
14494 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14495 Result.makeComplexFloat();
14496 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14497 To, Result.FloatReal) &&
14498 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14499 To, Result.FloatImag);
14503 llvm_unreachable("unknown cast resulting in complex value");
14506 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14507 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14508 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14510 // Track whether the LHS or RHS is real at the type system level. When this is
14511 // the case we can simplify our evaluation strategy.
14512 bool LHSReal = false, RHSReal = false;
14514 bool LHSOK;
14515 if (E->getLHS()->getType()->isRealFloatingType()) {
14516 LHSReal = true;
14517 APFloat &Real = Result.FloatReal;
14518 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14519 if (LHSOK) {
14520 Result.makeComplexFloat();
14521 Result.FloatImag = APFloat(Real.getSemantics());
14523 } else {
14524 LHSOK = Visit(E->getLHS());
14526 if (!LHSOK && !Info.noteFailure())
14527 return false;
14529 ComplexValue RHS;
14530 if (E->getRHS()->getType()->isRealFloatingType()) {
14531 RHSReal = true;
14532 APFloat &Real = RHS.FloatReal;
14533 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14534 return false;
14535 RHS.makeComplexFloat();
14536 RHS.FloatImag = APFloat(Real.getSemantics());
14537 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14538 return false;
14540 assert(!(LHSReal && RHSReal) &&
14541 "Cannot have both operands of a complex operation be real.");
14542 switch (E->getOpcode()) {
14543 default: return Error(E);
14544 case BO_Add:
14545 if (Result.isComplexFloat()) {
14546 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14547 APFloat::rmNearestTiesToEven);
14548 if (LHSReal)
14549 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14550 else if (!RHSReal)
14551 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14552 APFloat::rmNearestTiesToEven);
14553 } else {
14554 Result.getComplexIntReal() += RHS.getComplexIntReal();
14555 Result.getComplexIntImag() += RHS.getComplexIntImag();
14557 break;
14558 case BO_Sub:
14559 if (Result.isComplexFloat()) {
14560 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14561 APFloat::rmNearestTiesToEven);
14562 if (LHSReal) {
14563 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14564 Result.getComplexFloatImag().changeSign();
14565 } else if (!RHSReal) {
14566 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14567 APFloat::rmNearestTiesToEven);
14569 } else {
14570 Result.getComplexIntReal() -= RHS.getComplexIntReal();
14571 Result.getComplexIntImag() -= RHS.getComplexIntImag();
14573 break;
14574 case BO_Mul:
14575 if (Result.isComplexFloat()) {
14576 // This is an implementation of complex multiplication according to the
14577 // constraints laid out in C11 Annex G. The implementation uses the
14578 // following naming scheme:
14579 // (a + ib) * (c + id)
14580 ComplexValue LHS = Result;
14581 APFloat &A = LHS.getComplexFloatReal();
14582 APFloat &B = LHS.getComplexFloatImag();
14583 APFloat &C = RHS.getComplexFloatReal();
14584 APFloat &D = RHS.getComplexFloatImag();
14585 APFloat &ResR = Result.getComplexFloatReal();
14586 APFloat &ResI = Result.getComplexFloatImag();
14587 if (LHSReal) {
14588 assert(!RHSReal && "Cannot have two real operands for a complex op!");
14589 ResR = A * C;
14590 ResI = A * D;
14591 } else if (RHSReal) {
14592 ResR = C * A;
14593 ResI = C * B;
14594 } else {
14595 // In the fully general case, we need to handle NaNs and infinities
14596 // robustly.
14597 APFloat AC = A * C;
14598 APFloat BD = B * D;
14599 APFloat AD = A * D;
14600 APFloat BC = B * C;
14601 ResR = AC - BD;
14602 ResI = AD + BC;
14603 if (ResR.isNaN() && ResI.isNaN()) {
14604 bool Recalc = false;
14605 if (A.isInfinity() || B.isInfinity()) {
14606 A = APFloat::copySign(
14607 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14608 B = APFloat::copySign(
14609 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14610 if (C.isNaN())
14611 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14612 if (D.isNaN())
14613 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14614 Recalc = true;
14616 if (C.isInfinity() || D.isInfinity()) {
14617 C = APFloat::copySign(
14618 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14619 D = APFloat::copySign(
14620 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14621 if (A.isNaN())
14622 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14623 if (B.isNaN())
14624 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14625 Recalc = true;
14627 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14628 AD.isInfinity() || BC.isInfinity())) {
14629 if (A.isNaN())
14630 A = APFloat::copySign(APFloat(A.getSemantics()), A);
14631 if (B.isNaN())
14632 B = APFloat::copySign(APFloat(B.getSemantics()), B);
14633 if (C.isNaN())
14634 C = APFloat::copySign(APFloat(C.getSemantics()), C);
14635 if (D.isNaN())
14636 D = APFloat::copySign(APFloat(D.getSemantics()), D);
14637 Recalc = true;
14639 if (Recalc) {
14640 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14641 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14645 } else {
14646 ComplexValue LHS = Result;
14647 Result.getComplexIntReal() =
14648 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14649 LHS.getComplexIntImag() * RHS.getComplexIntImag());
14650 Result.getComplexIntImag() =
14651 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14652 LHS.getComplexIntImag() * RHS.getComplexIntReal());
14654 break;
14655 case BO_Div:
14656 if (Result.isComplexFloat()) {
14657 // This is an implementation of complex division according to the
14658 // constraints laid out in C11 Annex G. The implementation uses the
14659 // following naming scheme:
14660 // (a + ib) / (c + id)
14661 ComplexValue LHS = Result;
14662 APFloat &A = LHS.getComplexFloatReal();
14663 APFloat &B = LHS.getComplexFloatImag();
14664 APFloat &C = RHS.getComplexFloatReal();
14665 APFloat &D = RHS.getComplexFloatImag();
14666 APFloat &ResR = Result.getComplexFloatReal();
14667 APFloat &ResI = Result.getComplexFloatImag();
14668 if (RHSReal) {
14669 ResR = A / C;
14670 ResI = B / C;
14671 } else {
14672 if (LHSReal) {
14673 // No real optimizations we can do here, stub out with zero.
14674 B = APFloat::getZero(A.getSemantics());
14676 int DenomLogB = 0;
14677 APFloat MaxCD = maxnum(abs(C), abs(D));
14678 if (MaxCD.isFinite()) {
14679 DenomLogB = ilogb(MaxCD);
14680 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14681 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14683 APFloat Denom = C * C + D * D;
14684 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14685 APFloat::rmNearestTiesToEven);
14686 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14687 APFloat::rmNearestTiesToEven);
14688 if (ResR.isNaN() && ResI.isNaN()) {
14689 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14690 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14691 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14692 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14693 D.isFinite()) {
14694 A = APFloat::copySign(
14695 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14696 B = APFloat::copySign(
14697 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14698 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14699 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14700 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14701 C = APFloat::copySign(
14702 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14703 D = APFloat::copySign(
14704 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14705 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14706 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14710 } else {
14711 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14712 return Error(E, diag::note_expr_divide_by_zero);
14714 ComplexValue LHS = Result;
14715 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14716 RHS.getComplexIntImag() * RHS.getComplexIntImag();
14717 Result.getComplexIntReal() =
14718 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14719 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14720 Result.getComplexIntImag() =
14721 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14722 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14724 break;
14727 return true;
14730 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14731 // Get the operand value into 'Result'.
14732 if (!Visit(E->getSubExpr()))
14733 return false;
14735 switch (E->getOpcode()) {
14736 default:
14737 return Error(E);
14738 case UO_Extension:
14739 return true;
14740 case UO_Plus:
14741 // The result is always just the subexpr.
14742 return true;
14743 case UO_Minus:
14744 if (Result.isComplexFloat()) {
14745 Result.getComplexFloatReal().changeSign();
14746 Result.getComplexFloatImag().changeSign();
14748 else {
14749 Result.getComplexIntReal() = -Result.getComplexIntReal();
14750 Result.getComplexIntImag() = -Result.getComplexIntImag();
14752 return true;
14753 case UO_Not:
14754 if (Result.isComplexFloat())
14755 Result.getComplexFloatImag().changeSign();
14756 else
14757 Result.getComplexIntImag() = -Result.getComplexIntImag();
14758 return true;
14762 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14763 if (E->getNumInits() == 2) {
14764 if (E->getType()->isComplexType()) {
14765 Result.makeComplexFloat();
14766 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14767 return false;
14768 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14769 return false;
14770 } else {
14771 Result.makeComplexInt();
14772 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14773 return false;
14774 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14775 return false;
14777 return true;
14779 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14782 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14783 if (!IsConstantEvaluatedBuiltinCall(E))
14784 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14786 switch (E->getBuiltinCallee()) {
14787 case Builtin::BI__builtin_complex:
14788 Result.makeComplexFloat();
14789 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14790 return false;
14791 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14792 return false;
14793 return true;
14795 default:
14796 return false;
14800 //===----------------------------------------------------------------------===//
14801 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14802 // implicit conversion.
14803 //===----------------------------------------------------------------------===//
14805 namespace {
14806 class AtomicExprEvaluator :
14807 public ExprEvaluatorBase<AtomicExprEvaluator> {
14808 const LValue *This;
14809 APValue &Result;
14810 public:
14811 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14812 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14814 bool Success(const APValue &V, const Expr *E) {
14815 Result = V;
14816 return true;
14819 bool ZeroInitialization(const Expr *E) {
14820 ImplicitValueInitExpr VIE(
14821 E->getType()->castAs<AtomicType>()->getValueType());
14822 // For atomic-qualified class (and array) types in C++, initialize the
14823 // _Atomic-wrapped subobject directly, in-place.
14824 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14825 : Evaluate(Result, Info, &VIE);
14828 bool VisitCastExpr(const CastExpr *E) {
14829 switch (E->getCastKind()) {
14830 default:
14831 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14832 case CK_NonAtomicToAtomic:
14833 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14834 : Evaluate(Result, Info, E->getSubExpr());
14838 } // end anonymous namespace
14840 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14841 EvalInfo &Info) {
14842 assert(!E->isValueDependent());
14843 assert(E->isPRValue() && E->getType()->isAtomicType());
14844 return AtomicExprEvaluator(Info, This, Result).Visit(E);
14847 //===----------------------------------------------------------------------===//
14848 // Void expression evaluation, primarily for a cast to void on the LHS of a
14849 // comma operator
14850 //===----------------------------------------------------------------------===//
14852 namespace {
14853 class VoidExprEvaluator
14854 : public ExprEvaluatorBase<VoidExprEvaluator> {
14855 public:
14856 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14858 bool Success(const APValue &V, const Expr *e) { return true; }
14860 bool ZeroInitialization(const Expr *E) { return true; }
14862 bool VisitCastExpr(const CastExpr *E) {
14863 switch (E->getCastKind()) {
14864 default:
14865 return ExprEvaluatorBaseTy::VisitCastExpr(E);
14866 case CK_ToVoid:
14867 VisitIgnoredValue(E->getSubExpr());
14868 return true;
14872 bool VisitCallExpr(const CallExpr *E) {
14873 if (!IsConstantEvaluatedBuiltinCall(E))
14874 return ExprEvaluatorBaseTy::VisitCallExpr(E);
14876 switch (E->getBuiltinCallee()) {
14877 case Builtin::BI__assume:
14878 case Builtin::BI__builtin_assume:
14879 // The argument is not evaluated!
14880 return true;
14882 case Builtin::BI__builtin_operator_delete:
14883 return HandleOperatorDeleteCall(Info, E);
14885 default:
14886 return false;
14890 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14892 } // end anonymous namespace
14894 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14895 // We cannot speculatively evaluate a delete expression.
14896 if (Info.SpeculativeEvaluationDepth)
14897 return false;
14899 FunctionDecl *OperatorDelete = E->getOperatorDelete();
14900 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14901 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14902 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14903 return false;
14906 const Expr *Arg = E->getArgument();
14908 LValue Pointer;
14909 if (!EvaluatePointer(Arg, Pointer, Info))
14910 return false;
14911 if (Pointer.Designator.Invalid)
14912 return false;
14914 // Deleting a null pointer has no effect.
14915 if (Pointer.isNullPointer()) {
14916 // This is the only case where we need to produce an extension warning:
14917 // the only other way we can succeed is if we find a dynamic allocation,
14918 // and we will have warned when we allocated it in that case.
14919 if (!Info.getLangOpts().CPlusPlus20)
14920 Info.CCEDiag(E, diag::note_constexpr_new);
14921 return true;
14924 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
14925 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14926 if (!Alloc)
14927 return false;
14928 QualType AllocType = Pointer.Base.getDynamicAllocType();
14930 // For the non-array case, the designator must be empty if the static type
14931 // does not have a virtual destructor.
14932 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14933 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14934 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14935 << Arg->getType()->getPointeeType() << AllocType;
14936 return false;
14939 // For a class type with a virtual destructor, the selected operator delete
14940 // is the one looked up when building the destructor.
14941 if (!E->isArrayForm() && !E->isGlobalDelete()) {
14942 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14943 if (VirtualDelete &&
14944 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14945 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14946 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14947 return false;
14951 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14952 (*Alloc)->Value, AllocType))
14953 return false;
14955 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14956 // The element was already erased. This means the destructor call also
14957 // deleted the object.
14958 // FIXME: This probably results in undefined behavior before we get this
14959 // far, and should be diagnosed elsewhere first.
14960 Info.FFDiag(E, diag::note_constexpr_double_delete);
14961 return false;
14964 return true;
14967 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14968 assert(!E->isValueDependent());
14969 assert(E->isPRValue() && E->getType()->isVoidType());
14970 return VoidExprEvaluator(Info).Visit(E);
14973 //===----------------------------------------------------------------------===//
14974 // Top level Expr::EvaluateAsRValue method.
14975 //===----------------------------------------------------------------------===//
14977 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14978 assert(!E->isValueDependent());
14979 // In C, function designators are not lvalues, but we evaluate them as if they
14980 // are.
14981 QualType T = E->getType();
14982 if (E->isGLValue() || T->isFunctionType()) {
14983 LValue LV;
14984 if (!EvaluateLValue(E, LV, Info))
14985 return false;
14986 LV.moveInto(Result);
14987 } else if (T->isVectorType()) {
14988 if (!EvaluateVector(E, Result, Info))
14989 return false;
14990 } else if (T->isIntegralOrEnumerationType()) {
14991 if (!IntExprEvaluator(Info, Result).Visit(E))
14992 return false;
14993 } else if (T->hasPointerRepresentation()) {
14994 LValue LV;
14995 if (!EvaluatePointer(E, LV, Info))
14996 return false;
14997 LV.moveInto(Result);
14998 } else if (T->isRealFloatingType()) {
14999 llvm::APFloat F(0.0);
15000 if (!EvaluateFloat(E, F, Info))
15001 return false;
15002 Result = APValue(F);
15003 } else if (T->isAnyComplexType()) {
15004 ComplexValue C;
15005 if (!EvaluateComplex(E, C, Info))
15006 return false;
15007 C.moveInto(Result);
15008 } else if (T->isFixedPointType()) {
15009 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
15010 } else if (T->isMemberPointerType()) {
15011 MemberPtr P;
15012 if (!EvaluateMemberPointer(E, P, Info))
15013 return false;
15014 P.moveInto(Result);
15015 return true;
15016 } else if (T->isArrayType()) {
15017 LValue LV;
15018 APValue &Value =
15019 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15020 if (!EvaluateArray(E, LV, Value, Info))
15021 return false;
15022 Result = Value;
15023 } else if (T->isRecordType()) {
15024 LValue LV;
15025 APValue &Value =
15026 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15027 if (!EvaluateRecord(E, LV, Value, Info))
15028 return false;
15029 Result = Value;
15030 } else if (T->isVoidType()) {
15031 if (!Info.getLangOpts().CPlusPlus11)
15032 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
15033 << E->getType();
15034 if (!EvaluateVoid(E, Info))
15035 return false;
15036 } else if (T->isAtomicType()) {
15037 QualType Unqual = T.getAtomicUnqualifiedType();
15038 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15039 LValue LV;
15040 APValue &Value = Info.CurrentCall->createTemporary(
15041 E, Unqual, ScopeKind::FullExpression, LV);
15042 if (!EvaluateAtomic(E, &LV, Value, Info))
15043 return false;
15044 } else {
15045 if (!EvaluateAtomic(E, nullptr, Result, Info))
15046 return false;
15048 } else if (Info.getLangOpts().CPlusPlus11) {
15049 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15050 return false;
15051 } else {
15052 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
15053 return false;
15056 return true;
15059 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15060 /// cases, the in-place evaluation is essential, since later initializers for
15061 /// an object can indirectly refer to subobjects which were initialized earlier.
15062 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
15063 const Expr *E, bool AllowNonLiteralTypes) {
15064 assert(!E->isValueDependent());
15066 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
15067 return false;
15069 if (E->isPRValue()) {
15070 // Evaluate arrays and record types in-place, so that later initializers can
15071 // refer to earlier-initialized members of the object.
15072 QualType T = E->getType();
15073 if (T->isArrayType())
15074 return EvaluateArray(E, This, Result, Info);
15075 else if (T->isRecordType())
15076 return EvaluateRecord(E, This, Result, Info);
15077 else if (T->isAtomicType()) {
15078 QualType Unqual = T.getAtomicUnqualifiedType();
15079 if (Unqual->isArrayType() || Unqual->isRecordType())
15080 return EvaluateAtomic(E, &This, Result, Info);
15084 // For any other type, in-place evaluation is unimportant.
15085 return Evaluate(Result, Info, E);
15088 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15089 /// lvalue-to-rvalue cast if it is an lvalue.
15090 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
15091 assert(!E->isValueDependent());
15093 if (E->getType().isNull())
15094 return false;
15096 if (!CheckLiteralType(Info, E))
15097 return false;
15099 if (Info.EnableNewConstInterp) {
15100 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
15101 return false;
15102 } else {
15103 if (!::Evaluate(Result, Info, E))
15104 return false;
15107 // Implicit lvalue-to-rvalue cast.
15108 if (E->isGLValue()) {
15109 LValue LV;
15110 LV.setFrom(Info.Ctx, Result);
15111 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15112 return false;
15115 // Check this core constant expression is a constant expression.
15116 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15117 ConstantExprKind::Normal) &&
15118 CheckMemoryLeaks(Info);
15121 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
15122 const ASTContext &Ctx, bool &IsConst) {
15123 // Fast-path evaluations of integer literals, since we sometimes see files
15124 // containing vast quantities of these.
15125 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
15126 Result.Val = APValue(APSInt(L->getValue(),
15127 L->getType()->isUnsignedIntegerType()));
15128 IsConst = true;
15129 return true;
15132 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
15133 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15134 IsConst = true;
15135 return true;
15138 // This case should be rare, but we need to check it before we check on
15139 // the type below.
15140 if (Exp->getType().isNull()) {
15141 IsConst = false;
15142 return true;
15145 // FIXME: Evaluating values of large array and record types can cause
15146 // performance problems. Only do so in C++11 for now.
15147 if (Exp->isPRValue() &&
15148 (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
15149 !Ctx.getLangOpts().CPlusPlus11) {
15150 IsConst = false;
15151 return true;
15153 return false;
15156 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
15157 Expr::SideEffectsKind SEK) {
15158 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
15159 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
15162 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
15163 const ASTContext &Ctx, EvalInfo &Info) {
15164 assert(!E->isValueDependent());
15165 bool IsConst;
15166 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
15167 return IsConst;
15169 return EvaluateAsRValue(Info, E, Result.Val);
15172 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
15173 const ASTContext &Ctx,
15174 Expr::SideEffectsKind AllowSideEffects,
15175 EvalInfo &Info) {
15176 assert(!E->isValueDependent());
15177 if (!E->getType()->isIntegralOrEnumerationType())
15178 return false;
15180 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
15181 !ExprResult.Val.isInt() ||
15182 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15183 return false;
15185 return true;
15188 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
15189 const ASTContext &Ctx,
15190 Expr::SideEffectsKind AllowSideEffects,
15191 EvalInfo &Info) {
15192 assert(!E->isValueDependent());
15193 if (!E->getType()->isFixedPointType())
15194 return false;
15196 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
15197 return false;
15199 if (!ExprResult.Val.isFixedPoint() ||
15200 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15201 return false;
15203 return true;
15206 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15207 /// any crazy technique (that has nothing to do with language standards) that
15208 /// we want to. If this function returns true, it returns the folded constant
15209 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
15210 /// will be applied to the result.
15211 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
15212 bool InConstantContext) const {
15213 assert(!isValueDependent() &&
15214 "Expression evaluator can't be called on a dependent expression.");
15215 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
15216 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15217 Info.InConstantContext = InConstantContext;
15218 return ::EvaluateAsRValue(this, Result, Ctx, Info);
15221 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
15222 bool InConstantContext) const {
15223 assert(!isValueDependent() &&
15224 "Expression evaluator can't be called on a dependent expression.");
15225 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
15226 EvalResult Scratch;
15227 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
15228 HandleConversionToBool(Scratch.Val, Result);
15231 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
15232 SideEffectsKind AllowSideEffects,
15233 bool InConstantContext) const {
15234 assert(!isValueDependent() &&
15235 "Expression evaluator can't be called on a dependent expression.");
15236 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
15237 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15238 Info.InConstantContext = InConstantContext;
15239 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
15242 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
15243 SideEffectsKind AllowSideEffects,
15244 bool InConstantContext) const {
15245 assert(!isValueDependent() &&
15246 "Expression evaluator can't be called on a dependent expression.");
15247 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
15248 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
15249 Info.InConstantContext = InConstantContext;
15250 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
15253 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
15254 SideEffectsKind AllowSideEffects,
15255 bool InConstantContext) const {
15256 assert(!isValueDependent() &&
15257 "Expression evaluator can't be called on a dependent expression.");
15259 if (!getType()->isRealFloatingType())
15260 return false;
15262 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
15263 EvalResult ExprResult;
15264 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
15265 !ExprResult.Val.isFloat() ||
15266 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
15267 return false;
15269 Result = ExprResult.Val.getFloat();
15270 return true;
15273 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
15274 bool InConstantContext) const {
15275 assert(!isValueDependent() &&
15276 "Expression evaluator can't be called on a dependent expression.");
15278 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
15279 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
15280 Info.InConstantContext = InConstantContext;
15281 LValue LV;
15282 CheckedTemporaries CheckedTemps;
15283 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
15284 Result.HasSideEffects ||
15285 !CheckLValueConstantExpression(Info, getExprLoc(),
15286 Ctx.getLValueReferenceType(getType()), LV,
15287 ConstantExprKind::Normal, CheckedTemps))
15288 return false;
15290 LV.moveInto(Result.Val);
15291 return true;
15294 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
15295 APValue DestroyedValue, QualType Type,
15296 SourceLocation Loc, Expr::EvalStatus &EStatus,
15297 bool IsConstantDestruction) {
15298 EvalInfo Info(Ctx, EStatus,
15299 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
15300 : EvalInfo::EM_ConstantFold);
15301 Info.setEvaluatingDecl(Base, DestroyedValue,
15302 EvalInfo::EvaluatingDeclKind::Dtor);
15303 Info.InConstantContext = IsConstantDestruction;
15305 LValue LVal;
15306 LVal.set(Base);
15308 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
15309 EStatus.HasSideEffects)
15310 return false;
15312 if (!Info.discardCleanups())
15313 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15315 return true;
15318 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
15319 ConstantExprKind Kind) const {
15320 assert(!isValueDependent() &&
15321 "Expression evaluator can't be called on a dependent expression.");
15322 bool IsConst;
15323 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
15324 return true;
15326 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
15327 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
15328 EvalInfo Info(Ctx, Result, EM);
15329 Info.InConstantContext = true;
15331 // The type of the object we're initializing is 'const T' for a class NTTP.
15332 QualType T = getType();
15333 if (Kind == ConstantExprKind::ClassTemplateArgument)
15334 T.addConst();
15336 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
15337 // represent the result of the evaluation. CheckConstantExpression ensures
15338 // this doesn't escape.
15339 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
15340 APValue::LValueBase Base(&BaseMTE);
15342 Info.setEvaluatingDecl(Base, Result.Val);
15343 LValue LVal;
15344 LVal.set(Base);
15346 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
15347 return false;
15349 if (!Info.discardCleanups())
15350 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15352 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
15353 Result.Val, Kind))
15354 return false;
15355 if (!CheckMemoryLeaks(Info))
15356 return false;
15358 // If this is a class template argument, it's required to have constant
15359 // destruction too.
15360 if (Kind == ConstantExprKind::ClassTemplateArgument &&
15361 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
15362 true) ||
15363 Result.HasSideEffects)) {
15364 // FIXME: Prefix a note to indicate that the problem is lack of constant
15365 // destruction.
15366 return false;
15369 return true;
15372 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
15373 const VarDecl *VD,
15374 SmallVectorImpl<PartialDiagnosticAt> &Notes,
15375 bool IsConstantInitialization) const {
15376 assert(!isValueDependent() &&
15377 "Expression evaluator can't be called on a dependent expression.");
15379 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
15380 std::string Name;
15381 llvm::raw_string_ostream OS(Name);
15382 VD->printQualifiedName(OS);
15383 return Name;
15386 // FIXME: Evaluating initializers for large array and record types can cause
15387 // performance problems. Only do so in C++11 for now.
15388 if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
15389 !Ctx.getLangOpts().CPlusPlus11)
15390 return false;
15392 Expr::EvalStatus EStatus;
15393 EStatus.Diag = &Notes;
15395 EvalInfo Info(Ctx, EStatus,
15396 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
15397 ? EvalInfo::EM_ConstantExpression
15398 : EvalInfo::EM_ConstantFold);
15399 Info.setEvaluatingDecl(VD, Value);
15400 Info.InConstantContext = IsConstantInitialization;
15402 SourceLocation DeclLoc = VD->getLocation();
15403 QualType DeclTy = VD->getType();
15405 if (Info.EnableNewConstInterp) {
15406 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
15407 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
15408 return false;
15409 } else {
15410 LValue LVal;
15411 LVal.set(VD);
15413 if (!EvaluateInPlace(Value, Info, LVal, this,
15414 /*AllowNonLiteralTypes=*/true) ||
15415 EStatus.HasSideEffects)
15416 return false;
15418 // At this point, any lifetime-extended temporaries are completely
15419 // initialized.
15420 Info.performLifetimeExtension();
15422 if (!Info.discardCleanups())
15423 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
15425 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
15426 ConstantExprKind::Normal) &&
15427 CheckMemoryLeaks(Info);
15430 bool VarDecl::evaluateDestruction(
15431 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
15432 Expr::EvalStatus EStatus;
15433 EStatus.Diag = &Notes;
15435 // Only treat the destruction as constant destruction if we formally have
15436 // constant initialization (or are usable in a constant expression).
15437 bool IsConstantDestruction = hasConstantInitialization();
15439 // Make a copy of the value for the destructor to mutate, if we know it.
15440 // Otherwise, treat the value as default-initialized; if the destructor works
15441 // anyway, then the destruction is constant (and must be essentially empty).
15442 APValue DestroyedValue;
15443 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
15444 DestroyedValue = *getEvaluatedValue();
15445 else if (!getDefaultInitValue(getType(), DestroyedValue))
15446 return false;
15448 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
15449 getType(), getLocation(), EStatus,
15450 IsConstantDestruction) ||
15451 EStatus.HasSideEffects)
15452 return false;
15454 ensureEvaluatedStmt()->HasConstantDestruction = true;
15455 return true;
15458 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
15459 /// constant folded, but discard the result.
15460 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
15461 assert(!isValueDependent() &&
15462 "Expression evaluator can't be called on a dependent expression.");
15464 EvalResult Result;
15465 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
15466 !hasUnacceptableSideEffect(Result, SEK);
15469 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
15470 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15471 assert(!isValueDependent() &&
15472 "Expression evaluator can't be called on a dependent expression.");
15474 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
15475 EvalResult EVResult;
15476 EVResult.Diag = Diag;
15477 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15478 Info.InConstantContext = true;
15480 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
15481 (void)Result;
15482 assert(Result && "Could not evaluate expression");
15483 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15485 return EVResult.Val.getInt();
15488 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
15489 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
15490 assert(!isValueDependent() &&
15491 "Expression evaluator can't be called on a dependent expression.");
15493 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
15494 EvalResult EVResult;
15495 EVResult.Diag = Diag;
15496 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15497 Info.InConstantContext = true;
15498 Info.CheckingForUndefinedBehavior = true;
15500 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
15501 (void)Result;
15502 assert(Result && "Could not evaluate expression");
15503 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
15505 return EVResult.Val.getInt();
15508 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
15509 assert(!isValueDependent() &&
15510 "Expression evaluator can't be called on a dependent expression.");
15512 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
15513 bool IsConst;
15514 EvalResult EVResult;
15515 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15516 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15517 Info.CheckingForUndefinedBehavior = true;
15518 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15522 bool Expr::EvalResult::isGlobalLValue() const {
15523 assert(Val.isLValue());
15524 return IsGlobalLValue(Val.getLValueBase());
15527 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15528 /// an integer constant expression.
15530 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15531 /// comma, etc
15533 // CheckICE - This function does the fundamental ICE checking: the returned
15534 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15535 // and a (possibly null) SourceLocation indicating the location of the problem.
15537 // Note that to reduce code duplication, this helper does no evaluation
15538 // itself; the caller checks whether the expression is evaluatable, and
15539 // in the rare cases where CheckICE actually cares about the evaluated
15540 // value, it calls into Evaluate.
15542 namespace {
15544 enum ICEKind {
15545 /// This expression is an ICE.
15546 IK_ICE,
15547 /// This expression is not an ICE, but if it isn't evaluated, it's
15548 /// a legal subexpression for an ICE. This return value is used to handle
15549 /// the comma operator in C99 mode, and non-constant subexpressions.
15550 IK_ICEIfUnevaluated,
15551 /// This expression is not an ICE, and is not a legal subexpression for one.
15552 IK_NotICE
15555 struct ICEDiag {
15556 ICEKind Kind;
15557 SourceLocation Loc;
15559 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15564 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15566 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15568 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15569 Expr::EvalResult EVResult;
15570 Expr::EvalStatus Status;
15571 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15573 Info.InConstantContext = true;
15574 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15575 !EVResult.Val.isInt())
15576 return ICEDiag(IK_NotICE, E->getBeginLoc());
15578 return NoDiag();
15581 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15582 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15583 if (!E->getType()->isIntegralOrEnumerationType())
15584 return ICEDiag(IK_NotICE, E->getBeginLoc());
15586 switch (E->getStmtClass()) {
15587 #define ABSTRACT_STMT(Node)
15588 #define STMT(Node, Base) case Expr::Node##Class:
15589 #define EXPR(Node, Base)
15590 #include "clang/AST/StmtNodes.inc"
15591 case Expr::PredefinedExprClass:
15592 case Expr::FloatingLiteralClass:
15593 case Expr::ImaginaryLiteralClass:
15594 case Expr::StringLiteralClass:
15595 case Expr::ArraySubscriptExprClass:
15596 case Expr::MatrixSubscriptExprClass:
15597 case Expr::OMPArraySectionExprClass:
15598 case Expr::OMPArrayShapingExprClass:
15599 case Expr::OMPIteratorExprClass:
15600 case Expr::MemberExprClass:
15601 case Expr::CompoundAssignOperatorClass:
15602 case Expr::CompoundLiteralExprClass:
15603 case Expr::ExtVectorElementExprClass:
15604 case Expr::DesignatedInitExprClass:
15605 case Expr::ArrayInitLoopExprClass:
15606 case Expr::ArrayInitIndexExprClass:
15607 case Expr::NoInitExprClass:
15608 case Expr::DesignatedInitUpdateExprClass:
15609 case Expr::ImplicitValueInitExprClass:
15610 case Expr::ParenListExprClass:
15611 case Expr::VAArgExprClass:
15612 case Expr::AddrLabelExprClass:
15613 case Expr::StmtExprClass:
15614 case Expr::CXXMemberCallExprClass:
15615 case Expr::CUDAKernelCallExprClass:
15616 case Expr::CXXAddrspaceCastExprClass:
15617 case Expr::CXXDynamicCastExprClass:
15618 case Expr::CXXTypeidExprClass:
15619 case Expr::CXXUuidofExprClass:
15620 case Expr::MSPropertyRefExprClass:
15621 case Expr::MSPropertySubscriptExprClass:
15622 case Expr::CXXNullPtrLiteralExprClass:
15623 case Expr::UserDefinedLiteralClass:
15624 case Expr::CXXThisExprClass:
15625 case Expr::CXXThrowExprClass:
15626 case Expr::CXXNewExprClass:
15627 case Expr::CXXDeleteExprClass:
15628 case Expr::CXXPseudoDestructorExprClass:
15629 case Expr::UnresolvedLookupExprClass:
15630 case Expr::TypoExprClass:
15631 case Expr::RecoveryExprClass:
15632 case Expr::DependentScopeDeclRefExprClass:
15633 case Expr::CXXConstructExprClass:
15634 case Expr::CXXInheritedCtorInitExprClass:
15635 case Expr::CXXStdInitializerListExprClass:
15636 case Expr::CXXBindTemporaryExprClass:
15637 case Expr::ExprWithCleanupsClass:
15638 case Expr::CXXTemporaryObjectExprClass:
15639 case Expr::CXXUnresolvedConstructExprClass:
15640 case Expr::CXXDependentScopeMemberExprClass:
15641 case Expr::UnresolvedMemberExprClass:
15642 case Expr::ObjCStringLiteralClass:
15643 case Expr::ObjCBoxedExprClass:
15644 case Expr::ObjCArrayLiteralClass:
15645 case Expr::ObjCDictionaryLiteralClass:
15646 case Expr::ObjCEncodeExprClass:
15647 case Expr::ObjCMessageExprClass:
15648 case Expr::ObjCSelectorExprClass:
15649 case Expr::ObjCProtocolExprClass:
15650 case Expr::ObjCIvarRefExprClass:
15651 case Expr::ObjCPropertyRefExprClass:
15652 case Expr::ObjCSubscriptRefExprClass:
15653 case Expr::ObjCIsaExprClass:
15654 case Expr::ObjCAvailabilityCheckExprClass:
15655 case Expr::ShuffleVectorExprClass:
15656 case Expr::ConvertVectorExprClass:
15657 case Expr::BlockExprClass:
15658 case Expr::NoStmtClass:
15659 case Expr::OpaqueValueExprClass:
15660 case Expr::PackExpansionExprClass:
15661 case Expr::SubstNonTypeTemplateParmPackExprClass:
15662 case Expr::FunctionParmPackExprClass:
15663 case Expr::AsTypeExprClass:
15664 case Expr::ObjCIndirectCopyRestoreExprClass:
15665 case Expr::MaterializeTemporaryExprClass:
15666 case Expr::PseudoObjectExprClass:
15667 case Expr::AtomicExprClass:
15668 case Expr::LambdaExprClass:
15669 case Expr::CXXFoldExprClass:
15670 case Expr::CoawaitExprClass:
15671 case Expr::DependentCoawaitExprClass:
15672 case Expr::CoyieldExprClass:
15673 case Expr::SYCLUniqueStableNameExprClass:
15674 case Expr::CXXParenListInitExprClass:
15675 return ICEDiag(IK_NotICE, E->getBeginLoc());
15677 case Expr::InitListExprClass: {
15678 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15679 // form "T x = { a };" is equivalent to "T x = a;".
15680 // Unless we're initializing a reference, T is a scalar as it is known to be
15681 // of integral or enumeration type.
15682 if (E->isPRValue())
15683 if (cast<InitListExpr>(E)->getNumInits() == 1)
15684 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15685 return ICEDiag(IK_NotICE, E->getBeginLoc());
15688 case Expr::SizeOfPackExprClass:
15689 case Expr::GNUNullExprClass:
15690 case Expr::SourceLocExprClass:
15691 return NoDiag();
15693 case Expr::SubstNonTypeTemplateParmExprClass:
15694 return
15695 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15697 case Expr::ConstantExprClass:
15698 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15700 case Expr::ParenExprClass:
15701 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15702 case Expr::GenericSelectionExprClass:
15703 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15704 case Expr::IntegerLiteralClass:
15705 case Expr::FixedPointLiteralClass:
15706 case Expr::CharacterLiteralClass:
15707 case Expr::ObjCBoolLiteralExprClass:
15708 case Expr::CXXBoolLiteralExprClass:
15709 case Expr::CXXScalarValueInitExprClass:
15710 case Expr::TypeTraitExprClass:
15711 case Expr::ConceptSpecializationExprClass:
15712 case Expr::RequiresExprClass:
15713 case Expr::ArrayTypeTraitExprClass:
15714 case Expr::ExpressionTraitExprClass:
15715 case Expr::CXXNoexceptExprClass:
15716 return NoDiag();
15717 case Expr::CallExprClass:
15718 case Expr::CXXOperatorCallExprClass: {
15719 // C99 6.6/3 allows function calls within unevaluated subexpressions of
15720 // constant expressions, but they can never be ICEs because an ICE cannot
15721 // contain an operand of (pointer to) function type.
15722 const CallExpr *CE = cast<CallExpr>(E);
15723 if (CE->getBuiltinCallee())
15724 return CheckEvalInICE(E, Ctx);
15725 return ICEDiag(IK_NotICE, E->getBeginLoc());
15727 case Expr::CXXRewrittenBinaryOperatorClass:
15728 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15729 Ctx);
15730 case Expr::DeclRefExprClass: {
15731 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15732 if (isa<EnumConstantDecl>(D))
15733 return NoDiag();
15735 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15736 // integer variables in constant expressions:
15738 // C++ 7.1.5.1p2
15739 // A variable of non-volatile const-qualified integral or enumeration
15740 // type initialized by an ICE can be used in ICEs.
15742 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15743 // that mode, use of reference variables should not be allowed.
15744 const VarDecl *VD = dyn_cast<VarDecl>(D);
15745 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15746 !VD->getType()->isReferenceType())
15747 return NoDiag();
15749 return ICEDiag(IK_NotICE, E->getBeginLoc());
15751 case Expr::UnaryOperatorClass: {
15752 const UnaryOperator *Exp = cast<UnaryOperator>(E);
15753 switch (Exp->getOpcode()) {
15754 case UO_PostInc:
15755 case UO_PostDec:
15756 case UO_PreInc:
15757 case UO_PreDec:
15758 case UO_AddrOf:
15759 case UO_Deref:
15760 case UO_Coawait:
15761 // C99 6.6/3 allows increment and decrement within unevaluated
15762 // subexpressions of constant expressions, but they can never be ICEs
15763 // because an ICE cannot contain an lvalue operand.
15764 return ICEDiag(IK_NotICE, E->getBeginLoc());
15765 case UO_Extension:
15766 case UO_LNot:
15767 case UO_Plus:
15768 case UO_Minus:
15769 case UO_Not:
15770 case UO_Real:
15771 case UO_Imag:
15772 return CheckICE(Exp->getSubExpr(), Ctx);
15774 llvm_unreachable("invalid unary operator class");
15776 case Expr::OffsetOfExprClass: {
15777 // Note that per C99, offsetof must be an ICE. And AFAIK, using
15778 // EvaluateAsRValue matches the proposed gcc behavior for cases like
15779 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
15780 // compliance: we should warn earlier for offsetof expressions with
15781 // array subscripts that aren't ICEs, and if the array subscripts
15782 // are ICEs, the value of the offsetof must be an integer constant.
15783 return CheckEvalInICE(E, Ctx);
15785 case Expr::UnaryExprOrTypeTraitExprClass: {
15786 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15787 if ((Exp->getKind() == UETT_SizeOf) &&
15788 Exp->getTypeOfArgument()->isVariableArrayType())
15789 return ICEDiag(IK_NotICE, E->getBeginLoc());
15790 return NoDiag();
15792 case Expr::BinaryOperatorClass: {
15793 const BinaryOperator *Exp = cast<BinaryOperator>(E);
15794 switch (Exp->getOpcode()) {
15795 case BO_PtrMemD:
15796 case BO_PtrMemI:
15797 case BO_Assign:
15798 case BO_MulAssign:
15799 case BO_DivAssign:
15800 case BO_RemAssign:
15801 case BO_AddAssign:
15802 case BO_SubAssign:
15803 case BO_ShlAssign:
15804 case BO_ShrAssign:
15805 case BO_AndAssign:
15806 case BO_XorAssign:
15807 case BO_OrAssign:
15808 // C99 6.6/3 allows assignments within unevaluated subexpressions of
15809 // constant expressions, but they can never be ICEs because an ICE cannot
15810 // contain an lvalue operand.
15811 return ICEDiag(IK_NotICE, E->getBeginLoc());
15813 case BO_Mul:
15814 case BO_Div:
15815 case BO_Rem:
15816 case BO_Add:
15817 case BO_Sub:
15818 case BO_Shl:
15819 case BO_Shr:
15820 case BO_LT:
15821 case BO_GT:
15822 case BO_LE:
15823 case BO_GE:
15824 case BO_EQ:
15825 case BO_NE:
15826 case BO_And:
15827 case BO_Xor:
15828 case BO_Or:
15829 case BO_Comma:
15830 case BO_Cmp: {
15831 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15832 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15833 if (Exp->getOpcode() == BO_Div ||
15834 Exp->getOpcode() == BO_Rem) {
15835 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15836 // we don't evaluate one.
15837 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15838 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15839 if (REval == 0)
15840 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15841 if (REval.isSigned() && REval.isAllOnes()) {
15842 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15843 if (LEval.isMinSignedValue())
15844 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15848 if (Exp->getOpcode() == BO_Comma) {
15849 if (Ctx.getLangOpts().C99) {
15850 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15851 // if it isn't evaluated.
15852 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15853 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15854 } else {
15855 // In both C89 and C++, commas in ICEs are illegal.
15856 return ICEDiag(IK_NotICE, E->getBeginLoc());
15859 return Worst(LHSResult, RHSResult);
15861 case BO_LAnd:
15862 case BO_LOr: {
15863 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15864 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15865 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15866 // Rare case where the RHS has a comma "side-effect"; we need
15867 // to actually check the condition to see whether the side
15868 // with the comma is evaluated.
15869 if ((Exp->getOpcode() == BO_LAnd) !=
15870 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15871 return RHSResult;
15872 return NoDiag();
15875 return Worst(LHSResult, RHSResult);
15878 llvm_unreachable("invalid binary operator kind");
15880 case Expr::ImplicitCastExprClass:
15881 case Expr::CStyleCastExprClass:
15882 case Expr::CXXFunctionalCastExprClass:
15883 case Expr::CXXStaticCastExprClass:
15884 case Expr::CXXReinterpretCastExprClass:
15885 case Expr::CXXConstCastExprClass:
15886 case Expr::ObjCBridgedCastExprClass: {
15887 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15888 if (isa<ExplicitCastExpr>(E)) {
15889 if (const FloatingLiteral *FL
15890 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15891 unsigned DestWidth = Ctx.getIntWidth(E->getType());
15892 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15893 APSInt IgnoredVal(DestWidth, !DestSigned);
15894 bool Ignored;
15895 // If the value does not fit in the destination type, the behavior is
15896 // undefined, so we are not required to treat it as a constant
15897 // expression.
15898 if (FL->getValue().convertToInteger(IgnoredVal,
15899 llvm::APFloat::rmTowardZero,
15900 &Ignored) & APFloat::opInvalidOp)
15901 return ICEDiag(IK_NotICE, E->getBeginLoc());
15902 return NoDiag();
15905 switch (cast<CastExpr>(E)->getCastKind()) {
15906 case CK_LValueToRValue:
15907 case CK_AtomicToNonAtomic:
15908 case CK_NonAtomicToAtomic:
15909 case CK_NoOp:
15910 case CK_IntegralToBoolean:
15911 case CK_IntegralCast:
15912 return CheckICE(SubExpr, Ctx);
15913 default:
15914 return ICEDiag(IK_NotICE, E->getBeginLoc());
15917 case Expr::BinaryConditionalOperatorClass: {
15918 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15919 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15920 if (CommonResult.Kind == IK_NotICE) return CommonResult;
15921 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15922 if (FalseResult.Kind == IK_NotICE) return FalseResult;
15923 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15924 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15925 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15926 return FalseResult;
15928 case Expr::ConditionalOperatorClass: {
15929 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15930 // If the condition (ignoring parens) is a __builtin_constant_p call,
15931 // then only the true side is actually considered in an integer constant
15932 // expression, and it is fully evaluated. This is an important GNU
15933 // extension. See GCC PR38377 for discussion.
15934 if (const CallExpr *CallCE
15935 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15936 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15937 return CheckEvalInICE(E, Ctx);
15938 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15939 if (CondResult.Kind == IK_NotICE)
15940 return CondResult;
15942 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15943 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15945 if (TrueResult.Kind == IK_NotICE)
15946 return TrueResult;
15947 if (FalseResult.Kind == IK_NotICE)
15948 return FalseResult;
15949 if (CondResult.Kind == IK_ICEIfUnevaluated)
15950 return CondResult;
15951 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15952 return NoDiag();
15953 // Rare case where the diagnostics depend on which side is evaluated
15954 // Note that if we get here, CondResult is 0, and at least one of
15955 // TrueResult and FalseResult is non-zero.
15956 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15957 return FalseResult;
15958 return TrueResult;
15960 case Expr::CXXDefaultArgExprClass:
15961 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15962 case Expr::CXXDefaultInitExprClass:
15963 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15964 case Expr::ChooseExprClass: {
15965 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15967 case Expr::BuiltinBitCastExprClass: {
15968 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15969 return ICEDiag(IK_NotICE, E->getBeginLoc());
15970 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15974 llvm_unreachable("Invalid StmtClass!");
15977 /// Evaluate an expression as a C++11 integral constant expression.
15978 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15979 const Expr *E,
15980 llvm::APSInt *Value,
15981 SourceLocation *Loc) {
15982 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15983 if (Loc) *Loc = E->getExprLoc();
15984 return false;
15987 APValue Result;
15988 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15989 return false;
15991 if (!Result.isInt()) {
15992 if (Loc) *Loc = E->getExprLoc();
15993 return false;
15996 if (Value) *Value = Result.getInt();
15997 return true;
16000 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
16001 SourceLocation *Loc) const {
16002 assert(!isValueDependent() &&
16003 "Expression evaluator can't be called on a dependent expression.");
16005 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
16007 if (Ctx.getLangOpts().CPlusPlus11)
16008 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
16010 ICEDiag D = CheckICE(this, Ctx);
16011 if (D.Kind != IK_ICE) {
16012 if (Loc) *Loc = D.Loc;
16013 return false;
16015 return true;
16018 std::optional<llvm::APSInt>
16019 Expr::getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc,
16020 bool isEvaluated) const {
16021 if (isValueDependent()) {
16022 // Expression evaluator can't succeed on a dependent expression.
16023 return std::nullopt;
16026 APSInt Value;
16028 if (Ctx.getLangOpts().CPlusPlus11) {
16029 if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
16030 return Value;
16031 return std::nullopt;
16034 if (!isIntegerConstantExpr(Ctx, Loc))
16035 return std::nullopt;
16037 // The only possible side-effects here are due to UB discovered in the
16038 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
16039 // required to treat the expression as an ICE, so we produce the folded
16040 // value.
16041 EvalResult ExprResult;
16042 Expr::EvalStatus Status;
16043 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
16044 Info.InConstantContext = true;
16046 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
16047 llvm_unreachable("ICE cannot be evaluated!");
16049 return ExprResult.Val.getInt();
16052 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
16053 assert(!isValueDependent() &&
16054 "Expression evaluator can't be called on a dependent expression.");
16056 return CheckICE(this, Ctx).Kind == IK_ICE;
16059 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
16060 SourceLocation *Loc) const {
16061 assert(!isValueDependent() &&
16062 "Expression evaluator can't be called on a dependent expression.");
16064 // We support this checking in C++98 mode in order to diagnose compatibility
16065 // issues.
16066 assert(Ctx.getLangOpts().CPlusPlus);
16068 // Build evaluation settings.
16069 Expr::EvalStatus Status;
16070 SmallVector<PartialDiagnosticAt, 8> Diags;
16071 Status.Diag = &Diags;
16072 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
16074 APValue Scratch;
16075 bool IsConstExpr =
16076 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
16077 // FIXME: We don't produce a diagnostic for this, but the callers that
16078 // call us on arbitrary full-expressions should generally not care.
16079 Info.discardCleanups() && !Status.HasSideEffects;
16081 if (!Diags.empty()) {
16082 IsConstExpr = false;
16083 if (Loc) *Loc = Diags[0].first;
16084 } else if (!IsConstExpr) {
16085 // FIXME: This shouldn't happen.
16086 if (Loc) *Loc = getExprLoc();
16089 return IsConstExpr;
16092 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
16093 const FunctionDecl *Callee,
16094 ArrayRef<const Expr*> Args,
16095 const Expr *This) const {
16096 assert(!isValueDependent() &&
16097 "Expression evaluator can't be called on a dependent expression.");
16099 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
16100 std::string Name;
16101 llvm::raw_string_ostream OS(Name);
16102 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16103 /*Qualified=*/true);
16104 return Name;
16107 Expr::EvalStatus Status;
16108 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
16109 Info.InConstantContext = true;
16111 LValue ThisVal;
16112 const LValue *ThisPtr = nullptr;
16113 if (This) {
16114 #ifndef NDEBUG
16115 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
16116 assert(MD && "Don't provide `this` for non-methods.");
16117 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
16118 #endif
16119 if (!This->isValueDependent() &&
16120 EvaluateObjectArgument(Info, This, ThisVal) &&
16121 !Info.EvalStatus.HasSideEffects)
16122 ThisPtr = &ThisVal;
16124 // Ignore any side-effects from a failed evaluation. This is safe because
16125 // they can't interfere with any other argument evaluation.
16126 Info.EvalStatus.HasSideEffects = false;
16129 CallRef Call = Info.CurrentCall->createCall(Callee);
16130 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
16131 I != E; ++I) {
16132 unsigned Idx = I - Args.begin();
16133 if (Idx >= Callee->getNumParams())
16134 break;
16135 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16136 if ((*I)->isValueDependent() ||
16137 !EvaluateCallArg(PVD, *I, Call, Info) ||
16138 Info.EvalStatus.HasSideEffects) {
16139 // If evaluation fails, throw away the argument entirely.
16140 if (APValue *Slot = Info.getParamSlot(Call, PVD))
16141 *Slot = APValue();
16144 // Ignore any side-effects from a failed evaluation. This is safe because
16145 // they can't interfere with any other argument evaluation.
16146 Info.EvalStatus.HasSideEffects = false;
16149 // Parameter cleanups happen in the caller and are not part of this
16150 // evaluation.
16151 Info.discardCleanups();
16152 Info.EvalStatus.HasSideEffects = false;
16154 // Build fake call to Callee.
16155 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
16156 // FIXME: Missing ExprWithCleanups in enable_if conditions?
16157 FullExpressionRAII Scope(Info);
16158 return Evaluate(Value, Info, this) && Scope.destroy() &&
16159 !Info.EvalStatus.HasSideEffects;
16162 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
16163 SmallVectorImpl<
16164 PartialDiagnosticAt> &Diags) {
16165 // FIXME: It would be useful to check constexpr function templates, but at the
16166 // moment the constant expression evaluator cannot cope with the non-rigorous
16167 // ASTs which we build for dependent expressions.
16168 if (FD->isDependentContext())
16169 return true;
16171 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
16172 std::string Name;
16173 llvm::raw_string_ostream OS(Name);
16174 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16175 /*Qualified=*/true);
16176 return Name;
16179 Expr::EvalStatus Status;
16180 Status.Diag = &Diags;
16182 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16183 Info.InConstantContext = true;
16184 Info.CheckingPotentialConstantExpression = true;
16186 // The constexpr VM attempts to compile all methods to bytecode here.
16187 if (Info.EnableNewConstInterp) {
16188 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
16189 return Diags.empty();
16192 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
16193 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16195 // Fabricate an arbitrary expression on the stack and pretend that it
16196 // is a temporary being used as the 'this' pointer.
16197 LValue This;
16198 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
16199 This.set({&VIE, Info.CurrentCall->Index});
16201 ArrayRef<const Expr*> Args;
16203 APValue Scratch;
16204 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
16205 // Evaluate the call as a constant initializer, to allow the construction
16206 // of objects of non-literal types.
16207 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
16208 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
16209 } else {
16210 SourceLocation Loc = FD->getLocation();
16211 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
16212 Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
16215 return Diags.empty();
16218 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
16219 const FunctionDecl *FD,
16220 SmallVectorImpl<
16221 PartialDiagnosticAt> &Diags) {
16222 assert(!E->isValueDependent() &&
16223 "Expression evaluator can't be called on a dependent expression.");
16225 Expr::EvalStatus Status;
16226 Status.Diag = &Diags;
16228 EvalInfo Info(FD->getASTContext(), Status,
16229 EvalInfo::EM_ConstantExpressionUnevaluated);
16230 Info.InConstantContext = true;
16231 Info.CheckingPotentialConstantExpression = true;
16233 // Fabricate a call stack frame to give the arguments a plausible cover story.
16234 CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
16236 APValue ResultScratch;
16237 Evaluate(ResultScratch, Info, E);
16238 return Diags.empty();
16241 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
16242 unsigned Type) const {
16243 if (!getType()->isPointerType())
16244 return false;
16246 Expr::EvalStatus Status;
16247 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16248 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
16251 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
16252 EvalInfo &Info) {
16253 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
16254 return false;
16256 LValue String;
16258 if (!EvaluatePointer(E, String, Info))
16259 return false;
16261 QualType CharTy = E->getType()->getPointeeType();
16263 // Fast path: if it's a string literal, search the string value.
16264 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
16265 String.getLValueBase().dyn_cast<const Expr *>())) {
16266 StringRef Str = S->getBytes();
16267 int64_t Off = String.Offset.getQuantity();
16268 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
16269 S->getCharByteWidth() == 1 &&
16270 // FIXME: Add fast-path for wchar_t too.
16271 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
16272 Str = Str.substr(Off);
16274 StringRef::size_type Pos = Str.find(0);
16275 if (Pos != StringRef::npos)
16276 Str = Str.substr(0, Pos);
16278 Result = Str.size();
16279 return true;
16282 // Fall through to slow path.
16285 // Slow path: scan the bytes of the string looking for the terminating 0.
16286 for (uint64_t Strlen = 0; /**/; ++Strlen) {
16287 APValue Char;
16288 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
16289 !Char.isInt())
16290 return false;
16291 if (!Char.getInt()) {
16292 Result = Strlen;
16293 return true;
16295 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
16296 return false;
16300 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
16301 Expr::EvalStatus Status;
16302 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
16303 return EvaluateBuiltinStrLen(this, Result, Info);