1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
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
7 //===----------------------------------------------------------------------===//
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 "clang/AST/APValue.h"
36 #include "clang/AST/ASTContext.h"
37 #include "clang/AST/ASTDiagnostic.h"
38 #include "clang/AST/ASTLambda.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/CurrentSourceLocExprScope.h"
41 #include "clang/AST/CXXInheritance.h"
42 #include "clang/AST/Expr.h"
43 #include "clang/AST/OSLog.h"
44 #include "clang/AST/RecordLayout.h"
45 #include "clang/AST/StmtVisitor.h"
46 #include "clang/AST/TypeLoc.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/FixedPoint.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/SmallBitVector.h"
52 #include "llvm/Support/SaveAndRestore.h"
53 #include "llvm/Support/raw_ostream.h"
57 #define DEBUG_TYPE "exprconstant"
59 using namespace clang;
65 static bool IsGlobalLValue(APValue::LValueBase B);
69 struct CallStackFrame;
72 using SourceLocExprScopeGuard =
73 CurrentSourceLocExprScope::SourceLocExprScopeGuard;
75 static QualType getType(APValue::LValueBase B) {
76 if (!B) return QualType();
77 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
78 // FIXME: It's unclear where we're supposed to take the type from, and
79 // this actually matters for arrays of unknown bound. Eg:
81 // extern int arr[]; void f() { extern int arr[3]; };
82 // constexpr int *p = &arr[1]; // valid?
84 // For now, we take the array bound from the most recent declaration.
85 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
86 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
87 QualType T = Redecl->getType();
88 if (!T->isIncompleteArrayType())
94 if (B.is<TypeInfoLValue>())
95 return B.getTypeInfoType();
97 const Expr *Base = B.get<const Expr*>();
99 // For a materialized temporary, the type of the temporary we materialized
100 // may not be the type of the expression.
101 if (const MaterializeTemporaryExpr *MTE =
102 dyn_cast<MaterializeTemporaryExpr>(Base)) {
103 SmallVector<const Expr *, 2> CommaLHSs;
104 SmallVector<SubobjectAdjustment, 2> Adjustments;
105 const Expr *Temp = MTE->GetTemporaryExpr();
106 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
108 // Keep any cv-qualifiers from the reference if we generated a temporary
109 // for it directly. Otherwise use the type after adjustment.
110 if (!Adjustments.empty())
111 return Inner->getType();
114 return Base->getType();
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// field declaration.
119 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
120 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
122 /// Get an LValue path entry, which is known to not be an array index, as a
123 /// base class declaration.
124 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
125 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
127 /// Determine whether this LValue path entry for a base class names a virtual
129 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
130 return E.getAsBaseOrMember().getInt();
133 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
134 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
135 const FunctionDecl *Callee = CE->getDirectCallee();
136 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
139 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
140 /// This will look through a single cast.
142 /// Returns null if we couldn't unwrap a function with alloc_size.
143 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
144 if (!E->getType()->isPointerType())
147 E = E->IgnoreParens();
148 // If we're doing a variable assignment from e.g. malloc(N), there will
149 // probably be a cast of some kind. In exotic cases, we might also see a
150 // top-level ExprWithCleanups. Ignore them either way.
151 if (const auto *FE = dyn_cast<FullExpr>(E))
152 E = FE->getSubExpr()->IgnoreParens();
154 if (const auto *Cast = dyn_cast<CastExpr>(E))
155 E = Cast->getSubExpr()->IgnoreParens();
157 if (const auto *CE = dyn_cast<CallExpr>(E))
158 return getAllocSizeAttr(CE) ? CE : nullptr;
162 /// Determines whether or not the given Base contains a call to a function
163 /// with the alloc_size attribute.
164 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
165 const auto *E = Base.dyn_cast<const Expr *>();
166 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
169 /// The bound to claim that an array of unknown bound has.
170 /// The value in MostDerivedArraySize is undefined in this case. So, set it
171 /// to an arbitrary value that's likely to loudly break things if it's used.
172 static const uint64_t AssumedSizeForUnsizedArray =
173 std::numeric_limits<uint64_t>::max() / 2;
175 /// Determines if an LValue with the given LValueBase will have an unsized
176 /// array in its designator.
177 /// Find the path length and type of the most-derived subobject in the given
178 /// path, and find the size of the containing array, if any.
180 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
181 ArrayRef<APValue::LValuePathEntry> Path,
182 uint64_t &ArraySize, QualType &Type, bool &IsArray,
183 bool &FirstEntryIsUnsizedArray) {
184 // This only accepts LValueBases from APValues, and APValues don't support
185 // arrays that lack size info.
186 assert(!isBaseAnAllocSizeCall(Base) &&
187 "Unsized arrays shouldn't appear here");
188 unsigned MostDerivedLength = 0;
189 Type = getType(Base);
191 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
192 if (Type->isArrayType()) {
193 const ArrayType *AT = Ctx.getAsArrayType(Type);
194 Type = AT->getElementType();
195 MostDerivedLength = I + 1;
198 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
199 ArraySize = CAT->getSize().getZExtValue();
201 assert(I == 0 && "unexpected unsized array designator");
202 FirstEntryIsUnsizedArray = true;
203 ArraySize = AssumedSizeForUnsizedArray;
205 } else if (Type->isAnyComplexType()) {
206 const ComplexType *CT = Type->castAs<ComplexType>();
207 Type = CT->getElementType();
209 MostDerivedLength = I + 1;
211 } else if (const FieldDecl *FD = getAsField(Path[I])) {
212 Type = FD->getType();
214 MostDerivedLength = I + 1;
217 // Path[I] describes a base class.
222 return MostDerivedLength;
225 // The order of this enum is important for diagnostics.
226 enum CheckSubobjectKind {
227 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
231 /// A path from a glvalue to a subobject of that glvalue.
232 struct SubobjectDesignator {
233 /// True if the subobject was named in a manner not supported by C++11. Such
234 /// lvalues can still be folded, but they are not core constant expressions
235 /// and we cannot perform lvalue-to-rvalue conversions on them.
236 unsigned Invalid : 1;
238 /// Is this a pointer one past the end of an object?
239 unsigned IsOnePastTheEnd : 1;
241 /// Indicator of whether the first entry is an unsized array.
242 unsigned FirstEntryIsAnUnsizedArray : 1;
244 /// Indicator of whether the most-derived object is an array element.
245 unsigned MostDerivedIsArrayElement : 1;
247 /// The length of the path to the most-derived object of which this is a
249 unsigned MostDerivedPathLength : 28;
251 /// The size of the array of which the most-derived object is an element.
252 /// This will always be 0 if the most-derived object is not an array
253 /// element. 0 is not an indicator of whether or not the most-derived object
254 /// is an array, however, because 0-length arrays are allowed.
256 /// If the current array is an unsized array, the value of this is
258 uint64_t MostDerivedArraySize;
260 /// The type of the most derived object referred to by this address.
261 QualType MostDerivedType;
263 typedef APValue::LValuePathEntry PathEntry;
265 /// The entries on the path from the glvalue to the designated subobject.
266 SmallVector<PathEntry, 8> Entries;
268 SubobjectDesignator() : Invalid(true) {}
270 explicit SubobjectDesignator(QualType T)
271 : Invalid(false), IsOnePastTheEnd(false),
272 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
273 MostDerivedPathLength(0), MostDerivedArraySize(0),
274 MostDerivedType(T) {}
276 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
277 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
278 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279 MostDerivedPathLength(0), MostDerivedArraySize(0) {
280 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
282 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
283 ArrayRef<PathEntry> VEntries = V.getLValuePath();
284 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
285 if (V.getLValueBase()) {
286 bool IsArray = false;
287 bool FirstIsUnsizedArray = false;
288 MostDerivedPathLength = findMostDerivedSubobject(
289 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
290 MostDerivedType, IsArray, FirstIsUnsizedArray);
291 MostDerivedIsArrayElement = IsArray;
292 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
298 unsigned NewLength) {
302 assert(Base && "cannot truncate path for null pointer");
303 assert(NewLength <= Entries.size() && "not a truncation");
305 if (NewLength == Entries.size())
307 Entries.resize(NewLength);
309 bool IsArray = false;
310 bool FirstIsUnsizedArray = false;
311 MostDerivedPathLength = findMostDerivedSubobject(
312 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
313 FirstIsUnsizedArray);
314 MostDerivedIsArrayElement = IsArray;
315 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
323 /// Determine whether the most derived subobject is an array without a
325 bool isMostDerivedAnUnsizedArray() const {
326 assert(!Invalid && "Calling this makes no sense on invalid designators");
327 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
330 /// Determine what the most derived array's size is. Results in an assertion
331 /// failure if the most derived array lacks a size.
332 uint64_t getMostDerivedArraySize() const {
333 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
334 return MostDerivedArraySize;
337 /// Determine whether this is a one-past-the-end pointer.
338 bool isOnePastTheEnd() const {
342 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
343 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
344 MostDerivedArraySize)
349 /// Get the range of valid index adjustments in the form
350 /// {maximum value that can be subtracted from this pointer,
351 /// maximum value that can be added to this pointer}
352 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
353 if (Invalid || isMostDerivedAnUnsizedArray())
356 // [expr.add]p4: For the purposes of these operators, a pointer to a
357 // nonarray object behaves the same as a pointer to the first element of
358 // an array of length one with the type of the object as its element type.
359 bool IsArray = MostDerivedPathLength == Entries.size() &&
360 MostDerivedIsArrayElement;
361 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
362 : (uint64_t)IsOnePastTheEnd;
364 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
365 return {ArrayIndex, ArraySize - ArrayIndex};
368 /// Check that this refers to a valid subobject.
369 bool isValidSubobject() const {
372 return !isOnePastTheEnd();
374 /// Check that this refers to a valid subobject, and if not, produce a
375 /// relevant diagnostic and set the designator as invalid.
376 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
378 /// Get the type of the designated object.
379 QualType getType(ASTContext &Ctx) const {
380 assert(!Invalid && "invalid designator has no subobject type");
381 return MostDerivedPathLength == Entries.size()
383 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
386 /// Update this designator to refer to the first element within this array.
387 void addArrayUnchecked(const ConstantArrayType *CAT) {
388 Entries.push_back(PathEntry::ArrayIndex(0));
390 // This is a most-derived object.
391 MostDerivedType = CAT->getElementType();
392 MostDerivedIsArrayElement = true;
393 MostDerivedArraySize = CAT->getSize().getZExtValue();
394 MostDerivedPathLength = Entries.size();
396 /// Update this designator to refer to the first element within the array of
397 /// elements of type T. This is an array of unknown size.
398 void addUnsizedArrayUnchecked(QualType ElemTy) {
399 Entries.push_back(PathEntry::ArrayIndex(0));
401 MostDerivedType = ElemTy;
402 MostDerivedIsArrayElement = true;
403 // The value in MostDerivedArraySize is undefined in this case. So, set it
404 // to an arbitrary value that's likely to loudly break things if it's
406 MostDerivedArraySize = AssumedSizeForUnsizedArray;
407 MostDerivedPathLength = Entries.size();
409 /// Update this designator to refer to the given base or member of this
411 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
412 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
414 // If this isn't a base class, it's a new most-derived object.
415 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
416 MostDerivedType = FD->getType();
417 MostDerivedIsArrayElement = false;
418 MostDerivedArraySize = 0;
419 MostDerivedPathLength = Entries.size();
422 /// Update this designator to refer to the given complex component.
423 void addComplexUnchecked(QualType EltTy, bool Imag) {
424 Entries.push_back(PathEntry::ArrayIndex(Imag));
426 // This is technically a most-derived object, though in practice this
427 // is unlikely to matter.
428 MostDerivedType = EltTy;
429 MostDerivedIsArrayElement = true;
430 MostDerivedArraySize = 2;
431 MostDerivedPathLength = Entries.size();
433 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
434 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
436 /// Add N to the address of this subobject.
437 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
438 if (Invalid || !N) return;
439 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
440 if (isMostDerivedAnUnsizedArray()) {
441 diagnoseUnsizedArrayPointerArithmetic(Info, E);
442 // Can't verify -- trust that the user is doing the right thing (or if
443 // not, trust that the caller will catch the bad behavior).
444 // FIXME: Should we reject if this overflows, at least?
445 Entries.back() = PathEntry::ArrayIndex(
446 Entries.back().getAsArrayIndex() + TruncatedN);
450 // [expr.add]p4: For the purposes of these operators, a pointer to a
451 // nonarray object behaves the same as a pointer to the first element of
452 // an array of length one with the type of the object as its element type.
453 bool IsArray = MostDerivedPathLength == Entries.size() &&
454 MostDerivedIsArrayElement;
455 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
456 : (uint64_t)IsOnePastTheEnd;
458 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
460 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
461 // Calculate the actual index in a wide enough type, so we can include
463 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
464 (llvm::APInt&)N += ArrayIndex;
465 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
466 diagnosePointerArithmetic(Info, E, N);
471 ArrayIndex += TruncatedN;
472 assert(ArrayIndex <= ArraySize &&
473 "bounds check succeeded for out-of-bounds index");
476 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
478 IsOnePastTheEnd = (ArrayIndex != 0);
482 /// A stack frame in the constexpr call stack.
483 struct CallStackFrame {
486 /// Parent - The caller of this stack frame.
487 CallStackFrame *Caller;
489 /// Callee - The function which was called.
490 const FunctionDecl *Callee;
492 /// This - The binding for the this pointer in this call, if any.
495 /// Arguments - Parameter bindings for this function call, indexed by
496 /// parameters' function scope indices.
499 /// Source location information about the default argument or default
500 /// initializer expression we're evaluating, if any.
501 CurrentSourceLocExprScope CurSourceLocExprScope;
503 // Note that we intentionally use std::map here so that references to
504 // values are stable.
505 typedef std::pair<const void *, unsigned> MapKeyTy;
506 typedef std::map<MapKeyTy, APValue> MapTy;
507 /// Temporaries - Temporary lvalues materialized within this stack frame.
510 /// CallLoc - The location of the call expression for this call.
511 SourceLocation CallLoc;
513 /// Index - The call index of this call.
516 /// The stack of integers for tracking version numbers for temporaries.
517 SmallVector<unsigned, 2> TempVersionStack = {1};
518 unsigned CurTempVersion = TempVersionStack.back();
520 unsigned getTempVersion() const { return TempVersionStack.back(); }
522 void pushTempVersion() {
523 TempVersionStack.push_back(++CurTempVersion);
526 void popTempVersion() {
527 TempVersionStack.pop_back();
530 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
531 // on the overall stack usage of deeply-recursing constexpr evaluations.
532 // (We should cache this map rather than recomputing it repeatedly.)
533 // But let's try this and see how it goes; we can look into caching the map
534 // as a later change.
536 /// LambdaCaptureFields - Mapping from captured variables/this to
537 /// corresponding data members in the closure class.
538 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
539 FieldDecl *LambdaThisCaptureField;
541 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
542 const FunctionDecl *Callee, const LValue *This,
546 // Return the temporary for Key whose version number is Version.
547 APValue *getTemporary(const void *Key, unsigned Version) {
548 MapKeyTy KV(Key, Version);
549 auto LB = Temporaries.lower_bound(KV);
550 if (LB != Temporaries.end() && LB->first == KV)
552 // Pair (Key,Version) wasn't found in the map. Check that no elements
553 // in the map have 'Key' as their key.
554 assert((LB == Temporaries.end() || LB->first.first != Key) &&
555 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
556 "Element with key 'Key' found in map");
560 // Return the current temporary for Key in the map.
561 APValue *getCurrentTemporary(const void *Key) {
562 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
563 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
564 return &std::prev(UB)->second;
568 // Return the version number of the current temporary for Key.
569 unsigned getCurrentTemporaryVersion(const void *Key) const {
570 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572 return std::prev(UB)->first.second;
576 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
579 /// Temporarily override 'this'.
580 class ThisOverrideRAII {
582 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
583 : Frame(Frame), OldThis(Frame.This) {
585 Frame.This = NewThis;
587 ~ThisOverrideRAII() {
588 Frame.This = OldThis;
591 CallStackFrame &Frame;
592 const LValue *OldThis;
595 /// A partial diagnostic which we might know in advance that we are not going
597 class OptionalDiagnostic {
598 PartialDiagnostic *Diag;
601 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
605 OptionalDiagnostic &operator<<(const T &v) {
611 OptionalDiagnostic &operator<<(const APSInt &I) {
613 SmallVector<char, 32> Buffer;
615 *Diag << StringRef(Buffer.data(), Buffer.size());
620 OptionalDiagnostic &operator<<(const APFloat &F) {
622 // FIXME: Force the precision of the source value down so we don't
623 // print digits which are usually useless (we don't really care here if
624 // we truncate a digit by accident in edge cases). Ideally,
625 // APFloat::toString would automatically print the shortest
626 // representation which rounds to the correct value, but it's a bit
627 // tricky to implement.
629 llvm::APFloat::semanticsPrecision(F.getSemantics());
630 precision = (precision * 59 + 195) / 196;
631 SmallVector<char, 32> Buffer;
632 F.toString(Buffer, precision);
633 *Diag << StringRef(Buffer.data(), Buffer.size());
638 OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
640 SmallVector<char, 32> Buffer;
642 *Diag << StringRef(Buffer.data(), Buffer.size());
648 /// A cleanup, and a flag indicating whether it is lifetime-extended.
650 llvm::PointerIntPair<APValue*, 1, bool> Value;
653 Cleanup(APValue *Val, bool IsLifetimeExtended)
654 : Value(Val, IsLifetimeExtended) {}
656 bool isLifetimeExtended() const { return Value.getInt(); }
658 *Value.getPointer() = APValue();
662 /// A reference to an object whose construction we are currently evaluating.
663 struct ObjectUnderConstruction {
664 APValue::LValueBase Base;
665 ArrayRef<APValue::LValuePathEntry> Path;
666 friend bool operator==(const ObjectUnderConstruction &LHS,
667 const ObjectUnderConstruction &RHS) {
668 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
670 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671 return llvm::hash_combine(Obj.Base, Obj.Path);
674 enum class ConstructionPhase { None, Bases, AfterBases };
678 template<> struct DenseMapInfo<ObjectUnderConstruction> {
679 using Base = DenseMapInfo<APValue::LValueBase>;
680 static ObjectUnderConstruction getEmptyKey() {
681 return {Base::getEmptyKey(), {}}; }
682 static ObjectUnderConstruction getTombstoneKey() {
683 return {Base::getTombstoneKey(), {}};
685 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
686 return hash_value(Object);
688 static bool isEqual(const ObjectUnderConstruction &LHS,
689 const ObjectUnderConstruction &RHS) {
696 /// EvalInfo - This is a private struct used by the evaluator to capture
697 /// information about a subexpression as it is folded. It retains information
698 /// about the AST context, but also maintains information about the folded
701 /// If an expression could be evaluated, it is still possible it is not a C
702 /// "integer constant expression" or constant expression. If not, this struct
703 /// captures information about how and why not.
705 /// One bit of information passed *into* the request for constant folding
706 /// indicates whether the subexpression is "evaluated" or not according to C
707 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
708 /// evaluate the expression regardless of what the RHS is, but C only allows
709 /// certain things in certain situations.
713 /// EvalStatus - Contains information about the evaluation.
714 Expr::EvalStatus &EvalStatus;
716 /// CurrentCall - The top of the constexpr call stack.
717 CallStackFrame *CurrentCall;
719 /// CallStackDepth - The number of calls in the call stack right now.
720 unsigned CallStackDepth;
722 /// NextCallIndex - The next call index to assign.
723 unsigned NextCallIndex;
725 /// StepsLeft - The remaining number of evaluation steps we're permitted
726 /// to perform. This is essentially a limit for the number of statements
727 /// we will evaluate.
730 /// BottomFrame - The frame in which evaluation started. This must be
731 /// initialized after CurrentCall and CallStackDepth.
732 CallStackFrame BottomFrame;
734 /// A stack of values whose lifetimes end at the end of some surrounding
735 /// evaluation frame.
736 llvm::SmallVector<Cleanup, 16> CleanupStack;
738 /// EvaluatingDecl - This is the declaration whose initializer is being
739 /// evaluated, if any.
740 APValue::LValueBase EvaluatingDecl;
742 /// EvaluatingDeclValue - This is the value being constructed for the
743 /// declaration whose initializer is being evaluated, if any.
744 APValue *EvaluatingDeclValue;
746 /// Set of objects that are currently being constructed.
747 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
748 ObjectsUnderConstruction;
750 struct EvaluatingConstructorRAII {
752 ObjectUnderConstruction Object;
754 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
756 : EI(EI), Object(Object) {
758 EI.ObjectsUnderConstruction
759 .insert({Object, HasBases ? ConstructionPhase::Bases
760 : ConstructionPhase::AfterBases})
763 void finishedConstructingBases() {
764 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
766 ~EvaluatingConstructorRAII() {
767 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
772 isEvaluatingConstructor(APValue::LValueBase Base,
773 ArrayRef<APValue::LValuePathEntry> Path) {
774 return ObjectsUnderConstruction.lookup({Base, Path});
777 /// If we're currently speculatively evaluating, the outermost call stack
778 /// depth at which we can mutate state, otherwise 0.
779 unsigned SpeculativeEvaluationDepth = 0;
781 /// The current array initialization index, if we're performing array
783 uint64_t ArrayInitIndex = -1;
785 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
786 /// notes attached to it will also be stored, otherwise they will not be.
787 bool HasActiveDiagnostic;
789 /// Have we emitted a diagnostic explaining why we couldn't constant
790 /// fold (not just why it's not strictly a constant expression)?
791 bool HasFoldFailureDiagnostic;
793 /// Whether or not we're in a context where the front end requires a
795 bool InConstantContext;
797 enum EvaluationMode {
798 /// Evaluate as a constant expression. Stop if we find that the expression
799 /// is not a constant expression.
800 EM_ConstantExpression,
802 /// Evaluate as a potential constant expression. Keep going if we hit a
803 /// construct that we can't evaluate yet (because we don't yet know the
804 /// value of something) but stop if we hit something that could never be
805 /// a constant expression.
806 EM_PotentialConstantExpression,
808 /// Fold the expression to a constant. Stop if we hit a side-effect that
812 /// Evaluate the expression looking for integer overflow and similar
813 /// issues. Don't worry about side-effects, and try to visit all
815 EM_EvaluateForOverflow,
817 /// Evaluate in any way we know how. Don't worry about side-effects that
818 /// can't be modeled.
819 EM_IgnoreSideEffects,
821 /// Evaluate as a constant expression. Stop if we find that the expression
822 /// is not a constant expression. Some expressions can be retried in the
823 /// optimizer if we don't constant fold them here, but in an unevaluated
824 /// context we try to fold them immediately since the optimizer never
825 /// gets a chance to look at it.
826 EM_ConstantExpressionUnevaluated,
828 /// Evaluate as a potential constant expression. Keep going if we hit a
829 /// construct that we can't evaluate yet (because we don't yet know the
830 /// value of something) but stop if we hit something that could never be
831 /// a constant expression. Some expressions can be retried in the
832 /// optimizer if we don't constant fold them here, but in an unevaluated
833 /// context we try to fold them immediately since the optimizer never
834 /// gets a chance to look at it.
835 EM_PotentialConstantExpressionUnevaluated,
838 /// Are we checking whether the expression is a potential constant
840 bool checkingPotentialConstantExpression() const {
841 return EvalMode == EM_PotentialConstantExpression ||
842 EvalMode == EM_PotentialConstantExpressionUnevaluated;
845 /// Are we checking an expression for overflow?
846 // FIXME: We should check for any kind of undefined or suspicious behavior
847 // in such constructs, not just overflow.
848 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
850 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
851 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
852 CallStackDepth(0), NextCallIndex(1),
853 StepsLeft(getLangOpts().ConstexprStepLimit),
854 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
855 EvaluatingDecl((const ValueDecl *)nullptr),
856 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
857 HasFoldFailureDiagnostic(false),
858 InConstantContext(false), EvalMode(Mode) {}
860 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
861 EvaluatingDecl = Base;
862 EvaluatingDeclValue = &Value;
865 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
867 bool CheckCallLimit(SourceLocation Loc) {
868 // Don't perform any constexpr calls (other than the call we're checking)
869 // when checking a potential constant expression.
870 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
872 if (NextCallIndex == 0) {
873 // NextCallIndex has wrapped around.
874 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
877 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
879 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
880 << getLangOpts().ConstexprCallDepth;
884 std::pair<CallStackFrame *, unsigned>
885 getCallFrameAndDepth(unsigned CallIndex) {
886 assert(CallIndex && "no call index in getCallFrameAndDepth");
887 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
888 // be null in this loop.
889 unsigned Depth = CallStackDepth;
890 CallStackFrame *Frame = CurrentCall;
891 while (Frame->Index > CallIndex) {
892 Frame = Frame->Caller;
895 if (Frame->Index == CallIndex)
896 return {Frame, Depth};
900 bool nextStep(const Stmt *S) {
902 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
910 /// Add a diagnostic to the diagnostics list.
911 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
912 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
913 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
914 return EvalStatus.Diag->back().second;
917 /// Add notes containing a call stack to the current point of evaluation.
918 void addCallStack(unsigned Limit);
921 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
922 unsigned ExtraNotes, bool IsCCEDiag) {
924 if (EvalStatus.Diag) {
925 // If we have a prior diagnostic, it will be noting that the expression
926 // isn't a constant expression. This diagnostic is more important,
927 // unless we require this evaluation to produce a constant expression.
929 // FIXME: We might want to show both diagnostics to the user in
930 // EM_ConstantFold mode.
931 if (!EvalStatus.Diag->empty()) {
933 case EM_ConstantFold:
934 case EM_IgnoreSideEffects:
935 case EM_EvaluateForOverflow:
936 if (!HasFoldFailureDiagnostic)
938 // We've already failed to fold something. Keep that diagnostic.
940 case EM_ConstantExpression:
941 case EM_PotentialConstantExpression:
942 case EM_ConstantExpressionUnevaluated:
943 case EM_PotentialConstantExpressionUnevaluated:
944 HasActiveDiagnostic = false;
945 return OptionalDiagnostic();
949 unsigned CallStackNotes = CallStackDepth - 1;
950 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
952 CallStackNotes = std::min(CallStackNotes, Limit + 1);
953 if (checkingPotentialConstantExpression())
956 HasActiveDiagnostic = true;
957 HasFoldFailureDiagnostic = !IsCCEDiag;
958 EvalStatus.Diag->clear();
959 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
960 addDiag(Loc, DiagId);
961 if (!checkingPotentialConstantExpression())
963 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
965 HasActiveDiagnostic = false;
966 return OptionalDiagnostic();
969 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
971 FFDiag(SourceLocation Loc,
972 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
973 unsigned ExtraNotes = 0) {
974 return Diag(Loc, DiagId, ExtraNotes, false);
977 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
978 = diag::note_invalid_subexpr_in_const_expr,
979 unsigned ExtraNotes = 0) {
981 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
982 HasActiveDiagnostic = false;
983 return OptionalDiagnostic();
986 /// Diagnose that the evaluation does not produce a C++11 core constant
989 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
990 /// EM_PotentialConstantExpression mode and we produce one of these.
991 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
992 = diag::note_invalid_subexpr_in_const_expr,
993 unsigned ExtraNotes = 0) {
994 // Don't override a previous diagnostic. Don't bother collecting
995 // diagnostics if we're evaluating for overflow.
996 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
997 HasActiveDiagnostic = false;
998 return OptionalDiagnostic();
1000 return Diag(Loc, DiagId, ExtraNotes, true);
1002 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
1003 = diag::note_invalid_subexpr_in_const_expr,
1004 unsigned ExtraNotes = 0) {
1005 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
1007 /// Add a note to a prior diagnostic.
1008 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
1009 if (!HasActiveDiagnostic)
1010 return OptionalDiagnostic();
1011 return OptionalDiagnostic(&addDiag(Loc, DiagId));
1014 /// Add a stack of notes to a prior diagnostic.
1015 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1016 if (HasActiveDiagnostic) {
1017 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1018 Diags.begin(), Diags.end());
1022 /// Should we continue evaluation after encountering a side-effect that we
1024 bool keepEvaluatingAfterSideEffect() {
1026 case EM_PotentialConstantExpression:
1027 case EM_PotentialConstantExpressionUnevaluated:
1028 case EM_EvaluateForOverflow:
1029 case EM_IgnoreSideEffects:
1032 case EM_ConstantExpression:
1033 case EM_ConstantExpressionUnevaluated:
1034 case EM_ConstantFold:
1037 llvm_unreachable("Missed EvalMode case");
1040 /// Note that we have had a side-effect, and determine whether we should
1041 /// keep evaluating.
1042 bool noteSideEffect() {
1043 EvalStatus.HasSideEffects = true;
1044 return keepEvaluatingAfterSideEffect();
1047 /// Should we continue evaluation after encountering undefined behavior?
1048 bool keepEvaluatingAfterUndefinedBehavior() {
1050 case EM_EvaluateForOverflow:
1051 case EM_IgnoreSideEffects:
1052 case EM_ConstantFold:
1055 case EM_PotentialConstantExpression:
1056 case EM_PotentialConstantExpressionUnevaluated:
1057 case EM_ConstantExpression:
1058 case EM_ConstantExpressionUnevaluated:
1061 llvm_unreachable("Missed EvalMode case");
1064 /// Note that we hit something that was technically undefined behavior, but
1065 /// that we can evaluate past it (such as signed overflow or floating-point
1066 /// division by zero.)
1067 bool noteUndefinedBehavior() {
1068 EvalStatus.HasUndefinedBehavior = true;
1069 return keepEvaluatingAfterUndefinedBehavior();
1072 /// Should we continue evaluation as much as possible after encountering a
1073 /// construct which can't be reduced to a value?
1074 bool keepEvaluatingAfterFailure() {
1079 case EM_PotentialConstantExpression:
1080 case EM_PotentialConstantExpressionUnevaluated:
1081 case EM_EvaluateForOverflow:
1084 case EM_ConstantExpression:
1085 case EM_ConstantExpressionUnevaluated:
1086 case EM_ConstantFold:
1087 case EM_IgnoreSideEffects:
1090 llvm_unreachable("Missed EvalMode case");
1093 /// Notes that we failed to evaluate an expression that other expressions
1094 /// directly depend on, and determine if we should keep evaluating. This
1095 /// should only be called if we actually intend to keep evaluating.
1097 /// Call noteSideEffect() instead if we may be able to ignore the value that
1098 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1100 /// (Foo(), 1) // use noteSideEffect
1101 /// (Foo() || true) // use noteSideEffect
1102 /// Foo() + 1 // use noteFailure
1103 LLVM_NODISCARD bool noteFailure() {
1104 // Failure when evaluating some expression often means there is some
1105 // subexpression whose evaluation was skipped. Therefore, (because we
1106 // don't track whether we skipped an expression when unwinding after an
1107 // evaluation failure) every evaluation failure that bubbles up from a
1108 // subexpression implies that a side-effect has potentially happened. We
1109 // skip setting the HasSideEffects flag to true until we decide to
1110 // continue evaluating after that point, which happens here.
1111 bool KeepGoing = keepEvaluatingAfterFailure();
1112 EvalStatus.HasSideEffects |= KeepGoing;
1116 class ArrayInitLoopIndex {
1118 uint64_t OuterIndex;
1121 ArrayInitLoopIndex(EvalInfo &Info)
1122 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1123 Info.ArrayInitIndex = 0;
1125 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1127 operator uint64_t&() { return Info.ArrayInitIndex; }
1131 /// Object used to treat all foldable expressions as constant expressions.
1132 struct FoldConstant {
1135 bool HadNoPriorDiags;
1136 EvalInfo::EvaluationMode OldMode;
1138 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1141 HadNoPriorDiags(Info.EvalStatus.Diag &&
1142 Info.EvalStatus.Diag->empty() &&
1143 !Info.EvalStatus.HasSideEffects),
1144 OldMode(Info.EvalMode) {
1146 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1147 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1148 Info.EvalMode = EvalInfo::EM_ConstantFold;
1150 void keepDiagnostics() { Enabled = false; }
1152 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1153 !Info.EvalStatus.HasSideEffects)
1154 Info.EvalStatus.Diag->clear();
1155 Info.EvalMode = OldMode;
1159 /// RAII object used to set the current evaluation mode to ignore
1161 struct IgnoreSideEffectsRAII {
1163 EvalInfo::EvaluationMode OldMode;
1164 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1165 : Info(Info), OldMode(Info.EvalMode) {
1166 if (!Info.checkingPotentialConstantExpression())
1167 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1170 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1173 /// RAII object used to optionally suppress diagnostics and side-effects from
1174 /// a speculative evaluation.
1175 class SpeculativeEvaluationRAII {
1176 EvalInfo *Info = nullptr;
1177 Expr::EvalStatus OldStatus;
1178 unsigned OldSpeculativeEvaluationDepth;
1180 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1182 OldStatus = Other.OldStatus;
1183 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1184 Other.Info = nullptr;
1187 void maybeRestoreState() {
1191 Info->EvalStatus = OldStatus;
1192 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1196 SpeculativeEvaluationRAII() = default;
1198 SpeculativeEvaluationRAII(
1199 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1200 : Info(&Info), OldStatus(Info.EvalStatus),
1201 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1202 Info.EvalStatus.Diag = NewDiag;
1203 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1206 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1207 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1208 moveFromAndCancel(std::move(Other));
1211 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1212 maybeRestoreState();
1213 moveFromAndCancel(std::move(Other));
1217 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1220 /// RAII object wrapping a full-expression or block scope, and handling
1221 /// the ending of the lifetime of temporaries created within it.
1222 template<bool IsFullExpression>
1225 unsigned OldStackSize;
1227 ScopeRAII(EvalInfo &Info)
1228 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1229 // Push a new temporary version. This is needed to distinguish between
1230 // temporaries created in different iterations of a loop.
1231 Info.CurrentCall->pushTempVersion();
1234 // Body moved to a static method to encourage the compiler to inline away
1235 // instances of this class.
1236 cleanup(Info, OldStackSize);
1237 Info.CurrentCall->popTempVersion();
1240 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1241 unsigned NewEnd = OldStackSize;
1242 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1244 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1245 // Full-expression cleanup of a lifetime-extended temporary: nothing
1246 // to do, just move this cleanup to the right place in the stack.
1247 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1250 // End the lifetime of the object.
1251 Info.CleanupStack[I].endLifetime();
1254 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1255 Info.CleanupStack.end());
1258 typedef ScopeRAII<false> BlockScopeRAII;
1259 typedef ScopeRAII<true> FullExpressionRAII;
1262 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1263 CheckSubobjectKind CSK) {
1266 if (isOnePastTheEnd()) {
1267 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1272 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1273 // must actually be at least one array element; even a VLA cannot have a
1274 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1278 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1280 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1281 // Do not set the designator as invalid: we can represent this situation,
1282 // and correct handling of __builtin_object_size requires us to do so.
1285 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1288 // If we're complaining, we must be able to statically determine the size of
1289 // the most derived array.
1290 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1291 Info.CCEDiag(E, diag::note_constexpr_array_index)
1293 << static_cast<unsigned>(getMostDerivedArraySize());
1295 Info.CCEDiag(E, diag::note_constexpr_array_index)
1296 << N << /*non-array*/ 1;
1300 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1301 const FunctionDecl *Callee, const LValue *This,
1303 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1304 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1305 Info.CurrentCall = this;
1306 ++Info.CallStackDepth;
1309 CallStackFrame::~CallStackFrame() {
1310 assert(Info.CurrentCall == this && "calls retired out of order");
1311 --Info.CallStackDepth;
1312 Info.CurrentCall = Caller;
1315 APValue &CallStackFrame::createTemporary(const void *Key,
1316 bool IsLifetimeExtended) {
1317 unsigned Version = Info.CurrentCall->getTempVersion();
1318 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1319 assert(Result.isAbsent() && "temporary created multiple times");
1320 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1324 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1326 void EvalInfo::addCallStack(unsigned Limit) {
1327 // Determine which calls to skip, if any.
1328 unsigned ActiveCalls = CallStackDepth - 1;
1329 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1330 if (Limit && Limit < ActiveCalls) {
1331 SkipStart = Limit / 2 + Limit % 2;
1332 SkipEnd = ActiveCalls - Limit / 2;
1335 // Walk the call stack and add the diagnostics.
1336 unsigned CallIdx = 0;
1337 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1338 Frame = Frame->Caller, ++CallIdx) {
1340 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1341 if (CallIdx == SkipStart) {
1342 // Note that we're skipping calls.
1343 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1344 << unsigned(ActiveCalls - Limit);
1349 // Use a different note for an inheriting constructor, because from the
1350 // user's perspective it's not really a function at all.
1351 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1352 if (CD->isInheritingConstructor()) {
1353 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1359 SmallVector<char, 128> Buffer;
1360 llvm::raw_svector_ostream Out(Buffer);
1361 describeCall(Frame, Out);
1362 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1366 /// Kinds of access we can perform on an object, for diagnostics. Note that
1367 /// we consider a member function call to be a kind of access, even though
1368 /// it is not formally an access of the object, because it has (largely) the
1369 /// same set of semantic restrictions.
1380 static bool isModification(AccessKinds AK) {
1384 case AK_DynamicCast:
1392 llvm_unreachable("unknown access kind");
1395 /// Is this an access per the C++ definition?
1396 static bool isFormalAccess(AccessKinds AK) {
1397 return AK == AK_Read || isModification(AK);
1401 struct ComplexValue {
1406 APSInt IntReal, IntImag;
1407 APFloat FloatReal, FloatImag;
1409 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1411 void makeComplexFloat() { IsInt = false; }
1412 bool isComplexFloat() const { return !IsInt; }
1413 APFloat &getComplexFloatReal() { return FloatReal; }
1414 APFloat &getComplexFloatImag() { return FloatImag; }
1416 void makeComplexInt() { IsInt = true; }
1417 bool isComplexInt() const { return IsInt; }
1418 APSInt &getComplexIntReal() { return IntReal; }
1419 APSInt &getComplexIntImag() { return IntImag; }
1421 void moveInto(APValue &v) const {
1422 if (isComplexFloat())
1423 v = APValue(FloatReal, FloatImag);
1425 v = APValue(IntReal, IntImag);
1427 void setFrom(const APValue &v) {
1428 assert(v.isComplexFloat() || v.isComplexInt());
1429 if (v.isComplexFloat()) {
1431 FloatReal = v.getComplexFloatReal();
1432 FloatImag = v.getComplexFloatImag();
1435 IntReal = v.getComplexIntReal();
1436 IntImag = v.getComplexIntImag();
1442 APValue::LValueBase Base;
1444 SubobjectDesignator Designator;
1446 bool InvalidBase : 1;
1448 const APValue::LValueBase getLValueBase() const { return Base; }
1449 CharUnits &getLValueOffset() { return Offset; }
1450 const CharUnits &getLValueOffset() const { return Offset; }
1451 SubobjectDesignator &getLValueDesignator() { return Designator; }
1452 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1453 bool isNullPointer() const { return IsNullPtr;}
1455 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1456 unsigned getLValueVersion() const { return Base.getVersion(); }
1458 void moveInto(APValue &V) const {
1459 if (Designator.Invalid)
1460 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1462 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1463 V = APValue(Base, Offset, Designator.Entries,
1464 Designator.IsOnePastTheEnd, IsNullPtr);
1467 void setFrom(ASTContext &Ctx, const APValue &V) {
1468 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1469 Base = V.getLValueBase();
1470 Offset = V.getLValueOffset();
1471 InvalidBase = false;
1472 Designator = SubobjectDesignator(Ctx, V);
1473 IsNullPtr = V.isNullPointer();
1476 void set(APValue::LValueBase B, bool BInvalid = false) {
1478 // We only allow a few types of invalid bases. Enforce that here.
1480 const auto *E = B.get<const Expr *>();
1481 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1482 "Unexpected type of invalid base");
1487 Offset = CharUnits::fromQuantity(0);
1488 InvalidBase = BInvalid;
1489 Designator = SubobjectDesignator(getType(B));
1493 void setNull(QualType PointerTy, uint64_t TargetVal) {
1494 Base = (Expr *)nullptr;
1495 Offset = CharUnits::fromQuantity(TargetVal);
1496 InvalidBase = false;
1497 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1501 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1506 // Check that this LValue is not based on a null pointer. If it is, produce
1507 // a diagnostic and mark the designator as invalid.
1508 template <typename GenDiagType>
1509 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1510 if (Designator.Invalid)
1514 Designator.setInvalid();
1521 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1522 CheckSubobjectKind CSK) {
1523 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1524 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1528 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1530 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1531 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1535 // Check this LValue refers to an object. If not, set the designator to be
1536 // invalid and emit a diagnostic.
1537 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1538 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1539 Designator.checkSubobject(Info, E, CSK);
1542 void addDecl(EvalInfo &Info, const Expr *E,
1543 const Decl *D, bool Virtual = false) {
1544 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1545 Designator.addDeclUnchecked(D, Virtual);
1547 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1548 if (!Designator.Entries.empty()) {
1549 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1550 Designator.setInvalid();
1553 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1554 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1555 Designator.FirstEntryIsAnUnsizedArray = true;
1556 Designator.addUnsizedArrayUnchecked(ElemTy);
1559 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1560 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1561 Designator.addArrayUnchecked(CAT);
1563 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1564 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1565 Designator.addComplexUnchecked(EltTy, Imag);
1567 void clearIsNullPointer() {
1570 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1571 const APSInt &Index, CharUnits ElementSize) {
1572 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1573 // but we're not required to diagnose it and it's valid in C++.)
1577 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1578 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1580 uint64_t Offset64 = Offset.getQuantity();
1581 uint64_t ElemSize64 = ElementSize.getQuantity();
1582 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1583 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1585 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1586 Designator.adjustIndex(Info, E, Index);
1587 clearIsNullPointer();
1589 void adjustOffset(CharUnits N) {
1591 if (N.getQuantity())
1592 clearIsNullPointer();
1598 explicit MemberPtr(const ValueDecl *Decl) :
1599 DeclAndIsDerivedMember(Decl, false), Path() {}
1601 /// The member or (direct or indirect) field referred to by this member
1602 /// pointer, or 0 if this is a null member pointer.
1603 const ValueDecl *getDecl() const {
1604 return DeclAndIsDerivedMember.getPointer();
1606 /// Is this actually a member of some type derived from the relevant class?
1607 bool isDerivedMember() const {
1608 return DeclAndIsDerivedMember.getInt();
1610 /// Get the class which the declaration actually lives in.
1611 const CXXRecordDecl *getContainingRecord() const {
1612 return cast<CXXRecordDecl>(
1613 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1616 void moveInto(APValue &V) const {
1617 V = APValue(getDecl(), isDerivedMember(), Path);
1619 void setFrom(const APValue &V) {
1620 assert(V.isMemberPointer());
1621 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1622 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1624 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1625 Path.insert(Path.end(), P.begin(), P.end());
1628 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1629 /// whether the member is a member of some class derived from the class type
1630 /// of the member pointer.
1631 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1632 /// Path - The path of base/derived classes from the member declaration's
1633 /// class (exclusive) to the class type of the member pointer (inclusive).
1634 SmallVector<const CXXRecordDecl*, 4> Path;
1636 /// Perform a cast towards the class of the Decl (either up or down the
1638 bool castBack(const CXXRecordDecl *Class) {
1639 assert(!Path.empty());
1640 const CXXRecordDecl *Expected;
1641 if (Path.size() >= 2)
1642 Expected = Path[Path.size() - 2];
1644 Expected = getContainingRecord();
1645 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1646 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1647 // if B does not contain the original member and is not a base or
1648 // derived class of the class containing the original member, the result
1649 // of the cast is undefined.
1650 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1651 // (D::*). We consider that to be a language defect.
1657 /// Perform a base-to-derived member pointer cast.
1658 bool castToDerived(const CXXRecordDecl *Derived) {
1661 if (!isDerivedMember()) {
1662 Path.push_back(Derived);
1665 if (!castBack(Derived))
1668 DeclAndIsDerivedMember.setInt(false);
1671 /// Perform a derived-to-base member pointer cast.
1672 bool castToBase(const CXXRecordDecl *Base) {
1676 DeclAndIsDerivedMember.setInt(true);
1677 if (isDerivedMember()) {
1678 Path.push_back(Base);
1681 return castBack(Base);
1685 /// Compare two member pointers, which are assumed to be of the same type.
1686 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1687 if (!LHS.getDecl() || !RHS.getDecl())
1688 return !LHS.getDecl() && !RHS.getDecl();
1689 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1691 return LHS.Path == RHS.Path;
1695 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1696 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1697 const LValue &This, const Expr *E,
1698 bool AllowNonLiteralTypes = false);
1699 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1700 bool InvalidBaseOK = false);
1701 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1702 bool InvalidBaseOK = false);
1703 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1705 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1706 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1707 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1709 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1710 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1711 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1713 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1715 /// Evaluate an integer or fixed point expression into an APResult.
1716 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1719 /// Evaluate only a fixed point expression into an APResult.
1720 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1723 //===----------------------------------------------------------------------===//
1725 //===----------------------------------------------------------------------===//
1727 /// A helper function to create a temporary and set an LValue.
1728 template <class KeyTy>
1729 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1730 LValue &LV, CallStackFrame &Frame) {
1731 LV.set({Key, Frame.Info.CurrentCall->Index,
1732 Frame.Info.CurrentCall->getTempVersion()});
1733 return Frame.createTemporary(Key, IsLifetimeExtended);
1736 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1737 /// preserving its value (by extending by up to one bit as needed).
1738 static void negateAsSigned(APSInt &Int) {
1739 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1740 Int = Int.extend(Int.getBitWidth() + 1);
1741 Int.setIsSigned(true);
1746 /// Produce a string describing the given constexpr call.
1747 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1748 unsigned ArgIndex = 0;
1749 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1750 !isa<CXXConstructorDecl>(Frame->Callee) &&
1751 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1754 Out << *Frame->Callee << '(';
1756 if (Frame->This && IsMemberCall) {
1758 Frame->This->moveInto(Val);
1759 Val.printPretty(Out, Frame->Info.Ctx,
1760 Frame->This->Designator.MostDerivedType);
1761 // FIXME: Add parens around Val if needed.
1762 Out << "->" << *Frame->Callee << '(';
1763 IsMemberCall = false;
1766 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1767 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1768 if (ArgIndex > (unsigned)IsMemberCall)
1771 const ParmVarDecl *Param = *I;
1772 const APValue &Arg = Frame->Arguments[ArgIndex];
1773 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1775 if (ArgIndex == 0 && IsMemberCall)
1776 Out << "->" << *Frame->Callee << '(';
1782 /// Evaluate an expression to see if it had side-effects, and discard its
1784 /// \return \c true if the caller should keep evaluating.
1785 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1787 if (!Evaluate(Scratch, Info, E))
1788 // We don't need the value, but we might have skipped a side effect here.
1789 return Info.noteSideEffect();
1793 /// Should this call expression be treated as a string literal?
1794 static bool IsStringLiteralCall(const CallExpr *E) {
1795 unsigned Builtin = E->getBuiltinCallee();
1796 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1797 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1800 static bool IsGlobalLValue(APValue::LValueBase B) {
1801 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1802 // constant expression of pointer type that evaluates to...
1804 // ... a null pointer value, or a prvalue core constant expression of type
1806 if (!B) return true;
1808 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1809 // ... the address of an object with static storage duration,
1810 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1811 return VD->hasGlobalStorage();
1812 // ... the address of a function,
1813 return isa<FunctionDecl>(D);
1816 if (B.is<TypeInfoLValue>())
1819 const Expr *E = B.get<const Expr*>();
1820 switch (E->getStmtClass()) {
1823 case Expr::CompoundLiteralExprClass: {
1824 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1825 return CLE->isFileScope() && CLE->isLValue();
1827 case Expr::MaterializeTemporaryExprClass:
1828 // A materialized temporary might have been lifetime-extended to static
1829 // storage duration.
1830 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1831 // A string literal has static storage duration.
1832 case Expr::StringLiteralClass:
1833 case Expr::PredefinedExprClass:
1834 case Expr::ObjCStringLiteralClass:
1835 case Expr::ObjCEncodeExprClass:
1836 case Expr::CXXUuidofExprClass:
1838 case Expr::ObjCBoxedExprClass:
1839 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1840 case Expr::CallExprClass:
1841 return IsStringLiteralCall(cast<CallExpr>(E));
1842 // For GCC compatibility, &&label has static storage duration.
1843 case Expr::AddrLabelExprClass:
1845 // A Block literal expression may be used as the initialization value for
1846 // Block variables at global or local static scope.
1847 case Expr::BlockExprClass:
1848 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1849 case Expr::ImplicitValueInitExprClass:
1851 // We can never form an lvalue with an implicit value initialization as its
1852 // base through expression evaluation, so these only appear in one case: the
1853 // implicit variable declaration we invent when checking whether a constexpr
1854 // constructor can produce a constant expression. We must assume that such
1855 // an expression might be a global lvalue.
1860 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1861 return LVal.Base.dyn_cast<const ValueDecl*>();
1864 static bool IsLiteralLValue(const LValue &Value) {
1865 if (Value.getLValueCallIndex())
1867 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1868 return E && !isa<MaterializeTemporaryExpr>(E);
1871 static bool IsWeakLValue(const LValue &Value) {
1872 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1873 return Decl && Decl->isWeak();
1876 static bool isZeroSized(const LValue &Value) {
1877 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1878 if (Decl && isa<VarDecl>(Decl)) {
1879 QualType Ty = Decl->getType();
1880 if (Ty->isArrayType())
1881 return Ty->isIncompleteType() ||
1882 Decl->getASTContext().getTypeSize(Ty) == 0;
1887 static bool HasSameBase(const LValue &A, const LValue &B) {
1888 if (!A.getLValueBase())
1889 return !B.getLValueBase();
1890 if (!B.getLValueBase())
1893 if (A.getLValueBase().getOpaqueValue() !=
1894 B.getLValueBase().getOpaqueValue()) {
1895 const Decl *ADecl = GetLValueBaseDecl(A);
1898 const Decl *BDecl = GetLValueBaseDecl(B);
1899 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1903 return IsGlobalLValue(A.getLValueBase()) ||
1904 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1905 A.getLValueVersion() == B.getLValueVersion());
1908 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1909 assert(Base && "no location for a null lvalue");
1910 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1912 Info.Note(VD->getLocation(), diag::note_declared_at);
1913 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1914 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1915 // We have no information to show for a typeid(T) object.
1918 /// Check that this reference or pointer core constant expression is a valid
1919 /// value for an address or reference constant expression. Return true if we
1920 /// can fold this expression, whether or not it's a constant expression.
1921 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1922 QualType Type, const LValue &LVal,
1923 Expr::ConstExprUsage Usage) {
1924 bool IsReferenceType = Type->isReferenceType();
1926 APValue::LValueBase Base = LVal.getLValueBase();
1927 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1929 // Check that the object is a global. Note that the fake 'this' object we
1930 // manufacture when checking potential constant expressions is conservatively
1931 // assumed to be global here.
1932 if (!IsGlobalLValue(Base)) {
1933 if (Info.getLangOpts().CPlusPlus11) {
1934 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1935 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1936 << IsReferenceType << !Designator.Entries.empty()
1938 NoteLValueLocation(Info, Base);
1942 // Don't allow references to temporaries to escape.
1945 assert((Info.checkingPotentialConstantExpression() ||
1946 LVal.getLValueCallIndex() == 0) &&
1947 "have call index for global lvalue");
1949 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1950 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1951 // Check if this is a thread-local variable.
1952 if (Var->getTLSKind())
1955 // A dllimport variable never acts like a constant.
1956 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1959 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1960 // __declspec(dllimport) must be handled very carefully:
1961 // We must never initialize an expression with the thunk in C++.
1962 // Doing otherwise would allow the same id-expression to yield
1963 // different addresses for the same function in different translation
1964 // units. However, this means that we must dynamically initialize the
1965 // expression with the contents of the import address table at runtime.
1967 // The C language has no notion of ODR; furthermore, it has no notion of
1968 // dynamic initialization. This means that we are permitted to
1969 // perform initialization with the address of the thunk.
1970 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1971 FD->hasAttr<DLLImportAttr>())
1976 // Allow address constant expressions to be past-the-end pointers. This is
1977 // an extension: the standard requires them to point to an object.
1978 if (!IsReferenceType)
1981 // A reference constant expression must refer to an object.
1983 // FIXME: diagnostic
1988 // Does this refer one past the end of some object?
1989 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1991 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1992 << !Designator.Entries.empty() << !!VD << VD;
1993 NoteLValueLocation(Info, Base);
1999 /// Member pointers are constant expressions unless they point to a
2000 /// non-virtual dllimport member function.
2001 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2004 const APValue &Value,
2005 Expr::ConstExprUsage Usage) {
2006 const ValueDecl *Member = Value.getMemberPointerDecl();
2007 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2010 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2011 !FD->hasAttr<DLLImportAttr>();
2014 /// Check that this core constant expression is of literal type, and if not,
2015 /// produce an appropriate diagnostic.
2016 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2017 const LValue *This = nullptr) {
2018 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2021 // C++1y: A constant initializer for an object o [...] may also invoke
2022 // constexpr constructors for o and its subobjects even if those objects
2023 // are of non-literal class types.
2025 // C++11 missed this detail for aggregates, so classes like this:
2026 // struct foo_t { union { int i; volatile int j; } u; };
2027 // are not (obviously) initializable like so:
2028 // __attribute__((__require_constant_initialization__))
2029 // static const foo_t x = {{0}};
2030 // because "i" is a subobject with non-literal initialization (due to the
2031 // volatile member of the union). See:
2032 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2033 // Therefore, we use the C++1y behavior.
2034 if (This && Info.EvaluatingDecl == This->getLValueBase())
2037 // Prvalue constant expressions must be of literal types.
2038 if (Info.getLangOpts().CPlusPlus11)
2039 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2042 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2046 /// Check that this core constant expression value is a valid value for a
2047 /// constant expression. If not, report an appropriate diagnostic. Does not
2048 /// check that the expression is of literal type.
2050 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2051 const APValue &Value,
2052 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2053 SourceLocation SubobjectLoc = SourceLocation()) {
2054 if (!Value.hasValue()) {
2055 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2057 if (SubobjectLoc.isValid())
2058 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2062 // We allow _Atomic(T) to be initialized from anything that T can be
2063 // initialized from.
2064 if (const AtomicType *AT = Type->getAs<AtomicType>())
2065 Type = AT->getValueType();
2067 // Core issue 1454: For a literal constant expression of array or class type,
2068 // each subobject of its value shall have been initialized by a constant
2070 if (Value.isArray()) {
2071 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2072 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2073 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2074 Value.getArrayInitializedElt(I), Usage,
2078 if (!Value.hasArrayFiller())
2080 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2081 Usage, SubobjectLoc);
2083 if (Value.isUnion() && Value.getUnionField()) {
2084 return CheckConstantExpression(Info, DiagLoc,
2085 Value.getUnionField()->getType(),
2086 Value.getUnionValue(), Usage,
2087 Value.getUnionField()->getLocation());
2089 if (Value.isStruct()) {
2090 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2091 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2092 unsigned BaseIndex = 0;
2093 for (const CXXBaseSpecifier &BS : CD->bases()) {
2094 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2095 Value.getStructBase(BaseIndex), Usage,
2101 for (const auto *I : RD->fields()) {
2102 if (I->isUnnamedBitfield())
2105 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2106 Value.getStructField(I->getFieldIndex()),
2107 Usage, I->getLocation()))
2112 if (Value.isLValue()) {
2114 LVal.setFrom(Info.Ctx, Value);
2115 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2118 if (Value.isMemberPointer())
2119 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2121 // Everything else is fine.
2125 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2126 // A null base expression indicates a null pointer. These are always
2127 // evaluatable, and they are false unless the offset is zero.
2128 if (!Value.getLValueBase()) {
2129 Result = !Value.getLValueOffset().isZero();
2133 // We have a non-null base. These are generally known to be true, but if it's
2134 // a weak declaration it can be null at runtime.
2136 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2137 return !Decl || !Decl->isWeak();
2140 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2141 switch (Val.getKind()) {
2143 case APValue::Indeterminate:
2146 Result = Val.getInt().getBoolValue();
2148 case APValue::FixedPoint:
2149 Result = Val.getFixedPoint().getBoolValue();
2151 case APValue::Float:
2152 Result = !Val.getFloat().isZero();
2154 case APValue::ComplexInt:
2155 Result = Val.getComplexIntReal().getBoolValue() ||
2156 Val.getComplexIntImag().getBoolValue();
2158 case APValue::ComplexFloat:
2159 Result = !Val.getComplexFloatReal().isZero() ||
2160 !Val.getComplexFloatImag().isZero();
2162 case APValue::LValue:
2163 return EvalPointerValueAsBool(Val, Result);
2164 case APValue::MemberPointer:
2165 Result = Val.getMemberPointerDecl();
2167 case APValue::Vector:
2168 case APValue::Array:
2169 case APValue::Struct:
2170 case APValue::Union:
2171 case APValue::AddrLabelDiff:
2175 llvm_unreachable("unknown APValue kind");
2178 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2180 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2182 if (!Evaluate(Val, Info, E))
2184 return HandleConversionToBool(Val, Result);
2187 template<typename T>
2188 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2189 const T &SrcValue, QualType DestType) {
2190 Info.CCEDiag(E, diag::note_constexpr_overflow)
2191 << SrcValue << DestType;
2192 return Info.noteUndefinedBehavior();
2195 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2196 QualType SrcType, const APFloat &Value,
2197 QualType DestType, APSInt &Result) {
2198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2199 // Determine whether we are converting to unsigned or signed.
2200 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2202 Result = APSInt(DestWidth, !DestSigned);
2204 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2205 & APFloat::opInvalidOp)
2206 return HandleOverflow(Info, E, Value, DestType);
2210 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2211 QualType SrcType, QualType DestType,
2213 APFloat Value = Result;
2215 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2216 APFloat::rmNearestTiesToEven, &ignored);
2220 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2221 QualType DestType, QualType SrcType,
2222 const APSInt &Value) {
2223 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2224 // Figure out if this is a truncate, extend or noop cast.
2225 // If the input is signed, do a sign extend, noop, or truncate.
2226 APSInt Result = Value.extOrTrunc(DestWidth);
2227 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2228 if (DestType->isBooleanType())
2229 Result = Value.getBoolValue();
2233 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2234 QualType SrcType, const APSInt &Value,
2235 QualType DestType, APFloat &Result) {
2236 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2237 Result.convertFromAPInt(Value, Value.isSigned(),
2238 APFloat::rmNearestTiesToEven);
2242 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2243 APValue &Value, const FieldDecl *FD) {
2244 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2246 if (!Value.isInt()) {
2247 // Trying to store a pointer-cast-to-integer into a bitfield.
2248 // FIXME: In this case, we should provide the diagnostic for casting
2249 // a pointer to an integer.
2250 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2255 APSInt &Int = Value.getInt();
2256 unsigned OldBitWidth = Int.getBitWidth();
2257 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2258 if (NewBitWidth < OldBitWidth)
2259 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2263 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2266 if (!Evaluate(SVal, Info, E))
2269 Res = SVal.getInt();
2272 if (SVal.isFloat()) {
2273 Res = SVal.getFloat().bitcastToAPInt();
2276 if (SVal.isVector()) {
2277 QualType VecTy = E->getType();
2278 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2279 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2280 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2281 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2282 Res = llvm::APInt::getNullValue(VecSize);
2283 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2284 APValue &Elt = SVal.getVectorElt(i);
2285 llvm::APInt EltAsInt;
2287 EltAsInt = Elt.getInt();
2288 } else if (Elt.isFloat()) {
2289 EltAsInt = Elt.getFloat().bitcastToAPInt();
2291 // Don't try to handle vectors of anything other than int or float
2292 // (not sure if it's possible to hit this case).
2293 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2296 unsigned BaseEltSize = EltAsInt.getBitWidth();
2298 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2300 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2304 // Give up if the input isn't an int, float, or vector. For example, we
2305 // reject "(v4i16)(intptr_t)&a".
2306 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2310 /// Perform the given integer operation, which is known to need at most BitWidth
2311 /// bits, and check for overflow in the original type (if that type was not an
2313 template<typename Operation>
2314 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2315 const APSInt &LHS, const APSInt &RHS,
2316 unsigned BitWidth, Operation Op,
2318 if (LHS.isUnsigned()) {
2319 Result = Op(LHS, RHS);
2323 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2324 Result = Value.trunc(LHS.getBitWidth());
2325 if (Result.extend(BitWidth) != Value) {
2326 if (Info.checkingForOverflow())
2327 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2328 diag::warn_integer_constant_overflow)
2329 << Result.toString(10) << E->getType();
2331 return HandleOverflow(Info, E, Value, E->getType());
2336 /// Perform the given binary integer operation.
2337 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2338 BinaryOperatorKind Opcode, APSInt RHS,
2345 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2346 std::multiplies<APSInt>(), Result);
2348 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2349 std::plus<APSInt>(), Result);
2351 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2352 std::minus<APSInt>(), Result);
2353 case BO_And: Result = LHS & RHS; return true;
2354 case BO_Xor: Result = LHS ^ RHS; return true;
2355 case BO_Or: Result = LHS | RHS; return true;
2359 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2362 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2363 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2364 // this operation and gives the two's complement result.
2365 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2366 LHS.isSigned() && LHS.isMinSignedValue())
2367 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2371 if (Info.getLangOpts().OpenCL)
2372 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2373 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2374 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2376 else if (RHS.isSigned() && RHS.isNegative()) {
2377 // During constant-folding, a negative shift is an opposite shift. Such
2378 // a shift is not a constant expression.
2379 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2384 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2385 // the shifted type.
2386 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2388 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2389 << RHS << E->getType() << LHS.getBitWidth();
2390 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2391 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2392 // operand, and must not overflow the corresponding unsigned type.
2393 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2394 // E1 x 2^E2 module 2^N.
2395 if (LHS.isNegative())
2396 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2397 else if (LHS.countLeadingZeros() < SA)
2398 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2404 if (Info.getLangOpts().OpenCL)
2405 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2406 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2407 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2409 else if (RHS.isSigned() && RHS.isNegative()) {
2410 // During constant-folding, a negative shift is an opposite shift. Such a
2411 // shift is not a constant expression.
2412 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2417 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2419 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2421 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2422 << RHS << E->getType() << LHS.getBitWidth();
2427 case BO_LT: Result = LHS < RHS; return true;
2428 case BO_GT: Result = LHS > RHS; return true;
2429 case BO_LE: Result = LHS <= RHS; return true;
2430 case BO_GE: Result = LHS >= RHS; return true;
2431 case BO_EQ: Result = LHS == RHS; return true;
2432 case BO_NE: Result = LHS != RHS; return true;
2434 llvm_unreachable("BO_Cmp should be handled elsewhere");
2438 /// Perform the given binary floating-point operation, in-place, on LHS.
2439 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2440 APFloat &LHS, BinaryOperatorKind Opcode,
2441 const APFloat &RHS) {
2447 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2450 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2453 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2457 // If the second operand of / or % is zero the behavior is undefined.
2459 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2460 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2465 // If during the evaluation of an expression, the result is not
2466 // mathematically defined [...], the behavior is undefined.
2467 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2469 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2470 return Info.noteUndefinedBehavior();
2475 /// Cast an lvalue referring to a base subobject to a derived class, by
2476 /// truncating the lvalue's path to the given length.
2477 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2478 const RecordDecl *TruncatedType,
2479 unsigned TruncatedElements) {
2480 SubobjectDesignator &D = Result.Designator;
2482 // Check we actually point to a derived class object.
2483 if (TruncatedElements == D.Entries.size())
2485 assert(TruncatedElements >= D.MostDerivedPathLength &&
2486 "not casting to a derived class");
2487 if (!Result.checkSubobject(Info, E, CSK_Derived))
2490 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2491 const RecordDecl *RD = TruncatedType;
2492 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2493 if (RD->isInvalidDecl()) return false;
2494 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2495 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2496 if (isVirtualBaseClass(D.Entries[I]))
2497 Result.Offset -= Layout.getVBaseClassOffset(Base);
2499 Result.Offset -= Layout.getBaseClassOffset(Base);
2502 D.Entries.resize(TruncatedElements);
2506 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2507 const CXXRecordDecl *Derived,
2508 const CXXRecordDecl *Base,
2509 const ASTRecordLayout *RL = nullptr) {
2511 if (Derived->isInvalidDecl()) return false;
2512 RL = &Info.Ctx.getASTRecordLayout(Derived);
2515 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2516 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2520 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2521 const CXXRecordDecl *DerivedDecl,
2522 const CXXBaseSpecifier *Base) {
2523 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2525 if (!Base->isVirtual())
2526 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2528 SubobjectDesignator &D = Obj.Designator;
2532 // Extract most-derived object and corresponding type.
2533 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2534 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2537 // Find the virtual base class.
2538 if (DerivedDecl->isInvalidDecl()) return false;
2539 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2540 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2541 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2545 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2546 QualType Type, LValue &Result) {
2547 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2548 PathE = E->path_end();
2549 PathI != PathE; ++PathI) {
2550 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2553 Type = (*PathI)->getType();
2558 /// Cast an lvalue referring to a derived class to a known base subobject.
2559 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2560 const CXXRecordDecl *DerivedRD,
2561 const CXXRecordDecl *BaseRD) {
2562 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2563 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2564 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2565 llvm_unreachable("Class must be derived from the passed in base class!");
2567 for (CXXBasePathElement &Elem : Paths.front())
2568 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2573 /// Update LVal to refer to the given field, which must be a member of the type
2574 /// currently described by LVal.
2575 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2576 const FieldDecl *FD,
2577 const ASTRecordLayout *RL = nullptr) {
2579 if (FD->getParent()->isInvalidDecl()) return false;
2580 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2583 unsigned I = FD->getFieldIndex();
2584 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2585 LVal.addDecl(Info, E, FD);
2589 /// Update LVal to refer to the given indirect field.
2590 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2592 const IndirectFieldDecl *IFD) {
2593 for (const auto *C : IFD->chain())
2594 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2599 /// Get the size of the given type in char units.
2600 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2601 QualType Type, CharUnits &Size) {
2602 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2604 if (Type->isVoidType() || Type->isFunctionType()) {
2605 Size = CharUnits::One();
2609 if (Type->isDependentType()) {
2614 if (!Type->isConstantSizeType()) {
2615 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2616 // FIXME: Better diagnostic.
2621 Size = Info.Ctx.getTypeSizeInChars(Type);
2625 /// Update a pointer value to model pointer arithmetic.
2626 /// \param Info - Information about the ongoing evaluation.
2627 /// \param E - The expression being evaluated, for diagnostic purposes.
2628 /// \param LVal - The pointer value to be updated.
2629 /// \param EltTy - The pointee type represented by LVal.
2630 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2631 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2632 LValue &LVal, QualType EltTy,
2633 APSInt Adjustment) {
2634 CharUnits SizeOfPointee;
2635 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2638 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2642 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2643 LValue &LVal, QualType EltTy,
2644 int64_t Adjustment) {
2645 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2646 APSInt::get(Adjustment));
2649 /// Update an lvalue to refer to a component of a complex number.
2650 /// \param Info - Information about the ongoing evaluation.
2651 /// \param LVal - The lvalue to be updated.
2652 /// \param EltTy - The complex number's component type.
2653 /// \param Imag - False for the real component, true for the imaginary.
2654 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2655 LValue &LVal, QualType EltTy,
2658 CharUnits SizeOfComponent;
2659 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2661 LVal.Offset += SizeOfComponent;
2663 LVal.addComplex(Info, E, EltTy, Imag);
2667 /// Try to evaluate the initializer for a variable declaration.
2669 /// \param Info Information about the ongoing evaluation.
2670 /// \param E An expression to be used when printing diagnostics.
2671 /// \param VD The variable whose initializer should be obtained.
2672 /// \param Frame The frame in which the variable was created. Must be null
2673 /// if this variable is not local to the evaluation.
2674 /// \param Result Filled in with a pointer to the value of the variable.
2675 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2676 const VarDecl *VD, CallStackFrame *Frame,
2677 APValue *&Result, const LValue *LVal) {
2679 // If this is a parameter to an active constexpr function call, perform
2680 // argument substitution.
2681 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2682 // Assume arguments of a potential constant expression are unknown
2683 // constant expressions.
2684 if (Info.checkingPotentialConstantExpression())
2686 if (!Frame || !Frame->Arguments) {
2687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2690 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2694 // If this is a local variable, dig out its value.
2696 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2697 : Frame->getCurrentTemporary(VD);
2699 // Assume variables referenced within a lambda's call operator that were
2700 // not declared within the call operator are captures and during checking
2701 // of a potential constant expression, assume they are unknown constant
2703 assert(isLambdaCallOperator(Frame->Callee) &&
2704 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2705 "missing value for local variable");
2706 if (Info.checkingPotentialConstantExpression())
2708 // FIXME: implement capture evaluation during constant expr evaluation.
2709 Info.FFDiag(E->getBeginLoc(),
2710 diag::note_unimplemented_constexpr_lambda_feature_ast)
2711 << "captures not currently allowed";
2717 // Dig out the initializer, and use the declaration which it's attached to.
2718 const Expr *Init = VD->getAnyInitializer(VD);
2719 if (!Init || Init->isValueDependent()) {
2720 // If we're checking a potential constant expression, the variable could be
2721 // initialized later.
2722 if (!Info.checkingPotentialConstantExpression())
2723 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2727 // If we're currently evaluating the initializer of this declaration, use that
2729 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2730 Result = Info.EvaluatingDeclValue;
2734 // Never evaluate the initializer of a weak variable. We can't be sure that
2735 // this is the definition which will be used.
2737 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2741 // Check that we can fold the initializer. In C++, we will have already done
2742 // this in the cases where it matters for conformance.
2743 SmallVector<PartialDiagnosticAt, 8> Notes;
2744 if (!VD->evaluateValue(Notes)) {
2745 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2746 Notes.size() + 1) << VD;
2747 Info.Note(VD->getLocation(), diag::note_declared_at);
2748 Info.addNotes(Notes);
2750 } else if (!VD->checkInitIsICE()) {
2751 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2752 Notes.size() + 1) << VD;
2753 Info.Note(VD->getLocation(), diag::note_declared_at);
2754 Info.addNotes(Notes);
2757 Result = VD->getEvaluatedValue();
2761 static bool IsConstNonVolatile(QualType T) {
2762 Qualifiers Quals = T.getQualifiers();
2763 return Quals.hasConst() && !Quals.hasVolatile();
2766 /// Get the base index of the given base class within an APValue representing
2767 /// the given derived class.
2768 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2769 const CXXRecordDecl *Base) {
2770 Base = Base->getCanonicalDecl();
2772 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2773 E = Derived->bases_end(); I != E; ++I, ++Index) {
2774 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2778 llvm_unreachable("base class missing from derived class's bases list");
2781 /// Extract the value of a character from a string literal.
2782 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2784 assert(!isa<SourceLocExpr>(Lit) &&
2785 "SourceLocExpr should have already been converted to a StringLiteral");
2787 // FIXME: Support MakeStringConstant
2788 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2790 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2791 assert(Index <= Str.size() && "Index too large");
2792 return APSInt::getUnsigned(Str.c_str()[Index]);
2795 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2796 Lit = PE->getFunctionName();
2797 const StringLiteral *S = cast<StringLiteral>(Lit);
2798 const ConstantArrayType *CAT =
2799 Info.Ctx.getAsConstantArrayType(S->getType());
2800 assert(CAT && "string literal isn't an array");
2801 QualType CharType = CAT->getElementType();
2802 assert(CharType->isIntegerType() && "unexpected character type");
2804 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2805 CharType->isUnsignedIntegerType());
2806 if (Index < S->getLength())
2807 Value = S->getCodeUnit(Index);
2811 // Expand a string literal into an array of characters.
2813 // FIXME: This is inefficient; we should probably introduce something similar
2814 // to the LLVM ConstantDataArray to make this cheaper.
2815 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2817 const ConstantArrayType *CAT =
2818 Info.Ctx.getAsConstantArrayType(S->getType());
2819 assert(CAT && "string literal isn't an array");
2820 QualType CharType = CAT->getElementType();
2821 assert(CharType->isIntegerType() && "unexpected character type");
2823 unsigned Elts = CAT->getSize().getZExtValue();
2824 Result = APValue(APValue::UninitArray(),
2825 std::min(S->getLength(), Elts), Elts);
2826 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2827 CharType->isUnsignedIntegerType());
2828 if (Result.hasArrayFiller())
2829 Result.getArrayFiller() = APValue(Value);
2830 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2831 Value = S->getCodeUnit(I);
2832 Result.getArrayInitializedElt(I) = APValue(Value);
2836 // Expand an array so that it has more than Index filled elements.
2837 static void expandArray(APValue &Array, unsigned Index) {
2838 unsigned Size = Array.getArraySize();
2839 assert(Index < Size);
2841 // Always at least double the number of elements for which we store a value.
2842 unsigned OldElts = Array.getArrayInitializedElts();
2843 unsigned NewElts = std::max(Index+1, OldElts * 2);
2844 NewElts = std::min(Size, std::max(NewElts, 8u));
2846 // Copy the data across.
2847 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2848 for (unsigned I = 0; I != OldElts; ++I)
2849 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2850 for (unsigned I = OldElts; I != NewElts; ++I)
2851 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2852 if (NewValue.hasArrayFiller())
2853 NewValue.getArrayFiller() = Array.getArrayFiller();
2854 Array.swap(NewValue);
2857 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2858 /// conversion. If it's of class type, we may assume that the copy operation
2859 /// is trivial. Note that this is never true for a union type with fields
2860 /// (because the copy always "reads" the active member) and always true for
2861 /// a non-class type.
2862 static bool isReadByLvalueToRvalueConversion(QualType T) {
2863 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2864 if (!RD || (RD->isUnion() && !RD->field_empty()))
2869 for (auto *Field : RD->fields())
2870 if (isReadByLvalueToRvalueConversion(Field->getType()))
2873 for (auto &BaseSpec : RD->bases())
2874 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2880 /// Diagnose an attempt to read from any unreadable field within the specified
2881 /// type, which might be a class type.
2882 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2884 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2888 if (!RD->hasMutableFields())
2891 for (auto *Field : RD->fields()) {
2892 // If we're actually going to read this field in some way, then it can't
2893 // be mutable. If we're in a union, then assigning to a mutable field
2894 // (even an empty one) can change the active member, so that's not OK.
2895 // FIXME: Add core issue number for the union case.
2896 if (Field->isMutable() &&
2897 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2898 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2899 Info.Note(Field->getLocation(), diag::note_declared_at);
2903 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2907 for (auto &BaseSpec : RD->bases())
2908 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2911 // All mutable fields were empty, and thus not actually read.
2915 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2916 APValue::LValueBase Base) {
2917 // A temporary we created.
2918 if (Base.getCallIndex())
2921 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2925 // The variable whose initializer we're evaluating.
2926 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2927 if (declaresSameEntity(Evaluating, BaseD))
2930 // A temporary lifetime-extended by the variable whose initializer we're
2932 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2933 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2934 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2941 /// A handle to a complete object (an object that is not a subobject of
2942 /// another object).
2943 struct CompleteObject {
2944 /// The identity of the object.
2945 APValue::LValueBase Base;
2946 /// The value of the complete object.
2948 /// The type of the complete object.
2951 CompleteObject() : Value(nullptr) {}
2952 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2953 : Base(Base), Value(Value), Type(Type) {}
2955 bool mayReadMutableMembers(EvalInfo &Info) const {
2956 // In C++14 onwards, it is permitted to read a mutable member whose
2957 // lifetime began within the evaluation.
2958 // FIXME: Should we also allow this in C++11?
2959 if (!Info.getLangOpts().CPlusPlus14)
2961 return lifetimeStartedInEvaluation(Info, Base);
2964 explicit operator bool() const { return !Type.isNull(); }
2966 } // end anonymous namespace
2968 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2969 bool IsMutable = false) {
2970 // C++ [basic.type.qualifier]p1:
2971 // - A const object is an object of type const T or a non-mutable subobject
2972 // of a const object.
2973 if (ObjType.isConstQualified() && !IsMutable)
2974 SubobjType.addConst();
2975 // - A volatile object is an object of type const T or a subobject of a
2977 if (ObjType.isVolatileQualified())
2978 SubobjType.addVolatile();
2982 /// Find the designated sub-object of an rvalue.
2983 template<typename SubobjectHandler>
2984 typename SubobjectHandler::result_type
2985 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2986 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2988 // A diagnostic will have already been produced.
2989 return handler.failed();
2990 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2991 if (Info.getLangOpts().CPlusPlus11)
2992 Info.FFDiag(E, Sub.isOnePastTheEnd()
2993 ? diag::note_constexpr_access_past_end
2994 : diag::note_constexpr_access_unsized_array)
2995 << handler.AccessKind;
2998 return handler.failed();
3001 APValue *O = Obj.Value;
3002 QualType ObjType = Obj.Type;
3003 const FieldDecl *LastField = nullptr;
3004 const FieldDecl *VolatileField = nullptr;
3006 // Walk the designator's path to find the subobject.
3007 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3008 // Reading an indeterminate value is undefined, but assigning over one is OK.
3009 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
3010 if (!Info.checkingPotentialConstantExpression())
3011 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3012 << handler.AccessKind << O->isIndeterminate();
3013 return handler.failed();
3016 // C++ [class.ctor]p5:
3017 // const and volatile semantics are not applied on an object under
3019 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3020 ObjType->isRecordType() &&
3021 Info.isEvaluatingConstructor(
3022 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3023 Sub.Entries.begin() + I)) !=
3024 ConstructionPhase::None) {
3025 ObjType = Info.Ctx.getCanonicalType(ObjType);
3026 ObjType.removeLocalConst();
3027 ObjType.removeLocalVolatile();
3030 // If this is our last pass, check that the final object type is OK.
3031 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3032 // Accesses to volatile objects are prohibited.
3033 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3034 if (Info.getLangOpts().CPlusPlus) {
3037 const NamedDecl *Decl = nullptr;
3038 if (VolatileField) {
3040 Loc = VolatileField->getLocation();
3041 Decl = VolatileField;
3042 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3044 Loc = VD->getLocation();
3048 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3049 Loc = E->getExprLoc();
3051 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3052 << handler.AccessKind << DiagKind << Decl;
3053 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3055 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3057 return handler.failed();
3060 // If we are reading an object of class type, there may still be more
3061 // things we need to check: if there are any mutable subobjects, we
3062 // cannot perform this read. (This only happens when performing a trivial
3063 // copy or assignment.)
3064 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3065 !Obj.mayReadMutableMembers(Info) &&
3066 diagnoseUnreadableFields(Info, E, ObjType))
3067 return handler.failed();
3071 if (!handler.found(*O, ObjType))
3074 // If we modified a bit-field, truncate it to the right width.
3075 if (isModification(handler.AccessKind) &&
3076 LastField && LastField->isBitField() &&
3077 !truncateBitfieldValue(Info, E, *O, LastField))
3083 LastField = nullptr;
3084 if (ObjType->isArrayType()) {
3085 // Next subobject is an array element.
3086 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3087 assert(CAT && "vla in literal type?");
3088 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3089 if (CAT->getSize().ule(Index)) {
3090 // Note, it should not be possible to form a pointer with a valid
3091 // designator which points more than one past the end of the array.
3092 if (Info.getLangOpts().CPlusPlus11)
3093 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3094 << handler.AccessKind;
3097 return handler.failed();
3100 ObjType = CAT->getElementType();
3102 if (O->getArrayInitializedElts() > Index)
3103 O = &O->getArrayInitializedElt(Index);
3104 else if (handler.AccessKind != AK_Read) {
3105 expandArray(*O, Index);
3106 O = &O->getArrayInitializedElt(Index);
3108 O = &O->getArrayFiller();
3109 } else if (ObjType->isAnyComplexType()) {
3110 // Next subobject is a complex number.
3111 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3113 if (Info.getLangOpts().CPlusPlus11)
3114 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3115 << handler.AccessKind;
3118 return handler.failed();
3121 ObjType = getSubobjectType(
3122 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3124 assert(I == N - 1 && "extracting subobject of scalar?");
3125 if (O->isComplexInt()) {
3126 return handler.found(Index ? O->getComplexIntImag()
3127 : O->getComplexIntReal(), ObjType);
3129 assert(O->isComplexFloat());
3130 return handler.found(Index ? O->getComplexFloatImag()
3131 : O->getComplexFloatReal(), ObjType);
3133 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3134 if (Field->isMutable() && handler.AccessKind == AK_Read &&
3135 !Obj.mayReadMutableMembers(Info)) {
3136 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3138 Info.Note(Field->getLocation(), diag::note_declared_at);
3139 return handler.failed();
3142 // Next subobject is a class, struct or union field.
3143 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3144 if (RD->isUnion()) {
3145 const FieldDecl *UnionField = O->getUnionField();
3147 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3148 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3149 << handler.AccessKind << Field << !UnionField << UnionField;
3150 return handler.failed();
3152 O = &O->getUnionValue();
3154 O = &O->getStructField(Field->getFieldIndex());
3156 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3158 if (Field->getType().isVolatileQualified())
3159 VolatileField = Field;
3161 // Next subobject is a base class.
3162 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3163 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3164 O = &O->getStructBase(getBaseIndex(Derived, Base));
3166 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3172 struct ExtractSubobjectHandler {
3176 static const AccessKinds AccessKind = AK_Read;
3178 typedef bool result_type;
3179 bool failed() { return false; }
3180 bool found(APValue &Subobj, QualType SubobjType) {
3184 bool found(APSInt &Value, QualType SubobjType) {
3185 Result = APValue(Value);
3188 bool found(APFloat &Value, QualType SubobjType) {
3189 Result = APValue(Value);
3193 } // end anonymous namespace
3195 const AccessKinds ExtractSubobjectHandler::AccessKind;
3197 /// Extract the designated sub-object of an rvalue.
3198 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3199 const CompleteObject &Obj,
3200 const SubobjectDesignator &Sub,
3202 ExtractSubobjectHandler Handler = { Info, Result };
3203 return findSubobject(Info, E, Obj, Sub, Handler);
3207 struct ModifySubobjectHandler {
3212 typedef bool result_type;
3213 static const AccessKinds AccessKind = AK_Assign;
3215 bool checkConst(QualType QT) {
3216 // Assigning to a const object has undefined behavior.
3217 if (QT.isConstQualified()) {
3218 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3224 bool failed() { return false; }
3225 bool found(APValue &Subobj, QualType SubobjType) {
3226 if (!checkConst(SubobjType))
3228 // We've been given ownership of NewVal, so just swap it in.
3229 Subobj.swap(NewVal);
3232 bool found(APSInt &Value, QualType SubobjType) {
3233 if (!checkConst(SubobjType))
3235 if (!NewVal.isInt()) {
3236 // Maybe trying to write a cast pointer value into a complex?
3240 Value = NewVal.getInt();
3243 bool found(APFloat &Value, QualType SubobjType) {
3244 if (!checkConst(SubobjType))
3246 Value = NewVal.getFloat();
3250 } // end anonymous namespace
3252 const AccessKinds ModifySubobjectHandler::AccessKind;
3254 /// Update the designated sub-object of an rvalue to the given value.
3255 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3256 const CompleteObject &Obj,
3257 const SubobjectDesignator &Sub,
3259 ModifySubobjectHandler Handler = { Info, NewVal, E };
3260 return findSubobject(Info, E, Obj, Sub, Handler);
3263 /// Find the position where two subobject designators diverge, or equivalently
3264 /// the length of the common initial subsequence.
3265 static unsigned FindDesignatorMismatch(QualType ObjType,
3266 const SubobjectDesignator &A,
3267 const SubobjectDesignator &B,
3268 bool &WasArrayIndex) {
3269 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3270 for (/**/; I != N; ++I) {
3271 if (!ObjType.isNull() &&
3272 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3273 // Next subobject is an array element.
3274 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3275 WasArrayIndex = true;
3278 if (ObjType->isAnyComplexType())
3279 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3281 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3283 if (A.Entries[I].getAsBaseOrMember() !=
3284 B.Entries[I].getAsBaseOrMember()) {
3285 WasArrayIndex = false;
3288 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3289 // Next subobject is a field.
3290 ObjType = FD->getType();
3292 // Next subobject is a base class.
3293 ObjType = QualType();
3296 WasArrayIndex = false;
3300 /// Determine whether the given subobject designators refer to elements of the
3301 /// same array object.
3302 static bool AreElementsOfSameArray(QualType ObjType,
3303 const SubobjectDesignator &A,
3304 const SubobjectDesignator &B) {
3305 if (A.Entries.size() != B.Entries.size())
3308 bool IsArray = A.MostDerivedIsArrayElement;
3309 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3310 // A is a subobject of the array element.
3313 // If A (and B) designates an array element, the last entry will be the array
3314 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3315 // of length 1' case, and the entire path must match.
3317 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3318 return CommonLength >= A.Entries.size() - IsArray;
3321 /// Find the complete object to which an LValue refers.
3322 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3323 AccessKinds AK, const LValue &LVal,
3324 QualType LValType) {
3325 if (LVal.InvalidBase) {
3327 return CompleteObject();
3331 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3332 return CompleteObject();
3335 CallStackFrame *Frame = nullptr;
3337 if (LVal.getLValueCallIndex()) {
3338 std::tie(Frame, Depth) =
3339 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3341 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3342 << AK << LVal.Base.is<const ValueDecl*>();
3343 NoteLValueLocation(Info, LVal.Base);
3344 return CompleteObject();
3348 bool IsAccess = isFormalAccess(AK);
3350 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3351 // is not a constant expression (even if the object is non-volatile). We also
3352 // apply this rule to C++98, in order to conform to the expected 'volatile'
3354 if (IsAccess && LValType.isVolatileQualified()) {
3355 if (Info.getLangOpts().CPlusPlus)
3356 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3360 return CompleteObject();
3363 // Compute value storage location and type of base object.
3364 APValue *BaseVal = nullptr;
3365 QualType BaseType = getType(LVal.Base);
3367 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3368 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3369 // In C++11, constexpr, non-volatile variables initialized with constant
3370 // expressions are constant expressions too. Inside constexpr functions,
3371 // parameters are constant expressions even if they're non-const.
3372 // In C++1y, objects local to a constant expression (those with a Frame) are
3373 // both readable and writable inside constant expressions.
3374 // In C, such things can also be folded, although they are not ICEs.
3375 const VarDecl *VD = dyn_cast<VarDecl>(D);
3377 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3380 if (!VD || VD->isInvalidDecl()) {
3382 return CompleteObject();
3385 // Unless we're looking at a local variable or argument in a constexpr call,
3386 // the variable we're reading must be const.
3388 if (Info.getLangOpts().CPlusPlus14 &&
3390 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3391 // OK, we can read and modify an object if we're in the process of
3392 // evaluating its initializer, because its lifetime began in this
3394 } else if (isModification(AK)) {
3395 // All the remaining cases do not permit modification of the object.
3396 Info.FFDiag(E, diag::note_constexpr_modify_global);
3397 return CompleteObject();
3398 } else if (VD->isConstexpr()) {
3399 // OK, we can read this variable.
3400 } else if (BaseType->isIntegralOrEnumerationType()) {
3401 // In OpenCL if a variable is in constant address space it is a const
3403 if (!(BaseType.isConstQualified() ||
3404 (Info.getLangOpts().OpenCL &&
3405 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3407 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3408 if (Info.getLangOpts().CPlusPlus) {
3409 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3410 Info.Note(VD->getLocation(), diag::note_declared_at);
3414 return CompleteObject();
3416 } else if (!IsAccess) {
3417 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3418 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3419 // We support folding of const floating-point types, in order to make
3420 // static const data members of such types (supported as an extension)
3422 if (Info.getLangOpts().CPlusPlus11) {
3423 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3424 Info.Note(VD->getLocation(), diag::note_declared_at);
3428 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3429 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3430 // Keep evaluating to see what we can do.
3432 // FIXME: Allow folding of values of any literal type in all languages.
3433 if (Info.checkingPotentialConstantExpression() &&
3434 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3435 // The definition of this variable could be constexpr. We can't
3436 // access it right now, but may be able to in future.
3437 } else if (Info.getLangOpts().CPlusPlus11) {
3438 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3439 Info.Note(VD->getLocation(), diag::note_declared_at);
3443 return CompleteObject();
3447 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3448 return CompleteObject();
3450 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3453 if (const MaterializeTemporaryExpr *MTE =
3454 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3455 assert(MTE->getStorageDuration() == SD_Static &&
3456 "should have a frame for a non-global materialized temporary");
3458 // Per C++1y [expr.const]p2:
3459 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3460 // - a [...] glvalue of integral or enumeration type that refers to
3461 // a non-volatile const object [...]
3463 // - a [...] glvalue of literal type that refers to a non-volatile
3464 // object whose lifetime began within the evaluation of e.
3466 // C++11 misses the 'began within the evaluation of e' check and
3467 // instead allows all temporaries, including things like:
3470 // constexpr int k = r;
3471 // Therefore we use the C++14 rules in C++11 too.
3472 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3473 const ValueDecl *ED = MTE->getExtendingDecl();
3474 if (!(BaseType.isConstQualified() &&
3475 BaseType->isIntegralOrEnumerationType()) &&
3476 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3478 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3479 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3480 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3481 return CompleteObject();
3484 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3485 assert(BaseVal && "got reference to unevaluated temporary");
3488 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3491 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3493 << Val.getAsString(Info.Ctx,
3494 Info.Ctx.getLValueReferenceType(LValType));
3495 NoteLValueLocation(Info, LVal.Base);
3496 return CompleteObject();
3499 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3500 assert(BaseVal && "missing value for temporary");
3504 // In C++14, we can't safely access any mutable state when we might be
3505 // evaluating after an unmodeled side effect.
3507 // FIXME: Not all local state is mutable. Allow local constant subobjects
3508 // to be read here (but take care with 'mutable' fields).
3509 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3510 Info.EvalStatus.HasSideEffects) ||
3511 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3512 return CompleteObject();
3514 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3517 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3518 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3519 /// glvalue referred to by an entity of reference type.
3521 /// \param Info - Information about the ongoing evaluation.
3522 /// \param Conv - The expression for which we are performing the conversion.
3523 /// Used for diagnostics.
3524 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3525 /// case of a non-class type).
3526 /// \param LVal - The glvalue on which we are attempting to perform this action.
3527 /// \param RVal - The produced value will be placed here.
3528 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3530 const LValue &LVal, APValue &RVal) {
3531 if (LVal.Designator.Invalid)
3534 // Check for special cases where there is no existing APValue to look at.
3535 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3537 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3538 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3539 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3540 // initializer until now for such expressions. Such an expression can't be
3541 // an ICE in C, so this only matters for fold.
3542 if (Type.isVolatileQualified()) {
3547 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3549 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3550 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3551 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3552 // Special-case character extraction so we don't have to construct an
3553 // APValue for the whole string.
3554 assert(LVal.Designator.Entries.size() <= 1 &&
3555 "Can only read characters from string literals");
3556 if (LVal.Designator.Entries.empty()) {
3557 // Fail for now for LValue to RValue conversion of an array.
3558 // (This shouldn't show up in C/C++, but it could be triggered by a
3559 // weird EvaluateAsRValue call from a tool.)
3563 if (LVal.Designator.isOnePastTheEnd()) {
3564 if (Info.getLangOpts().CPlusPlus11)
3565 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3570 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3571 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3576 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3577 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3580 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3581 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3582 QualType LValType, APValue &Val) {
3583 if (LVal.Designator.Invalid)
3586 if (!Info.getLangOpts().CPlusPlus14) {
3591 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3592 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3596 struct CompoundAssignSubobjectHandler {
3599 QualType PromotedLHSType;
3600 BinaryOperatorKind Opcode;
3603 static const AccessKinds AccessKind = AK_Assign;
3605 typedef bool result_type;
3607 bool checkConst(QualType QT) {
3608 // Assigning to a const object has undefined behavior.
3609 if (QT.isConstQualified()) {
3610 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3616 bool failed() { return false; }
3617 bool found(APValue &Subobj, QualType SubobjType) {
3618 switch (Subobj.getKind()) {
3620 return found(Subobj.getInt(), SubobjType);
3621 case APValue::Float:
3622 return found(Subobj.getFloat(), SubobjType);
3623 case APValue::ComplexInt:
3624 case APValue::ComplexFloat:
3625 // FIXME: Implement complex compound assignment.
3628 case APValue::LValue:
3629 return foundPointer(Subobj, SubobjType);
3631 // FIXME: can this happen?
3636 bool found(APSInt &Value, QualType SubobjType) {
3637 if (!checkConst(SubobjType))
3640 if (!SubobjType->isIntegerType()) {
3641 // We don't support compound assignment on integer-cast-to-pointer
3649 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3650 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3652 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3654 } else if (RHS.isFloat()) {
3655 APFloat FValue(0.0);
3656 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3658 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3659 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3666 bool found(APFloat &Value, QualType SubobjType) {
3667 return checkConst(SubobjType) &&
3668 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3670 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3671 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3673 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3674 if (!checkConst(SubobjType))
3677 QualType PointeeType;
3678 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3679 PointeeType = PT->getPointeeType();
3681 if (PointeeType.isNull() || !RHS.isInt() ||
3682 (Opcode != BO_Add && Opcode != BO_Sub)) {
3687 APSInt Offset = RHS.getInt();
3688 if (Opcode == BO_Sub)
3689 negateAsSigned(Offset);
3692 LVal.setFrom(Info.Ctx, Subobj);
3693 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3695 LVal.moveInto(Subobj);
3699 } // end anonymous namespace
3701 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3703 /// Perform a compound assignment of LVal <op>= RVal.
3704 static bool handleCompoundAssignment(
3705 EvalInfo &Info, const Expr *E,
3706 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3707 BinaryOperatorKind Opcode, const APValue &RVal) {
3708 if (LVal.Designator.Invalid)
3711 if (!Info.getLangOpts().CPlusPlus14) {
3716 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3717 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3719 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3723 struct IncDecSubobjectHandler {
3725 const UnaryOperator *E;
3726 AccessKinds AccessKind;
3729 typedef bool result_type;
3731 bool checkConst(QualType QT) {
3732 // Assigning to a const object has undefined behavior.
3733 if (QT.isConstQualified()) {
3734 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3740 bool failed() { return false; }
3741 bool found(APValue &Subobj, QualType SubobjType) {
3742 // Stash the old value. Also clear Old, so we don't clobber it later
3743 // if we're post-incrementing a complex.
3749 switch (Subobj.getKind()) {
3751 return found(Subobj.getInt(), SubobjType);
3752 case APValue::Float:
3753 return found(Subobj.getFloat(), SubobjType);
3754 case APValue::ComplexInt:
3755 return found(Subobj.getComplexIntReal(),
3756 SubobjType->castAs<ComplexType>()->getElementType()
3757 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3758 case APValue::ComplexFloat:
3759 return found(Subobj.getComplexFloatReal(),
3760 SubobjType->castAs<ComplexType>()->getElementType()
3761 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3762 case APValue::LValue:
3763 return foundPointer(Subobj, SubobjType);
3765 // FIXME: can this happen?
3770 bool found(APSInt &Value, QualType SubobjType) {
3771 if (!checkConst(SubobjType))
3774 if (!SubobjType->isIntegerType()) {
3775 // We don't support increment / decrement on integer-cast-to-pointer
3781 if (Old) *Old = APValue(Value);
3783 // bool arithmetic promotes to int, and the conversion back to bool
3784 // doesn't reduce mod 2^n, so special-case it.
3785 if (SubobjType->isBooleanType()) {
3786 if (AccessKind == AK_Increment)
3793 bool WasNegative = Value.isNegative();
3794 if (AccessKind == AK_Increment) {
3797 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3798 APSInt ActualValue(Value, /*IsUnsigned*/true);
3799 return HandleOverflow(Info, E, ActualValue, SubobjType);
3804 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3805 unsigned BitWidth = Value.getBitWidth();
3806 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3807 ActualValue.setBit(BitWidth);
3808 return HandleOverflow(Info, E, ActualValue, SubobjType);
3813 bool found(APFloat &Value, QualType SubobjType) {
3814 if (!checkConst(SubobjType))
3817 if (Old) *Old = APValue(Value);
3819 APFloat One(Value.getSemantics(), 1);
3820 if (AccessKind == AK_Increment)
3821 Value.add(One, APFloat::rmNearestTiesToEven);
3823 Value.subtract(One, APFloat::rmNearestTiesToEven);
3826 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3827 if (!checkConst(SubobjType))
3830 QualType PointeeType;
3831 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3832 PointeeType = PT->getPointeeType();
3839 LVal.setFrom(Info.Ctx, Subobj);
3840 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3841 AccessKind == AK_Increment ? 1 : -1))
3843 LVal.moveInto(Subobj);
3847 } // end anonymous namespace
3849 /// Perform an increment or decrement on LVal.
3850 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3851 QualType LValType, bool IsIncrement, APValue *Old) {
3852 if (LVal.Designator.Invalid)
3855 if (!Info.getLangOpts().CPlusPlus14) {
3860 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3861 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3862 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3863 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3866 /// Build an lvalue for the object argument of a member function call.
3867 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3869 if (Object->getType()->isPointerType())
3870 return EvaluatePointer(Object, This, Info);
3872 if (Object->isGLValue())
3873 return EvaluateLValue(Object, This, Info);
3875 if (Object->getType()->isLiteralType(Info.Ctx))
3876 return EvaluateTemporary(Object, This, Info);
3878 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3882 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3883 /// lvalue referring to the result.
3885 /// \param Info - Information about the ongoing evaluation.
3886 /// \param LV - An lvalue referring to the base of the member pointer.
3887 /// \param RHS - The member pointer expression.
3888 /// \param IncludeMember - Specifies whether the member itself is included in
3889 /// the resulting LValue subobject designator. This is not possible when
3890 /// creating a bound member function.
3891 /// \return The field or method declaration to which the member pointer refers,
3892 /// or 0 if evaluation fails.
3893 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3897 bool IncludeMember = true) {
3899 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3902 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3903 // member value, the behavior is undefined.
3904 if (!MemPtr.getDecl()) {
3905 // FIXME: Specific diagnostic.
3910 if (MemPtr.isDerivedMember()) {
3911 // This is a member of some derived class. Truncate LV appropriately.
3912 // The end of the derived-to-base path for the base object must match the
3913 // derived-to-base path for the member pointer.
3914 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3915 LV.Designator.Entries.size()) {
3919 unsigned PathLengthToMember =
3920 LV.Designator.Entries.size() - MemPtr.Path.size();
3921 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3922 const CXXRecordDecl *LVDecl = getAsBaseClass(
3923 LV.Designator.Entries[PathLengthToMember + I]);
3924 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3925 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3931 // Truncate the lvalue to the appropriate derived class.
3932 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3933 PathLengthToMember))
3935 } else if (!MemPtr.Path.empty()) {
3936 // Extend the LValue path with the member pointer's path.
3937 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3938 MemPtr.Path.size() + IncludeMember);
3940 // Walk down to the appropriate base class.
3941 if (const PointerType *PT = LVType->getAs<PointerType>())
3942 LVType = PT->getPointeeType();
3943 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3944 assert(RD && "member pointer access on non-class-type expression");
3945 // The first class in the path is that of the lvalue.
3946 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3947 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3948 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3952 // Finally cast to the class containing the member.
3953 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3954 MemPtr.getContainingRecord()))
3958 // Add the member. Note that we cannot build bound member functions here.
3959 if (IncludeMember) {
3960 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3961 if (!HandleLValueMember(Info, RHS, LV, FD))
3963 } else if (const IndirectFieldDecl *IFD =
3964 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3965 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3968 llvm_unreachable("can't construct reference to bound member function");
3972 return MemPtr.getDecl();
3975 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3976 const BinaryOperator *BO,
3978 bool IncludeMember = true) {
3979 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3981 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3982 if (Info.noteFailure()) {
3984 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3989 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3990 BO->getRHS(), IncludeMember);
3993 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3994 /// the provided lvalue, which currently refers to the base object.
3995 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3997 SubobjectDesignator &D = Result.Designator;
3998 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4001 QualType TargetQT = E->getType();
4002 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4003 TargetQT = PT->getPointeeType();
4005 // Check this cast lands within the final derived-to-base subobject path.
4006 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4007 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4008 << D.MostDerivedType << TargetQT;
4012 // Check the type of the final cast. We don't need to check the path,
4013 // since a cast can only be formed if the path is unique.
4014 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4015 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4016 const CXXRecordDecl *FinalType;
4017 if (NewEntriesSize == D.MostDerivedPathLength)
4018 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4020 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4021 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4022 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4023 << D.MostDerivedType << TargetQT;
4027 // Truncate the lvalue to the appropriate derived class.
4028 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4032 enum EvalStmtResult {
4033 /// Evaluation failed.
4035 /// Hit a 'return' statement.
4037 /// Evaluation succeeded.
4039 /// Hit a 'continue' statement.
4041 /// Hit a 'break' statement.
4043 /// Still scanning for 'case' or 'default' statement.
4048 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4049 // We don't need to evaluate the initializer for a static local.
4050 if (!VD->hasLocalStorage())
4054 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4056 const Expr *InitE = VD->getInit();
4058 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4059 << false << VD->getType();
4064 if (InitE->isValueDependent())
4067 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4068 // Wipe out any partially-computed value, to allow tracking that this
4069 // evaluation failed.
4077 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4080 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4081 OK &= EvaluateVarDecl(Info, VD);
4083 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4084 for (auto *BD : DD->bindings())
4085 if (auto *VD = BD->getHoldingVar())
4086 OK &= EvaluateDecl(Info, VD);
4092 /// Evaluate a condition (either a variable declaration or an expression).
4093 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4094 const Expr *Cond, bool &Result) {
4095 FullExpressionRAII Scope(Info);
4096 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4098 return EvaluateAsBooleanCondition(Cond, Result, Info);
4102 /// A location where the result (returned value) of evaluating a
4103 /// statement should be stored.
4105 /// The APValue that should be filled in with the returned value.
4107 /// The location containing the result, if any (used to support RVO).
4111 struct TempVersionRAII {
4112 CallStackFrame &Frame;
4114 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4115 Frame.pushTempVersion();
4118 ~TempVersionRAII() {
4119 Frame.popTempVersion();
4125 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4127 const SwitchCase *SC = nullptr);
4129 /// Evaluate the body of a loop, and translate the result as appropriate.
4130 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4132 const SwitchCase *Case = nullptr) {
4133 BlockScopeRAII Scope(Info);
4134 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4136 return ESR_Succeeded;
4139 return ESR_Continue;
4142 case ESR_CaseNotFound:
4145 llvm_unreachable("Invalid EvalStmtResult!");
4148 /// Evaluate a switch statement.
4149 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4150 const SwitchStmt *SS) {
4151 BlockScopeRAII Scope(Info);
4153 // Evaluate the switch condition.
4156 FullExpressionRAII Scope(Info);
4157 if (const Stmt *Init = SS->getInit()) {
4158 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4159 if (ESR != ESR_Succeeded)
4162 if (SS->getConditionVariable() &&
4163 !EvaluateDecl(Info, SS->getConditionVariable()))
4165 if (!EvaluateInteger(SS->getCond(), Value, Info))
4169 // Find the switch case corresponding to the value of the condition.
4170 // FIXME: Cache this lookup.
4171 const SwitchCase *Found = nullptr;
4172 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4173 SC = SC->getNextSwitchCase()) {
4174 if (isa<DefaultStmt>(SC)) {
4179 const CaseStmt *CS = cast<CaseStmt>(SC);
4180 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4181 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4183 if (LHS <= Value && Value <= RHS) {
4190 return ESR_Succeeded;
4192 // Search the switch body for the switch case and evaluate it from there.
4193 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4195 return ESR_Succeeded;
4201 case ESR_CaseNotFound:
4202 // This can only happen if the switch case is nested within a statement
4203 // expression. We have no intention of supporting that.
4204 Info.FFDiag(Found->getBeginLoc(),
4205 diag::note_constexpr_stmt_expr_unsupported);
4208 llvm_unreachable("Invalid EvalStmtResult!");
4211 // Evaluate a statement.
4212 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4213 const Stmt *S, const SwitchCase *Case) {
4214 if (!Info.nextStep(S))
4217 // If we're hunting down a 'case' or 'default' label, recurse through
4218 // substatements until we hit the label.
4220 // FIXME: We don't start the lifetime of objects whose initialization we
4221 // jump over. However, such objects must be of class type with a trivial
4222 // default constructor that initialize all subobjects, so must be empty,
4223 // so this almost never matters.
4224 switch (S->getStmtClass()) {
4225 case Stmt::CompoundStmtClass:
4226 // FIXME: Precompute which substatement of a compound statement we
4227 // would jump to, and go straight there rather than performing a
4228 // linear scan each time.
4229 case Stmt::LabelStmtClass:
4230 case Stmt::AttributedStmtClass:
4231 case Stmt::DoStmtClass:
4234 case Stmt::CaseStmtClass:
4235 case Stmt::DefaultStmtClass:
4240 case Stmt::IfStmtClass: {
4241 // FIXME: Precompute which side of an 'if' we would jump to, and go
4242 // straight there rather than scanning both sides.
4243 const IfStmt *IS = cast<IfStmt>(S);
4245 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4246 // preceded by our switch label.
4247 BlockScopeRAII Scope(Info);
4249 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4250 if (ESR != ESR_CaseNotFound || !IS->getElse())
4252 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4255 case Stmt::WhileStmtClass: {
4256 EvalStmtResult ESR =
4257 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4258 if (ESR != ESR_Continue)
4263 case Stmt::ForStmtClass: {
4264 const ForStmt *FS = cast<ForStmt>(S);
4265 EvalStmtResult ESR =
4266 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4267 if (ESR != ESR_Continue)
4270 FullExpressionRAII IncScope(Info);
4271 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4277 case Stmt::DeclStmtClass:
4278 // FIXME: If the variable has initialization that can't be jumped over,
4279 // bail out of any immediately-surrounding compound-statement too.
4281 return ESR_CaseNotFound;
4285 switch (S->getStmtClass()) {
4287 if (const Expr *E = dyn_cast<Expr>(S)) {
4288 // Don't bother evaluating beyond an expression-statement which couldn't
4290 FullExpressionRAII Scope(Info);
4291 if (!EvaluateIgnoredValue(Info, E))
4293 return ESR_Succeeded;
4296 Info.FFDiag(S->getBeginLoc());
4299 case Stmt::NullStmtClass:
4300 return ESR_Succeeded;
4302 case Stmt::DeclStmtClass: {
4303 const DeclStmt *DS = cast<DeclStmt>(S);
4304 for (const auto *DclIt : DS->decls()) {
4305 // Each declaration initialization is its own full-expression.
4306 // FIXME: This isn't quite right; if we're performing aggregate
4307 // initialization, each braced subexpression is its own full-expression.
4308 FullExpressionRAII Scope(Info);
4309 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4312 return ESR_Succeeded;
4315 case Stmt::ReturnStmtClass: {
4316 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4317 FullExpressionRAII Scope(Info);
4320 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4321 : Evaluate(Result.Value, Info, RetExpr)))
4323 return ESR_Returned;
4326 case Stmt::CompoundStmtClass: {
4327 BlockScopeRAII Scope(Info);
4329 const CompoundStmt *CS = cast<CompoundStmt>(S);
4330 for (const auto *BI : CS->body()) {
4331 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4332 if (ESR == ESR_Succeeded)
4334 else if (ESR != ESR_CaseNotFound)
4337 return Case ? ESR_CaseNotFound : ESR_Succeeded;
4340 case Stmt::IfStmtClass: {
4341 const IfStmt *IS = cast<IfStmt>(S);
4343 // Evaluate the condition, as either a var decl or as an expression.
4344 BlockScopeRAII Scope(Info);
4345 if (const Stmt *Init = IS->getInit()) {
4346 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4347 if (ESR != ESR_Succeeded)
4351 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4354 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4355 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4356 if (ESR != ESR_Succeeded)
4359 return ESR_Succeeded;
4362 case Stmt::WhileStmtClass: {
4363 const WhileStmt *WS = cast<WhileStmt>(S);
4365 BlockScopeRAII Scope(Info);
4367 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4373 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4374 if (ESR != ESR_Continue)
4377 return ESR_Succeeded;
4380 case Stmt::DoStmtClass: {
4381 const DoStmt *DS = cast<DoStmt>(S);
4384 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4385 if (ESR != ESR_Continue)
4389 FullExpressionRAII CondScope(Info);
4390 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4393 return ESR_Succeeded;
4396 case Stmt::ForStmtClass: {
4397 const ForStmt *FS = cast<ForStmt>(S);
4398 BlockScopeRAII Scope(Info);
4399 if (FS->getInit()) {
4400 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4401 if (ESR != ESR_Succeeded)
4405 BlockScopeRAII Scope(Info);
4406 bool Continue = true;
4407 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4408 FS->getCond(), Continue))
4413 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4414 if (ESR != ESR_Continue)
4418 FullExpressionRAII IncScope(Info);
4419 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4423 return ESR_Succeeded;
4426 case Stmt::CXXForRangeStmtClass: {
4427 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4428 BlockScopeRAII Scope(Info);
4430 // Evaluate the init-statement if present.
4431 if (FS->getInit()) {
4432 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4433 if (ESR != ESR_Succeeded)
4437 // Initialize the __range variable.
4438 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4439 if (ESR != ESR_Succeeded)
4442 // Create the __begin and __end iterators.
4443 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4444 if (ESR != ESR_Succeeded)
4446 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4447 if (ESR != ESR_Succeeded)
4451 // Condition: __begin != __end.
4453 bool Continue = true;
4454 FullExpressionRAII CondExpr(Info);
4455 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4461 // User's variable declaration, initialized by *__begin.
4462 BlockScopeRAII InnerScope(Info);
4463 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4464 if (ESR != ESR_Succeeded)
4468 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4469 if (ESR != ESR_Continue)
4472 // Increment: ++__begin
4473 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4477 return ESR_Succeeded;
4480 case Stmt::SwitchStmtClass:
4481 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4483 case Stmt::ContinueStmtClass:
4484 return ESR_Continue;
4486 case Stmt::BreakStmtClass:
4489 case Stmt::LabelStmtClass:
4490 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4492 case Stmt::AttributedStmtClass:
4493 // As a general principle, C++11 attributes can be ignored without
4494 // any semantic impact.
4495 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4498 case Stmt::CaseStmtClass:
4499 case Stmt::DefaultStmtClass:
4500 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4501 case Stmt::CXXTryStmtClass:
4502 // Evaluate try blocks by evaluating all sub statements.
4503 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4507 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4508 /// default constructor. If so, we'll fold it whether or not it's marked as
4509 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4510 /// so we need special handling.
4511 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4512 const CXXConstructorDecl *CD,
4513 bool IsValueInitialization) {
4514 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4517 // Value-initialization does not call a trivial default constructor, so such a
4518 // call is a core constant expression whether or not the constructor is
4520 if (!CD->isConstexpr() && !IsValueInitialization) {
4521 if (Info.getLangOpts().CPlusPlus11) {
4522 // FIXME: If DiagDecl is an implicitly-declared special member function,
4523 // we should be much more explicit about why it's not constexpr.
4524 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4525 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4526 Info.Note(CD->getLocation(), diag::note_declared_at);
4528 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4534 /// CheckConstexprFunction - Check that a function can be called in a constant
4536 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4537 const FunctionDecl *Declaration,
4538 const FunctionDecl *Definition,
4540 // Potential constant expressions can contain calls to declared, but not yet
4541 // defined, constexpr functions.
4542 if (Info.checkingPotentialConstantExpression() && !Definition &&
4543 Declaration->isConstexpr())
4546 // Bail out if the function declaration itself is invalid. We will
4547 // have produced a relevant diagnostic while parsing it, so just
4548 // note the problematic sub-expression.
4549 if (Declaration->isInvalidDecl()) {
4550 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4554 // DR1872: An instantiated virtual constexpr function can't be called in a
4555 // constant expression (prior to C++20). We can still constant-fold such a
4557 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4558 cast<CXXMethodDecl>(Declaration)->isVirtual())
4559 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4561 if (Definition && Definition->isInvalidDecl()) {
4562 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4566 // Can we evaluate this function call?
4567 if (Definition && Definition->isConstexpr() && Body)
4570 if (Info.getLangOpts().CPlusPlus11) {
4571 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4573 // If this function is not constexpr because it is an inherited
4574 // non-constexpr constructor, diagnose that directly.
4575 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4576 if (CD && CD->isInheritingConstructor()) {
4577 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4578 if (!Inherited->isConstexpr())
4579 DiagDecl = CD = Inherited;
4582 // FIXME: If DiagDecl is an implicitly-declared special member function
4583 // or an inheriting constructor, we should be much more explicit about why
4584 // it's not constexpr.
4585 if (CD && CD->isInheritingConstructor())
4586 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4587 << CD->getInheritedConstructor().getConstructor()->getParent();
4589 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4590 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4591 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4593 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4599 struct CheckDynamicTypeHandler {
4600 AccessKinds AccessKind;
4601 typedef bool result_type;
4602 bool failed() { return false; }
4603 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4604 bool found(APSInt &Value, QualType SubobjType) { return true; }
4605 bool found(APFloat &Value, QualType SubobjType) { return true; }
4607 } // end anonymous namespace
4609 /// Check that we can access the notional vptr of an object / determine its
4611 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4612 AccessKinds AK, bool Polymorphic) {
4613 if (This.Designator.Invalid)
4616 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4622 // The object is not usable in constant expressions, so we can't inspect
4623 // its value to see if it's in-lifetime or what the active union members
4624 // are. We can still check for a one-past-the-end lvalue.
4625 if (This.Designator.isOnePastTheEnd() ||
4626 This.Designator.isMostDerivedAnUnsizedArray()) {
4627 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4628 ? diag::note_constexpr_access_past_end
4629 : diag::note_constexpr_access_unsized_array)
4632 } else if (Polymorphic) {
4633 // Conservatively refuse to perform a polymorphic operation if we would
4634 // not be able to read a notional 'vptr' value.
4637 QualType StarThisType =
4638 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4639 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4640 << AK << Val.getAsString(Info.Ctx, StarThisType);
4646 CheckDynamicTypeHandler Handler{AK};
4647 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4650 /// Check that the pointee of the 'this' pointer in a member function call is
4651 /// either within its lifetime or in its period of construction or destruction.
4652 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4653 const LValue &This) {
4654 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4657 struct DynamicType {
4658 /// The dynamic class type of the object.
4659 const CXXRecordDecl *Type;
4660 /// The corresponding path length in the lvalue.
4661 unsigned PathLength;
4664 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4665 unsigned PathLength) {
4666 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4667 Designator.Entries.size() && "invalid path length");
4668 return (PathLength == Designator.MostDerivedPathLength)
4669 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4670 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4673 /// Determine the dynamic type of an object.
4674 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4675 LValue &This, AccessKinds AK) {
4676 // If we don't have an lvalue denoting an object of class type, there is no
4677 // meaningful dynamic type. (We consider objects of non-class type to have no
4679 if (!checkDynamicType(Info, E, This, AK, true))
4682 // Refuse to compute a dynamic type in the presence of virtual bases. This
4683 // shouldn't happen other than in constant-folding situations, since literal
4684 // types can't have virtual bases.
4686 // Note that consumers of DynamicType assume that the type has no virtual
4687 // bases, and will need modifications if this restriction is relaxed.
4688 const CXXRecordDecl *Class =
4689 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4690 if (!Class || Class->getNumVBases()) {
4695 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4696 // binary search here instead. But the overwhelmingly common case is that
4697 // we're not in the middle of a constructor, so it probably doesn't matter
4699 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4700 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4701 PathLength <= Path.size(); ++PathLength) {
4702 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4703 Path.slice(0, PathLength))) {
4704 case ConstructionPhase::Bases:
4705 // We're constructing a base class. This is not the dynamic type.
4708 case ConstructionPhase::None:
4709 case ConstructionPhase::AfterBases:
4710 // We've finished constructing the base classes, so this is the dynamic
4712 return DynamicType{getBaseClassType(This.Designator, PathLength),
4717 // CWG issue 1517: we're constructing a base class of the object described by
4718 // 'This', so that object has not yet begun its period of construction and
4719 // any polymorphic operation on it results in undefined behavior.
4724 /// Perform virtual dispatch.
4725 static const CXXMethodDecl *HandleVirtualDispatch(
4726 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4727 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4728 Optional<DynamicType> DynType =
4729 ComputeDynamicType(Info, E, This, AK_MemberCall);
4733 // Find the final overrider. It must be declared in one of the classes on the
4734 // path from the dynamic type to the static type.
4735 // FIXME: If we ever allow literal types to have virtual base classes, that
4737 const CXXMethodDecl *Callee = Found;
4738 unsigned PathLength = DynType->PathLength;
4739 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4740 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4741 const CXXMethodDecl *Overrider =
4742 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4749 // C++2a [class.abstract]p6:
4750 // the effect of making a virtual call to a pure virtual function [...] is
4752 if (Callee->isPure()) {
4753 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4754 Info.Note(Callee->getLocation(), diag::note_declared_at);
4758 // If necessary, walk the rest of the path to determine the sequence of
4759 // covariant adjustment steps to apply.
4760 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4761 Found->getReturnType())) {
4762 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4763 for (unsigned CovariantPathLength = PathLength + 1;
4764 CovariantPathLength != This.Designator.Entries.size();
4765 ++CovariantPathLength) {
4766 const CXXRecordDecl *NextClass =
4767 getBaseClassType(This.Designator, CovariantPathLength);
4768 const CXXMethodDecl *Next =
4769 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4770 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4771 Next->getReturnType(), CovariantAdjustmentPath.back()))
4772 CovariantAdjustmentPath.push_back(Next->getReturnType());
4774 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4775 CovariantAdjustmentPath.back()))
4776 CovariantAdjustmentPath.push_back(Found->getReturnType());
4779 // Perform 'this' adjustment.
4780 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4786 /// Perform the adjustment from a value returned by a virtual function to
4787 /// a value of the statically expected type, which may be a pointer or
4788 /// reference to a base class of the returned type.
4789 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4791 ArrayRef<QualType> Path) {
4792 assert(Result.isLValue() &&
4793 "unexpected kind of APValue for covariant return");
4794 if (Result.isNullPointer())
4798 LVal.setFrom(Info.Ctx, Result);
4800 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4801 for (unsigned I = 1; I != Path.size(); ++I) {
4802 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4803 assert(OldClass && NewClass && "unexpected kind of covariant return");
4804 if (OldClass != NewClass &&
4805 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4807 OldClass = NewClass;
4810 LVal.moveInto(Result);
4814 /// Determine whether \p Base, which is known to be a direct base class of
4815 /// \p Derived, is a public base class.
4816 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4817 const CXXRecordDecl *Base) {
4818 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4819 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4820 if (BaseClass && declaresSameEntity(BaseClass, Base))
4821 return BaseSpec.getAccessSpecifier() == AS_public;
4823 llvm_unreachable("Base is not a direct base of Derived");
4826 /// Apply the given dynamic cast operation on the provided lvalue.
4828 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4829 /// to find a suitable target subobject.
4830 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4832 // We can't do anything with a non-symbolic pointer value.
4833 SubobjectDesignator &D = Ptr.Designator;
4837 // C++ [expr.dynamic.cast]p6:
4838 // If v is a null pointer value, the result is a null pointer value.
4839 if (Ptr.isNullPointer() && !E->isGLValue())
4842 // For all the other cases, we need the pointer to point to an object within
4843 // its lifetime / period of construction / destruction, and we need to know
4844 // its dynamic type.
4845 Optional<DynamicType> DynType =
4846 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4850 // C++ [expr.dynamic.cast]p7:
4851 // If T is "pointer to cv void", then the result is a pointer to the most
4853 if (E->getType()->isVoidPointerType())
4854 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4856 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4857 assert(C && "dynamic_cast target is not void pointer nor class");
4858 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4860 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4861 // C++ [expr.dynamic.cast]p9:
4862 if (!E->isGLValue()) {
4863 // The value of a failed cast to pointer type is the null pointer value
4864 // of the required result type.
4865 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4866 Ptr.setNull(E->getType(), TargetVal);
4870 // A failed cast to reference type throws [...] std::bad_cast.
4872 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4873 DynType->Type->isDerivedFrom(C)))
4875 else if (!Paths || Paths->begin() == Paths->end())
4877 else if (Paths->isAmbiguous(CQT))
4880 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4883 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4884 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4885 << Info.Ctx.getRecordType(DynType->Type)
4886 << E->getType().getUnqualifiedType();
4890 // Runtime check, phase 1:
4891 // Walk from the base subobject towards the derived object looking for the
4893 for (int PathLength = Ptr.Designator.Entries.size();
4894 PathLength >= (int)DynType->PathLength; --PathLength) {
4895 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4896 if (declaresSameEntity(Class, C))
4897 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4898 // We can only walk across public inheritance edges.
4899 if (PathLength > (int)DynType->PathLength &&
4900 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4902 return RuntimeCheckFailed(nullptr);
4905 // Runtime check, phase 2:
4906 // Search the dynamic type for an unambiguous public base of type C.
4907 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4908 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4909 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4910 Paths.front().Access == AS_public) {
4911 // Downcast to the dynamic type...
4912 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4914 // ... then upcast to the chosen base class subobject.
4915 for (CXXBasePathElement &Elem : Paths.front())
4916 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4921 // Otherwise, the runtime check fails.
4922 return RuntimeCheckFailed(&Paths);
4926 struct StartLifetimeOfUnionMemberHandler {
4927 const FieldDecl *Field;
4929 static const AccessKinds AccessKind = AK_Assign;
4931 APValue getDefaultInitValue(QualType SubobjType) {
4932 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4934 return APValue((const FieldDecl*)nullptr);
4936 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4937 std::distance(RD->field_begin(), RD->field_end()));
4940 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4941 End = RD->bases_end(); I != End; ++I, ++Index)
4942 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4944 for (const auto *I : RD->fields()) {
4945 if (I->isUnnamedBitfield())
4947 Struct.getStructField(I->getFieldIndex()) =
4948 getDefaultInitValue(I->getType());
4953 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4954 SubobjType->getAsArrayTypeUnsafe())) {
4955 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4956 if (Array.hasArrayFiller())
4957 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4961 return APValue::IndeterminateValue();
4964 typedef bool result_type;
4965 bool failed() { return false; }
4966 bool found(APValue &Subobj, QualType SubobjType) {
4967 // We are supposed to perform no initialization but begin the lifetime of
4968 // the object. We interpret that as meaning to do what default
4969 // initialization of the object would do if all constructors involved were
4971 // * All base, non-variant member, and array element subobjects' lifetimes
4973 // * No variant members' lifetimes begin
4974 // * All scalar subobjects whose lifetimes begin have indeterminate values
4975 assert(SubobjType->isUnionType());
4976 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4977 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4980 bool found(APSInt &Value, QualType SubobjType) {
4981 llvm_unreachable("wrong value kind for union object");
4983 bool found(APFloat &Value, QualType SubobjType) {
4984 llvm_unreachable("wrong value kind for union object");
4987 } // end anonymous namespace
4989 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4991 /// Handle a builtin simple-assignment or a call to a trivial assignment
4992 /// operator whose left-hand side might involve a union member access. If it
4993 /// does, implicitly start the lifetime of any accessed union elements per
4994 /// C++20 [class.union]5.
4995 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4996 const LValue &LHS) {
4997 if (LHS.InvalidBase || LHS.Designator.Invalid)
5000 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5001 // C++ [class.union]p5:
5002 // define the set S(E) of subexpressions of E as follows:
5003 unsigned PathLength = LHS.Designator.Entries.size();
5004 for (const Expr *E = LHSExpr; E != nullptr;) {
5005 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
5006 if (auto *ME = dyn_cast<MemberExpr>(E)) {
5007 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5011 // ... and also contains A.B if B names a union member
5012 if (FD->getParent()->isUnion())
5013 UnionPathLengths.push_back({PathLength - 1, FD});
5017 assert(declaresSameEntity(FD,
5018 LHS.Designator.Entries[PathLength]
5019 .getAsBaseOrMember().getPointer()));
5021 // -- If E is of the form A[B] and is interpreted as a built-in array
5022 // subscripting operator, S(E) is [S(the array operand, if any)].
5023 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5024 // Step over an ArrayToPointerDecay implicit cast.
5025 auto *Base = ASE->getBase()->IgnoreImplicit();
5026 if (!Base->getType()->isArrayType())
5032 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5033 // Step over a derived-to-base conversion.
5034 E = ICE->getSubExpr();
5035 if (ICE->getCastKind() == CK_NoOp)
5037 if (ICE->getCastKind() != CK_DerivedToBase &&
5038 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5040 // Walk path backwards as we walk up from the base to the derived class.
5041 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5044 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5045 LHS.Designator.Entries[PathLength]
5046 .getAsBaseOrMember().getPointer()));
5049 // -- Otherwise, S(E) is empty.
5055 // Common case: no unions' lifetimes are started.
5056 if (UnionPathLengths.empty())
5059 // if modification of X [would access an inactive union member], an object
5060 // of the type of X is implicitly created
5061 CompleteObject Obj =
5062 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5065 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5066 llvm::reverse(UnionPathLengths)) {
5067 // Form a designator for the union object.
5068 SubobjectDesignator D = LHS.Designator;
5069 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5071 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5072 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5079 /// Determine if a class has any fields that might need to be copied by a
5080 /// trivial copy or move operation.
5081 static bool hasFields(const CXXRecordDecl *RD) {
5082 if (!RD || RD->isEmpty())
5084 for (auto *FD : RD->fields()) {
5085 if (FD->isUnnamedBitfield())
5089 for (auto &Base : RD->bases())
5090 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5096 typedef SmallVector<APValue, 8> ArgVector;
5099 /// EvaluateArgs - Evaluate the arguments to a function call.
5100 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5101 EvalInfo &Info, const FunctionDecl *Callee) {
5102 bool Success = true;
5103 llvm::SmallBitVector ForbiddenNullArgs;
5104 if (Callee->hasAttr<NonNullAttr>()) {
5105 ForbiddenNullArgs.resize(Args.size());
5106 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5107 if (!Attr->args_size()) {
5108 ForbiddenNullArgs.set();
5111 for (auto Idx : Attr->args()) {
5112 unsigned ASTIdx = Idx.getASTIndex();
5113 if (ASTIdx >= Args.size())
5115 ForbiddenNullArgs[ASTIdx] = 1;
5119 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
5121 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5122 // If we're checking for a potential constant expression, evaluate all
5123 // initializers even if some of them fail.
5124 if (!Info.noteFailure())
5127 } else if (!ForbiddenNullArgs.empty() &&
5128 ForbiddenNullArgs[I - Args.begin()] &&
5129 ArgValues[I - Args.begin()].isNullPointer()) {
5130 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5131 if (!Info.noteFailure())
5139 /// Evaluate a function call.
5140 static bool HandleFunctionCall(SourceLocation CallLoc,
5141 const FunctionDecl *Callee, const LValue *This,
5142 ArrayRef<const Expr*> Args, const Stmt *Body,
5143 EvalInfo &Info, APValue &Result,
5144 const LValue *ResultSlot) {
5145 ArgVector ArgValues(Args.size());
5146 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5149 if (!Info.CheckCallLimit(CallLoc))
5152 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5154 // For a trivial copy or move assignment, perform an APValue copy. This is
5155 // essential for unions, where the operations performed by the assignment
5156 // operator cannot be represented as statements.
5158 // Skip this for non-union classes with no fields; in that case, the defaulted
5159 // copy/move does not actually read the object.
5160 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5161 if (MD && MD->isDefaulted() &&
5162 (MD->getParent()->isUnion() ||
5163 (MD->isTrivial() && hasFields(MD->getParent())))) {
5165 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5167 RHS.setFrom(Info.Ctx, ArgValues[0]);
5169 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5172 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5173 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5175 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5178 This->moveInto(Result);
5180 } else if (MD && isLambdaCallOperator(MD)) {
5181 // We're in a lambda; determine the lambda capture field maps unless we're
5182 // just constexpr checking a lambda's call operator. constexpr checking is
5183 // done before the captures have been added to the closure object (unless
5184 // we're inferring constexpr-ness), so we don't have access to them in this
5185 // case. But since we don't need the captures to constexpr check, we can
5186 // just ignore them.
5187 if (!Info.checkingPotentialConstantExpression())
5188 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5189 Frame.LambdaThisCaptureField);
5192 StmtResult Ret = {Result, ResultSlot};
5193 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5194 if (ESR == ESR_Succeeded) {
5195 if (Callee->getReturnType()->isVoidType())
5197 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5199 return ESR == ESR_Returned;
5202 /// Evaluate a constructor call.
5203 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5205 const CXXConstructorDecl *Definition,
5206 EvalInfo &Info, APValue &Result) {
5207 SourceLocation CallLoc = E->getExprLoc();
5208 if (!Info.CheckCallLimit(CallLoc))
5211 const CXXRecordDecl *RD = Definition->getParent();
5212 if (RD->getNumVBases()) {
5213 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5217 EvalInfo::EvaluatingConstructorRAII EvalObj(
5219 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5221 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5223 // FIXME: Creating an APValue just to hold a nonexistent return value is
5226 StmtResult Ret = {RetVal, nullptr};
5228 // If it's a delegating constructor, delegate.
5229 if (Definition->isDelegatingConstructor()) {
5230 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5232 FullExpressionRAII InitScope(Info);
5233 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5236 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5239 // For a trivial copy or move constructor, perform an APValue copy. This is
5240 // essential for unions (or classes with anonymous union members), where the
5241 // operations performed by the constructor cannot be represented by
5242 // ctor-initializers.
5244 // Skip this for empty non-union classes; we should not perform an
5245 // lvalue-to-rvalue conversion on them because their copy constructor does not
5246 // actually read them.
5247 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5248 (Definition->getParent()->isUnion() ||
5249 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5251 RHS.setFrom(Info.Ctx, ArgValues[0]);
5252 return handleLValueToRValueConversion(
5253 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5257 // Reserve space for the struct members.
5258 if (!RD->isUnion() && !Result.hasValue())
5259 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5260 std::distance(RD->field_begin(), RD->field_end()));
5262 if (RD->isInvalidDecl()) return false;
5263 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5265 // A scope for temporaries lifetime-extended by reference members.
5266 BlockScopeRAII LifetimeExtendedScope(Info);
5268 bool Success = true;
5269 unsigned BasesSeen = 0;
5271 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5273 for (const auto *I : Definition->inits()) {
5274 LValue Subobject = This;
5275 LValue SubobjectParent = This;
5276 APValue *Value = &Result;
5278 // Determine the subobject to initialize.
5279 FieldDecl *FD = nullptr;
5280 if (I->isBaseInitializer()) {
5281 QualType BaseType(I->getBaseClass(), 0);
5283 // Non-virtual base classes are initialized in the order in the class
5284 // definition. We have already checked for virtual base classes.
5285 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5286 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5287 "base class initializers not in expected order");
5290 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5291 BaseType->getAsCXXRecordDecl(), &Layout))
5293 Value = &Result.getStructBase(BasesSeen++);
5294 } else if ((FD = I->getMember())) {
5295 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5297 if (RD->isUnion()) {
5298 Result = APValue(FD);
5299 Value = &Result.getUnionValue();
5301 Value = &Result.getStructField(FD->getFieldIndex());
5303 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5304 // Walk the indirect field decl's chain to find the object to initialize,
5305 // and make sure we've initialized every step along it.
5306 auto IndirectFieldChain = IFD->chain();
5307 for (auto *C : IndirectFieldChain) {
5308 FD = cast<FieldDecl>(C);
5309 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5310 // Switch the union field if it differs. This happens if we had
5311 // preceding zero-initialization, and we're now initializing a union
5312 // subobject other than the first.
5313 // FIXME: In this case, the values of the other subobjects are
5314 // specified, since zero-initialization sets all padding bits to zero.
5315 if (!Value->hasValue() ||
5316 (Value->isUnion() && Value->getUnionField() != FD)) {
5318 *Value = APValue(FD);
5320 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5321 std::distance(CD->field_begin(), CD->field_end()));
5323 // Store Subobject as its parent before updating it for the last element
5325 if (C == IndirectFieldChain.back())
5326 SubobjectParent = Subobject;
5327 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5330 Value = &Value->getUnionValue();
5332 Value = &Value->getStructField(FD->getFieldIndex());
5335 llvm_unreachable("unknown base initializer kind");
5338 // Need to override This for implicit field initializers as in this case
5339 // This refers to innermost anonymous struct/union containing initializer,
5340 // not to currently constructed class.
5341 const Expr *Init = I->getInit();
5342 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5343 isa<CXXDefaultInitExpr>(Init));
5344 FullExpressionRAII InitScope(Info);
5345 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5346 (FD && FD->isBitField() &&
5347 !truncateBitfieldValue(Info, Init, *Value, FD))) {
5348 // If we're checking for a potential constant expression, evaluate all
5349 // initializers even if some of them fail.
5350 if (!Info.noteFailure())
5355 // This is the point at which the dynamic type of the object becomes this
5357 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5358 EvalObj.finishedConstructingBases();
5362 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5365 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5366 ArrayRef<const Expr*> Args,
5367 const CXXConstructorDecl *Definition,
5368 EvalInfo &Info, APValue &Result) {
5369 ArgVector ArgValues(Args.size());
5370 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5373 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5377 //===----------------------------------------------------------------------===//
5378 // Generic Evaluation
5379 //===----------------------------------------------------------------------===//
5382 class BitCastBuffer {
5383 // FIXME: We're going to need bit-level granularity when we support
5385 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5386 // we don't support a host or target where that is the case. Still, we should
5387 // use a more generic type in case we ever do.
5388 SmallVector<Optional<unsigned char>, 32> Bytes;
5390 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5391 "Need at least 8 bit unsigned char");
5393 bool TargetIsLittleEndian;
5396 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5397 : Bytes(Width.getQuantity()),
5398 TargetIsLittleEndian(TargetIsLittleEndian) {}
5401 bool readObject(CharUnits Offset, CharUnits Width,
5402 SmallVectorImpl<unsigned char> &Output) const {
5403 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5404 // If a byte of an integer is uninitialized, then the whole integer is
5406 if (!Bytes[I.getQuantity()])
5408 Output.push_back(*Bytes[I.getQuantity()]);
5410 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5411 std::reverse(Output.begin(), Output.end());
5415 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5416 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5417 std::reverse(Input.begin(), Input.end());
5420 for (unsigned char Byte : Input) {
5421 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5422 Bytes[Offset.getQuantity() + Index] = Byte;
5427 size_t size() { return Bytes.size(); }
5430 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5431 /// target would represent the value at runtime.
5432 class APValueToBufferConverter {
5434 BitCastBuffer Buffer;
5435 const CastExpr *BCE;
5437 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5438 const CastExpr *BCE)
5440 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5443 bool visit(const APValue &Val, QualType Ty) {
5444 return visit(Val, Ty, CharUnits::fromQuantity(0));
5447 // Write out Val with type Ty into Buffer starting at Offset.
5448 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5449 assert((size_t)Offset.getQuantity() <= Buffer.size());
5451 // As a special case, nullptr_t has an indeterminate value.
5452 if (Ty->isNullPtrType())
5455 // Dig through Src to find the byte at SrcOffset.
5456 switch (Val.getKind()) {
5457 case APValue::Indeterminate:
5462 return visitInt(Val.getInt(), Ty, Offset);
5463 case APValue::Float:
5464 return visitFloat(Val.getFloat(), Ty, Offset);
5465 case APValue::Array:
5466 return visitArray(Val, Ty, Offset);
5467 case APValue::Struct:
5468 return visitRecord(Val, Ty, Offset);
5470 case APValue::ComplexInt:
5471 case APValue::ComplexFloat:
5472 case APValue::Vector:
5473 case APValue::FixedPoint:
5474 // FIXME: We should support these.
5476 case APValue::Union:
5477 case APValue::MemberPointer:
5478 case APValue::AddrLabelDiff: {
5479 Info.FFDiag(BCE->getBeginLoc(),
5480 diag::note_constexpr_bit_cast_unsupported_type)
5485 case APValue::LValue:
5486 llvm_unreachable("LValue subobject in bit_cast?");
5488 llvm_unreachable("Unhandled APValue::ValueKind");
5491 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5492 const RecordDecl *RD = Ty->getAsRecordDecl();
5493 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5495 // Visit the base classes.
5496 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5497 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5498 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5499 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5501 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5502 Layout.getBaseClassOffset(BaseDecl) + Offset))
5507 // Visit the fields.
5508 unsigned FieldIdx = 0;
5509 for (FieldDecl *FD : RD->fields()) {
5510 if (FD->isBitField()) {
5511 Info.FFDiag(BCE->getBeginLoc(),
5512 diag::note_constexpr_bit_cast_unsupported_bitfield);
5516 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5518 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5519 "only bit-fields can have sub-char alignment");
5520 CharUnits FieldOffset =
5521 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5522 QualType FieldTy = FD->getType();
5523 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5531 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5533 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5537 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5538 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5539 unsigned ArraySize = Val.getArraySize();
5540 // First, initialize the initialized elements.
5541 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5542 const APValue &SubObj = Val.getArrayInitializedElt(I);
5543 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5547 // Next, initialize the rest of the array using the filler.
5548 if (Val.hasArrayFiller()) {
5549 const APValue &Filler = Val.getArrayFiller();
5550 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5551 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5559 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5560 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5561 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5562 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5563 Buffer.writeObject(Offset, Bytes);
5567 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5568 APSInt AsInt(Val.bitcastToAPInt());
5569 return visitInt(AsInt, Ty, Offset);
5573 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5574 const CastExpr *BCE) {
5575 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5576 APValueToBufferConverter Converter(Info, DstSize, BCE);
5577 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5579 return Converter.Buffer;
5583 /// Write an BitCastBuffer into an APValue.
5584 class BufferToAPValueConverter {
5586 const BitCastBuffer &Buffer;
5587 const CastExpr *BCE;
5589 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5590 const CastExpr *BCE)
5591 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5593 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5594 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5595 // Ideally this will be unreachable.
5596 llvm::NoneType unsupportedType(QualType Ty) {
5597 Info.FFDiag(BCE->getBeginLoc(),
5598 diag::note_constexpr_bit_cast_unsupported_type)
5603 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5604 const EnumType *EnumSugar = nullptr) {
5605 if (T->isNullPtrType()) {
5606 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5607 return APValue((Expr *)nullptr,
5608 /*Offset=*/CharUnits::fromQuantity(NullValue),
5609 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5612 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5613 SmallVector<uint8_t, 8> Bytes;
5614 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5615 // If this is std::byte or unsigned char, then its okay to store an
5616 // indeterminate value.
5617 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5619 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5620 T->isSpecificBuiltinType(BuiltinType::Char_U));
5621 if (!IsStdByte && !IsUChar) {
5622 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
5623 Info.FFDiag(BCE->getExprLoc(),
5624 diag::note_constexpr_bit_cast_indet_dest)
5625 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5629 return APValue::IndeterminateValue();
5632 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5633 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5635 if (T->isIntegralOrEnumerationType()) {
5636 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5637 return APValue(Val);
5640 if (T->isRealFloatingType()) {
5641 const llvm::fltSemantics &Semantics =
5642 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5643 return APValue(APFloat(Semantics, Val));
5646 return unsupportedType(QualType(T, 0));
5649 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5650 const RecordDecl *RD = RTy->getAsRecordDecl();
5651 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5653 unsigned NumBases = 0;
5654 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5655 NumBases = CXXRD->getNumBases();
5657 APValue ResultVal(APValue::UninitStruct(), NumBases,
5658 std::distance(RD->field_begin(), RD->field_end()));
5660 // Visit the base classes.
5661 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5662 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5663 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5664 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5665 if (BaseDecl->isEmpty() ||
5666 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5669 Optional<APValue> SubObj = visitType(
5670 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5673 ResultVal.getStructBase(I) = *SubObj;
5677 // Visit the fields.
5678 unsigned FieldIdx = 0;
5679 for (FieldDecl *FD : RD->fields()) {
5680 // FIXME: We don't currently support bit-fields. A lot of the logic for
5681 // this is in CodeGen, so we need to factor it around.
5682 if (FD->isBitField()) {
5683 Info.FFDiag(BCE->getBeginLoc(),
5684 diag::note_constexpr_bit_cast_unsupported_bitfield);
5688 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5689 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5691 CharUnits FieldOffset =
5692 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5694 QualType FieldTy = FD->getType();
5695 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5698 ResultVal.getStructField(FieldIdx) = *SubObj;
5705 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5706 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5707 assert(!RepresentationType.isNull() &&
5708 "enum forward decl should be caught by Sema");
5709 const BuiltinType *AsBuiltin =
5710 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5711 assert(AsBuiltin && "non-integral enum underlying type?");
5712 // Recurse into the underlying type. Treat std::byte transparently as
5714 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5717 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5718 size_t Size = Ty->getSize().getLimitedValue();
5719 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5721 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5722 for (size_t I = 0; I != Size; ++I) {
5723 Optional<APValue> ElementValue =
5724 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5727 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5733 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5734 return unsupportedType(QualType(Ty, 0));
5737 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5738 QualType Can = Ty.getCanonicalType();
5740 switch (Can->getTypeClass()) {
5741 #define TYPE(Class, Base) \
5743 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5744 #define ABSTRACT_TYPE(Class, Base)
5745 #define NON_CANONICAL_TYPE(Class, Base) \
5747 llvm_unreachable("non-canonical type should be impossible!");
5748 #define DEPENDENT_TYPE(Class, Base) \
5751 "dependent types aren't supported in the constant evaluator!");
5752 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5754 llvm_unreachable("either dependent or not canonical!");
5755 #include "clang/AST/TypeNodes.def"
5757 llvm_unreachable("Unhandled Type::TypeClass");
5761 // Pull out a full value of type DstType.
5762 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5763 const CastExpr *BCE) {
5764 BufferToAPValueConverter Converter(Info, Buffer, BCE);
5765 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5769 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5770 QualType Ty, EvalInfo *Info,
5771 const ASTContext &Ctx,
5772 bool CheckingDest) {
5773 Ty = Ty.getCanonicalType();
5775 auto diag = [&](int Reason) {
5777 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5778 << CheckingDest << (Reason == 4) << Reason;
5781 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5783 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5784 << NoteTy << Construct << Ty;
5788 if (Ty->isUnionType())
5790 if (Ty->isPointerType())
5792 if (Ty->isMemberPointerType())
5794 if (Ty.isVolatileQualified())
5797 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5798 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5799 for (CXXBaseSpecifier &BS : CXXRD->bases())
5800 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5802 return note(1, BS.getType(), BS.getBeginLoc());
5804 for (FieldDecl *FD : Record->fields()) {
5805 if (FD->getType()->isReferenceType())
5807 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5809 return note(0, FD->getType(), FD->getBeginLoc());
5813 if (Ty->isArrayType() &&
5814 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5815 Info, Ctx, CheckingDest))
5821 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5822 const ASTContext &Ctx,
5823 const CastExpr *BCE) {
5824 bool DestOK = checkBitCastConstexprEligibilityType(
5825 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5826 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5828 BCE->getSubExpr()->getType(), Info, Ctx, false);
5832 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5833 APValue &SourceValue,
5834 const CastExpr *BCE) {
5835 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5836 "no host or target supports non 8-bit chars");
5837 assert(SourceValue.isLValue() &&
5838 "LValueToRValueBitcast requires an lvalue operand!");
5840 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5843 LValue SourceLValue;
5844 APValue SourceRValue;
5845 SourceLValue.setFrom(Info.Ctx, SourceValue);
5846 if (!handleLValueToRValueConversion(Info, BCE,
5847 BCE->getSubExpr()->getType().withConst(),
5848 SourceLValue, SourceRValue))
5851 // Read out SourceValue into a char buffer.
5852 Optional<BitCastBuffer> Buffer =
5853 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5857 // Write out the buffer into a new APValue.
5858 Optional<APValue> MaybeDestValue =
5859 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5860 if (!MaybeDestValue)
5863 DestValue = std::move(*MaybeDestValue);
5867 template <class Derived>
5868 class ExprEvaluatorBase
5869 : public ConstStmtVisitor<Derived, bool> {
5871 Derived &getDerived() { return static_cast<Derived&>(*this); }
5872 bool DerivedSuccess(const APValue &V, const Expr *E) {
5873 return getDerived().Success(V, E);
5875 bool DerivedZeroInitialization(const Expr *E) {
5876 return getDerived().ZeroInitialization(E);
5879 // Check whether a conditional operator with a non-constant condition is a
5880 // potential constant expression. If neither arm is a potential constant
5881 // expression, then the conditional operator is not either.
5882 template<typename ConditionalOperator>
5883 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5884 assert(Info.checkingPotentialConstantExpression());
5886 // Speculatively evaluate both arms.
5887 SmallVector<PartialDiagnosticAt, 8> Diag;
5889 SpeculativeEvaluationRAII Speculate(Info, &Diag);
5890 StmtVisitorTy::Visit(E->getFalseExpr());
5896 SpeculativeEvaluationRAII Speculate(Info, &Diag);
5898 StmtVisitorTy::Visit(E->getTrueExpr());
5903 Error(E, diag::note_constexpr_conditional_never_const);
5907 template<typename ConditionalOperator>
5908 bool HandleConditionalOperator(const ConditionalOperator *E) {
5910 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5911 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5912 CheckPotentialConstantConditional(E);
5915 if (Info.noteFailure()) {
5916 StmtVisitorTy::Visit(E->getTrueExpr());
5917 StmtVisitorTy::Visit(E->getFalseExpr());
5922 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5923 return StmtVisitorTy::Visit(EvalExpr);
5928 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5929 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5931 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5932 return Info.CCEDiag(E, D);
5935 bool ZeroInitialization(const Expr *E) { return Error(E); }
5938 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5940 EvalInfo &getEvalInfo() { return Info; }
5942 /// Report an evaluation error. This should only be called when an error is
5943 /// first discovered. When propagating an error, just return false.
5944 bool Error(const Expr *E, diag::kind D) {
5948 bool Error(const Expr *E) {
5949 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5952 bool VisitStmt(const Stmt *) {
5953 llvm_unreachable("Expression evaluator should not be called on stmts");
5955 bool VisitExpr(const Expr *E) {
5959 bool VisitConstantExpr(const ConstantExpr *E)
5960 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5961 bool VisitParenExpr(const ParenExpr *E)
5962 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5963 bool VisitUnaryExtension(const UnaryOperator *E)
5964 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5965 bool VisitUnaryPlus(const UnaryOperator *E)
5966 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5967 bool VisitChooseExpr(const ChooseExpr *E)
5968 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5969 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5970 { return StmtVisitorTy::Visit(E->getResultExpr()); }
5971 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5972 { return StmtVisitorTy::Visit(E->getReplacement()); }
5973 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5974 TempVersionRAII RAII(*Info.CurrentCall);
5975 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5976 return StmtVisitorTy::Visit(E->getExpr());
5978 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5979 TempVersionRAII RAII(*Info.CurrentCall);
5980 // The initializer may not have been parsed yet, or might be erroneous.
5983 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5984 return StmtVisitorTy::Visit(E->getExpr());
5987 // We cannot create any objects for which cleanups are required, so there is
5988 // nothing to do here; all cleanups must come from unevaluated subexpressions.
5989 bool VisitExprWithCleanups(const ExprWithCleanups *E)
5990 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5992 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5993 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5994 return static_cast<Derived*>(this)->VisitCastExpr(E);
5996 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5997 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5998 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5999 return static_cast<Derived*>(this)->VisitCastExpr(E);
6001 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6002 return static_cast<Derived*>(this)->VisitCastExpr(E);
6005 bool VisitBinaryOperator(const BinaryOperator *E) {
6006 switch (E->getOpcode()) {
6011 VisitIgnoredValue(E->getLHS());
6012 return StmtVisitorTy::Visit(E->getRHS());
6017 if (!HandleMemberPointerAccess(Info, E, Obj))
6020 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6022 return DerivedSuccess(Result, E);
6027 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6028 // Evaluate and cache the common expression. We treat it as a temporary,
6029 // even though it's not quite the same thing.
6030 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
6031 Info, E->getCommon()))
6034 return HandleConditionalOperator(E);
6037 bool VisitConditionalOperator(const ConditionalOperator *E) {
6038 bool IsBcpCall = false;
6039 // If the condition (ignoring parens) is a __builtin_constant_p call,
6040 // the result is a constant expression if it can be folded without
6041 // side-effects. This is an important GNU extension. See GCC PR38377
6043 if (const CallExpr *CallCE =
6044 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6045 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6048 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6049 // constant expression; we can't check whether it's potentially foldable.
6050 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6053 FoldConstant Fold(Info, IsBcpCall);
6054 if (!HandleConditionalOperator(E)) {
6055 Fold.keepDiagnostics();
6062 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6063 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6064 return DerivedSuccess(*Value, E);
6066 const Expr *Source = E->getSourceExpr();
6069 if (Source == E) { // sanity checking.
6070 assert(0 && "OpaqueValueExpr recursively refers to itself");
6073 return StmtVisitorTy::Visit(Source);
6076 bool VisitCallExpr(const CallExpr *E) {
6078 if (!handleCallExpr(E, Result, nullptr))
6080 return DerivedSuccess(Result, E);
6083 bool handleCallExpr(const CallExpr *E, APValue &Result,
6084 const LValue *ResultSlot) {
6085 const Expr *Callee = E->getCallee()->IgnoreParens();
6086 QualType CalleeType = Callee->getType();
6088 const FunctionDecl *FD = nullptr;
6089 LValue *This = nullptr, ThisVal;
6090 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6091 bool HasQualifier = false;
6093 // Extract function decl and 'this' pointer from the callee.
6094 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6095 const CXXMethodDecl *Member = nullptr;
6096 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6097 // Explicit bound member calls, such as x.f() or p->g();
6098 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6100 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6102 return Error(Callee);
6104 HasQualifier = ME->hasQualifier();
6105 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6106 // Indirect bound member calls ('.*' or '->*').
6107 Member = dyn_cast_or_null<CXXMethodDecl>(
6108 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6110 return Error(Callee);
6113 return Error(Callee);
6115 } else if (CalleeType->isFunctionPointerType()) {
6117 if (!EvaluatePointer(Callee, Call, Info))
6120 if (!Call.getLValueOffset().isZero())
6121 return Error(Callee);
6122 FD = dyn_cast_or_null<FunctionDecl>(
6123 Call.getLValueBase().dyn_cast<const ValueDecl*>());
6125 return Error(Callee);
6126 // Don't call function pointers which have been cast to some other type.
6127 // Per DR (no number yet), the caller and callee can differ in noexcept.
6128 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6129 CalleeType->getPointeeType(), FD->getType())) {
6133 // Overloaded operator calls to member functions are represented as normal
6134 // calls with '*this' as the first argument.
6135 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6136 if (MD && !MD->isStatic()) {
6137 // FIXME: When selecting an implicit conversion for an overloaded
6138 // operator delete, we sometimes try to evaluate calls to conversion
6139 // operators without a 'this' parameter!
6143 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6146 Args = Args.slice(1);
6147 } else if (MD && MD->isLambdaStaticInvoker()) {
6148 // Map the static invoker for the lambda back to the call operator.
6149 // Conveniently, we don't have to slice out the 'this' argument (as is
6150 // being done for the non-static case), since a static member function
6151 // doesn't have an implicit argument passed in.
6152 const CXXRecordDecl *ClosureClass = MD->getParent();
6154 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6155 "Number of captures must be zero for conversion to function-ptr");
6157 const CXXMethodDecl *LambdaCallOp =
6158 ClosureClass->getLambdaCallOperator();
6160 // Set 'FD', the function that will be called below, to the call
6161 // operator. If the closure object represents a generic lambda, find
6162 // the corresponding specialization of the call operator.
6164 if (ClosureClass->isGenericLambda()) {
6165 assert(MD->isFunctionTemplateSpecialization() &&
6166 "A generic lambda's static-invoker function must be a "
6167 "template specialization");
6168 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6169 FunctionTemplateDecl *CallOpTemplate =
6170 LambdaCallOp->getDescribedFunctionTemplate();
6171 void *InsertPos = nullptr;
6172 FunctionDecl *CorrespondingCallOpSpecialization =
6173 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6174 assert(CorrespondingCallOpSpecialization &&
6175 "We must always have a function call operator specialization "
6176 "that corresponds to our static invoker specialization");
6177 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6184 SmallVector<QualType, 4> CovariantAdjustmentPath;
6186 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
6187 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6188 // Perform virtual dispatch, if necessary.
6189 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6190 CovariantAdjustmentPath);
6194 // Check that the 'this' pointer points to an object of the right type.
6195 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6200 const FunctionDecl *Definition = nullptr;
6201 Stmt *Body = FD->getBody(Definition);
6203 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6204 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
6205 Result, ResultSlot))
6208 if (!CovariantAdjustmentPath.empty() &&
6209 !HandleCovariantReturnAdjustment(Info, E, Result,
6210 CovariantAdjustmentPath))
6216 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6217 return StmtVisitorTy::Visit(E->getInitializer());
6219 bool VisitInitListExpr(const InitListExpr *E) {
6220 if (E->getNumInits() == 0)
6221 return DerivedZeroInitialization(E);
6222 if (E->getNumInits() == 1)
6223 return StmtVisitorTy::Visit(E->getInit(0));
6226 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
6227 return DerivedZeroInitialization(E);
6229 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
6230 return DerivedZeroInitialization(E);
6232 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
6233 return DerivedZeroInitialization(E);
6236 /// A member expression where the object is a prvalue is itself a prvalue.
6237 bool VisitMemberExpr(const MemberExpr *E) {
6238 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6239 "missing temporary materialization conversion");
6240 assert(!E->isArrow() && "missing call to bound member function?");
6243 if (!Evaluate(Val, Info, E->getBase()))
6246 QualType BaseTy = E->getBase()->getType();
6248 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
6249 if (!FD) return Error(E);
6250 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
6251 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6252 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6254 // Note: there is no lvalue base here. But this case should only ever
6255 // happen in C or in C++98, where we cannot be evaluating a constexpr
6256 // constructor, which is the only case the base matters.
6257 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
6258 SubobjectDesignator Designator(BaseTy);
6259 Designator.addDeclUnchecked(FD);
6262 return extractSubobject(Info, E, Obj, Designator, Result) &&
6263 DerivedSuccess(Result, E);
6266 bool VisitCastExpr(const CastExpr *E) {
6267 switch (E->getCastKind()) {
6271 case CK_AtomicToNonAtomic: {
6273 // This does not need to be done in place even for class/array types:
6274 // atomic-to-non-atomic conversion implies copying the object
6276 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
6278 return DerivedSuccess(AtomicVal, E);
6282 case CK_UserDefinedConversion:
6283 return StmtVisitorTy::Visit(E->getSubExpr());
6285 case CK_LValueToRValue: {
6287 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6290 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6291 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6294 return DerivedSuccess(RVal, E);
6296 case CK_LValueToRValueBitCast: {
6297 APValue DestValue, SourceValue;
6298 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6300 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6302 return DerivedSuccess(DestValue, E);
6309 bool VisitUnaryPostInc(const UnaryOperator *UO) {
6310 return VisitUnaryPostIncDec(UO);
6312 bool VisitUnaryPostDec(const UnaryOperator *UO) {
6313 return VisitUnaryPostIncDec(UO);
6315 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
6316 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6320 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6323 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6324 UO->isIncrementOp(), &RVal))
6326 return DerivedSuccess(RVal, UO);
6329 bool VisitStmtExpr(const StmtExpr *E) {
6330 // We will have checked the full-expressions inside the statement expression
6331 // when they were completed, and don't need to check them again now.
6332 if (Info.checkingForOverflow())
6335 BlockScopeRAII Scope(Info);
6336 const CompoundStmt *CS = E->getSubStmt();
6337 if (CS->body_empty())
6340 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6341 BE = CS->body_end();
6344 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6346 Info.FFDiag((*BI)->getBeginLoc(),
6347 diag::note_constexpr_stmt_expr_unsupported);
6350 return this->Visit(FinalExpr);
6353 APValue ReturnValue;
6354 StmtResult Result = { ReturnValue, nullptr };
6355 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
6356 if (ESR != ESR_Succeeded) {
6357 // FIXME: If the statement-expression terminated due to 'return',
6358 // 'break', or 'continue', it would be nice to propagate that to
6359 // the outer statement evaluation rather than bailing out.
6360 if (ESR != ESR_Failed)
6361 Info.FFDiag((*BI)->getBeginLoc(),
6362 diag::note_constexpr_stmt_expr_unsupported);
6367 llvm_unreachable("Return from function from the loop above.");
6370 /// Visit a value which is evaluated, but whose value is ignored.
6371 void VisitIgnoredValue(const Expr *E) {
6372 EvaluateIgnoredValue(Info, E);
6375 /// Potentially visit a MemberExpr's base expression.
6376 void VisitIgnoredBaseExpression(const Expr *E) {
6377 // While MSVC doesn't evaluate the base expression, it does diagnose the
6378 // presence of side-effecting behavior.
6379 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6381 VisitIgnoredValue(E);
6387 //===----------------------------------------------------------------------===//
6388 // Common base class for lvalue and temporary evaluation.
6389 //===----------------------------------------------------------------------===//
6391 template<class Derived>
6392 class LValueExprEvaluatorBase
6393 : public ExprEvaluatorBase<Derived> {
6397 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
6398 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
6400 bool Success(APValue::LValueBase B) {
6405 bool evaluatePointer(const Expr *E, LValue &Result) {
6406 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6410 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6411 : ExprEvaluatorBaseTy(Info), Result(Result),
6412 InvalidBaseOK(InvalidBaseOK) {}
6414 bool Success(const APValue &V, const Expr *E) {
6415 Result.setFrom(this->Info.Ctx, V);
6419 bool VisitMemberExpr(const MemberExpr *E) {
6420 // Handle non-static data members.
6424 EvalOK = evaluatePointer(E->getBase(), Result);
6425 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
6426 } else if (E->getBase()->isRValue()) {
6427 assert(E->getBase()->getType()->isRecordType());
6428 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
6429 BaseTy = E->getBase()->getType();
6431 EvalOK = this->Visit(E->getBase());
6432 BaseTy = E->getBase()->getType();
6437 Result.setInvalid(E);
6441 const ValueDecl *MD = E->getMemberDecl();
6442 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6443 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6444 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6446 if (!HandleLValueMember(this->Info, E, Result, FD))
6448 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
6449 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6452 return this->Error(E);
6454 if (MD->getType()->isReferenceType()) {
6456 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
6459 return Success(RefValue, E);
6464 bool VisitBinaryOperator(const BinaryOperator *E) {
6465 switch (E->getOpcode()) {
6467 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6471 return HandleMemberPointerAccess(this->Info, E, Result);
6475 bool VisitCastExpr(const CastExpr *E) {
6476 switch (E->getCastKind()) {
6478 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6480 case CK_DerivedToBase:
6481 case CK_UncheckedDerivedToBase:
6482 if (!this->Visit(E->getSubExpr()))
6485 // Now figure out the necessary offset to add to the base LV to get from
6486 // the derived class to the base class.
6487 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6494 //===----------------------------------------------------------------------===//
6495 // LValue Evaluation
6497 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6498 // function designators (in C), decl references to void objects (in C), and
6499 // temporaries (if building with -Wno-address-of-temporary).
6501 // LValue evaluation produces values comprising a base expression of one of the
6507 // * CompoundLiteralExpr in C (and in global scope in C++)
6510 // * ObjCStringLiteralExpr
6514 // * CallExpr for a MakeStringConstant builtin
6515 // - typeid(T) expressions, as TypeInfoLValues
6516 // - Locals and temporaries
6517 // * MaterializeTemporaryExpr
6518 // * Any Expr, with a CallIndex indicating the function in which the temporary
6519 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
6520 // from the AST (FIXME).
6521 // * A MaterializeTemporaryExpr that has static storage duration, with no
6522 // CallIndex, for a lifetime-extended temporary.
6523 // plus an offset in bytes.
6524 //===----------------------------------------------------------------------===//
6526 class LValueExprEvaluator
6527 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6529 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6530 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6532 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6533 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6535 bool VisitDeclRefExpr(const DeclRefExpr *E);
6536 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6537 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6538 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6539 bool VisitMemberExpr(const MemberExpr *E);
6540 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6541 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6542 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6543 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6544 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6545 bool VisitUnaryDeref(const UnaryOperator *E);
6546 bool VisitUnaryReal(const UnaryOperator *E);
6547 bool VisitUnaryImag(const UnaryOperator *E);
6548 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6549 return VisitUnaryPreIncDec(UO);
6551 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6552 return VisitUnaryPreIncDec(UO);
6554 bool VisitBinAssign(const BinaryOperator *BO);
6555 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6557 bool VisitCastExpr(const CastExpr *E) {
6558 switch (E->getCastKind()) {
6560 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6562 case CK_LValueBitCast:
6563 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6564 if (!Visit(E->getSubExpr()))
6566 Result.Designator.setInvalid();
6569 case CK_BaseToDerived:
6570 if (!Visit(E->getSubExpr()))
6572 return HandleBaseToDerivedCast(Info, E, Result);
6575 if (!Visit(E->getSubExpr()))
6577 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6581 } // end anonymous namespace
6583 /// Evaluate an expression as an lvalue. This can be legitimately called on
6584 /// expressions which are not glvalues, in three cases:
6585 /// * function designators in C, and
6586 /// * "extern void" objects
6587 /// * @selector() expressions in Objective-C
6588 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6589 bool InvalidBaseOK) {
6590 assert(E->isGLValue() || E->getType()->isFunctionType() ||
6591 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6592 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6595 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6596 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6598 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6599 return VisitVarDecl(E, VD);
6600 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6601 return Visit(BD->getBinding());
6606 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6608 // If we are within a lambda's call operator, check whether the 'VD' referred
6609 // to within 'E' actually represents a lambda-capture that maps to a
6610 // data-member/field within the closure object, and if so, evaluate to the
6611 // field or what the field refers to.
6612 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6613 isa<DeclRefExpr>(E) &&
6614 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6615 // We don't always have a complete capture-map when checking or inferring if
6616 // the function call operator meets the requirements of a constexpr function
6617 // - but we don't need to evaluate the captures to determine constexprness
6618 // (dcl.constexpr C++17).
6619 if (Info.checkingPotentialConstantExpression())
6622 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6623 // Start with 'Result' referring to the complete closure object...
6624 Result = *Info.CurrentCall->This;
6625 // ... then update it to refer to the field of the closure object
6626 // that represents the capture.
6627 if (!HandleLValueMember(Info, E, Result, FD))
6629 // And if the field is of reference type, update 'Result' to refer to what
6630 // the field refers to.
6631 if (FD->getType()->isReferenceType()) {
6633 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6636 Result.setFrom(Info.Ctx, RVal);
6641 CallStackFrame *Frame = nullptr;
6642 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6643 // Only if a local variable was declared in the function currently being
6644 // evaluated, do we expect to be able to find its value in the current
6645 // frame. (Otherwise it was likely declared in an enclosing context and
6646 // could either have a valid evaluatable value (for e.g. a constexpr
6647 // variable) or be ill-formed (and trigger an appropriate evaluation
6649 if (Info.CurrentCall->Callee &&
6650 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6651 Frame = Info.CurrentCall;
6655 if (!VD->getType()->isReferenceType()) {
6657 Result.set({VD, Frame->Index,
6658 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6665 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6667 if (!V->hasValue()) {
6668 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6669 // adjust the diagnostic to say that.
6670 if (!Info.checkingPotentialConstantExpression())
6671 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6674 return Success(*V, E);
6677 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6678 const MaterializeTemporaryExpr *E) {
6679 // Walk through the expression to find the materialized temporary itself.
6680 SmallVector<const Expr *, 2> CommaLHSs;
6681 SmallVector<SubobjectAdjustment, 2> Adjustments;
6682 const Expr *Inner = E->GetTemporaryExpr()->
6683 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6685 // If we passed any comma operators, evaluate their LHSs.
6686 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6687 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6690 // A materialized temporary with static storage duration can appear within the
6691 // result of a constant expression evaluation, so we need to preserve its
6692 // value for use outside this evaluation.
6694 if (E->getStorageDuration() == SD_Static) {
6695 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6699 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6703 QualType Type = Inner->getType();
6705 // Materialize the temporary itself.
6706 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6707 (E->getStorageDuration() == SD_Static &&
6708 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6713 // Adjust our lvalue to refer to the desired subobject.
6714 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6716 switch (Adjustments[I].Kind) {
6717 case SubobjectAdjustment::DerivedToBaseAdjustment:
6718 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6721 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6724 case SubobjectAdjustment::FieldAdjustment:
6725 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6727 Type = Adjustments[I].Field->getType();
6730 case SubobjectAdjustment::MemberPointerAdjustment:
6731 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6732 Adjustments[I].Ptr.RHS))
6734 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6743 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6744 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6745 "lvalue compound literal in c++?");
6746 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6747 // only see this when folding in C, so there's no standard to follow here.
6751 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6752 TypeInfoLValue TypeInfo;
6754 if (!E->isPotentiallyEvaluated()) {
6755 if (E->isTypeOperand())
6756 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6758 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6760 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6761 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6762 << E->getExprOperand()->getType()
6763 << E->getExprOperand()->getSourceRange();
6766 if (!Visit(E->getExprOperand()))
6769 Optional<DynamicType> DynType =
6770 ComputeDynamicType(Info, E, Result, AK_TypeId);
6775 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6778 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6781 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6785 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6786 // Handle static data members.
6787 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6788 VisitIgnoredBaseExpression(E->getBase());
6789 return VisitVarDecl(E, VD);
6792 // Handle static member functions.
6793 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6794 if (MD->isStatic()) {
6795 VisitIgnoredBaseExpression(E->getBase());
6800 // Handle non-static data members.
6801 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6804 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6805 // FIXME: Deal with vectors as array subscript bases.
6806 if (E->getBase()->getType()->isVectorType())
6809 bool Success = true;
6810 if (!evaluatePointer(E->getBase(), Result)) {
6811 if (!Info.noteFailure())
6817 if (!EvaluateInteger(E->getIdx(), Index, Info))
6821 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6824 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6825 return evaluatePointer(E->getSubExpr(), Result);
6828 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6829 if (!Visit(E->getSubExpr()))
6831 // __real is a no-op on scalar lvalues.
6832 if (E->getSubExpr()->getType()->isAnyComplexType())
6833 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6837 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6838 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6839 "lvalue __imag__ on scalar?");
6840 if (!Visit(E->getSubExpr()))
6842 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6846 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6847 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6850 if (!this->Visit(UO->getSubExpr()))
6853 return handleIncDec(
6854 this->Info, UO, Result, UO->getSubExpr()->getType(),
6855 UO->isIncrementOp(), nullptr);
6858 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6859 const CompoundAssignOperator *CAO) {
6860 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6865 // The overall lvalue result is the result of evaluating the LHS.
6866 if (!this->Visit(CAO->getLHS())) {
6867 if (Info.noteFailure())
6868 Evaluate(RHS, this->Info, CAO->getRHS());
6872 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6875 return handleCompoundAssignment(
6877 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6878 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6881 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6882 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6887 if (!this->Visit(E->getLHS())) {
6888 if (Info.noteFailure())
6889 Evaluate(NewVal, this->Info, E->getRHS());
6893 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6896 if (Info.getLangOpts().CPlusPlus2a &&
6897 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6900 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6904 //===----------------------------------------------------------------------===//
6905 // Pointer Evaluation
6906 //===----------------------------------------------------------------------===//
6908 /// Attempts to compute the number of bytes available at the pointer
6909 /// returned by a function with the alloc_size attribute. Returns true if we
6910 /// were successful. Places an unsigned number into `Result`.
6912 /// This expects the given CallExpr to be a call to a function with an
6913 /// alloc_size attribute.
6914 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6915 const CallExpr *Call,
6916 llvm::APInt &Result) {
6917 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6919 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6920 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6921 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6922 if (Call->getNumArgs() <= SizeArgNo)
6925 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6926 Expr::EvalResult ExprResult;
6927 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6929 Into = ExprResult.Val.getInt();
6930 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6932 Into = Into.zextOrSelf(BitsInSizeT);
6937 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6940 if (!AllocSize->getNumElemsParam().isValid()) {
6941 Result = std::move(SizeOfElem);
6945 APSInt NumberOfElems;
6946 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6947 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6951 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6955 Result = std::move(BytesAvailable);
6959 /// Convenience function. LVal's base must be a call to an alloc_size
6961 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6963 llvm::APInt &Result) {
6964 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6965 "Can't get the size of a non alloc_size function");
6966 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6967 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6968 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6971 /// Attempts to evaluate the given LValueBase as the result of a call to
6972 /// a function with the alloc_size attribute. If it was possible to do so, this
6973 /// function will return true, make Result's Base point to said function call,
6974 /// and mark Result's Base as invalid.
6975 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6980 // Because we do no form of static analysis, we only support const variables.
6982 // Additionally, we can't support parameters, nor can we support static
6983 // variables (in the latter case, use-before-assign isn't UB; in the former,
6984 // we have no clue what they'll be assigned to).
6986 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6987 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6990 const Expr *Init = VD->getAnyInitializer();
6994 const Expr *E = Init->IgnoreParens();
6995 if (!tryUnwrapAllocSizeCall(E))
6998 // Store E instead of E unwrapped so that the type of the LValue's base is
6999 // what the user wanted.
7000 Result.setInvalid(E);
7002 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7003 Result.addUnsizedArray(Info, E, Pointee);
7008 class PointerExprEvaluator
7009 : public ExprEvaluatorBase<PointerExprEvaluator> {
7013 bool Success(const Expr *E) {
7018 bool evaluateLValue(const Expr *E, LValue &Result) {
7019 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7022 bool evaluatePointer(const Expr *E, LValue &Result) {
7023 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7026 bool visitNonBuiltinCallExpr(const CallExpr *E);
7029 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7030 : ExprEvaluatorBaseTy(info), Result(Result),
7031 InvalidBaseOK(InvalidBaseOK) {}
7033 bool Success(const APValue &V, const Expr *E) {
7034 Result.setFrom(Info.Ctx, V);
7037 bool ZeroInitialization(const Expr *E) {
7038 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7039 Result.setNull(E->getType(), TargetVal);
7043 bool VisitBinaryOperator(const BinaryOperator *E);
7044 bool VisitCastExpr(const CastExpr* E);
7045 bool VisitUnaryAddrOf(const UnaryOperator *E);
7046 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7047 { return Success(E); }
7048 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7049 if (E->isExpressibleAsConstantInitializer())
7051 if (Info.noteFailure())
7052 EvaluateIgnoredValue(Info, E->getSubExpr());
7055 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7056 { return Success(E); }
7057 bool VisitCallExpr(const CallExpr *E);
7058 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7059 bool VisitBlockExpr(const BlockExpr *E) {
7060 if (!E->getBlockDecl()->hasCaptures())
7064 bool VisitCXXThisExpr(const CXXThisExpr *E) {
7065 // Can't look at 'this' when checking a potential constant expression.
7066 if (Info.checkingPotentialConstantExpression())
7068 if (!Info.CurrentCall->This) {
7069 if (Info.getLangOpts().CPlusPlus11)
7070 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7075 Result = *Info.CurrentCall->This;
7076 // If we are inside a lambda's call operator, the 'this' expression refers
7077 // to the enclosing '*this' object (either by value or reference) which is
7078 // either copied into the closure object's field that represents the '*this'
7079 // or refers to '*this'.
7080 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7081 // Update 'Result' to refer to the data member/field of the closure object
7082 // that represents the '*this' capture.
7083 if (!HandleLValueMember(Info, E, Result,
7084 Info.CurrentCall->LambdaThisCaptureField))
7086 // If we captured '*this' by reference, replace the field with its referent.
7087 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7088 ->isPointerType()) {
7090 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7094 Result.setFrom(Info.Ctx, RVal);
7100 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7101 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7102 APValue LValResult = E->EvaluateInContext(
7103 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7104 Result.setFrom(Info.Ctx, LValResult);
7108 // FIXME: Missing: @protocol, @selector
7110 } // end anonymous namespace
7112 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7113 bool InvalidBaseOK) {
7114 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7115 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7118 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7119 if (E->getOpcode() != BO_Add &&
7120 E->getOpcode() != BO_Sub)
7121 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7123 const Expr *PExp = E->getLHS();
7124 const Expr *IExp = E->getRHS();
7125 if (IExp->getType()->isPointerType())
7126 std::swap(PExp, IExp);
7128 bool EvalPtrOK = evaluatePointer(PExp, Result);
7129 if (!EvalPtrOK && !Info.noteFailure())
7132 llvm::APSInt Offset;
7133 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7136 if (E->getOpcode() == BO_Sub)
7137 negateAsSigned(Offset);
7139 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7140 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7143 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7144 return evaluateLValue(E->getSubExpr(), Result);
7147 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7148 const Expr *SubExpr = E->getSubExpr();
7150 switch (E->getCastKind()) {
7154 case CK_CPointerToObjCPointerCast:
7155 case CK_BlockPointerToObjCPointerCast:
7156 case CK_AnyPointerToBlockPointerCast:
7157 case CK_AddressSpaceConversion:
7158 if (!Visit(SubExpr))
7160 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7161 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7162 // also static_casts, but we disallow them as a resolution to DR1312.
7163 if (!E->getType()->isVoidPointerType()) {
7164 Result.Designator.setInvalid();
7165 if (SubExpr->getType()->isVoidPointerType())
7166 CCEDiag(E, diag::note_constexpr_invalid_cast)
7167 << 3 << SubExpr->getType();
7169 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7171 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7172 ZeroInitialization(E);
7175 case CK_DerivedToBase:
7176 case CK_UncheckedDerivedToBase:
7177 if (!evaluatePointer(E->getSubExpr(), Result))
7179 if (!Result.Base && Result.Offset.isZero())
7182 // Now figure out the necessary offset to add to the base LV to get from
7183 // the derived class to the base class.
7184 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7185 castAs<PointerType>()->getPointeeType(),
7188 case CK_BaseToDerived:
7189 if (!Visit(E->getSubExpr()))
7191 if (!Result.Base && Result.Offset.isZero())
7193 return HandleBaseToDerivedCast(Info, E, Result);
7196 if (!Visit(E->getSubExpr()))
7198 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7200 case CK_NullToPointer:
7201 VisitIgnoredValue(E->getSubExpr());
7202 return ZeroInitialization(E);
7204 case CK_IntegralToPointer: {
7205 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7208 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
7211 if (Value.isInt()) {
7212 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7213 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
7214 Result.Base = (Expr*)nullptr;
7215 Result.InvalidBase = false;
7216 Result.Offset = CharUnits::fromQuantity(N);
7217 Result.Designator.setInvalid();
7218 Result.IsNullPtr = false;
7221 // Cast is of an lvalue, no need to change value.
7222 Result.setFrom(Info.Ctx, Value);
7227 case CK_ArrayToPointerDecay: {
7228 if (SubExpr->isGLValue()) {
7229 if (!evaluateLValue(SubExpr, Result))
7232 APValue &Value = createTemporary(SubExpr, false, Result,
7234 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
7237 // The result is a pointer to the first element of the array.
7238 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7239 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
7240 Result.addArray(Info, E, CAT);
7242 Result.addUnsizedArray(Info, E, AT->getElementType());
7246 case CK_FunctionToPointerDecay:
7247 return evaluateLValue(SubExpr, Result);
7249 case CK_LValueToRValue: {
7251 if (!evaluateLValue(E->getSubExpr(), LVal))
7255 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7256 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7258 return InvalidBaseOK &&
7259 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
7260 return Success(RVal, E);
7264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7267 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7268 UnaryExprOrTypeTrait ExprKind) {
7269 // C++ [expr.alignof]p3:
7270 // When alignof is applied to a reference type, the result is the
7271 // alignment of the referenced type.
7272 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7273 T = Ref->getPointeeType();
7275 if (T.getQualifiers().hasUnaligned())
7276 return CharUnits::One();
7278 const bool AlignOfReturnsPreferred =
7279 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7281 // __alignof is defined to return the preferred alignment.
7282 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7284 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7285 return Info.Ctx.toCharUnitsFromBits(
7286 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7287 // alignof and _Alignof are defined to return the ABI alignment.
7288 else if (ExprKind == UETT_AlignOf)
7289 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7291 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
7294 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7295 UnaryExprOrTypeTrait ExprKind) {
7296 E = E->IgnoreParens();
7298 // The kinds of expressions that we have special-case logic here for
7299 // should be kept up to date with the special checks for those
7300 // expressions in Sema.
7302 // alignof decl is always accepted, even if it doesn't make sense: we default
7303 // to 1 in those cases.
7304 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7305 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7306 /*RefAsPointee*/true);
7308 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7309 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7310 /*RefAsPointee*/true);
7312 return GetAlignOfType(Info, E->getType(), ExprKind);
7315 // To be clear: this happily visits unsupported builtins. Better name welcomed.
7316 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7317 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7320 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
7323 Result.setInvalid(E);
7324 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
7325 Result.addUnsizedArray(Info, E, PointeeTy);
7329 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
7330 if (IsStringLiteralCall(E))
7333 if (unsigned BuiltinOp = E->getBuiltinCallee())
7334 return VisitBuiltinCallExpr(E, BuiltinOp);
7336 return visitNonBuiltinCallExpr(E);
7339 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7340 unsigned BuiltinOp) {
7341 switch (BuiltinOp) {
7342 case Builtin::BI__builtin_addressof:
7343 return evaluateLValue(E->getArg(0), Result);
7344 case Builtin::BI__builtin_assume_aligned: {
7345 // We need to be very careful here because: if the pointer does not have the
7346 // asserted alignment, then the behavior is undefined, and undefined
7347 // behavior is non-constant.
7348 if (!evaluatePointer(E->getArg(0), Result))
7351 LValue OffsetResult(Result);
7353 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7355 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
7357 if (E->getNumArgs() > 2) {
7359 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7362 int64_t AdditionalOffset = -Offset.getZExtValue();
7363 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7366 // If there is a base object, then it must have the correct alignment.
7367 if (OffsetResult.Base) {
7368 CharUnits BaseAlignment;
7369 if (const ValueDecl *VD =
7370 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7371 BaseAlignment = Info.Ctx.getDeclAlign(VD);
7372 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7373 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
7375 BaseAlignment = GetAlignOfType(
7376 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
7379 if (BaseAlignment < Align) {
7380 Result.Designator.setInvalid();
7381 // FIXME: Add support to Diagnostic for long / long long.
7382 CCEDiag(E->getArg(0),
7383 diag::note_constexpr_baa_insufficient_alignment) << 0
7384 << (unsigned)BaseAlignment.getQuantity()
7385 << (unsigned)Align.getQuantity();
7390 // The offset must also have the correct alignment.
7391 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
7392 Result.Designator.setInvalid();
7395 ? CCEDiag(E->getArg(0),
7396 diag::note_constexpr_baa_insufficient_alignment) << 1
7397 : CCEDiag(E->getArg(0),
7398 diag::note_constexpr_baa_value_insufficient_alignment))
7399 << (int)OffsetResult.Offset.getQuantity()
7400 << (unsigned)Align.getQuantity();
7406 case Builtin::BI__builtin_launder:
7407 return evaluatePointer(E->getArg(0), Result);
7408 case Builtin::BIstrchr:
7409 case Builtin::BIwcschr:
7410 case Builtin::BImemchr:
7411 case Builtin::BIwmemchr:
7412 if (Info.getLangOpts().CPlusPlus11)
7413 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7414 << /*isConstexpr*/0 << /*isConstructor*/0
7415 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7417 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7419 case Builtin::BI__builtin_strchr:
7420 case Builtin::BI__builtin_wcschr:
7421 case Builtin::BI__builtin_memchr:
7422 case Builtin::BI__builtin_char_memchr:
7423 case Builtin::BI__builtin_wmemchr: {
7424 if (!Visit(E->getArg(0)))
7427 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7429 uint64_t MaxLength = uint64_t(-1);
7430 if (BuiltinOp != Builtin::BIstrchr &&
7431 BuiltinOp != Builtin::BIwcschr &&
7432 BuiltinOp != Builtin::BI__builtin_strchr &&
7433 BuiltinOp != Builtin::BI__builtin_wcschr) {
7435 if (!EvaluateInteger(E->getArg(2), N, Info))
7437 MaxLength = N.getExtValue();
7439 // We cannot find the value if there are no candidates to match against.
7440 if (MaxLength == 0u)
7441 return ZeroInitialization(E);
7442 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7443 Result.Designator.Invalid)
7445 QualType CharTy = Result.Designator.getType(Info.Ctx);
7446 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7447 BuiltinOp == Builtin::BI__builtin_memchr;
7449 Info.Ctx.hasSameUnqualifiedType(
7450 CharTy, E->getArg(0)->getType()->getPointeeType()));
7451 // Pointers to const void may point to objects of incomplete type.
7452 if (IsRawByte && CharTy->isIncompleteType()) {
7453 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7456 // Give up on byte-oriented matching against multibyte elements.
7457 // FIXME: We can compare the bytes in the correct order.
7458 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7460 // Figure out what value we're actually looking for (after converting to
7461 // the corresponding unsigned type if necessary).
7462 uint64_t DesiredVal;
7463 bool StopAtNull = false;
7464 switch (BuiltinOp) {
7465 case Builtin::BIstrchr:
7466 case Builtin::BI__builtin_strchr:
7467 // strchr compares directly to the passed integer, and therefore
7468 // always fails if given an int that is not a char.
7469 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7470 E->getArg(1)->getType(),
7473 return ZeroInitialization(E);
7476 case Builtin::BImemchr:
7477 case Builtin::BI__builtin_memchr:
7478 case Builtin::BI__builtin_char_memchr:
7479 // memchr compares by converting both sides to unsigned char. That's also
7480 // correct for strchr if we get this far (to cope with plain char being
7481 // unsigned in the strchr case).
7482 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7485 case Builtin::BIwcschr:
7486 case Builtin::BI__builtin_wcschr:
7489 case Builtin::BIwmemchr:
7490 case Builtin::BI__builtin_wmemchr:
7491 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7492 DesiredVal = Desired.getZExtValue();
7496 for (; MaxLength; --MaxLength) {
7498 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7501 if (Char.getInt().getZExtValue() == DesiredVal)
7503 if (StopAtNull && !Char.getInt())
7505 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7508 // Not found: return nullptr.
7509 return ZeroInitialization(E);
7512 case Builtin::BImemcpy:
7513 case Builtin::BImemmove:
7514 case Builtin::BIwmemcpy:
7515 case Builtin::BIwmemmove:
7516 if (Info.getLangOpts().CPlusPlus11)
7517 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7518 << /*isConstexpr*/0 << /*isConstructor*/0
7519 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7521 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7523 case Builtin::BI__builtin_memcpy:
7524 case Builtin::BI__builtin_memmove:
7525 case Builtin::BI__builtin_wmemcpy:
7526 case Builtin::BI__builtin_wmemmove: {
7527 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7528 BuiltinOp == Builtin::BIwmemmove ||
7529 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7530 BuiltinOp == Builtin::BI__builtin_wmemmove;
7531 bool Move = BuiltinOp == Builtin::BImemmove ||
7532 BuiltinOp == Builtin::BIwmemmove ||
7533 BuiltinOp == Builtin::BI__builtin_memmove ||
7534 BuiltinOp == Builtin::BI__builtin_wmemmove;
7536 // The result of mem* is the first argument.
7537 if (!Visit(E->getArg(0)))
7539 LValue Dest = Result;
7542 if (!EvaluatePointer(E->getArg(1), Src, Info))
7546 if (!EvaluateInteger(E->getArg(2), N, Info))
7548 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7550 // If the size is zero, we treat this as always being a valid no-op.
7551 // (Even if one of the src and dest pointers is null.)
7555 // Otherwise, if either of the operands is null, we can't proceed. Don't
7556 // try to determine the type of the copied objects, because there aren't
7558 if (!Src.Base || !Dest.Base) {
7560 (!Src.Base ? Src : Dest).moveInto(Val);
7561 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7562 << Move << WChar << !!Src.Base
7563 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7566 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7569 // We require that Src and Dest are both pointers to arrays of
7570 // trivially-copyable type. (For the wide version, the designator will be
7571 // invalid if the designated object is not a wchar_t.)
7572 QualType T = Dest.Designator.getType(Info.Ctx);
7573 QualType SrcT = Src.Designator.getType(Info.Ctx);
7574 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7575 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7578 if (T->isIncompleteType()) {
7579 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7582 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7583 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7587 // Figure out how many T's we're copying.
7588 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7591 llvm::APInt OrigN = N;
7592 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7594 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7595 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7601 // Check that the copying will remain within the arrays, just so that we
7602 // can give a more meaningful diagnostic. This implicitly also checks that
7603 // N fits into 64 bits.
7604 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7605 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7606 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7607 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7608 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7609 << N.toString(10, /*Signed*/false);
7612 uint64_t NElems = N.getZExtValue();
7613 uint64_t NBytes = NElems * TSize;
7615 // Check for overlap.
7617 if (HasSameBase(Src, Dest)) {
7618 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7619 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7620 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7621 // Dest is inside the source region.
7623 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7626 // For memmove and friends, copy backwards.
7627 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7628 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7631 } else if (!Move && SrcOffset >= DestOffset &&
7632 SrcOffset - DestOffset < NBytes) {
7633 // Src is inside the destination region for memcpy: invalid.
7634 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7641 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7642 !handleAssignment(Info, E, Dest, T, Val))
7644 // Do not iterate past the last element; if we're copying backwards, that
7645 // might take us off the start of the array.
7648 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7649 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7655 return visitNonBuiltinCallExpr(E);
7659 //===----------------------------------------------------------------------===//
7660 // Member Pointer Evaluation
7661 //===----------------------------------------------------------------------===//
7664 class MemberPointerExprEvaluator
7665 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7668 bool Success(const ValueDecl *D) {
7669 Result = MemberPtr(D);
7674 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7675 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7677 bool Success(const APValue &V, const Expr *E) {
7681 bool ZeroInitialization(const Expr *E) {
7682 return Success((const ValueDecl*)nullptr);
7685 bool VisitCastExpr(const CastExpr *E);
7686 bool VisitUnaryAddrOf(const UnaryOperator *E);
7688 } // end anonymous namespace
7690 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7692 assert(E->isRValue() && E->getType()->isMemberPointerType());
7693 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7696 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7697 switch (E->getCastKind()) {
7699 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7701 case CK_NullToMemberPointer:
7702 VisitIgnoredValue(E->getSubExpr());
7703 return ZeroInitialization(E);
7705 case CK_BaseToDerivedMemberPointer: {
7706 if (!Visit(E->getSubExpr()))
7708 if (E->path_empty())
7710 // Base-to-derived member pointer casts store the path in derived-to-base
7711 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7712 // the wrong end of the derived->base arc, so stagger the path by one class.
7713 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7714 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7715 PathI != PathE; ++PathI) {
7716 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7717 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7718 if (!Result.castToDerived(Derived))
7721 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7722 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7727 case CK_DerivedToBaseMemberPointer:
7728 if (!Visit(E->getSubExpr()))
7730 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7731 PathE = E->path_end(); PathI != PathE; ++PathI) {
7732 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7733 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7734 if (!Result.castToBase(Base))
7741 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7742 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7743 // member can be formed.
7744 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7747 //===----------------------------------------------------------------------===//
7748 // Record Evaluation
7749 //===----------------------------------------------------------------------===//
7752 class RecordExprEvaluator
7753 : public ExprEvaluatorBase<RecordExprEvaluator> {
7758 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7759 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7761 bool Success(const APValue &V, const Expr *E) {
7765 bool ZeroInitialization(const Expr *E) {
7766 return ZeroInitialization(E, E->getType());
7768 bool ZeroInitialization(const Expr *E, QualType T);
7770 bool VisitCallExpr(const CallExpr *E) {
7771 return handleCallExpr(E, Result, &This);
7773 bool VisitCastExpr(const CastExpr *E);
7774 bool VisitInitListExpr(const InitListExpr *E);
7775 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7776 return VisitCXXConstructExpr(E, E->getType());
7778 bool VisitLambdaExpr(const LambdaExpr *E);
7779 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7780 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7781 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7783 bool VisitBinCmp(const BinaryOperator *E);
7787 /// Perform zero-initialization on an object of non-union class type.
7788 /// C++11 [dcl.init]p5:
7789 /// To zero-initialize an object or reference of type T means:
7791 /// -- if T is a (possibly cv-qualified) non-union class type,
7792 /// each non-static data member and each base-class subobject is
7793 /// zero-initialized
7794 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7795 const RecordDecl *RD,
7796 const LValue &This, APValue &Result) {
7797 assert(!RD->isUnion() && "Expected non-union class type");
7798 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7799 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7800 std::distance(RD->field_begin(), RD->field_end()));
7802 if (RD->isInvalidDecl()) return false;
7803 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7807 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7808 End = CD->bases_end(); I != End; ++I, ++Index) {
7809 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7810 LValue Subobject = This;
7811 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7813 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7814 Result.getStructBase(Index)))
7819 for (const auto *I : RD->fields()) {
7820 // -- if T is a reference type, no initialization is performed.
7821 if (I->getType()->isReferenceType())
7824 LValue Subobject = This;
7825 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7828 ImplicitValueInitExpr VIE(I->getType());
7829 if (!EvaluateInPlace(
7830 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7837 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7838 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7839 if (RD->isInvalidDecl()) return false;
7840 if (RD->isUnion()) {
7841 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7842 // object's first non-static named data member is zero-initialized
7843 RecordDecl::field_iterator I = RD->field_begin();
7844 if (I == RD->field_end()) {
7845 Result = APValue((const FieldDecl*)nullptr);
7849 LValue Subobject = This;
7850 if (!HandleLValueMember(Info, E, Subobject, *I))
7852 Result = APValue(*I);
7853 ImplicitValueInitExpr VIE(I->getType());
7854 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7857 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7858 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7862 return HandleClassZeroInitialization(Info, E, RD, This, Result);
7865 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7866 switch (E->getCastKind()) {
7868 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7870 case CK_ConstructorConversion:
7871 return Visit(E->getSubExpr());
7873 case CK_DerivedToBase:
7874 case CK_UncheckedDerivedToBase: {
7875 APValue DerivedObject;
7876 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7878 if (!DerivedObject.isStruct())
7879 return Error(E->getSubExpr());
7881 // Derived-to-base rvalue conversion: just slice off the derived part.
7882 APValue *Value = &DerivedObject;
7883 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7884 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7885 PathE = E->path_end(); PathI != PathE; ++PathI) {
7886 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7887 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7888 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7897 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7898 if (E->isTransparent())
7899 return Visit(E->getInit(0));
7901 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7902 if (RD->isInvalidDecl()) return false;
7903 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7904 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7906 EvalInfo::EvaluatingConstructorRAII EvalObj(
7908 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7909 CXXRD && CXXRD->getNumBases());
7911 if (RD->isUnion()) {
7912 const FieldDecl *Field = E->getInitializedFieldInUnion();
7913 Result = APValue(Field);
7917 // If the initializer list for a union does not contain any elements, the
7918 // first element of the union is value-initialized.
7919 // FIXME: The element should be initialized from an initializer list.
7920 // Is this difference ever observable for initializer lists which
7922 ImplicitValueInitExpr VIE(Field->getType());
7923 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7925 LValue Subobject = This;
7926 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7929 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7930 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7931 isa<CXXDefaultInitExpr>(InitExpr));
7933 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7936 if (!Result.hasValue())
7937 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7938 std::distance(RD->field_begin(), RD->field_end()));
7939 unsigned ElementNo = 0;
7940 bool Success = true;
7942 // Initialize base classes.
7943 if (CXXRD && CXXRD->getNumBases()) {
7944 for (const auto &Base : CXXRD->bases()) {
7945 assert(ElementNo < E->getNumInits() && "missing init for base class");
7946 const Expr *Init = E->getInit(ElementNo);
7948 LValue Subobject = This;
7949 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7952 APValue &FieldVal = Result.getStructBase(ElementNo);
7953 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7954 if (!Info.noteFailure())
7961 EvalObj.finishedConstructingBases();
7964 // Initialize members.
7965 for (const auto *Field : RD->fields()) {
7966 // Anonymous bit-fields are not considered members of the class for
7967 // purposes of aggregate initialization.
7968 if (Field->isUnnamedBitfield())
7971 LValue Subobject = This;
7973 bool HaveInit = ElementNo < E->getNumInits();
7975 // FIXME: Diagnostics here should point to the end of the initializer
7976 // list, not the start.
7977 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7978 Subobject, Field, &Layout))
7981 // Perform an implicit value-initialization for members beyond the end of
7982 // the initializer list.
7983 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7984 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7986 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7987 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7988 isa<CXXDefaultInitExpr>(Init));
7990 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7991 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7992 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7993 FieldVal, Field))) {
7994 if (!Info.noteFailure())
8003 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8005 // Note that E's type is not necessarily the type of our class here; we might
8006 // be initializing an array element instead.
8007 const CXXConstructorDecl *FD = E->getConstructor();
8008 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
8010 bool ZeroInit = E->requiresZeroInitialization();
8011 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
8012 // If we've already performed zero-initialization, we're already done.
8013 if (Result.hasValue())
8016 // We can get here in two different ways:
8017 // 1) We're performing value-initialization, and should zero-initialize
8019 // 2) We're performing default-initialization of an object with a trivial
8020 // constexpr default constructor, in which case we should start the
8021 // lifetimes of all the base subobjects (there can be no data member
8022 // subobjects in this case) per [basic.life]p1.
8023 // Either way, ZeroInitialization is appropriate.
8024 return ZeroInitialization(E, T);
8027 const FunctionDecl *Definition = nullptr;
8028 auto Body = FD->getBody(Definition);
8030 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8033 // Avoid materializing a temporary for an elidable copy/move constructor.
8034 if (E->isElidable() && !ZeroInit)
8035 if (const MaterializeTemporaryExpr *ME
8036 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8037 return Visit(ME->GetTemporaryExpr());
8039 if (ZeroInit && !ZeroInitialization(E, T))
8042 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
8043 return HandleConstructorCall(E, This, Args,
8044 cast<CXXConstructorDecl>(Definition), Info,
8048 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8049 const CXXInheritedCtorInitExpr *E) {
8050 if (!Info.CurrentCall) {
8051 assert(Info.checkingPotentialConstantExpression());
8055 const CXXConstructorDecl *FD = E->getConstructor();
8056 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8059 const FunctionDecl *Definition = nullptr;
8060 auto Body = FD->getBody(Definition);
8062 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8065 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
8066 cast<CXXConstructorDecl>(Definition), Info,
8070 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8071 const CXXStdInitializerListExpr *E) {
8072 const ConstantArrayType *ArrayType =
8073 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8076 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8079 // Get a pointer to the first element of the array.
8080 Array.addArray(Info, E, ArrayType);
8082 // FIXME: Perform the checks on the field types in SemaInit.
8083 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8084 RecordDecl::field_iterator Field = Record->field_begin();
8085 if (Field == Record->field_end())
8089 if (!Field->getType()->isPointerType() ||
8090 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8091 ArrayType->getElementType()))
8094 // FIXME: What if the initializer_list type has base classes, etc?
8095 Result = APValue(APValue::UninitStruct(), 0, 2);
8096 Array.moveInto(Result.getStructField(0));
8098 if (++Field == Record->field_end())
8101 if (Field->getType()->isPointerType() &&
8102 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8103 ArrayType->getElementType())) {
8105 if (!HandleLValueArrayAdjustment(Info, E, Array,
8106 ArrayType->getElementType(),
8107 ArrayType->getSize().getZExtValue()))
8109 Array.moveInto(Result.getStructField(1));
8110 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8112 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8116 if (++Field != Record->field_end())
8122 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8123 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8124 if (ClosureClass->isInvalidDecl()) return false;
8126 if (Info.checkingPotentialConstantExpression()) return true;
8128 const size_t NumFields =
8129 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
8131 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8132 E->capture_init_end()) &&
8133 "The number of lambda capture initializers should equal the number of "
8134 "fields within the closure type");
8136 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8137 // Iterate through all the lambda's closure object's fields and initialize
8139 auto *CaptureInitIt = E->capture_init_begin();
8140 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8141 bool Success = true;
8142 for (const auto *Field : ClosureClass->fields()) {
8143 assert(CaptureInitIt != E->capture_init_end());
8144 // Get the initializer for this field
8145 Expr *const CurFieldInit = *CaptureInitIt++;
8147 // If there is no initializer, either this is a VLA or an error has
8152 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8153 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8154 if (!Info.keepEvaluatingAfterFailure())
8163 static bool EvaluateRecord(const Expr *E, const LValue &This,
8164 APValue &Result, EvalInfo &Info) {
8165 assert(E->isRValue() && E->getType()->isRecordType() &&
8166 "can't evaluate expression as a record rvalue");
8167 return RecordExprEvaluator(Info, This, Result).Visit(E);
8170 //===----------------------------------------------------------------------===//
8171 // Temporary Evaluation
8173 // Temporaries are represented in the AST as rvalues, but generally behave like
8174 // lvalues. The full-object of which the temporary is a subobject is implicitly
8175 // materialized so that a reference can bind to it.
8176 //===----------------------------------------------------------------------===//
8178 class TemporaryExprEvaluator
8179 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8181 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
8182 LValueExprEvaluatorBaseTy(Info, Result, false) {}
8184 /// Visit an expression which constructs the value of this temporary.
8185 bool VisitConstructExpr(const Expr *E) {
8186 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8187 return EvaluateInPlace(Value, Info, Result, E);
8190 bool VisitCastExpr(const CastExpr *E) {
8191 switch (E->getCastKind()) {
8193 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8195 case CK_ConstructorConversion:
8196 return VisitConstructExpr(E->getSubExpr());
8199 bool VisitInitListExpr(const InitListExpr *E) {
8200 return VisitConstructExpr(E);
8202 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8203 return VisitConstructExpr(E);
8205 bool VisitCallExpr(const CallExpr *E) {
8206 return VisitConstructExpr(E);
8208 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8209 return VisitConstructExpr(E);
8211 bool VisitLambdaExpr(const LambdaExpr *E) {
8212 return VisitConstructExpr(E);
8215 } // end anonymous namespace
8217 /// Evaluate an expression of record type as a temporary.
8218 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
8219 assert(E->isRValue() && E->getType()->isRecordType());
8220 return TemporaryExprEvaluator(Info, Result).Visit(E);
8223 //===----------------------------------------------------------------------===//
8224 // Vector Evaluation
8225 //===----------------------------------------------------------------------===//
8228 class VectorExprEvaluator
8229 : public ExprEvaluatorBase<VectorExprEvaluator> {
8233 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8234 : ExprEvaluatorBaseTy(info), Result(Result) {}
8236 bool Success(ArrayRef<APValue> V, const Expr *E) {
8237 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8238 // FIXME: remove this APValue copy.
8239 Result = APValue(V.data(), V.size());
8242 bool Success(const APValue &V, const Expr *E) {
8243 assert(V.isVector());
8247 bool ZeroInitialization(const Expr *E);
8249 bool VisitUnaryReal(const UnaryOperator *E)
8250 { return Visit(E->getSubExpr()); }
8251 bool VisitCastExpr(const CastExpr* E);
8252 bool VisitInitListExpr(const InitListExpr *E);
8253 bool VisitUnaryImag(const UnaryOperator *E);
8254 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
8255 // binary comparisons, binary and/or/xor,
8256 // shufflevector, ExtVectorElementExpr
8258 } // end anonymous namespace
8260 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
8261 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
8262 return VectorExprEvaluator(Info, Result).Visit(E);
8265 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
8266 const VectorType *VTy = E->getType()->castAs<VectorType>();
8267 unsigned NElts = VTy->getNumElements();
8269 const Expr *SE = E->getSubExpr();
8270 QualType SETy = SE->getType();
8272 switch (E->getCastKind()) {
8273 case CK_VectorSplat: {
8274 APValue Val = APValue();
8275 if (SETy->isIntegerType()) {
8277 if (!EvaluateInteger(SE, IntResult, Info))
8279 Val = APValue(std::move(IntResult));
8280 } else if (SETy->isRealFloatingType()) {
8281 APFloat FloatResult(0.0);
8282 if (!EvaluateFloat(SE, FloatResult, Info))
8284 Val = APValue(std::move(FloatResult));
8289 // Splat and create vector APValue.
8290 SmallVector<APValue, 4> Elts(NElts, Val);
8291 return Success(Elts, E);
8294 // Evaluate the operand into an APInt we can extract from.
8295 llvm::APInt SValInt;
8296 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8298 // Extract the elements
8299 QualType EltTy = VTy->getElementType();
8300 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8301 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8302 SmallVector<APValue, 4> Elts;
8303 if (EltTy->isRealFloatingType()) {
8304 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
8305 unsigned FloatEltSize = EltSize;
8306 if (&Sem == &APFloat::x87DoubleExtended())
8308 for (unsigned i = 0; i < NElts; i++) {
8311 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8313 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
8314 Elts.push_back(APValue(APFloat(Sem, Elt)));
8316 } else if (EltTy->isIntegerType()) {
8317 for (unsigned i = 0; i < NElts; i++) {
8320 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8322 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8323 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8328 return Success(Elts, E);
8331 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8336 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8337 const VectorType *VT = E->getType()->castAs<VectorType>();
8338 unsigned NumInits = E->getNumInits();
8339 unsigned NumElements = VT->getNumElements();
8341 QualType EltTy = VT->getElementType();
8342 SmallVector<APValue, 4> Elements;
8344 // The number of initializers can be less than the number of
8345 // vector elements. For OpenCL, this can be due to nested vector
8346 // initialization. For GCC compatibility, missing trailing elements
8347 // should be initialized with zeroes.
8348 unsigned CountInits = 0, CountElts = 0;
8349 while (CountElts < NumElements) {
8350 // Handle nested vector initialization.
8351 if (CountInits < NumInits
8352 && E->getInit(CountInits)->getType()->isVectorType()) {
8354 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8356 unsigned vlen = v.getVectorLength();
8357 for (unsigned j = 0; j < vlen; j++)
8358 Elements.push_back(v.getVectorElt(j));
8360 } else if (EltTy->isIntegerType()) {
8361 llvm::APSInt sInt(32);
8362 if (CountInits < NumInits) {
8363 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
8365 } else // trailing integer zero.
8366 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8367 Elements.push_back(APValue(sInt));
8370 llvm::APFloat f(0.0);
8371 if (CountInits < NumInits) {
8372 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
8374 } else // trailing float zero.
8375 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8376 Elements.push_back(APValue(f));
8381 return Success(Elements, E);
8385 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
8386 const VectorType *VT = E->getType()->getAs<VectorType>();
8387 QualType EltTy = VT->getElementType();
8388 APValue ZeroElement;
8389 if (EltTy->isIntegerType())
8390 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8393 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8395 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
8396 return Success(Elements, E);
8399 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8400 VisitIgnoredValue(E->getSubExpr());
8401 return ZeroInitialization(E);
8404 //===----------------------------------------------------------------------===//
8406 //===----------------------------------------------------------------------===//
8409 class ArrayExprEvaluator
8410 : public ExprEvaluatorBase<ArrayExprEvaluator> {
8415 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8416 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
8418 bool Success(const APValue &V, const Expr *E) {
8419 assert(V.isArray() && "expected array");
8424 bool ZeroInitialization(const Expr *E) {
8425 const ConstantArrayType *CAT =
8426 Info.Ctx.getAsConstantArrayType(E->getType());
8430 Result = APValue(APValue::UninitArray(), 0,
8431 CAT->getSize().getZExtValue());
8432 if (!Result.hasArrayFiller()) return true;
8434 // Zero-initialize all elements.
8435 LValue Subobject = This;
8436 Subobject.addArray(Info, E, CAT);
8437 ImplicitValueInitExpr VIE(CAT->getElementType());
8438 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
8441 bool VisitCallExpr(const CallExpr *E) {
8442 return handleCallExpr(E, Result, &This);
8444 bool VisitInitListExpr(const InitListExpr *E);
8445 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
8446 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
8447 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8448 const LValue &Subobject,
8449 APValue *Value, QualType Type);
8450 bool VisitStringLiteral(const StringLiteral *E) {
8451 expandStringLiteral(Info, E, Result);
8455 } // end anonymous namespace
8457 static bool EvaluateArray(const Expr *E, const LValue &This,
8458 APValue &Result, EvalInfo &Info) {
8459 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
8460 return ArrayExprEvaluator(Info, This, Result).Visit(E);
8463 // Return true iff the given array filler may depend on the element index.
8464 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8465 // For now, just whitelist non-class value-initialization and initialization
8466 // lists comprised of them.
8467 if (isa<ImplicitValueInitExpr>(FillerExpr))
8469 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8470 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8471 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8479 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8480 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8484 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8485 // an appropriately-typed string literal enclosed in braces.
8486 if (E->isStringLiteralInit())
8487 return Visit(E->getInit(0));
8489 bool Success = true;
8491 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8492 "zero-initialized array shouldn't have any initialized elts");
8494 if (Result.isArray() && Result.hasArrayFiller())
8495 Filler = Result.getArrayFiller();
8497 unsigned NumEltsToInit = E->getNumInits();
8498 unsigned NumElts = CAT->getSize().getZExtValue();
8499 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8501 // If the initializer might depend on the array index, run it for each
8503 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8504 NumEltsToInit = NumElts;
8506 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8507 << NumEltsToInit << ".\n");
8509 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8511 // If the array was previously zero-initialized, preserve the
8512 // zero-initialized values.
8513 if (Filler.hasValue()) {
8514 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8515 Result.getArrayInitializedElt(I) = Filler;
8516 if (Result.hasArrayFiller())
8517 Result.getArrayFiller() = Filler;
8520 LValue Subobject = This;
8521 Subobject.addArray(Info, E, CAT);
8522 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8524 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8525 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8526 Info, Subobject, Init) ||
8527 !HandleLValueArrayAdjustment(Info, Init, Subobject,
8528 CAT->getElementType(), 1)) {
8529 if (!Info.noteFailure())
8535 if (!Result.hasArrayFiller())
8538 // If we get here, we have a trivial filler, which we can just evaluate
8539 // once and splat over the rest of the array elements.
8540 assert(FillerExpr && "no array filler for incomplete init list");
8541 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8542 FillerExpr) && Success;
8545 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8546 if (E->getCommonExpr() &&
8547 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8548 Info, E->getCommonExpr()->getSourceExpr()))
8551 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8553 uint64_t Elements = CAT->getSize().getZExtValue();
8554 Result = APValue(APValue::UninitArray(), Elements, Elements);
8556 LValue Subobject = This;
8557 Subobject.addArray(Info, E, CAT);
8559 bool Success = true;
8560 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8561 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8562 Info, Subobject, E->getSubExpr()) ||
8563 !HandleLValueArrayAdjustment(Info, E, Subobject,
8564 CAT->getElementType(), 1)) {
8565 if (!Info.noteFailure())
8574 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8575 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8578 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8579 const LValue &Subobject,
8582 bool HadZeroInit = Value->hasValue();
8584 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8585 unsigned N = CAT->getSize().getZExtValue();
8587 // Preserve the array filler if we had prior zero-initialization.
8589 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8592 *Value = APValue(APValue::UninitArray(), N, N);
8595 for (unsigned I = 0; I != N; ++I)
8596 Value->getArrayInitializedElt(I) = Filler;
8598 // Initialize the elements.
8599 LValue ArrayElt = Subobject;
8600 ArrayElt.addArray(Info, E, CAT);
8601 for (unsigned I = 0; I != N; ++I)
8602 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8603 CAT->getElementType()) ||
8604 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8605 CAT->getElementType(), 1))
8611 if (!Type->isRecordType())
8614 return RecordExprEvaluator(Info, Subobject, *Value)
8615 .VisitCXXConstructExpr(E, Type);
8618 //===----------------------------------------------------------------------===//
8619 // Integer Evaluation
8621 // As a GNU extension, we support casting pointers to sufficiently-wide integer
8622 // types and back in constant folding. Integer values are thus represented
8623 // either as an integer-valued APValue, or as an lvalue-valued APValue.
8624 //===----------------------------------------------------------------------===//
8627 class IntExprEvaluator
8628 : public ExprEvaluatorBase<IntExprEvaluator> {
8631 IntExprEvaluator(EvalInfo &info, APValue &result)
8632 : ExprEvaluatorBaseTy(info), Result(result) {}
8634 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8635 assert(E->getType()->isIntegralOrEnumerationType() &&
8636 "Invalid evaluation result.");
8637 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8638 "Invalid evaluation result.");
8639 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8640 "Invalid evaluation result.");
8641 Result = APValue(SI);
8644 bool Success(const llvm::APSInt &SI, const Expr *E) {
8645 return Success(SI, E, Result);
8648 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8649 assert(E->getType()->isIntegralOrEnumerationType() &&
8650 "Invalid evaluation result.");
8651 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8652 "Invalid evaluation result.");
8653 Result = APValue(APSInt(I));
8654 Result.getInt().setIsUnsigned(
8655 E->getType()->isUnsignedIntegerOrEnumerationType());
8658 bool Success(const llvm::APInt &I, const Expr *E) {
8659 return Success(I, E, Result);
8662 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8663 assert(E->getType()->isIntegralOrEnumerationType() &&
8664 "Invalid evaluation result.");
8665 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8668 bool Success(uint64_t Value, const Expr *E) {
8669 return Success(Value, E, Result);
8672 bool Success(CharUnits Size, const Expr *E) {
8673 return Success(Size.getQuantity(), E);
8676 bool Success(const APValue &V, const Expr *E) {
8677 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
8681 return Success(V.getInt(), E);
8684 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8686 //===--------------------------------------------------------------------===//
8688 //===--------------------------------------------------------------------===//
8690 bool VisitConstantExpr(const ConstantExpr *E);
8692 bool VisitIntegerLiteral(const IntegerLiteral *E) {
8693 return Success(E->getValue(), E);
8695 bool VisitCharacterLiteral(const CharacterLiteral *E) {
8696 return Success(E->getValue(), E);
8699 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8700 bool VisitDeclRefExpr(const DeclRefExpr *E) {
8701 if (CheckReferencedDecl(E, E->getDecl()))
8704 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8706 bool VisitMemberExpr(const MemberExpr *E) {
8707 if (CheckReferencedDecl(E, E->getMemberDecl())) {
8708 VisitIgnoredBaseExpression(E->getBase());
8712 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8715 bool VisitCallExpr(const CallExpr *E);
8716 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8717 bool VisitBinaryOperator(const BinaryOperator *E);
8718 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8719 bool VisitUnaryOperator(const UnaryOperator *E);
8721 bool VisitCastExpr(const CastExpr* E);
8722 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8724 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8725 return Success(E->getValue(), E);
8728 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8729 return Success(E->getValue(), E);
8732 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8733 if (Info.ArrayInitIndex == uint64_t(-1)) {
8734 // We were asked to evaluate this subexpression independent of the
8735 // enclosing ArrayInitLoopExpr. We can't do that.
8739 return Success(Info.ArrayInitIndex, E);
8742 // Note, GNU defines __null as an integer, not a pointer.
8743 bool VisitGNUNullExpr(const GNUNullExpr *E) {
8744 return ZeroInitialization(E);
8747 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8748 return Success(E->getValue(), E);
8751 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8752 return Success(E->getValue(), E);
8755 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8756 return Success(E->getValue(), E);
8759 bool VisitUnaryReal(const UnaryOperator *E);
8760 bool VisitUnaryImag(const UnaryOperator *E);
8762 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8763 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8764 bool VisitSourceLocExpr(const SourceLocExpr *E);
8765 // FIXME: Missing: array subscript of vector, member of vector
8768 class FixedPointExprEvaluator
8769 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8773 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8774 : ExprEvaluatorBaseTy(info), Result(result) {}
8776 bool Success(const llvm::APInt &I, const Expr *E) {
8778 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8781 bool Success(uint64_t Value, const Expr *E) {
8783 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8786 bool Success(const APValue &V, const Expr *E) {
8787 return Success(V.getFixedPoint(), E);
8790 bool Success(const APFixedPoint &V, const Expr *E) {
8791 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8792 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8793 "Invalid evaluation result.");
8794 Result = APValue(V);
8798 //===--------------------------------------------------------------------===//
8800 //===--------------------------------------------------------------------===//
8802 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8803 return Success(E->getValue(), E);
8806 bool VisitCastExpr(const CastExpr *E);
8807 bool VisitUnaryOperator(const UnaryOperator *E);
8808 bool VisitBinaryOperator(const BinaryOperator *E);
8810 } // end anonymous namespace
8812 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8813 /// produce either the integer value or a pointer.
8815 /// GCC has a heinous extension which folds casts between pointer types and
8816 /// pointer-sized integral types. We support this by allowing the evaluation of
8817 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8818 /// Some simple arithmetic on such values is supported (they are treated much
8820 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8822 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8823 return IntExprEvaluator(Info, Result).Visit(E);
8826 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8828 if (!EvaluateIntegerOrLValue(E, Val, Info))
8831 // FIXME: It would be better to produce the diagnostic for casting
8832 // a pointer to an integer.
8833 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8836 Result = Val.getInt();
8840 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8841 APValue Evaluated = E->EvaluateInContext(
8842 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8843 return Success(Evaluated, E);
8846 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8848 if (E->getType()->isFixedPointType()) {
8850 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8852 if (!Val.isFixedPoint())
8855 Result = Val.getFixedPoint();
8861 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8863 if (E->getType()->isIntegerType()) {
8864 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8866 if (!EvaluateInteger(E, Val, Info))
8868 Result = APFixedPoint(Val, FXSema);
8870 } else if (E->getType()->isFixedPointType()) {
8871 return EvaluateFixedPoint(E, Result, Info);
8876 /// Check whether the given declaration can be directly converted to an integral
8877 /// rvalue. If not, no diagnostic is produced; there are other things we can
8879 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8880 // Enums are integer constant exprs.
8881 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8882 // Check for signedness/width mismatches between E type and ECD value.
8883 bool SameSign = (ECD->getInitVal().isSigned()
8884 == E->getType()->isSignedIntegerOrEnumerationType());
8885 bool SameWidth = (ECD->getInitVal().getBitWidth()
8886 == Info.Ctx.getIntWidth(E->getType()));
8887 if (SameSign && SameWidth)
8888 return Success(ECD->getInitVal(), E);
8890 // Get rid of mismatch (otherwise Success assertions will fail)
8891 // by computing a new value matching the type of E.
8892 llvm::APSInt Val = ECD->getInitVal();
8894 Val.setIsSigned(!ECD->getInitVal().isSigned());
8896 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8897 return Success(Val, E);
8903 /// Values returned by __builtin_classify_type, chosen to match the values
8904 /// produced by GCC's builtin.
8905 enum class GCCTypeClass {
8909 // GCC reserves 2 for character types, but instead classifies them as
8914 // GCC reserves 6 for references, but appears to never use it (because
8915 // expressions never have reference type, presumably).
8916 PointerToDataMember = 7,
8919 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8920 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8921 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8922 // uses 12 for that purpose, same as for a class or struct. Maybe it
8923 // internally implements a pointer to member as a struct? Who knows.
8924 PointerToMemberFunction = 12, // Not a bug, see above.
8927 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8928 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8929 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8933 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8936 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8937 assert(!T->isDependentType() && "unexpected dependent type");
8939 QualType CanTy = T.getCanonicalType();
8940 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8942 switch (CanTy->getTypeClass()) {
8943 #define TYPE(ID, BASE)
8944 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8945 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8946 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8947 #include "clang/AST/TypeNodes.def"
8949 case Type::DeducedTemplateSpecialization:
8950 llvm_unreachable("unexpected non-canonical or dependent type");
8953 switch (BT->getKind()) {
8954 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8955 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8956 case BuiltinType::ID: return GCCTypeClass::Integer;
8957 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8958 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8959 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8960 case BuiltinType::ID: break;
8961 #include "clang/AST/BuiltinTypes.def"
8962 case BuiltinType::Void:
8963 return GCCTypeClass::Void;
8965 case BuiltinType::Bool:
8966 return GCCTypeClass::Bool;
8968 case BuiltinType::Char_U:
8969 case BuiltinType::UChar:
8970 case BuiltinType::WChar_U:
8971 case BuiltinType::Char8:
8972 case BuiltinType::Char16:
8973 case BuiltinType::Char32:
8974 case BuiltinType::UShort:
8975 case BuiltinType::UInt:
8976 case BuiltinType::ULong:
8977 case BuiltinType::ULongLong:
8978 case BuiltinType::UInt128:
8979 return GCCTypeClass::Integer;
8981 case BuiltinType::UShortAccum:
8982 case BuiltinType::UAccum:
8983 case BuiltinType::ULongAccum:
8984 case BuiltinType::UShortFract:
8985 case BuiltinType::UFract:
8986 case BuiltinType::ULongFract:
8987 case BuiltinType::SatUShortAccum:
8988 case BuiltinType::SatUAccum:
8989 case BuiltinType::SatULongAccum:
8990 case BuiltinType::SatUShortFract:
8991 case BuiltinType::SatUFract:
8992 case BuiltinType::SatULongFract:
8993 return GCCTypeClass::None;
8995 case BuiltinType::NullPtr:
8997 case BuiltinType::ObjCId:
8998 case BuiltinType::ObjCClass:
8999 case BuiltinType::ObjCSel:
9000 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
9001 case BuiltinType::Id:
9002 #include "clang/Basic/OpenCLImageTypes.def"
9003 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
9004 case BuiltinType::Id:
9005 #include "clang/Basic/OpenCLExtensionTypes.def"
9006 case BuiltinType::OCLSampler:
9007 case BuiltinType::OCLEvent:
9008 case BuiltinType::OCLClkEvent:
9009 case BuiltinType::OCLQueue:
9010 case BuiltinType::OCLReserveID:
9011 return GCCTypeClass::None;
9013 case BuiltinType::Dependent:
9014 llvm_unreachable("unexpected dependent type");
9016 llvm_unreachable("unexpected placeholder type");
9019 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
9022 case Type::ConstantArray:
9023 case Type::VariableArray:
9024 case Type::IncompleteArray:
9025 case Type::FunctionNoProto:
9026 case Type::FunctionProto:
9027 return GCCTypeClass::Pointer;
9029 case Type::MemberPointer:
9030 return CanTy->isMemberDataPointerType()
9031 ? GCCTypeClass::PointerToDataMember
9032 : GCCTypeClass::PointerToMemberFunction;
9035 return GCCTypeClass::Complex;
9038 return CanTy->isUnionType() ? GCCTypeClass::Union
9039 : GCCTypeClass::ClassOrStruct;
9042 // GCC classifies _Atomic T the same as T.
9043 return EvaluateBuiltinClassifyType(
9044 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
9046 case Type::BlockPointer:
9048 case Type::ExtVector:
9049 case Type::ObjCObject:
9050 case Type::ObjCInterface:
9051 case Type::ObjCObjectPointer:
9053 // GCC classifies vectors as None. We follow its lead and classify all
9054 // other types that don't fit into the regular classification the same way.
9055 return GCCTypeClass::None;
9057 case Type::LValueReference:
9058 case Type::RValueReference:
9059 llvm_unreachable("invalid type for expression");
9062 llvm_unreachable("unexpected type class");
9065 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9068 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9069 // If no argument was supplied, default to None. This isn't
9070 // ideal, however it is what gcc does.
9071 if (E->getNumArgs() == 0)
9072 return GCCTypeClass::None;
9074 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9075 // being an ICE, but still folds it to a constant using the type of the first
9077 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
9080 /// EvaluateBuiltinConstantPForLValue - Determine the result of
9081 /// __builtin_constant_p when applied to the given pointer.
9083 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
9084 /// or it points to the first character of a string literal.
9085 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9086 APValue::LValueBase Base = LV.getLValueBase();
9087 if (Base.isNull()) {
9088 // A null base is acceptable.
9090 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9091 if (!isa<StringLiteral>(E))
9093 return LV.getLValueOffset().isZero();
9094 } else if (Base.is<TypeInfoLValue>()) {
9095 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9096 // evaluate to true.
9099 // Any other base is not constant enough for GCC.
9104 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9105 /// GCC as we can manage.
9106 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9107 // This evaluation is not permitted to have side-effects, so evaluate it in
9108 // a speculative evaluation context.
9109 SpeculativeEvaluationRAII SpeculativeEval(Info);
9111 // Constant-folding is always enabled for the operand of __builtin_constant_p
9112 // (even when the enclosing evaluation context otherwise requires a strict
9113 // language-specific constant expression).
9114 FoldConstant Fold(Info, true);
9116 QualType ArgType = Arg->getType();
9118 // __builtin_constant_p always has one operand. The rules which gcc follows
9119 // are not precisely documented, but are as follows:
9121 // - If the operand is of integral, floating, complex or enumeration type,
9122 // and can be folded to a known value of that type, it returns 1.
9123 // - If the operand can be folded to a pointer to the first character
9124 // of a string literal (or such a pointer cast to an integral type)
9125 // or to a null pointer or an integer cast to a pointer, it returns 1.
9127 // Otherwise, it returns 0.
9129 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9130 // its support for this did not work prior to GCC 9 and is not yet well
9132 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9133 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9134 ArgType->isNullPtrType()) {
9136 if (!::EvaluateAsRValue(Info, Arg, V)) {
9137 Fold.keepDiagnostics();
9141 // For a pointer (possibly cast to integer), there are special rules.
9142 if (V.getKind() == APValue::LValue)
9143 return EvaluateBuiltinConstantPForLValue(V);
9145 // Otherwise, any constant value is good enough.
9146 return V.hasValue();
9149 // Anything else isn't considered to be sufficiently constant.
9153 /// Retrieves the "underlying object type" of the given expression,
9154 /// as used by __builtin_object_size.
9155 static QualType getObjectType(APValue::LValueBase B) {
9156 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9157 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9158 return VD->getType();
9159 } else if (const Expr *E = B.get<const Expr*>()) {
9160 if (isa<CompoundLiteralExpr>(E))
9161 return E->getType();
9162 } else if (B.is<TypeInfoLValue>()) {
9163 return B.getTypeInfoType();
9169 /// A more selective version of E->IgnoreParenCasts for
9170 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9171 /// to change the type of E.
9172 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9174 /// Always returns an RValue with a pointer representation.
9175 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9176 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9178 auto *NoParens = E->IgnoreParens();
9179 auto *Cast = dyn_cast<CastExpr>(NoParens);
9180 if (Cast == nullptr)
9183 // We only conservatively allow a few kinds of casts, because this code is
9184 // inherently a simple solution that seeks to support the common case.
9185 auto CastKind = Cast->getCastKind();
9186 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9187 CastKind != CK_AddressSpaceConversion)
9190 auto *SubExpr = Cast->getSubExpr();
9191 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9193 return ignorePointerCastsAndParens(SubExpr);
9196 /// Checks to see if the given LValue's Designator is at the end of the LValue's
9197 /// record layout. e.g.
9198 /// struct { struct { int a, b; } fst, snd; } obj;
9204 /// obj.snd.b // yes
9206 /// Please note: this function is specialized for how __builtin_object_size
9207 /// views "objects".
9209 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
9210 /// correct result, it will always return true.
9211 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9212 assert(!LVal.Designator.Invalid);
9214 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9215 const RecordDecl *Parent = FD->getParent();
9216 Invalid = Parent->isInvalidDecl();
9217 if (Invalid || Parent->isUnion())
9219 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9220 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9223 auto &Base = LVal.getLValueBase();
9224 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9225 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9227 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9229 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9230 for (auto *FD : IFD->chain()) {
9232 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9239 QualType BaseType = getType(Base);
9240 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9241 // If we don't know the array bound, conservatively assume we're looking at
9242 // the final array element.
9244 if (BaseType->isIncompleteArrayType())
9245 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9247 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9250 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9251 const auto &Entry = LVal.Designator.Entries[I];
9252 if (BaseType->isArrayType()) {
9253 // Because __builtin_object_size treats arrays as objects, we can ignore
9254 // the index iff this is the last array in the Designator.
9257 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9258 uint64_t Index = Entry.getAsArrayIndex();
9259 if (Index + 1 != CAT->getSize())
9261 BaseType = CAT->getElementType();
9262 } else if (BaseType->isAnyComplexType()) {
9263 const auto *CT = BaseType->castAs<ComplexType>();
9264 uint64_t Index = Entry.getAsArrayIndex();
9267 BaseType = CT->getElementType();
9268 } else if (auto *FD = getAsField(Entry)) {
9270 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9272 BaseType = FD->getType();
9274 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
9281 /// Tests to see if the LValue has a user-specified designator (that isn't
9282 /// necessarily valid). Note that this always returns 'true' if the LValue has
9283 /// an unsized array as its first designator entry, because there's currently no
9284 /// way to tell if the user typed *foo or foo[0].
9285 static bool refersToCompleteObject(const LValue &LVal) {
9286 if (LVal.Designator.Invalid)
9289 if (!LVal.Designator.Entries.empty())
9290 return LVal.Designator.isMostDerivedAnUnsizedArray();
9292 if (!LVal.InvalidBase)
9295 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9297 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9298 return !E || !isa<MemberExpr>(E);
9301 /// Attempts to detect a user writing into a piece of memory that's impossible
9302 /// to figure out the size of by just using types.
9303 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9304 const SubobjectDesignator &Designator = LVal.Designator;
9306 // - Users can only write off of the end when we have an invalid base. Invalid
9307 // bases imply we don't know where the memory came from.
9308 // - We used to be a bit more aggressive here; we'd only be conservative if
9309 // the array at the end was flexible, or if it had 0 or 1 elements. This
9310 // broke some common standard library extensions (PR30346), but was
9311 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9312 // with some sort of whitelist. OTOH, it seems that GCC is always
9313 // conservative with the last element in structs (if it's an array), so our
9314 // current behavior is more compatible than a whitelisting approach would
9316 return LVal.InvalidBase &&
9317 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9318 Designator.MostDerivedIsArrayElement &&
9319 isDesignatorAtObjectEnd(Ctx, LVal);
9322 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9323 /// Fails if the conversion would cause loss of precision.
9324 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9325 CharUnits &Result) {
9326 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9327 if (Int.ugt(CharUnitsMax))
9329 Result = CharUnits::fromQuantity(Int.getZExtValue());
9333 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9334 /// determine how many bytes exist from the beginning of the object to either
9335 /// the end of the current subobject, or the end of the object itself, depending
9336 /// on what the LValue looks like + the value of Type.
9338 /// If this returns false, the value of Result is undefined.
9339 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9340 unsigned Type, const LValue &LVal,
9341 CharUnits &EndOffset) {
9342 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
9344 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9345 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9347 return HandleSizeof(Info, ExprLoc, Ty, Result);
9350 // We want to evaluate the size of the entire object. This is a valid fallback
9351 // for when Type=1 and the designator is invalid, because we're asked for an
9353 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9354 // Type=3 wants a lower bound, so we can't fall back to this.
9355 if (Type == 3 && !DetermineForCompleteObject)
9358 llvm::APInt APEndOffset;
9359 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9360 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9361 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9363 if (LVal.InvalidBase)
9366 QualType BaseTy = getObjectType(LVal.getLValueBase());
9367 return CheckedHandleSizeof(BaseTy, EndOffset);
9370 // We want to evaluate the size of a subobject.
9371 const SubobjectDesignator &Designator = LVal.Designator;
9373 // The following is a moderately common idiom in C:
9375 // struct Foo { int a; char c[1]; };
9376 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9377 // strcpy(&F->c[0], Bar);
9379 // In order to not break too much legacy code, we need to support it.
9380 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9381 // If we can resolve this to an alloc_size call, we can hand that back,
9382 // because we know for certain how many bytes there are to write to.
9383 llvm::APInt APEndOffset;
9384 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9385 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9386 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9388 // If we cannot determine the size of the initial allocation, then we can't
9389 // given an accurate upper-bound. However, we are still able to give
9390 // conservative lower-bounds for Type=3.
9395 CharUnits BytesPerElem;
9396 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
9399 // According to the GCC documentation, we want the size of the subobject
9400 // denoted by the pointer. But that's not quite right -- what we actually
9401 // want is the size of the immediately-enclosing array, if there is one.
9402 int64_t ElemsRemaining;
9403 if (Designator.MostDerivedIsArrayElement &&
9404 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9405 uint64_t ArraySize = Designator.getMostDerivedArraySize();
9406 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
9407 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9409 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9412 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9416 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
9417 /// returns true and stores the result in @p Size.
9419 /// If @p WasError is non-null, this will report whether the failure to evaluate
9420 /// is to be treated as an Error in IntExprEvaluator.
9421 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9422 EvalInfo &Info, uint64_t &Size) {
9423 // Determine the denoted object.
9426 // The operand of __builtin_object_size is never evaluated for side-effects.
9427 // If there are any, but we can determine the pointed-to object anyway, then
9428 // ignore the side-effects.
9429 SpeculativeEvaluationRAII SpeculativeEval(Info);
9430 IgnoreSideEffectsRAII Fold(Info);
9432 if (E->isGLValue()) {
9433 // It's possible for us to be given GLValues if we're called via
9434 // Expr::tryEvaluateObjectSize.
9436 if (!EvaluateAsRValue(Info, E, RVal))
9438 LVal.setFrom(Info.Ctx, RVal);
9439 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9440 /*InvalidBaseOK=*/true))
9444 // If we point to before the start of the object, there are no accessible
9446 if (LVal.getLValueOffset().isNegative()) {
9451 CharUnits EndOffset;
9452 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9455 // If we've fallen outside of the end offset, just pretend there's nothing to
9456 // write to/read from.
9457 if (EndOffset <= LVal.getLValueOffset())
9460 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9464 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9465 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
9466 if (E->getResultAPValueKind() != APValue::None)
9467 return Success(E->getAPValueResult(), E);
9468 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9471 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
9472 if (unsigned BuiltinOp = E->getBuiltinCallee())
9473 return VisitBuiltinCallExpr(E, BuiltinOp);
9475 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9478 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9479 unsigned BuiltinOp) {
9480 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9482 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9484 case Builtin::BI__builtin_dynamic_object_size:
9485 case Builtin::BI__builtin_object_size: {
9486 // The type was checked when we built the expression.
9488 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9489 assert(Type <= 3 && "unexpected type");
9492 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9493 return Success(Size, E);
9495 if (E->getArg(0)->HasSideEffects(Info.Ctx))
9496 return Success((Type & 2) ? 0 : -1, E);
9498 // Expression had no side effects, but we couldn't statically determine the
9499 // size of the referenced object.
9500 switch (Info.EvalMode) {
9501 case EvalInfo::EM_ConstantExpression:
9502 case EvalInfo::EM_PotentialConstantExpression:
9503 case EvalInfo::EM_ConstantFold:
9504 case EvalInfo::EM_EvaluateForOverflow:
9505 case EvalInfo::EM_IgnoreSideEffects:
9506 // Leave it to IR generation.
9508 case EvalInfo::EM_ConstantExpressionUnevaluated:
9509 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
9510 // Reduce it to a constant now.
9511 return Success((Type & 2) ? 0 : -1, E);
9514 llvm_unreachable("unexpected EvalMode");
9517 case Builtin::BI__builtin_os_log_format_buffer_size: {
9518 analyze_os_log::OSLogBufferLayout Layout;
9519 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9520 return Success(Layout.size().getQuantity(), E);
9523 case Builtin::BI__builtin_bswap16:
9524 case Builtin::BI__builtin_bswap32:
9525 case Builtin::BI__builtin_bswap64: {
9527 if (!EvaluateInteger(E->getArg(0), Val, Info))
9530 return Success(Val.byteSwap(), E);
9533 case Builtin::BI__builtin_classify_type:
9534 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9536 case Builtin::BI__builtin_clrsb:
9537 case Builtin::BI__builtin_clrsbl:
9538 case Builtin::BI__builtin_clrsbll: {
9540 if (!EvaluateInteger(E->getArg(0), Val, Info))
9543 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9546 case Builtin::BI__builtin_clz:
9547 case Builtin::BI__builtin_clzl:
9548 case Builtin::BI__builtin_clzll:
9549 case Builtin::BI__builtin_clzs: {
9551 if (!EvaluateInteger(E->getArg(0), Val, Info))
9556 return Success(Val.countLeadingZeros(), E);
9559 case Builtin::BI__builtin_constant_p: {
9560 const Expr *Arg = E->getArg(0);
9561 if (EvaluateBuiltinConstantP(Info, Arg))
9562 return Success(true, E);
9563 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9564 // Outside a constant context, eagerly evaluate to false in the presence
9565 // of side-effects in order to avoid -Wunsequenced false-positives in
9566 // a branch on __builtin_constant_p(expr).
9567 return Success(false, E);
9569 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9573 case Builtin::BI__builtin_is_constant_evaluated:
9574 return Success(Info.InConstantContext, E);
9576 case Builtin::BI__builtin_ctz:
9577 case Builtin::BI__builtin_ctzl:
9578 case Builtin::BI__builtin_ctzll:
9579 case Builtin::BI__builtin_ctzs: {
9581 if (!EvaluateInteger(E->getArg(0), Val, Info))
9586 return Success(Val.countTrailingZeros(), E);
9589 case Builtin::BI__builtin_eh_return_data_regno: {
9590 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9591 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9592 return Success(Operand, E);
9595 case Builtin::BI__builtin_expect:
9596 return Visit(E->getArg(0));
9598 case Builtin::BI__builtin_ffs:
9599 case Builtin::BI__builtin_ffsl:
9600 case Builtin::BI__builtin_ffsll: {
9602 if (!EvaluateInteger(E->getArg(0), Val, Info))
9605 unsigned N = Val.countTrailingZeros();
9606 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9609 case Builtin::BI__builtin_fpclassify: {
9611 if (!EvaluateFloat(E->getArg(5), Val, Info))
9614 switch (Val.getCategory()) {
9615 case APFloat::fcNaN: Arg = 0; break;
9616 case APFloat::fcInfinity: Arg = 1; break;
9617 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9618 case APFloat::fcZero: Arg = 4; break;
9620 return Visit(E->getArg(Arg));
9623 case Builtin::BI__builtin_isinf_sign: {
9625 return EvaluateFloat(E->getArg(0), Val, Info) &&
9626 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9629 case Builtin::BI__builtin_isinf: {
9631 return EvaluateFloat(E->getArg(0), Val, Info) &&
9632 Success(Val.isInfinity() ? 1 : 0, E);
9635 case Builtin::BI__builtin_isfinite: {
9637 return EvaluateFloat(E->getArg(0), Val, Info) &&
9638 Success(Val.isFinite() ? 1 : 0, E);
9641 case Builtin::BI__builtin_isnan: {
9643 return EvaluateFloat(E->getArg(0), Val, Info) &&
9644 Success(Val.isNaN() ? 1 : 0, E);
9647 case Builtin::BI__builtin_isnormal: {
9649 return EvaluateFloat(E->getArg(0), Val, Info) &&
9650 Success(Val.isNormal() ? 1 : 0, E);
9653 case Builtin::BI__builtin_parity:
9654 case Builtin::BI__builtin_parityl:
9655 case Builtin::BI__builtin_parityll: {
9657 if (!EvaluateInteger(E->getArg(0), Val, Info))
9660 return Success(Val.countPopulation() % 2, E);
9663 case Builtin::BI__builtin_popcount:
9664 case Builtin::BI__builtin_popcountl:
9665 case Builtin::BI__builtin_popcountll: {
9667 if (!EvaluateInteger(E->getArg(0), Val, Info))
9670 return Success(Val.countPopulation(), E);
9673 case Builtin::BIstrlen:
9674 case Builtin::BIwcslen:
9675 // A call to strlen is not a constant expression.
9676 if (Info.getLangOpts().CPlusPlus11)
9677 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9678 << /*isConstexpr*/0 << /*isConstructor*/0
9679 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9681 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9683 case Builtin::BI__builtin_strlen:
9684 case Builtin::BI__builtin_wcslen: {
9685 // As an extension, we support __builtin_strlen() as a constant expression,
9686 // and support folding strlen() to a constant.
9688 if (!EvaluatePointer(E->getArg(0), String, Info))
9691 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9693 // Fast path: if it's a string literal, search the string value.
9694 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9695 String.getLValueBase().dyn_cast<const Expr *>())) {
9696 // The string literal may have embedded null characters. Find the first
9697 // one and truncate there.
9698 StringRef Str = S->getBytes();
9699 int64_t Off = String.Offset.getQuantity();
9700 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9701 S->getCharByteWidth() == 1 &&
9702 // FIXME: Add fast-path for wchar_t too.
9703 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9704 Str = Str.substr(Off);
9706 StringRef::size_type Pos = Str.find(0);
9707 if (Pos != StringRef::npos)
9708 Str = Str.substr(0, Pos);
9710 return Success(Str.size(), E);
9713 // Fall through to slow path to issue appropriate diagnostic.
9716 // Slow path: scan the bytes of the string looking for the terminating 0.
9717 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9719 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9723 return Success(Strlen, E);
9724 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9729 case Builtin::BIstrcmp:
9730 case Builtin::BIwcscmp:
9731 case Builtin::BIstrncmp:
9732 case Builtin::BIwcsncmp:
9733 case Builtin::BImemcmp:
9734 case Builtin::BIbcmp:
9735 case Builtin::BIwmemcmp:
9736 // A call to strlen is not a constant expression.
9737 if (Info.getLangOpts().CPlusPlus11)
9738 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9739 << /*isConstexpr*/0 << /*isConstructor*/0
9740 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9742 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9744 case Builtin::BI__builtin_strcmp:
9745 case Builtin::BI__builtin_wcscmp:
9746 case Builtin::BI__builtin_strncmp:
9747 case Builtin::BI__builtin_wcsncmp:
9748 case Builtin::BI__builtin_memcmp:
9749 case Builtin::BI__builtin_bcmp:
9750 case Builtin::BI__builtin_wmemcmp: {
9751 LValue String1, String2;
9752 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9753 !EvaluatePointer(E->getArg(1), String2, Info))
9756 uint64_t MaxLength = uint64_t(-1);
9757 if (BuiltinOp != Builtin::BIstrcmp &&
9758 BuiltinOp != Builtin::BIwcscmp &&
9759 BuiltinOp != Builtin::BI__builtin_strcmp &&
9760 BuiltinOp != Builtin::BI__builtin_wcscmp) {
9762 if (!EvaluateInteger(E->getArg(2), N, Info))
9764 MaxLength = N.getExtValue();
9767 // Empty substrings compare equal by definition.
9768 if (MaxLength == 0u)
9769 return Success(0, E);
9771 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9772 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9773 String1.Designator.Invalid || String2.Designator.Invalid)
9776 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9777 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9779 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9780 BuiltinOp == Builtin::BIbcmp ||
9781 BuiltinOp == Builtin::BI__builtin_memcmp ||
9782 BuiltinOp == Builtin::BI__builtin_bcmp;
9785 (Info.Ctx.hasSameUnqualifiedType(
9786 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9787 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9789 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9790 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9791 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9792 Char1.isInt() && Char2.isInt();
9794 const auto &AdvanceElems = [&] {
9795 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9796 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9800 uint64_t BytesRemaining = MaxLength;
9801 // Pointers to const void may point to objects of incomplete type.
9802 if (CharTy1->isIncompleteType()) {
9803 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9806 if (CharTy2->isIncompleteType()) {
9807 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9810 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9811 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9812 // Give up on comparing between elements with disparate widths.
9813 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9815 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9816 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9817 "following loop considers at least one element");
9819 APValue Char1, Char2;
9820 if (!ReadCurElems(Char1, Char2))
9822 // We have compatible in-memory widths, but a possible type and
9823 // (for `bool`) internal representation mismatch.
9824 // Assuming two's complement representation, including 0 for `false` and
9825 // 1 for `true`, we can check an appropriate number of elements for
9826 // equality even if they are not byte-sized.
9827 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9828 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9829 if (Char1InMem.ne(Char2InMem)) {
9830 // If the elements are byte-sized, then we can produce a three-way
9831 // comparison result in a straightforward manner.
9832 if (BytesPerElement == 1u) {
9833 // memcmp always compares unsigned chars.
9834 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9836 // The result is byte-order sensitive, and we have multibyte elements.
9837 // FIXME: We can compare the remaining bytes in the correct order.
9840 if (!AdvanceElems())
9842 if (BytesRemaining <= BytesPerElement)
9844 BytesRemaining -= BytesPerElement;
9846 // Enough elements are equal to account for the memcmp limit.
9847 return Success(0, E);
9851 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9852 BuiltinOp != Builtin::BIwmemcmp &&
9853 BuiltinOp != Builtin::BI__builtin_memcmp &&
9854 BuiltinOp != Builtin::BI__builtin_bcmp &&
9855 BuiltinOp != Builtin::BI__builtin_wmemcmp);
9856 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9857 BuiltinOp == Builtin::BIwcsncmp ||
9858 BuiltinOp == Builtin::BIwmemcmp ||
9859 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9860 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9861 BuiltinOp == Builtin::BI__builtin_wmemcmp;
9863 for (; MaxLength; --MaxLength) {
9864 APValue Char1, Char2;
9865 if (!ReadCurElems(Char1, Char2))
9867 if (Char1.getInt() != Char2.getInt()) {
9868 if (IsWide) // wmemcmp compares with wchar_t signedness.
9869 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9870 // memcmp always compares unsigned chars.
9871 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9873 if (StopAtNull && !Char1.getInt())
9874 return Success(0, E);
9875 assert(!(StopAtNull && !Char2.getInt()));
9876 if (!AdvanceElems())
9879 // We hit the strncmp / memcmp limit.
9880 return Success(0, E);
9883 case Builtin::BI__atomic_always_lock_free:
9884 case Builtin::BI__atomic_is_lock_free:
9885 case Builtin::BI__c11_atomic_is_lock_free: {
9887 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9890 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9891 // of two less than the maximum inline atomic width, we know it is
9892 // lock-free. If the size isn't a power of two, or greater than the
9893 // maximum alignment where we promote atomics, we know it is not lock-free
9894 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9895 // the answer can only be determined at runtime; for example, 16-byte
9896 // atomics have lock-free implementations on some, but not all,
9897 // x86-64 processors.
9899 // Check power-of-two.
9900 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9901 if (Size.isPowerOfTwo()) {
9902 // Check against inlining width.
9903 unsigned InlineWidthBits =
9904 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9905 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9906 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9907 Size == CharUnits::One() ||
9908 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9909 Expr::NPC_NeverValueDependent))
9910 // OK, we will inline appropriately-aligned operations of this size,
9911 // and _Atomic(T) is appropriately-aligned.
9912 return Success(1, E);
9914 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9915 castAs<PointerType>()->getPointeeType();
9916 if (!PointeeType->isIncompleteType() &&
9917 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9918 // OK, we will inline operations on this object.
9919 return Success(1, E);
9924 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9925 Success(0, E) : Error(E);
9927 case Builtin::BIomp_is_initial_device:
9928 // We can decide statically which value the runtime would return if called.
9929 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9930 case Builtin::BI__builtin_add_overflow:
9931 case Builtin::BI__builtin_sub_overflow:
9932 case Builtin::BI__builtin_mul_overflow:
9933 case Builtin::BI__builtin_sadd_overflow:
9934 case Builtin::BI__builtin_uadd_overflow:
9935 case Builtin::BI__builtin_uaddl_overflow:
9936 case Builtin::BI__builtin_uaddll_overflow:
9937 case Builtin::BI__builtin_usub_overflow:
9938 case Builtin::BI__builtin_usubl_overflow:
9939 case Builtin::BI__builtin_usubll_overflow:
9940 case Builtin::BI__builtin_umul_overflow:
9941 case Builtin::BI__builtin_umull_overflow:
9942 case Builtin::BI__builtin_umulll_overflow:
9943 case Builtin::BI__builtin_saddl_overflow:
9944 case Builtin::BI__builtin_saddll_overflow:
9945 case Builtin::BI__builtin_ssub_overflow:
9946 case Builtin::BI__builtin_ssubl_overflow:
9947 case Builtin::BI__builtin_ssubll_overflow:
9948 case Builtin::BI__builtin_smul_overflow:
9949 case Builtin::BI__builtin_smull_overflow:
9950 case Builtin::BI__builtin_smulll_overflow: {
9951 LValue ResultLValue;
9954 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9955 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9956 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9957 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9961 bool DidOverflow = false;
9963 // If the types don't have to match, enlarge all 3 to the largest of them.
9964 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9965 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9966 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9967 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9968 ResultType->isSignedIntegerOrEnumerationType();
9969 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9970 ResultType->isSignedIntegerOrEnumerationType();
9971 uint64_t LHSSize = LHS.getBitWidth();
9972 uint64_t RHSSize = RHS.getBitWidth();
9973 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9974 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9976 // Add an additional bit if the signedness isn't uniformly agreed to. We
9977 // could do this ONLY if there is a signed and an unsigned that both have
9978 // MaxBits, but the code to check that is pretty nasty. The issue will be
9979 // caught in the shrink-to-result later anyway.
9980 if (IsSigned && !AllSigned)
9983 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9984 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9985 Result = APSInt(MaxBits, !IsSigned);
9988 // Find largest int.
9989 switch (BuiltinOp) {
9991 llvm_unreachable("Invalid value for BuiltinOp");
9992 case Builtin::BI__builtin_add_overflow:
9993 case Builtin::BI__builtin_sadd_overflow:
9994 case Builtin::BI__builtin_saddl_overflow:
9995 case Builtin::BI__builtin_saddll_overflow:
9996 case Builtin::BI__builtin_uadd_overflow:
9997 case Builtin::BI__builtin_uaddl_overflow:
9998 case Builtin::BI__builtin_uaddll_overflow:
9999 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
10000 : LHS.uadd_ov(RHS, DidOverflow);
10002 case Builtin::BI__builtin_sub_overflow:
10003 case Builtin::BI__builtin_ssub_overflow:
10004 case Builtin::BI__builtin_ssubl_overflow:
10005 case Builtin::BI__builtin_ssubll_overflow:
10006 case Builtin::BI__builtin_usub_overflow:
10007 case Builtin::BI__builtin_usubl_overflow:
10008 case Builtin::BI__builtin_usubll_overflow:
10009 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
10010 : LHS.usub_ov(RHS, DidOverflow);
10012 case Builtin::BI__builtin_mul_overflow:
10013 case Builtin::BI__builtin_smul_overflow:
10014 case Builtin::BI__builtin_smull_overflow:
10015 case Builtin::BI__builtin_smulll_overflow:
10016 case Builtin::BI__builtin_umul_overflow:
10017 case Builtin::BI__builtin_umull_overflow:
10018 case Builtin::BI__builtin_umulll_overflow:
10019 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10020 : LHS.umul_ov(RHS, DidOverflow);
10024 // In the case where multiple sizes are allowed, truncate and see if
10025 // the values are the same.
10026 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10027 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10028 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10029 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10030 // since it will give us the behavior of a TruncOrSelf in the case where
10031 // its parameter <= its size. We previously set Result to be at least the
10032 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10033 // will work exactly like TruncOrSelf.
10034 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10035 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10037 if (!APSInt::isSameValue(Temp, Result))
10038 DidOverflow = true;
10042 APValue APV{Result};
10043 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10045 return Success(DidOverflow, E);
10050 /// Determine whether this is a pointer past the end of the complete
10051 /// object referred to by the lvalue.
10052 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10053 const LValue &LV) {
10054 // A null pointer can be viewed as being "past the end" but we don't
10055 // choose to look at it that way here.
10056 if (!LV.getLValueBase())
10059 // If the designator is valid and refers to a subobject, we're not pointing
10061 if (!LV.getLValueDesignator().Invalid &&
10062 !LV.getLValueDesignator().isOnePastTheEnd())
10065 // A pointer to an incomplete type might be past-the-end if the type's size is
10066 // zero. We cannot tell because the type is incomplete.
10067 QualType Ty = getType(LV.getLValueBase());
10068 if (Ty->isIncompleteType())
10071 // We're a past-the-end pointer if we point to the byte after the object,
10072 // no matter what our type or path is.
10073 auto Size = Ctx.getTypeSizeInChars(Ty);
10074 return LV.getLValueOffset() == Size;
10079 /// Data recursive integer evaluator of certain binary operators.
10081 /// We use a data recursive algorithm for binary operators so that we are able
10082 /// to handle extreme cases of chained binary operators without causing stack
10084 class DataRecursiveIntBinOpEvaluator {
10085 struct EvalResult {
10089 EvalResult() : Failed(false) { }
10091 void swap(EvalResult &RHS) {
10093 Failed = RHS.Failed;
10094 RHS.Failed = false;
10100 EvalResult LHSResult; // meaningful only for binary operator expression.
10101 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10104 Job(Job &&) = default;
10106 void startSpeculativeEval(EvalInfo &Info) {
10107 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10111 SpeculativeEvaluationRAII SpecEvalRAII;
10114 SmallVector<Job, 16> Queue;
10116 IntExprEvaluator &IntEval;
10118 APValue &FinalResult;
10121 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10122 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10124 /// True if \param E is a binary operator that we are going to handle
10125 /// data recursively.
10126 /// We handle binary operators that are comma, logical, or that have operands
10127 /// with integral or enumeration type.
10128 static bool shouldEnqueue(const BinaryOperator *E) {
10129 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10130 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10131 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10132 E->getRHS()->getType()->isIntegralOrEnumerationType());
10135 bool Traverse(const BinaryOperator *E) {
10137 EvalResult PrevResult;
10138 while (!Queue.empty())
10139 process(PrevResult);
10141 if (PrevResult.Failed) return false;
10143 FinalResult.swap(PrevResult.Val);
10148 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10149 return IntEval.Success(Value, E, Result);
10151 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10152 return IntEval.Success(Value, E, Result);
10154 bool Error(const Expr *E) {
10155 return IntEval.Error(E);
10157 bool Error(const Expr *E, diag::kind D) {
10158 return IntEval.Error(E, D);
10161 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10162 return Info.CCEDiag(E, D);
10165 // Returns true if visiting the RHS is necessary, false otherwise.
10166 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10167 bool &SuppressRHSDiags);
10169 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10170 const BinaryOperator *E, APValue &Result);
10172 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10173 Result.Failed = !Evaluate(Result.Val, Info, E);
10175 Result.Val = APValue();
10178 void process(EvalResult &Result);
10180 void enqueue(const Expr *E) {
10181 E = E->IgnoreParens();
10182 Queue.resize(Queue.size()+1);
10183 Queue.back().E = E;
10184 Queue.back().Kind = Job::AnyExprKind;
10190 bool DataRecursiveIntBinOpEvaluator::
10191 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10192 bool &SuppressRHSDiags) {
10193 if (E->getOpcode() == BO_Comma) {
10194 // Ignore LHS but note if we could not evaluate it.
10195 if (LHSResult.Failed)
10196 return Info.noteSideEffect();
10200 if (E->isLogicalOp()) {
10202 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10203 // We were able to evaluate the LHS, see if we can get away with not
10204 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10205 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10206 Success(LHSAsBool, E, LHSResult.Val);
10207 return false; // Ignore RHS
10210 LHSResult.Failed = true;
10212 // Since we weren't able to evaluate the left hand side, it
10213 // might have had side effects.
10214 if (!Info.noteSideEffect())
10217 // We can't evaluate the LHS; however, sometimes the result
10218 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10219 // Don't ignore RHS and suppress diagnostics from this arm.
10220 SuppressRHSDiags = true;
10226 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10227 E->getRHS()->getType()->isIntegralOrEnumerationType());
10229 if (LHSResult.Failed && !Info.noteFailure())
10230 return false; // Ignore RHS;
10235 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10237 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10238 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10240 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10241 CharUnits &Offset = LVal.getLValueOffset();
10242 uint64_t Offset64 = Offset.getQuantity();
10243 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10244 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10245 : Offset64 + Index64);
10248 bool DataRecursiveIntBinOpEvaluator::
10249 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10250 const BinaryOperator *E, APValue &Result) {
10251 if (E->getOpcode() == BO_Comma) {
10252 if (RHSResult.Failed)
10254 Result = RHSResult.Val;
10258 if (E->isLogicalOp()) {
10259 bool lhsResult, rhsResult;
10260 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10261 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10265 if (E->getOpcode() == BO_LOr)
10266 return Success(lhsResult || rhsResult, E, Result);
10268 return Success(lhsResult && rhsResult, E, Result);
10272 // We can't evaluate the LHS; however, sometimes the result
10273 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10274 if (rhsResult == (E->getOpcode() == BO_LOr))
10275 return Success(rhsResult, E, Result);
10282 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10283 E->getRHS()->getType()->isIntegralOrEnumerationType());
10285 if (LHSResult.Failed || RHSResult.Failed)
10288 const APValue &LHSVal = LHSResult.Val;
10289 const APValue &RHSVal = RHSResult.Val;
10291 // Handle cases like (unsigned long)&a + 4.
10292 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10294 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10298 // Handle cases like 4 + (unsigned long)&a
10299 if (E->getOpcode() == BO_Add &&
10300 RHSVal.isLValue() && LHSVal.isInt()) {
10302 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10306 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10307 // Handle (intptr_t)&&A - (intptr_t)&&B.
10308 if (!LHSVal.getLValueOffset().isZero() ||
10309 !RHSVal.getLValueOffset().isZero())
10311 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10312 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10313 if (!LHSExpr || !RHSExpr)
10315 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10316 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10317 if (!LHSAddrExpr || !RHSAddrExpr)
10319 // Make sure both labels come from the same function.
10320 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10321 RHSAddrExpr->getLabel()->getDeclContext())
10323 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10327 // All the remaining cases expect both operands to be an integer
10328 if (!LHSVal.isInt() || !RHSVal.isInt())
10331 // Set up the width and signedness manually, in case it can't be deduced
10332 // from the operation we're performing.
10333 // FIXME: Don't do this in the cases where we can deduce it.
10334 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10335 E->getType()->isUnsignedIntegerOrEnumerationType());
10336 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10337 RHSVal.getInt(), Value))
10339 return Success(Value, E, Result);
10342 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
10343 Job &job = Queue.back();
10345 switch (job.Kind) {
10346 case Job::AnyExprKind: {
10347 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10348 if (shouldEnqueue(Bop)) {
10349 job.Kind = Job::BinOpKind;
10350 enqueue(Bop->getLHS());
10355 EvaluateExpr(job.E, Result);
10360 case Job::BinOpKind: {
10361 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10362 bool SuppressRHSDiags = false;
10363 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
10367 if (SuppressRHSDiags)
10368 job.startSpeculativeEval(Info);
10369 job.LHSResult.swap(Result);
10370 job.Kind = Job::BinOpVisitedLHSKind;
10371 enqueue(Bop->getRHS());
10375 case Job::BinOpVisitedLHSKind: {
10376 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10379 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
10385 llvm_unreachable("Invalid Job::Kind!");
10389 /// Used when we determine that we should fail, but can keep evaluating prior to
10390 /// noting that we had a failure.
10391 class DelayedNoteFailureRAII {
10396 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10397 : Info(Info), NoteFailure(NoteFailure) {}
10398 ~DelayedNoteFailureRAII() {
10400 bool ContinueAfterFailure = Info.noteFailure();
10401 (void)ContinueAfterFailure;
10402 assert(ContinueAfterFailure &&
10403 "Shouldn't have kept evaluating on failure.");
10409 template <class SuccessCB, class AfterCB>
10411 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10412 SuccessCB &&Success, AfterCB &&DoAfter) {
10413 assert(E->isComparisonOp() && "expected comparison operator");
10414 assert((E->getOpcode() == BO_Cmp ||
10415 E->getType()->isIntegralOrEnumerationType()) &&
10416 "unsupported binary expression evaluation");
10417 auto Error = [&](const Expr *E) {
10418 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10422 using CCR = ComparisonCategoryResult;
10423 bool IsRelational = E->isRelationalOp();
10424 bool IsEquality = E->isEqualityOp();
10425 if (E->getOpcode() == BO_Cmp) {
10426 const ComparisonCategoryInfo &CmpInfo =
10427 Info.Ctx.CompCategories.getInfoForType(E->getType());
10428 IsRelational = CmpInfo.isOrdered();
10429 IsEquality = CmpInfo.isEquality();
10432 QualType LHSTy = E->getLHS()->getType();
10433 QualType RHSTy = E->getRHS()->getType();
10435 if (LHSTy->isIntegralOrEnumerationType() &&
10436 RHSTy->isIntegralOrEnumerationType()) {
10438 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10439 if (!LHSOK && !Info.noteFailure())
10441 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10444 return Success(CCR::Less, E);
10446 return Success(CCR::Greater, E);
10447 return Success(CCR::Equal, E);
10450 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10451 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10452 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10454 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10455 if (!LHSOK && !Info.noteFailure())
10457 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10460 return Success(CCR::Less, E);
10462 return Success(CCR::Greater, E);
10463 return Success(CCR::Equal, E);
10466 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10467 ComplexValue LHS, RHS;
10469 if (E->isAssignmentOp()) {
10471 EvaluateLValue(E->getLHS(), LV, Info);
10473 } else if (LHSTy->isRealFloatingType()) {
10474 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10476 LHS.makeComplexFloat();
10477 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10480 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10482 if (!LHSOK && !Info.noteFailure())
10485 if (E->getRHS()->getType()->isRealFloatingType()) {
10486 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10488 RHS.makeComplexFloat();
10489 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10490 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10493 if (LHS.isComplexFloat()) {
10494 APFloat::cmpResult CR_r =
10495 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10496 APFloat::cmpResult CR_i =
10497 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10498 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10499 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10501 assert(IsEquality && "invalid complex comparison");
10502 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10503 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10504 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10508 if (LHSTy->isRealFloatingType() &&
10509 RHSTy->isRealFloatingType()) {
10510 APFloat RHS(0.0), LHS(0.0);
10512 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10513 if (!LHSOK && !Info.noteFailure())
10516 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10519 assert(E->isComparisonOp() && "Invalid binary operator!");
10520 auto GetCmpRes = [&]() {
10521 switch (LHS.compare(RHS)) {
10522 case APFloat::cmpEqual:
10524 case APFloat::cmpLessThan:
10526 case APFloat::cmpGreaterThan:
10527 return CCR::Greater;
10528 case APFloat::cmpUnordered:
10529 return CCR::Unordered;
10531 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10533 return Success(GetCmpRes(), E);
10536 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10537 LValue LHSValue, RHSValue;
10539 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10540 if (!LHSOK && !Info.noteFailure())
10543 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10546 // Reject differing bases from the normal codepath; we special-case
10547 // comparisons to null.
10548 if (!HasSameBase(LHSValue, RHSValue)) {
10549 // Inequalities and subtractions between unrelated pointers have
10550 // unspecified or undefined behavior.
10553 // A constant address may compare equal to the address of a symbol.
10554 // The one exception is that address of an object cannot compare equal
10555 // to a null pointer constant.
10556 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10557 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10559 // It's implementation-defined whether distinct literals will have
10560 // distinct addresses. In clang, the result of such a comparison is
10561 // unspecified, so it is not a constant expression. However, we do know
10562 // that the address of a literal will be non-null.
10563 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10564 LHSValue.Base && RHSValue.Base)
10566 // We can't tell whether weak symbols will end up pointing to the same
10568 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10570 // We can't compare the address of the start of one object with the
10571 // past-the-end address of another object, per C++ DR1652.
10572 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10573 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10574 (RHSValue.Base && RHSValue.Offset.isZero() &&
10575 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10577 // We can't tell whether an object is at the same address as another
10578 // zero sized object.
10579 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10580 (LHSValue.Base && isZeroSized(RHSValue)))
10582 return Success(CCR::Nonequal, E);
10585 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10586 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10588 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10589 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10591 // C++11 [expr.rel]p3:
10592 // Pointers to void (after pointer conversions) can be compared, with a
10593 // result defined as follows: If both pointers represent the same
10594 // address or are both the null pointer value, the result is true if the
10595 // operator is <= or >= and false otherwise; otherwise the result is
10597 // We interpret this as applying to pointers to *cv* void.
10598 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10599 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10601 // C++11 [expr.rel]p2:
10602 // - If two pointers point to non-static data members of the same object,
10603 // or to subobjects or array elements fo such members, recursively, the
10604 // pointer to the later declared member compares greater provided the
10605 // two members have the same access control and provided their class is
10608 // - Otherwise pointer comparisons are unspecified.
10609 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10610 bool WasArrayIndex;
10611 unsigned Mismatch = FindDesignatorMismatch(
10612 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10613 // At the point where the designators diverge, the comparison has a
10614 // specified value if:
10615 // - we are comparing array indices
10616 // - we are comparing fields of a union, or fields with the same access
10617 // Otherwise, the result is unspecified and thus the comparison is not a
10618 // constant expression.
10619 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10620 Mismatch < RHSDesignator.Entries.size()) {
10621 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10622 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10624 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10626 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10627 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10628 << RF->getParent() << RF;
10630 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10631 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10632 << LF->getParent() << LF;
10633 else if (!LF->getParent()->isUnion() &&
10634 LF->getAccess() != RF->getAccess())
10636 diag::note_constexpr_pointer_comparison_differing_access)
10637 << LF << LF->getAccess() << RF << RF->getAccess()
10638 << LF->getParent();
10642 // The comparison here must be unsigned, and performed with the same
10643 // width as the pointer.
10644 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10645 uint64_t CompareLHS = LHSOffset.getQuantity();
10646 uint64_t CompareRHS = RHSOffset.getQuantity();
10647 assert(PtrSize <= 64 && "Unexpected pointer width");
10648 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10649 CompareLHS &= Mask;
10650 CompareRHS &= Mask;
10652 // If there is a base and this is a relational operator, we can only
10653 // compare pointers within the object in question; otherwise, the result
10654 // depends on where the object is located in memory.
10655 if (!LHSValue.Base.isNull() && IsRelational) {
10656 QualType BaseTy = getType(LHSValue.Base);
10657 if (BaseTy->isIncompleteType())
10659 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10660 uint64_t OffsetLimit = Size.getQuantity();
10661 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10665 if (CompareLHS < CompareRHS)
10666 return Success(CCR::Less, E);
10667 if (CompareLHS > CompareRHS)
10668 return Success(CCR::Greater, E);
10669 return Success(CCR::Equal, E);
10672 if (LHSTy->isMemberPointerType()) {
10673 assert(IsEquality && "unexpected member pointer operation");
10674 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10676 MemberPtr LHSValue, RHSValue;
10678 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10679 if (!LHSOK && !Info.noteFailure())
10682 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10685 // C++11 [expr.eq]p2:
10686 // If both operands are null, they compare equal. Otherwise if only one is
10687 // null, they compare unequal.
10688 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10689 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10690 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10693 // Otherwise if either is a pointer to a virtual member function, the
10694 // result is unspecified.
10695 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10696 if (MD->isVirtual())
10697 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10698 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10699 if (MD->isVirtual())
10700 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10702 // Otherwise they compare equal if and only if they would refer to the
10703 // same member of the same most derived object or the same subobject if
10704 // they were dereferenced with a hypothetical object of the associated
10706 bool Equal = LHSValue == RHSValue;
10707 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10710 if (LHSTy->isNullPtrType()) {
10711 assert(E->isComparisonOp() && "unexpected nullptr operation");
10712 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10713 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10714 // are compared, the result is true of the operator is <=, >= or ==, and
10715 // false otherwise.
10716 return Success(CCR::Equal, E);
10722 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10723 if (!CheckLiteralType(Info, E))
10726 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10727 const BinaryOperator *E) {
10728 // Evaluation succeeded. Lookup the information for the comparison category
10729 // type and fetch the VarDecl for the result.
10730 const ComparisonCategoryInfo &CmpInfo =
10731 Info.Ctx.CompCategories.getInfoForType(E->getType());
10732 const VarDecl *VD =
10733 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10734 // Check and evaluate the result as a constant expression.
10737 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10739 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10741 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10742 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10746 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10747 // We don't call noteFailure immediately because the assignment happens after
10748 // we evaluate LHS and RHS.
10749 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10752 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10753 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10754 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10756 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10757 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10758 "DataRecursiveIntBinOpEvaluator should have handled integral types");
10760 if (E->isComparisonOp()) {
10761 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10762 // comparisons and then translating the result.
10763 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10764 const BinaryOperator *E) {
10765 using CCR = ComparisonCategoryResult;
10766 bool IsEqual = ResKind == CCR::Equal,
10767 IsLess = ResKind == CCR::Less,
10768 IsGreater = ResKind == CCR::Greater;
10769 auto Op = E->getOpcode();
10772 llvm_unreachable("unsupported binary operator");
10775 return Success(IsEqual == (Op == BO_EQ), E);
10776 case BO_LT: return Success(IsLess, E);
10777 case BO_GT: return Success(IsGreater, E);
10778 case BO_LE: return Success(IsEqual || IsLess, E);
10779 case BO_GE: return Success(IsEqual || IsGreater, E);
10782 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10783 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10787 QualType LHSTy = E->getLHS()->getType();
10788 QualType RHSTy = E->getRHS()->getType();
10790 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10791 E->getOpcode() == BO_Sub) {
10792 LValue LHSValue, RHSValue;
10794 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10795 if (!LHSOK && !Info.noteFailure())
10798 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10801 // Reject differing bases from the normal codepath; we special-case
10802 // comparisons to null.
10803 if (!HasSameBase(LHSValue, RHSValue)) {
10804 // Handle &&A - &&B.
10805 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10807 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10808 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10809 if (!LHSExpr || !RHSExpr)
10811 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10812 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10813 if (!LHSAddrExpr || !RHSAddrExpr)
10815 // Make sure both labels come from the same function.
10816 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10817 RHSAddrExpr->getLabel()->getDeclContext())
10819 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10821 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10822 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10824 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10825 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10827 // C++11 [expr.add]p6:
10828 // Unless both pointers point to elements of the same array object, or
10829 // one past the last element of the array object, the behavior is
10831 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10832 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10834 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10836 QualType Type = E->getLHS()->getType();
10837 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10839 CharUnits ElementSize;
10840 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10843 // As an extension, a type may have zero size (empty struct or union in
10844 // C, array of zero length). Pointer subtraction in such cases has
10845 // undefined behavior, so is not constant.
10846 if (ElementSize.isZero()) {
10847 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10852 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10853 // and produce incorrect results when it overflows. Such behavior
10854 // appears to be non-conforming, but is common, so perhaps we should
10855 // assume the standard intended for such cases to be undefined behavior
10856 // and check for them.
10858 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10859 // overflow in the final conversion to ptrdiff_t.
10860 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10861 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10862 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10864 APSInt TrueResult = (LHS - RHS) / ElemSize;
10865 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10867 if (Result.extend(65) != TrueResult &&
10868 !HandleOverflow(Info, E, TrueResult, E->getType()))
10870 return Success(Result, E);
10873 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10876 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10877 /// a result as the expression's type.
10878 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10879 const UnaryExprOrTypeTraitExpr *E) {
10880 switch(E->getKind()) {
10881 case UETT_PreferredAlignOf:
10882 case UETT_AlignOf: {
10883 if (E->isArgumentType())
10884 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10887 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10891 case UETT_VecStep: {
10892 QualType Ty = E->getTypeOfArgument();
10894 if (Ty->isVectorType()) {
10895 unsigned n = Ty->castAs<VectorType>()->getNumElements();
10897 // The vec_step built-in functions that take a 3-component
10898 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10902 return Success(n, E);
10904 return Success(1, E);
10907 case UETT_SizeOf: {
10908 QualType SrcTy = E->getTypeOfArgument();
10909 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10910 // the result is the size of the referenced type."
10911 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10912 SrcTy = Ref->getPointeeType();
10915 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10917 return Success(Sizeof, E);
10919 case UETT_OpenMPRequiredSimdAlign:
10920 assert(E->isArgumentType());
10922 Info.Ctx.toCharUnitsFromBits(
10923 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10928 llvm_unreachable("unknown expr/type trait");
10931 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10933 unsigned n = OOE->getNumComponents();
10936 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10937 for (unsigned i = 0; i != n; ++i) {
10938 OffsetOfNode ON = OOE->getComponent(i);
10939 switch (ON.getKind()) {
10940 case OffsetOfNode::Array: {
10941 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10943 if (!EvaluateInteger(Idx, IdxResult, Info))
10945 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10948 CurrentType = AT->getElementType();
10949 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10950 Result += IdxResult.getSExtValue() * ElementSize;
10954 case OffsetOfNode::Field: {
10955 FieldDecl *MemberDecl = ON.getField();
10956 const RecordType *RT = CurrentType->getAs<RecordType>();
10959 RecordDecl *RD = RT->getDecl();
10960 if (RD->isInvalidDecl()) return false;
10961 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10962 unsigned i = MemberDecl->getFieldIndex();
10963 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10964 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10965 CurrentType = MemberDecl->getType().getNonReferenceType();
10969 case OffsetOfNode::Identifier:
10970 llvm_unreachable("dependent __builtin_offsetof");
10972 case OffsetOfNode::Base: {
10973 CXXBaseSpecifier *BaseSpec = ON.getBase();
10974 if (BaseSpec->isVirtual())
10977 // Find the layout of the class whose base we are looking into.
10978 const RecordType *RT = CurrentType->getAs<RecordType>();
10981 RecordDecl *RD = RT->getDecl();
10982 if (RD->isInvalidDecl()) return false;
10983 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10985 // Find the base class itself.
10986 CurrentType = BaseSpec->getType();
10987 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10991 // Add the offset to the base.
10992 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10997 return Success(Result, OOE);
11000 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11001 switch (E->getOpcode()) {
11003 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
11007 // FIXME: Should extension allow i-c-e extension expressions in its scope?
11008 // If so, we could clear the diagnostic ID.
11009 return Visit(E->getSubExpr());
11011 // The result is just the value.
11012 return Visit(E->getSubExpr());
11014 if (!Visit(E->getSubExpr()))
11016 if (!Result.isInt()) return Error(E);
11017 const APSInt &Value = Result.getInt();
11018 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11019 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11022 return Success(-Value, E);
11025 if (!Visit(E->getSubExpr()))
11027 if (!Result.isInt()) return Error(E);
11028 return Success(~Result.getInt(), E);
11032 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11034 return Success(!bres, E);
11039 /// HandleCast - This is used to evaluate implicit or explicit casts where the
11040 /// result type is integer.
11041 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11042 const Expr *SubExpr = E->getSubExpr();
11043 QualType DestType = E->getType();
11044 QualType SrcType = SubExpr->getType();
11046 switch (E->getCastKind()) {
11047 case CK_BaseToDerived:
11048 case CK_DerivedToBase:
11049 case CK_UncheckedDerivedToBase:
11052 case CK_ArrayToPointerDecay:
11053 case CK_FunctionToPointerDecay:
11054 case CK_NullToPointer:
11055 case CK_NullToMemberPointer:
11056 case CK_BaseToDerivedMemberPointer:
11057 case CK_DerivedToBaseMemberPointer:
11058 case CK_ReinterpretMemberPointer:
11059 case CK_ConstructorConversion:
11060 case CK_IntegralToPointer:
11062 case CK_VectorSplat:
11063 case CK_IntegralToFloating:
11064 case CK_FloatingCast:
11065 case CK_CPointerToObjCPointerCast:
11066 case CK_BlockPointerToObjCPointerCast:
11067 case CK_AnyPointerToBlockPointerCast:
11068 case CK_ObjCObjectLValueCast:
11069 case CK_FloatingRealToComplex:
11070 case CK_FloatingComplexToReal:
11071 case CK_FloatingComplexCast:
11072 case CK_FloatingComplexToIntegralComplex:
11073 case CK_IntegralRealToComplex:
11074 case CK_IntegralComplexCast:
11075 case CK_IntegralComplexToFloatingComplex:
11076 case CK_BuiltinFnToFnPtr:
11077 case CK_ZeroToOCLOpaqueType:
11078 case CK_NonAtomicToAtomic:
11079 case CK_AddressSpaceConversion:
11080 case CK_IntToOCLSampler:
11081 case CK_FixedPointCast:
11082 case CK_IntegralToFixedPoint:
11083 llvm_unreachable("invalid cast kind for integral value");
11087 case CK_LValueBitCast:
11088 case CK_ARCProduceObject:
11089 case CK_ARCConsumeObject:
11090 case CK_ARCReclaimReturnedObject:
11091 case CK_ARCExtendBlockObject:
11092 case CK_CopyAndAutoreleaseBlockObject:
11095 case CK_UserDefinedConversion:
11096 case CK_LValueToRValue:
11097 case CK_AtomicToNonAtomic:
11099 case CK_LValueToRValueBitCast:
11100 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11102 case CK_MemberPointerToBoolean:
11103 case CK_PointerToBoolean:
11104 case CK_IntegralToBoolean:
11105 case CK_FloatingToBoolean:
11106 case CK_BooleanToSignedIntegral:
11107 case CK_FloatingComplexToBoolean:
11108 case CK_IntegralComplexToBoolean: {
11110 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11112 uint64_t IntResult = BoolResult;
11113 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11114 IntResult = (uint64_t)-1;
11115 return Success(IntResult, E);
11118 case CK_FixedPointToIntegral: {
11119 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11120 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11123 llvm::APSInt Result = Src.convertToInt(
11124 Info.Ctx.getIntWidth(DestType),
11125 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11126 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11128 return Success(Result, E);
11131 case CK_FixedPointToBoolean: {
11132 // Unsigned padding does not affect this.
11134 if (!Evaluate(Val, Info, SubExpr))
11136 return Success(Val.getFixedPoint().getBoolValue(), E);
11139 case CK_IntegralCast: {
11140 if (!Visit(SubExpr))
11143 if (!Result.isInt()) {
11144 // Allow casts of address-of-label differences if they are no-ops
11145 // or narrowing. (The narrowing case isn't actually guaranteed to
11146 // be constant-evaluatable except in some narrow cases which are hard
11147 // to detect here. We let it through on the assumption the user knows
11148 // what they are doing.)
11149 if (Result.isAddrLabelDiff())
11150 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11151 // Only allow casts of lvalues if they are lossless.
11152 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11155 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11156 Result.getInt()), E);
11159 case CK_PointerToIntegral: {
11160 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11163 if (!EvaluatePointer(SubExpr, LV, Info))
11166 if (LV.getLValueBase()) {
11167 // Only allow based lvalue casts if they are lossless.
11168 // FIXME: Allow a larger integer size than the pointer size, and allow
11169 // narrowing back down to pointer width in subsequent integral casts.
11170 // FIXME: Check integer type's active bits, not its type size.
11171 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11174 LV.Designator.setInvalid();
11175 LV.moveInto(Result);
11182 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11183 llvm_unreachable("Can't cast this!");
11185 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11188 case CK_IntegralComplexToReal: {
11190 if (!EvaluateComplex(SubExpr, C, Info))
11192 return Success(C.getComplexIntReal(), E);
11195 case CK_FloatingToIntegral: {
11197 if (!EvaluateFloat(SubExpr, F, Info))
11201 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11203 return Success(Value, E);
11207 llvm_unreachable("unknown cast resulting in integral value");
11210 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11211 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11213 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11215 if (!LV.isComplexInt())
11217 return Success(LV.getComplexIntReal(), E);
11220 return Visit(E->getSubExpr());
11223 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11224 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11226 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11228 if (!LV.isComplexInt())
11230 return Success(LV.getComplexIntImag(), E);
11233 VisitIgnoredValue(E->getSubExpr());
11234 return Success(0, E);
11237 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11238 return Success(E->getPackLength(), E);
11241 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11242 return Success(E->getValue(), E);
11245 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11246 switch (E->getOpcode()) {
11248 // Invalid unary operators
11251 // The result is just the value.
11252 return Visit(E->getSubExpr());
11254 if (!Visit(E->getSubExpr())) return false;
11255 if (!Result.isFixedPoint())
11258 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11259 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11261 return Success(Negated, E);
11265 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11267 return Success(!bres, E);
11272 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11273 const Expr *SubExpr = E->getSubExpr();
11274 QualType DestType = E->getType();
11275 assert(DestType->isFixedPointType() &&
11276 "Expected destination type to be a fixed point type");
11277 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11279 switch (E->getCastKind()) {
11280 case CK_FixedPointCast: {
11281 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11282 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11285 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11286 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11288 return Success(Result, E);
11290 case CK_IntegralToFixedPoint: {
11292 if (!EvaluateInteger(SubExpr, Src, Info))
11296 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11297 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11299 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11302 return Success(IntResult, E);
11305 case CK_LValueToRValue:
11306 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11312 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11313 const Expr *LHS = E->getLHS();
11314 const Expr *RHS = E->getRHS();
11315 FixedPointSemantics ResultFXSema =
11316 Info.Ctx.getFixedPointSemantics(E->getType());
11318 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11319 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11321 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11322 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11325 switch (E->getOpcode()) {
11327 bool AddOverflow, ConversionOverflow;
11328 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11329 .convert(ResultFXSema, &ConversionOverflow);
11330 if ((AddOverflow || ConversionOverflow) &&
11331 !HandleOverflow(Info, E, Result, E->getType()))
11333 return Success(Result, E);
11338 llvm_unreachable("Should've exited before this");
11341 //===----------------------------------------------------------------------===//
11342 // Float Evaluation
11343 //===----------------------------------------------------------------------===//
11346 class FloatExprEvaluator
11347 : public ExprEvaluatorBase<FloatExprEvaluator> {
11350 FloatExprEvaluator(EvalInfo &info, APFloat &result)
11351 : ExprEvaluatorBaseTy(info), Result(result) {}
11353 bool Success(const APValue &V, const Expr *e) {
11354 Result = V.getFloat();
11358 bool ZeroInitialization(const Expr *E) {
11359 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11363 bool VisitCallExpr(const CallExpr *E);
11365 bool VisitUnaryOperator(const UnaryOperator *E);
11366 bool VisitBinaryOperator(const BinaryOperator *E);
11367 bool VisitFloatingLiteral(const FloatingLiteral *E);
11368 bool VisitCastExpr(const CastExpr *E);
11370 bool VisitUnaryReal(const UnaryOperator *E);
11371 bool VisitUnaryImag(const UnaryOperator *E);
11373 // FIXME: Missing: array subscript of vector, member of vector
11375 } // end anonymous namespace
11377 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
11378 assert(E->isRValue() && E->getType()->isRealFloatingType());
11379 return FloatExprEvaluator(Info, Result).Visit(E);
11382 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11386 llvm::APFloat &Result) {
11387 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11388 if (!S) return false;
11390 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11394 // Treat empty strings as if they were zero.
11395 if (S->getString().empty())
11396 fill = llvm::APInt(32, 0);
11397 else if (S->getString().getAsInteger(0, fill))
11400 if (Context.getTargetInfo().isNan2008()) {
11402 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11404 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11406 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11407 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11408 // a different encoding to what became a standard in 2008, and for pre-
11409 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11410 // sNaN. This is now known as "legacy NaN" encoding.
11412 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11414 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11420 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11421 switch (E->getBuiltinCallee()) {
11423 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11425 case Builtin::BI__builtin_huge_val:
11426 case Builtin::BI__builtin_huge_valf:
11427 case Builtin::BI__builtin_huge_vall:
11428 case Builtin::BI__builtin_huge_valf128:
11429 case Builtin::BI__builtin_inf:
11430 case Builtin::BI__builtin_inff:
11431 case Builtin::BI__builtin_infl:
11432 case Builtin::BI__builtin_inff128: {
11433 const llvm::fltSemantics &Sem =
11434 Info.Ctx.getFloatTypeSemantics(E->getType());
11435 Result = llvm::APFloat::getInf(Sem);
11439 case Builtin::BI__builtin_nans:
11440 case Builtin::BI__builtin_nansf:
11441 case Builtin::BI__builtin_nansl:
11442 case Builtin::BI__builtin_nansf128:
11443 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11448 case Builtin::BI__builtin_nan:
11449 case Builtin::BI__builtin_nanf:
11450 case Builtin::BI__builtin_nanl:
11451 case Builtin::BI__builtin_nanf128:
11452 // If this is __builtin_nan() turn this into a nan, otherwise we
11453 // can't constant fold it.
11454 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11459 case Builtin::BI__builtin_fabs:
11460 case Builtin::BI__builtin_fabsf:
11461 case Builtin::BI__builtin_fabsl:
11462 case Builtin::BI__builtin_fabsf128:
11463 if (!EvaluateFloat(E->getArg(0), Result, Info))
11466 if (Result.isNegative())
11467 Result.changeSign();
11470 // FIXME: Builtin::BI__builtin_powi
11471 // FIXME: Builtin::BI__builtin_powif
11472 // FIXME: Builtin::BI__builtin_powil
11474 case Builtin::BI__builtin_copysign:
11475 case Builtin::BI__builtin_copysignf:
11476 case Builtin::BI__builtin_copysignl:
11477 case Builtin::BI__builtin_copysignf128: {
11479 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11480 !EvaluateFloat(E->getArg(1), RHS, Info))
11482 Result.copySign(RHS);
11488 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11489 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11491 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11493 Result = CV.FloatReal;
11497 return Visit(E->getSubExpr());
11500 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11501 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11503 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11505 Result = CV.FloatImag;
11509 VisitIgnoredValue(E->getSubExpr());
11510 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11511 Result = llvm::APFloat::getZero(Sem);
11515 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11516 switch (E->getOpcode()) {
11517 default: return Error(E);
11519 return EvaluateFloat(E->getSubExpr(), Result, Info);
11521 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11523 Result.changeSign();
11528 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11529 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11530 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11533 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11534 if (!LHSOK && !Info.noteFailure())
11536 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11537 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11540 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11541 Result = E->getValue();
11545 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11546 const Expr* SubExpr = E->getSubExpr();
11548 switch (E->getCastKind()) {
11550 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11552 case CK_IntegralToFloating: {
11554 return EvaluateInteger(SubExpr, IntResult, Info) &&
11555 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11556 E->getType(), Result);
11559 case CK_FloatingCast: {
11560 if (!Visit(SubExpr))
11562 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11566 case CK_FloatingComplexToReal: {
11568 if (!EvaluateComplex(SubExpr, V, Info))
11570 Result = V.getComplexFloatReal();
11576 //===----------------------------------------------------------------------===//
11577 // Complex Evaluation (for float and integer)
11578 //===----------------------------------------------------------------------===//
11581 class ComplexExprEvaluator
11582 : public ExprEvaluatorBase<ComplexExprEvaluator> {
11583 ComplexValue &Result;
11586 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11587 : ExprEvaluatorBaseTy(info), Result(Result) {}
11589 bool Success(const APValue &V, const Expr *e) {
11594 bool ZeroInitialization(const Expr *E);
11596 //===--------------------------------------------------------------------===//
11598 //===--------------------------------------------------------------------===//
11600 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11601 bool VisitCastExpr(const CastExpr *E);
11602 bool VisitBinaryOperator(const BinaryOperator *E);
11603 bool VisitUnaryOperator(const UnaryOperator *E);
11604 bool VisitInitListExpr(const InitListExpr *E);
11606 } // end anonymous namespace
11608 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11610 assert(E->isRValue() && E->getType()->isAnyComplexType());
11611 return ComplexExprEvaluator(Info, Result).Visit(E);
11614 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11615 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11616 if (ElemTy->isRealFloatingType()) {
11617 Result.makeComplexFloat();
11618 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11619 Result.FloatReal = Zero;
11620 Result.FloatImag = Zero;
11622 Result.makeComplexInt();
11623 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11624 Result.IntReal = Zero;
11625 Result.IntImag = Zero;
11630 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11631 const Expr* SubExpr = E->getSubExpr();
11633 if (SubExpr->getType()->isRealFloatingType()) {
11634 Result.makeComplexFloat();
11635 APFloat &Imag = Result.FloatImag;
11636 if (!EvaluateFloat(SubExpr, Imag, Info))
11639 Result.FloatReal = APFloat(Imag.getSemantics());
11642 assert(SubExpr->getType()->isIntegerType() &&
11643 "Unexpected imaginary literal.");
11645 Result.makeComplexInt();
11646 APSInt &Imag = Result.IntImag;
11647 if (!EvaluateInteger(SubExpr, Imag, Info))
11650 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11655 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11657 switch (E->getCastKind()) {
11659 case CK_BaseToDerived:
11660 case CK_DerivedToBase:
11661 case CK_UncheckedDerivedToBase:
11664 case CK_ArrayToPointerDecay:
11665 case CK_FunctionToPointerDecay:
11666 case CK_NullToPointer:
11667 case CK_NullToMemberPointer:
11668 case CK_BaseToDerivedMemberPointer:
11669 case CK_DerivedToBaseMemberPointer:
11670 case CK_MemberPointerToBoolean:
11671 case CK_ReinterpretMemberPointer:
11672 case CK_ConstructorConversion:
11673 case CK_IntegralToPointer:
11674 case CK_PointerToIntegral:
11675 case CK_PointerToBoolean:
11677 case CK_VectorSplat:
11678 case CK_IntegralCast:
11679 case CK_BooleanToSignedIntegral:
11680 case CK_IntegralToBoolean:
11681 case CK_IntegralToFloating:
11682 case CK_FloatingToIntegral:
11683 case CK_FloatingToBoolean:
11684 case CK_FloatingCast:
11685 case CK_CPointerToObjCPointerCast:
11686 case CK_BlockPointerToObjCPointerCast:
11687 case CK_AnyPointerToBlockPointerCast:
11688 case CK_ObjCObjectLValueCast:
11689 case CK_FloatingComplexToReal:
11690 case CK_FloatingComplexToBoolean:
11691 case CK_IntegralComplexToReal:
11692 case CK_IntegralComplexToBoolean:
11693 case CK_ARCProduceObject:
11694 case CK_ARCConsumeObject:
11695 case CK_ARCReclaimReturnedObject:
11696 case CK_ARCExtendBlockObject:
11697 case CK_CopyAndAutoreleaseBlockObject:
11698 case CK_BuiltinFnToFnPtr:
11699 case CK_ZeroToOCLOpaqueType:
11700 case CK_NonAtomicToAtomic:
11701 case CK_AddressSpaceConversion:
11702 case CK_IntToOCLSampler:
11703 case CK_FixedPointCast:
11704 case CK_FixedPointToBoolean:
11705 case CK_FixedPointToIntegral:
11706 case CK_IntegralToFixedPoint:
11707 llvm_unreachable("invalid cast kind for complex value");
11709 case CK_LValueToRValue:
11710 case CK_AtomicToNonAtomic:
11712 case CK_LValueToRValueBitCast:
11713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11716 case CK_LValueBitCast:
11717 case CK_UserDefinedConversion:
11720 case CK_FloatingRealToComplex: {
11721 APFloat &Real = Result.FloatReal;
11722 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11725 Result.makeComplexFloat();
11726 Result.FloatImag = APFloat(Real.getSemantics());
11730 case CK_FloatingComplexCast: {
11731 if (!Visit(E->getSubExpr()))
11734 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11736 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11738 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11739 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11742 case CK_FloatingComplexToIntegralComplex: {
11743 if (!Visit(E->getSubExpr()))
11746 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11748 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11749 Result.makeComplexInt();
11750 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11751 To, Result.IntReal) &&
11752 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11753 To, Result.IntImag);
11756 case CK_IntegralRealToComplex: {
11757 APSInt &Real = Result.IntReal;
11758 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11761 Result.makeComplexInt();
11762 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11766 case CK_IntegralComplexCast: {
11767 if (!Visit(E->getSubExpr()))
11770 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11772 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11774 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11775 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11779 case CK_IntegralComplexToFloatingComplex: {
11780 if (!Visit(E->getSubExpr()))
11783 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11785 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11786 Result.makeComplexFloat();
11787 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11788 To, Result.FloatReal) &&
11789 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11790 To, Result.FloatImag);
11794 llvm_unreachable("unknown cast resulting in complex value");
11797 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11798 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11799 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11801 // Track whether the LHS or RHS is real at the type system level. When this is
11802 // the case we can simplify our evaluation strategy.
11803 bool LHSReal = false, RHSReal = false;
11806 if (E->getLHS()->getType()->isRealFloatingType()) {
11808 APFloat &Real = Result.FloatReal;
11809 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11811 Result.makeComplexFloat();
11812 Result.FloatImag = APFloat(Real.getSemantics());
11815 LHSOK = Visit(E->getLHS());
11817 if (!LHSOK && !Info.noteFailure())
11821 if (E->getRHS()->getType()->isRealFloatingType()) {
11823 APFloat &Real = RHS.FloatReal;
11824 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11826 RHS.makeComplexFloat();
11827 RHS.FloatImag = APFloat(Real.getSemantics());
11828 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11831 assert(!(LHSReal && RHSReal) &&
11832 "Cannot have both operands of a complex operation be real.");
11833 switch (E->getOpcode()) {
11834 default: return Error(E);
11836 if (Result.isComplexFloat()) {
11837 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11838 APFloat::rmNearestTiesToEven);
11840 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11842 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11843 APFloat::rmNearestTiesToEven);
11845 Result.getComplexIntReal() += RHS.getComplexIntReal();
11846 Result.getComplexIntImag() += RHS.getComplexIntImag();
11850 if (Result.isComplexFloat()) {
11851 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11852 APFloat::rmNearestTiesToEven);
11854 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11855 Result.getComplexFloatImag().changeSign();
11856 } else if (!RHSReal) {
11857 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11858 APFloat::rmNearestTiesToEven);
11861 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11862 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11866 if (Result.isComplexFloat()) {
11867 // This is an implementation of complex multiplication according to the
11868 // constraints laid out in C11 Annex G. The implementation uses the
11869 // following naming scheme:
11870 // (a + ib) * (c + id)
11871 ComplexValue LHS = Result;
11872 APFloat &A = LHS.getComplexFloatReal();
11873 APFloat &B = LHS.getComplexFloatImag();
11874 APFloat &C = RHS.getComplexFloatReal();
11875 APFloat &D = RHS.getComplexFloatImag();
11876 APFloat &ResR = Result.getComplexFloatReal();
11877 APFloat &ResI = Result.getComplexFloatImag();
11879 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11882 } else if (RHSReal) {
11886 // In the fully general case, we need to handle NaNs and infinities
11888 APFloat AC = A * C;
11889 APFloat BD = B * D;
11890 APFloat AD = A * D;
11891 APFloat BC = B * C;
11894 if (ResR.isNaN() && ResI.isNaN()) {
11895 bool Recalc = false;
11896 if (A.isInfinity() || B.isInfinity()) {
11897 A = APFloat::copySign(
11898 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11899 B = APFloat::copySign(
11900 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11902 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11904 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11907 if (C.isInfinity() || D.isInfinity()) {
11908 C = APFloat::copySign(
11909 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11910 D = APFloat::copySign(
11911 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11913 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11915 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11918 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11919 AD.isInfinity() || BC.isInfinity())) {
11921 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11923 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11925 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11927 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11931 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11932 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11937 ComplexValue LHS = Result;
11938 Result.getComplexIntReal() =
11939 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11940 LHS.getComplexIntImag() * RHS.getComplexIntImag());
11941 Result.getComplexIntImag() =
11942 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11943 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11947 if (Result.isComplexFloat()) {
11948 // This is an implementation of complex division according to the
11949 // constraints laid out in C11 Annex G. The implementation uses the
11950 // following naming scheme:
11951 // (a + ib) / (c + id)
11952 ComplexValue LHS = Result;
11953 APFloat &A = LHS.getComplexFloatReal();
11954 APFloat &B = LHS.getComplexFloatImag();
11955 APFloat &C = RHS.getComplexFloatReal();
11956 APFloat &D = RHS.getComplexFloatImag();
11957 APFloat &ResR = Result.getComplexFloatReal();
11958 APFloat &ResI = Result.getComplexFloatImag();
11964 // No real optimizations we can do here, stub out with zero.
11965 B = APFloat::getZero(A.getSemantics());
11968 APFloat MaxCD = maxnum(abs(C), abs(D));
11969 if (MaxCD.isFinite()) {
11970 DenomLogB = ilogb(MaxCD);
11971 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11972 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11974 APFloat Denom = C * C + D * D;
11975 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11976 APFloat::rmNearestTiesToEven);
11977 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11978 APFloat::rmNearestTiesToEven);
11979 if (ResR.isNaN() && ResI.isNaN()) {
11980 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11981 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11982 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11983 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11985 A = APFloat::copySign(
11986 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11987 B = APFloat::copySign(
11988 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11989 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11990 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11991 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11992 C = APFloat::copySign(
11993 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11994 D = APFloat::copySign(
11995 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11996 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11997 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
12002 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
12003 return Error(E, diag::note_expr_divide_by_zero);
12005 ComplexValue LHS = Result;
12006 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
12007 RHS.getComplexIntImag() * RHS.getComplexIntImag();
12008 Result.getComplexIntReal() =
12009 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
12010 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
12011 Result.getComplexIntImag() =
12012 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
12013 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12021 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12022 // Get the operand value into 'Result'.
12023 if (!Visit(E->getSubExpr()))
12026 switch (E->getOpcode()) {
12032 // The result is always just the subexpr.
12035 if (Result.isComplexFloat()) {
12036 Result.getComplexFloatReal().changeSign();
12037 Result.getComplexFloatImag().changeSign();
12040 Result.getComplexIntReal() = -Result.getComplexIntReal();
12041 Result.getComplexIntImag() = -Result.getComplexIntImag();
12045 if (Result.isComplexFloat())
12046 Result.getComplexFloatImag().changeSign();
12048 Result.getComplexIntImag() = -Result.getComplexIntImag();
12053 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12054 if (E->getNumInits() == 2) {
12055 if (E->getType()->isComplexType()) {
12056 Result.makeComplexFloat();
12057 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12059 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12062 Result.makeComplexInt();
12063 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12065 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12070 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12073 //===----------------------------------------------------------------------===//
12074 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12075 // implicit conversion.
12076 //===----------------------------------------------------------------------===//
12079 class AtomicExprEvaluator :
12080 public ExprEvaluatorBase<AtomicExprEvaluator> {
12081 const LValue *This;
12084 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12085 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12087 bool Success(const APValue &V, const Expr *E) {
12092 bool ZeroInitialization(const Expr *E) {
12093 ImplicitValueInitExpr VIE(
12094 E->getType()->castAs<AtomicType>()->getValueType());
12095 // For atomic-qualified class (and array) types in C++, initialize the
12096 // _Atomic-wrapped subobject directly, in-place.
12097 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12098 : Evaluate(Result, Info, &VIE);
12101 bool VisitCastExpr(const CastExpr *E) {
12102 switch (E->getCastKind()) {
12104 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12105 case CK_NonAtomicToAtomic:
12106 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12107 : Evaluate(Result, Info, E->getSubExpr());
12111 } // end anonymous namespace
12113 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12115 assert(E->isRValue() && E->getType()->isAtomicType());
12116 return AtomicExprEvaluator(Info, This, Result).Visit(E);
12119 //===----------------------------------------------------------------------===//
12120 // Void expression evaluation, primarily for a cast to void on the LHS of a
12122 //===----------------------------------------------------------------------===//
12125 class VoidExprEvaluator
12126 : public ExprEvaluatorBase<VoidExprEvaluator> {
12128 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12130 bool Success(const APValue &V, const Expr *e) { return true; }
12132 bool ZeroInitialization(const Expr *E) { return true; }
12134 bool VisitCastExpr(const CastExpr *E) {
12135 switch (E->getCastKind()) {
12137 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12139 VisitIgnoredValue(E->getSubExpr());
12144 bool VisitCallExpr(const CallExpr *E) {
12145 switch (E->getBuiltinCallee()) {
12147 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12148 case Builtin::BI__assume:
12149 case Builtin::BI__builtin_assume:
12150 // The argument is not evaluated!
12155 } // end anonymous namespace
12157 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12158 assert(E->isRValue() && E->getType()->isVoidType());
12159 return VoidExprEvaluator(Info).Visit(E);
12162 //===----------------------------------------------------------------------===//
12163 // Top level Expr::EvaluateAsRValue method.
12164 //===----------------------------------------------------------------------===//
12166 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12167 // In C, function designators are not lvalues, but we evaluate them as if they
12169 QualType T = E->getType();
12170 if (E->isGLValue() || T->isFunctionType()) {
12172 if (!EvaluateLValue(E, LV, Info))
12174 LV.moveInto(Result);
12175 } else if (T->isVectorType()) {
12176 if (!EvaluateVector(E, Result, Info))
12178 } else if (T->isIntegralOrEnumerationType()) {
12179 if (!IntExprEvaluator(Info, Result).Visit(E))
12181 } else if (T->hasPointerRepresentation()) {
12183 if (!EvaluatePointer(E, LV, Info))
12185 LV.moveInto(Result);
12186 } else if (T->isRealFloatingType()) {
12187 llvm::APFloat F(0.0);
12188 if (!EvaluateFloat(E, F, Info))
12190 Result = APValue(F);
12191 } else if (T->isAnyComplexType()) {
12193 if (!EvaluateComplex(E, C, Info))
12195 C.moveInto(Result);
12196 } else if (T->isFixedPointType()) {
12197 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12198 } else if (T->isMemberPointerType()) {
12200 if (!EvaluateMemberPointer(E, P, Info))
12202 P.moveInto(Result);
12204 } else if (T->isArrayType()) {
12206 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12207 if (!EvaluateArray(E, LV, Value, Info))
12210 } else if (T->isRecordType()) {
12212 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12213 if (!EvaluateRecord(E, LV, Value, Info))
12216 } else if (T->isVoidType()) {
12217 if (!Info.getLangOpts().CPlusPlus11)
12218 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
12220 if (!EvaluateVoid(E, Info))
12222 } else if (T->isAtomicType()) {
12223 QualType Unqual = T.getAtomicUnqualifiedType();
12224 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12226 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12227 if (!EvaluateAtomic(E, &LV, Value, Info))
12230 if (!EvaluateAtomic(E, nullptr, Result, Info))
12233 } else if (Info.getLangOpts().CPlusPlus11) {
12234 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
12237 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12244 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12245 /// cases, the in-place evaluation is essential, since later initializers for
12246 /// an object can indirectly refer to subobjects which were initialized earlier.
12247 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
12248 const Expr *E, bool AllowNonLiteralTypes) {
12249 assert(!E->isValueDependent());
12251 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
12254 if (E->isRValue()) {
12255 // Evaluate arrays and record types in-place, so that later initializers can
12256 // refer to earlier-initialized members of the object.
12257 QualType T = E->getType();
12258 if (T->isArrayType())
12259 return EvaluateArray(E, This, Result, Info);
12260 else if (T->isRecordType())
12261 return EvaluateRecord(E, This, Result, Info);
12262 else if (T->isAtomicType()) {
12263 QualType Unqual = T.getAtomicUnqualifiedType();
12264 if (Unqual->isArrayType() || Unqual->isRecordType())
12265 return EvaluateAtomic(E, &This, Result, Info);
12269 // For any other type, in-place evaluation is unimportant.
12270 return Evaluate(Result, Info, E);
12273 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12274 /// lvalue-to-rvalue cast if it is an lvalue.
12275 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
12276 if (E->getType().isNull())
12279 if (!CheckLiteralType(Info, E))
12282 if (!::Evaluate(Result, Info, E))
12285 if (E->isGLValue()) {
12287 LV.setFrom(Info.Ctx, Result);
12288 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12292 // Check this core constant expression is a constant expression.
12293 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12296 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
12297 const ASTContext &Ctx, bool &IsConst) {
12298 // Fast-path evaluations of integer literals, since we sometimes see files
12299 // containing vast quantities of these.
12300 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12301 Result.Val = APValue(APSInt(L->getValue(),
12302 L->getType()->isUnsignedIntegerType()));
12307 // This case should be rare, but we need to check it before we check on
12309 if (Exp->getType().isNull()) {
12314 // FIXME: Evaluating values of large array and record types can cause
12315 // performance problems. Only do so in C++11 for now.
12316 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12317 Exp->getType()->isRecordType()) &&
12318 !Ctx.getLangOpts().CPlusPlus11) {
12325 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12326 Expr::SideEffectsKind SEK) {
12327 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12328 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12331 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12332 const ASTContext &Ctx, EvalInfo &Info) {
12334 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12337 return EvaluateAsRValue(Info, E, Result.Val);
12340 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12341 const ASTContext &Ctx,
12342 Expr::SideEffectsKind AllowSideEffects,
12344 if (!E->getType()->isIntegralOrEnumerationType())
12347 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12348 !ExprResult.Val.isInt() ||
12349 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12355 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12356 const ASTContext &Ctx,
12357 Expr::SideEffectsKind AllowSideEffects,
12359 if (!E->getType()->isFixedPointType())
12362 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12365 if (!ExprResult.Val.isFixedPoint() ||
12366 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12372 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
12373 /// any crazy technique (that has nothing to do with language standards) that
12374 /// we want to. If this function returns true, it returns the folded constant
12375 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12376 /// will be applied to the result.
12377 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12378 bool InConstantContext) const {
12379 assert(!isValueDependent() &&
12380 "Expression evaluator can't be called on a dependent expression.");
12381 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12382 Info.InConstantContext = InConstantContext;
12383 return ::EvaluateAsRValue(this, Result, Ctx, Info);
12386 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12387 bool InConstantContext) const {
12388 assert(!isValueDependent() &&
12389 "Expression evaluator can't be called on a dependent expression.");
12390 EvalResult Scratch;
12391 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
12392 HandleConversionToBool(Scratch.Val, Result);
12395 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12396 SideEffectsKind AllowSideEffects,
12397 bool InConstantContext) const {
12398 assert(!isValueDependent() &&
12399 "Expression evaluator can't be called on a dependent expression.");
12400 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12401 Info.InConstantContext = InConstantContext;
12402 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12405 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
12406 SideEffectsKind AllowSideEffects,
12407 bool InConstantContext) const {
12408 assert(!isValueDependent() &&
12409 "Expression evaluator can't be called on a dependent expression.");
12410 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12411 Info.InConstantContext = InConstantContext;
12412 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12415 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12416 SideEffectsKind AllowSideEffects,
12417 bool InConstantContext) const {
12418 assert(!isValueDependent() &&
12419 "Expression evaluator can't be called on a dependent expression.");
12421 if (!getType()->isRealFloatingType())
12424 EvalResult ExprResult;
12425 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12426 !ExprResult.Val.isFloat() ||
12427 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12430 Result = ExprResult.Val.getFloat();
12434 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12435 bool InConstantContext) const {
12436 assert(!isValueDependent() &&
12437 "Expression evaluator can't be called on a dependent expression.");
12439 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12440 Info.InConstantContext = InConstantContext;
12442 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12443 !CheckLValueConstantExpression(Info, getExprLoc(),
12444 Ctx.getLValueReferenceType(getType()), LV,
12445 Expr::EvaluateForCodeGen))
12448 LV.moveInto(Result.Val);
12452 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12453 const ASTContext &Ctx) const {
12454 assert(!isValueDependent() &&
12455 "Expression evaluator can't be called on a dependent expression.");
12457 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12458 EvalInfo Info(Ctx, Result, EM);
12459 Info.InConstantContext = true;
12461 if (!::Evaluate(Result.Val, Info, this))
12464 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12468 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12470 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12471 assert(!isValueDependent() &&
12472 "Expression evaluator can't be called on a dependent expression.");
12474 // FIXME: Evaluating initializers for large array and record types can cause
12475 // performance problems. Only do so in C++11 for now.
12476 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12477 !Ctx.getLangOpts().CPlusPlus11)
12480 Expr::EvalStatus EStatus;
12481 EStatus.Diag = &Notes;
12483 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12484 ? EvalInfo::EM_ConstantExpression
12485 : EvalInfo::EM_ConstantFold);
12486 InitInfo.setEvaluatingDecl(VD, Value);
12487 InitInfo.InConstantContext = true;
12492 // C++11 [basic.start.init]p2:
12493 // Variables with static storage duration or thread storage duration shall be
12494 // zero-initialized before any other initialization takes place.
12495 // This behavior is not present in C.
12496 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12497 !VD->getType()->isReferenceType()) {
12498 ImplicitValueInitExpr VIE(VD->getType());
12499 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12500 /*AllowNonLiteralTypes=*/true))
12504 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12505 /*AllowNonLiteralTypes=*/true) ||
12506 EStatus.HasSideEffects)
12509 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12513 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12514 /// constant folded, but discard the result.
12515 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12516 assert(!isValueDependent() &&
12517 "Expression evaluator can't be called on a dependent expression.");
12520 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12521 !hasUnacceptableSideEffect(Result, SEK);
12524 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12525 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12526 assert(!isValueDependent() &&
12527 "Expression evaluator can't be called on a dependent expression.");
12529 EvalResult EVResult;
12530 EVResult.Diag = Diag;
12531 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12532 Info.InConstantContext = true;
12534 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12536 assert(Result && "Could not evaluate expression");
12537 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12539 return EVResult.Val.getInt();
12542 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12543 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12544 assert(!isValueDependent() &&
12545 "Expression evaluator can't be called on a dependent expression.");
12547 EvalResult EVResult;
12548 EVResult.Diag = Diag;
12549 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12550 Info.InConstantContext = true;
12552 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12554 assert(Result && "Could not evaluate expression");
12555 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12557 return EVResult.Val.getInt();
12560 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12561 assert(!isValueDependent() &&
12562 "Expression evaluator can't be called on a dependent expression.");
12565 EvalResult EVResult;
12566 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12567 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
12568 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12572 bool Expr::EvalResult::isGlobalLValue() const {
12573 assert(Val.isLValue());
12574 return IsGlobalLValue(Val.getLValueBase());
12578 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12579 /// an integer constant expression.
12581 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12584 // CheckICE - This function does the fundamental ICE checking: the returned
12585 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12586 // and a (possibly null) SourceLocation indicating the location of the problem.
12588 // Note that to reduce code duplication, this helper does no evaluation
12589 // itself; the caller checks whether the expression is evaluatable, and
12590 // in the rare cases where CheckICE actually cares about the evaluated
12591 // value, it calls into Evaluate.
12596 /// This expression is an ICE.
12598 /// This expression is not an ICE, but if it isn't evaluated, it's
12599 /// a legal subexpression for an ICE. This return value is used to handle
12600 /// the comma operator in C99 mode, and non-constant subexpressions.
12601 IK_ICEIfUnevaluated,
12602 /// This expression is not an ICE, and is not a legal subexpression for one.
12608 SourceLocation Loc;
12610 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12615 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12617 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12619 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12620 Expr::EvalResult EVResult;
12621 Expr::EvalStatus Status;
12622 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12624 Info.InConstantContext = true;
12625 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12626 !EVResult.Val.isInt())
12627 return ICEDiag(IK_NotICE, E->getBeginLoc());
12632 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12633 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12634 if (!E->getType()->isIntegralOrEnumerationType())
12635 return ICEDiag(IK_NotICE, E->getBeginLoc());
12637 switch (E->getStmtClass()) {
12638 #define ABSTRACT_STMT(Node)
12639 #define STMT(Node, Base) case Expr::Node##Class:
12640 #define EXPR(Node, Base)
12641 #include "clang/AST/StmtNodes.inc"
12642 case Expr::PredefinedExprClass:
12643 case Expr::FloatingLiteralClass:
12644 case Expr::ImaginaryLiteralClass:
12645 case Expr::StringLiteralClass:
12646 case Expr::ArraySubscriptExprClass:
12647 case Expr::OMPArraySectionExprClass:
12648 case Expr::MemberExprClass:
12649 case Expr::CompoundAssignOperatorClass:
12650 case Expr::CompoundLiteralExprClass:
12651 case Expr::ExtVectorElementExprClass:
12652 case Expr::DesignatedInitExprClass:
12653 case Expr::ArrayInitLoopExprClass:
12654 case Expr::ArrayInitIndexExprClass:
12655 case Expr::NoInitExprClass:
12656 case Expr::DesignatedInitUpdateExprClass:
12657 case Expr::ImplicitValueInitExprClass:
12658 case Expr::ParenListExprClass:
12659 case Expr::VAArgExprClass:
12660 case Expr::AddrLabelExprClass:
12661 case Expr::StmtExprClass:
12662 case Expr::CXXMemberCallExprClass:
12663 case Expr::CUDAKernelCallExprClass:
12664 case Expr::CXXDynamicCastExprClass:
12665 case Expr::CXXTypeidExprClass:
12666 case Expr::CXXUuidofExprClass:
12667 case Expr::MSPropertyRefExprClass:
12668 case Expr::MSPropertySubscriptExprClass:
12669 case Expr::CXXNullPtrLiteralExprClass:
12670 case Expr::UserDefinedLiteralClass:
12671 case Expr::CXXThisExprClass:
12672 case Expr::CXXThrowExprClass:
12673 case Expr::CXXNewExprClass:
12674 case Expr::CXXDeleteExprClass:
12675 case Expr::CXXPseudoDestructorExprClass:
12676 case Expr::UnresolvedLookupExprClass:
12677 case Expr::TypoExprClass:
12678 case Expr::DependentScopeDeclRefExprClass:
12679 case Expr::CXXConstructExprClass:
12680 case Expr::CXXInheritedCtorInitExprClass:
12681 case Expr::CXXStdInitializerListExprClass:
12682 case Expr::CXXBindTemporaryExprClass:
12683 case Expr::ExprWithCleanupsClass:
12684 case Expr::CXXTemporaryObjectExprClass:
12685 case Expr::CXXUnresolvedConstructExprClass:
12686 case Expr::CXXDependentScopeMemberExprClass:
12687 case Expr::UnresolvedMemberExprClass:
12688 case Expr::ObjCStringLiteralClass:
12689 case Expr::ObjCBoxedExprClass:
12690 case Expr::ObjCArrayLiteralClass:
12691 case Expr::ObjCDictionaryLiteralClass:
12692 case Expr::ObjCEncodeExprClass:
12693 case Expr::ObjCMessageExprClass:
12694 case Expr::ObjCSelectorExprClass:
12695 case Expr::ObjCProtocolExprClass:
12696 case Expr::ObjCIvarRefExprClass:
12697 case Expr::ObjCPropertyRefExprClass:
12698 case Expr::ObjCSubscriptRefExprClass:
12699 case Expr::ObjCIsaExprClass:
12700 case Expr::ObjCAvailabilityCheckExprClass:
12701 case Expr::ShuffleVectorExprClass:
12702 case Expr::ConvertVectorExprClass:
12703 case Expr::BlockExprClass:
12704 case Expr::NoStmtClass:
12705 case Expr::OpaqueValueExprClass:
12706 case Expr::PackExpansionExprClass:
12707 case Expr::SubstNonTypeTemplateParmPackExprClass:
12708 case Expr::FunctionParmPackExprClass:
12709 case Expr::AsTypeExprClass:
12710 case Expr::ObjCIndirectCopyRestoreExprClass:
12711 case Expr::MaterializeTemporaryExprClass:
12712 case Expr::PseudoObjectExprClass:
12713 case Expr::AtomicExprClass:
12714 case Expr::LambdaExprClass:
12715 case Expr::CXXFoldExprClass:
12716 case Expr::CoawaitExprClass:
12717 case Expr::DependentCoawaitExprClass:
12718 case Expr::CoyieldExprClass:
12719 return ICEDiag(IK_NotICE, E->getBeginLoc());
12721 case Expr::InitListExprClass: {
12722 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12723 // form "T x = { a };" is equivalent to "T x = a;".
12724 // Unless we're initializing a reference, T is a scalar as it is known to be
12725 // of integral or enumeration type.
12727 if (cast<InitListExpr>(E)->getNumInits() == 1)
12728 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12729 return ICEDiag(IK_NotICE, E->getBeginLoc());
12732 case Expr::SizeOfPackExprClass:
12733 case Expr::GNUNullExprClass:
12734 case Expr::SourceLocExprClass:
12737 case Expr::SubstNonTypeTemplateParmExprClass:
12739 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12741 case Expr::ConstantExprClass:
12742 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12744 case Expr::ParenExprClass:
12745 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12746 case Expr::GenericSelectionExprClass:
12747 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12748 case Expr::IntegerLiteralClass:
12749 case Expr::FixedPointLiteralClass:
12750 case Expr::CharacterLiteralClass:
12751 case Expr::ObjCBoolLiteralExprClass:
12752 case Expr::CXXBoolLiteralExprClass:
12753 case Expr::CXXScalarValueInitExprClass:
12754 case Expr::TypeTraitExprClass:
12755 case Expr::ArrayTypeTraitExprClass:
12756 case Expr::ExpressionTraitExprClass:
12757 case Expr::CXXNoexceptExprClass:
12759 case Expr::CallExprClass:
12760 case Expr::CXXOperatorCallExprClass: {
12761 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12762 // constant expressions, but they can never be ICEs because an ICE cannot
12763 // contain an operand of (pointer to) function type.
12764 const CallExpr *CE = cast<CallExpr>(E);
12765 if (CE->getBuiltinCallee())
12766 return CheckEvalInICE(E, Ctx);
12767 return ICEDiag(IK_NotICE, E->getBeginLoc());
12769 case Expr::DeclRefExprClass: {
12770 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12772 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12773 if (Ctx.getLangOpts().CPlusPlus &&
12774 D && IsConstNonVolatile(D->getType())) {
12775 // Parameter variables are never constants. Without this check,
12776 // getAnyInitializer() can find a default argument, which leads
12778 if (isa<ParmVarDecl>(D))
12779 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12782 // A variable of non-volatile const-qualified integral or enumeration
12783 // type initialized by an ICE can be used in ICEs.
12784 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12785 if (!Dcl->getType()->isIntegralOrEnumerationType())
12786 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12789 // Look for a declaration of this variable that has an initializer, and
12790 // check whether it is an ICE.
12791 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12794 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12797 return ICEDiag(IK_NotICE, E->getBeginLoc());
12799 case Expr::UnaryOperatorClass: {
12800 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12801 switch (Exp->getOpcode()) {
12809 // C99 6.6/3 allows increment and decrement within unevaluated
12810 // subexpressions of constant expressions, but they can never be ICEs
12811 // because an ICE cannot contain an lvalue operand.
12812 return ICEDiag(IK_NotICE, E->getBeginLoc());
12820 return CheckICE(Exp->getSubExpr(), Ctx);
12822 llvm_unreachable("invalid unary operator class");
12824 case Expr::OffsetOfExprClass: {
12825 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12826 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12827 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12828 // compliance: we should warn earlier for offsetof expressions with
12829 // array subscripts that aren't ICEs, and if the array subscripts
12830 // are ICEs, the value of the offsetof must be an integer constant.
12831 return CheckEvalInICE(E, Ctx);
12833 case Expr::UnaryExprOrTypeTraitExprClass: {
12834 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12835 if ((Exp->getKind() == UETT_SizeOf) &&
12836 Exp->getTypeOfArgument()->isVariableArrayType())
12837 return ICEDiag(IK_NotICE, E->getBeginLoc());
12840 case Expr::BinaryOperatorClass: {
12841 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12842 switch (Exp->getOpcode()) {
12856 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12857 // constant expressions, but they can never be ICEs because an ICE cannot
12858 // contain an lvalue operand.
12859 return ICEDiag(IK_NotICE, E->getBeginLoc());
12879 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12880 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12881 if (Exp->getOpcode() == BO_Div ||
12882 Exp->getOpcode() == BO_Rem) {
12883 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12884 // we don't evaluate one.
12885 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12886 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12888 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12889 if (REval.isSigned() && REval.isAllOnesValue()) {
12890 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12891 if (LEval.isMinSignedValue())
12892 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12896 if (Exp->getOpcode() == BO_Comma) {
12897 if (Ctx.getLangOpts().C99) {
12898 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12899 // if it isn't evaluated.
12900 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12901 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12903 // In both C89 and C++, commas in ICEs are illegal.
12904 return ICEDiag(IK_NotICE, E->getBeginLoc());
12907 return Worst(LHSResult, RHSResult);
12911 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12912 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12913 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12914 // Rare case where the RHS has a comma "side-effect"; we need
12915 // to actually check the condition to see whether the side
12916 // with the comma is evaluated.
12917 if ((Exp->getOpcode() == BO_LAnd) !=
12918 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12923 return Worst(LHSResult, RHSResult);
12926 llvm_unreachable("invalid binary operator kind");
12928 case Expr::ImplicitCastExprClass:
12929 case Expr::CStyleCastExprClass:
12930 case Expr::CXXFunctionalCastExprClass:
12931 case Expr::CXXStaticCastExprClass:
12932 case Expr::CXXReinterpretCastExprClass:
12933 case Expr::CXXConstCastExprClass:
12934 case Expr::ObjCBridgedCastExprClass: {
12935 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12936 if (isa<ExplicitCastExpr>(E)) {
12937 if (const FloatingLiteral *FL
12938 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12939 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12940 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12941 APSInt IgnoredVal(DestWidth, !DestSigned);
12943 // If the value does not fit in the destination type, the behavior is
12944 // undefined, so we are not required to treat it as a constant
12946 if (FL->getValue().convertToInteger(IgnoredVal,
12947 llvm::APFloat::rmTowardZero,
12948 &Ignored) & APFloat::opInvalidOp)
12949 return ICEDiag(IK_NotICE, E->getBeginLoc());
12953 switch (cast<CastExpr>(E)->getCastKind()) {
12954 case CK_LValueToRValue:
12955 case CK_AtomicToNonAtomic:
12956 case CK_NonAtomicToAtomic:
12958 case CK_IntegralToBoolean:
12959 case CK_IntegralCast:
12960 return CheckICE(SubExpr, Ctx);
12962 return ICEDiag(IK_NotICE, E->getBeginLoc());
12965 case Expr::BinaryConditionalOperatorClass: {
12966 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12967 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12968 if (CommonResult.Kind == IK_NotICE) return CommonResult;
12969 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12970 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12971 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12972 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12973 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12974 return FalseResult;
12976 case Expr::ConditionalOperatorClass: {
12977 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12978 // If the condition (ignoring parens) is a __builtin_constant_p call,
12979 // then only the true side is actually considered in an integer constant
12980 // expression, and it is fully evaluated. This is an important GNU
12981 // extension. See GCC PR38377 for discussion.
12982 if (const CallExpr *CallCE
12983 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12984 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12985 return CheckEvalInICE(E, Ctx);
12986 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12987 if (CondResult.Kind == IK_NotICE)
12990 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12991 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12993 if (TrueResult.Kind == IK_NotICE)
12995 if (FalseResult.Kind == IK_NotICE)
12996 return FalseResult;
12997 if (CondResult.Kind == IK_ICEIfUnevaluated)
12999 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
13001 // Rare case where the diagnostics depend on which side is evaluated
13002 // Note that if we get here, CondResult is 0, and at least one of
13003 // TrueResult and FalseResult is non-zero.
13004 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
13005 return FalseResult;
13008 case Expr::CXXDefaultArgExprClass:
13009 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
13010 case Expr::CXXDefaultInitExprClass:
13011 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
13012 case Expr::ChooseExprClass: {
13013 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
13015 case Expr::BuiltinBitCastExprClass: {
13016 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13017 return ICEDiag(IK_NotICE, E->getBeginLoc());
13018 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13022 llvm_unreachable("Invalid StmtClass!");
13025 /// Evaluate an expression as a C++11 integral constant expression.
13026 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
13028 llvm::APSInt *Value,
13029 SourceLocation *Loc) {
13030 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13031 if (Loc) *Loc = E->getExprLoc();
13036 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
13039 if (!Result.isInt()) {
13040 if (Loc) *Loc = E->getExprLoc();
13044 if (Value) *Value = Result.getInt();
13048 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13049 SourceLocation *Loc) const {
13050 assert(!isValueDependent() &&
13051 "Expression evaluator can't be called on a dependent expression.");
13053 if (Ctx.getLangOpts().CPlusPlus11)
13054 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
13056 ICEDiag D = CheckICE(this, Ctx);
13057 if (D.Kind != IK_ICE) {
13058 if (Loc) *Loc = D.Loc;
13064 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
13065 SourceLocation *Loc, bool isEvaluated) const {
13066 assert(!isValueDependent() &&
13067 "Expression evaluator can't be called on a dependent expression.");
13069 if (Ctx.getLangOpts().CPlusPlus11)
13070 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13072 if (!isIntegerConstantExpr(Ctx, Loc))
13075 // The only possible side-effects here are due to UB discovered in the
13076 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13077 // required to treat the expression as an ICE, so we produce the folded
13079 EvalResult ExprResult;
13080 Expr::EvalStatus Status;
13081 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13082 Info.InConstantContext = true;
13084 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13085 llvm_unreachable("ICE cannot be evaluated!");
13087 Value = ExprResult.Val.getInt();
13091 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
13092 assert(!isValueDependent() &&
13093 "Expression evaluator can't be called on a dependent expression.");
13095 return CheckICE(this, Ctx).Kind == IK_ICE;
13098 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
13099 SourceLocation *Loc) const {
13100 assert(!isValueDependent() &&
13101 "Expression evaluator can't be called on a dependent expression.");
13103 // We support this checking in C++98 mode in order to diagnose compatibility
13105 assert(Ctx.getLangOpts().CPlusPlus);
13107 // Build evaluation settings.
13108 Expr::EvalStatus Status;
13109 SmallVector<PartialDiagnosticAt, 8> Diags;
13110 Status.Diag = &Diags;
13111 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13114 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13116 if (!Diags.empty()) {
13117 IsConstExpr = false;
13118 if (Loc) *Loc = Diags[0].first;
13119 } else if (!IsConstExpr) {
13120 // FIXME: This shouldn't happen.
13121 if (Loc) *Loc = getExprLoc();
13124 return IsConstExpr;
13127 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13128 const FunctionDecl *Callee,
13129 ArrayRef<const Expr*> Args,
13130 const Expr *This) const {
13131 assert(!isValueDependent() &&
13132 "Expression evaluator can't be called on a dependent expression.");
13134 Expr::EvalStatus Status;
13135 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
13136 Info.InConstantContext = true;
13139 const LValue *ThisPtr = nullptr;
13142 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13143 assert(MD && "Don't provide `this` for non-methods.");
13144 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13146 if (EvaluateObjectArgument(Info, This, ThisVal))
13147 ThisPtr = &ThisVal;
13148 if (Info.EvalStatus.HasSideEffects)
13152 ArgVector ArgValues(Args.size());
13153 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13155 if ((*I)->isValueDependent() ||
13156 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
13157 // If evaluation fails, throw away the argument entirely.
13158 ArgValues[I - Args.begin()] = APValue();
13159 if (Info.EvalStatus.HasSideEffects)
13163 // Build fake call to Callee.
13164 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
13166 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13169 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
13171 PartialDiagnosticAt> &Diags) {
13172 // FIXME: It would be useful to check constexpr function templates, but at the
13173 // moment the constant expression evaluator cannot cope with the non-rigorous
13174 // ASTs which we build for dependent expressions.
13175 if (FD->isDependentContext())
13178 Expr::EvalStatus Status;
13179 Status.Diag = &Diags;
13181 EvalInfo Info(FD->getASTContext(), Status,
13182 EvalInfo::EM_PotentialConstantExpression);
13183 Info.InConstantContext = true;
13185 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13186 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
13188 // Fabricate an arbitrary expression on the stack and pretend that it
13189 // is a temporary being used as the 'this' pointer.
13191 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
13192 This.set({&VIE, Info.CurrentCall->Index});
13194 ArrayRef<const Expr*> Args;
13197 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13198 // Evaluate the call as a constant initializer, to allow the construction
13199 // of objects of non-literal types.
13200 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
13201 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13203 SourceLocation Loc = FD->getLocation();
13204 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
13205 Args, FD->getBody(), Info, Scratch, nullptr);
13208 return Diags.empty();
13211 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13212 const FunctionDecl *FD,
13214 PartialDiagnosticAt> &Diags) {
13215 assert(!E->isValueDependent() &&
13216 "Expression evaluator can't be called on a dependent expression.");
13218 Expr::EvalStatus Status;
13219 Status.Diag = &Diags;
13221 EvalInfo Info(FD->getASTContext(), Status,
13222 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
13223 Info.InConstantContext = true;
13225 // Fabricate a call stack frame to give the arguments a plausible cover story.
13226 ArrayRef<const Expr*> Args;
13227 ArgVector ArgValues(0);
13228 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
13231 "Failed to set up arguments for potential constant evaluation");
13232 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
13234 APValue ResultScratch;
13235 Evaluate(ResultScratch, Info, E);
13236 return Diags.empty();
13239 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13240 unsigned Type) const {
13241 if (!getType()->isPointerType())
13244 Expr::EvalStatus Status;
13245 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
13246 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);