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 /// Whether we're checking that an expression is a potential constant
798 /// expression. If so, do not fail on constructs that could become constant
799 /// later on (such as a use of an undefined global).
800 bool CheckingPotentialConstantExpression = false;
802 /// Whether we're checking for an expression that has undefined behavior.
803 /// If so, we will produce warnings if we encounter an operation that is
804 /// always undefined.
805 bool CheckingForUndefinedBehavior = false;
807 enum EvaluationMode {
808 /// Evaluate as a constant expression. Stop if we find that the expression
809 /// is not a constant expression.
810 EM_ConstantExpression,
812 /// Evaluate as a constant expression. Stop if we find that the expression
813 /// is not a constant expression. Some expressions can be retried in the
814 /// optimizer if we don't constant fold them here, but in an unevaluated
815 /// context we try to fold them immediately since the optimizer never
816 /// gets a chance to look at it.
817 EM_ConstantExpressionUnevaluated,
819 /// Fold the expression to a constant. Stop if we hit a side-effect that
823 /// Evaluate in any way we know how. Don't worry about side-effects that
824 /// can't be modeled.
825 EM_IgnoreSideEffects,
828 /// Are we checking whether the expression is a potential constant
830 bool checkingPotentialConstantExpression() const {
831 return CheckingPotentialConstantExpression;
834 /// Are we checking an expression for overflow?
835 // FIXME: We should check for any kind of undefined or suspicious behavior
836 // in such constructs, not just overflow.
837 bool checkingForUndefinedBehavior() { return CheckingForUndefinedBehavior; }
839 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
840 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
841 CallStackDepth(0), NextCallIndex(1),
842 StepsLeft(getLangOpts().ConstexprStepLimit),
843 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
844 EvaluatingDecl((const ValueDecl *)nullptr),
845 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
846 HasFoldFailureDiagnostic(false),
847 InConstantContext(false), EvalMode(Mode) {}
849 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
850 EvaluatingDecl = Base;
851 EvaluatingDeclValue = &Value;
854 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
856 bool CheckCallLimit(SourceLocation Loc) {
857 // Don't perform any constexpr calls (other than the call we're checking)
858 // when checking a potential constant expression.
859 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
861 if (NextCallIndex == 0) {
862 // NextCallIndex has wrapped around.
863 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
866 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
868 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
869 << getLangOpts().ConstexprCallDepth;
873 std::pair<CallStackFrame *, unsigned>
874 getCallFrameAndDepth(unsigned CallIndex) {
875 assert(CallIndex && "no call index in getCallFrameAndDepth");
876 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
877 // be null in this loop.
878 unsigned Depth = CallStackDepth;
879 CallStackFrame *Frame = CurrentCall;
880 while (Frame->Index > CallIndex) {
881 Frame = Frame->Caller;
884 if (Frame->Index == CallIndex)
885 return {Frame, Depth};
889 bool nextStep(const Stmt *S) {
891 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
899 /// Add a diagnostic to the diagnostics list.
900 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
901 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
902 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
903 return EvalStatus.Diag->back().second;
906 /// Add notes containing a call stack to the current point of evaluation.
907 void addCallStack(unsigned Limit);
910 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
911 unsigned ExtraNotes, bool IsCCEDiag) {
913 if (EvalStatus.Diag) {
914 // If we have a prior diagnostic, it will be noting that the expression
915 // isn't a constant expression. This diagnostic is more important,
916 // unless we require this evaluation to produce a constant expression.
918 // FIXME: We might want to show both diagnostics to the user in
919 // EM_ConstantFold mode.
920 if (!EvalStatus.Diag->empty()) {
922 case EM_ConstantFold:
923 case EM_IgnoreSideEffects:
924 if (!HasFoldFailureDiagnostic)
926 // We've already failed to fold something. Keep that diagnostic.
928 case EM_ConstantExpression:
929 case EM_ConstantExpressionUnevaluated:
930 HasActiveDiagnostic = false;
931 return OptionalDiagnostic();
935 unsigned CallStackNotes = CallStackDepth - 1;
936 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
938 CallStackNotes = std::min(CallStackNotes, Limit + 1);
939 if (checkingPotentialConstantExpression())
942 HasActiveDiagnostic = true;
943 HasFoldFailureDiagnostic = !IsCCEDiag;
944 EvalStatus.Diag->clear();
945 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
946 addDiag(Loc, DiagId);
947 if (!checkingPotentialConstantExpression())
949 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
951 HasActiveDiagnostic = false;
952 return OptionalDiagnostic();
955 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
957 FFDiag(SourceLocation Loc,
958 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
959 unsigned ExtraNotes = 0) {
960 return Diag(Loc, DiagId, ExtraNotes, false);
963 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
964 = diag::note_invalid_subexpr_in_const_expr,
965 unsigned ExtraNotes = 0) {
967 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
968 HasActiveDiagnostic = false;
969 return OptionalDiagnostic();
972 /// Diagnose that the evaluation does not produce a C++11 core constant
975 /// FIXME: Stop evaluating if we're in EM_ConstantExpression mode
976 /// and we produce one of these.
977 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
978 = diag::note_invalid_subexpr_in_const_expr,
979 unsigned ExtraNotes = 0) {
980 // Don't override a previous diagnostic. Don't bother collecting
981 // diagnostics if we're evaluating for overflow.
982 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
983 HasActiveDiagnostic = false;
984 return OptionalDiagnostic();
986 return Diag(Loc, DiagId, ExtraNotes, true);
988 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
989 = diag::note_invalid_subexpr_in_const_expr,
990 unsigned ExtraNotes = 0) {
991 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
993 /// Add a note to a prior diagnostic.
994 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
995 if (!HasActiveDiagnostic)
996 return OptionalDiagnostic();
997 return OptionalDiagnostic(&addDiag(Loc, DiagId));
1000 /// Add a stack of notes to a prior diagnostic.
1001 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1002 if (HasActiveDiagnostic) {
1003 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1004 Diags.begin(), Diags.end());
1008 /// Should we continue evaluation after encountering a side-effect that we
1010 bool keepEvaluatingAfterSideEffect() {
1012 case EM_IgnoreSideEffects:
1015 case EM_ConstantExpression:
1016 case EM_ConstantExpressionUnevaluated:
1017 case EM_ConstantFold:
1018 // By default, assume any side effect might be valid in some other
1019 // evaluation of this expression from a different context.
1020 return checkingPotentialConstantExpression() ||
1021 checkingForUndefinedBehavior();
1023 llvm_unreachable("Missed EvalMode case");
1026 /// Note that we have had a side-effect, and determine whether we should
1027 /// keep evaluating.
1028 bool noteSideEffect() {
1029 EvalStatus.HasSideEffects = true;
1030 return keepEvaluatingAfterSideEffect();
1033 /// Should we continue evaluation after encountering undefined behavior?
1034 bool keepEvaluatingAfterUndefinedBehavior() {
1036 case EM_IgnoreSideEffects:
1037 case EM_ConstantFold:
1040 case EM_ConstantExpression:
1041 case EM_ConstantExpressionUnevaluated:
1042 return checkingForUndefinedBehavior();
1044 llvm_unreachable("Missed EvalMode case");
1047 /// Note that we hit something that was technically undefined behavior, but
1048 /// that we can evaluate past it (such as signed overflow or floating-point
1049 /// division by zero.)
1050 bool noteUndefinedBehavior() {
1051 EvalStatus.HasUndefinedBehavior = true;
1052 return keepEvaluatingAfterUndefinedBehavior();
1055 /// Should we continue evaluation as much as possible after encountering a
1056 /// construct which can't be reduced to a value?
1057 bool keepEvaluatingAfterFailure() {
1062 case EM_ConstantExpression:
1063 case EM_ConstantExpressionUnevaluated:
1064 case EM_ConstantFold:
1065 case EM_IgnoreSideEffects:
1066 return checkingPotentialConstantExpression() ||
1067 checkingForUndefinedBehavior();
1069 llvm_unreachable("Missed EvalMode case");
1072 /// Notes that we failed to evaluate an expression that other expressions
1073 /// directly depend on, and determine if we should keep evaluating. This
1074 /// should only be called if we actually intend to keep evaluating.
1076 /// Call noteSideEffect() instead if we may be able to ignore the value that
1077 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1079 /// (Foo(), 1) // use noteSideEffect
1080 /// (Foo() || true) // use noteSideEffect
1081 /// Foo() + 1 // use noteFailure
1082 LLVM_NODISCARD bool noteFailure() {
1083 // Failure when evaluating some expression often means there is some
1084 // subexpression whose evaluation was skipped. Therefore, (because we
1085 // don't track whether we skipped an expression when unwinding after an
1086 // evaluation failure) every evaluation failure that bubbles up from a
1087 // subexpression implies that a side-effect has potentially happened. We
1088 // skip setting the HasSideEffects flag to true until we decide to
1089 // continue evaluating after that point, which happens here.
1090 bool KeepGoing = keepEvaluatingAfterFailure();
1091 EvalStatus.HasSideEffects |= KeepGoing;
1095 class ArrayInitLoopIndex {
1097 uint64_t OuterIndex;
1100 ArrayInitLoopIndex(EvalInfo &Info)
1101 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1102 Info.ArrayInitIndex = 0;
1104 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1106 operator uint64_t&() { return Info.ArrayInitIndex; }
1110 /// Object used to treat all foldable expressions as constant expressions.
1111 struct FoldConstant {
1114 bool HadNoPriorDiags;
1115 EvalInfo::EvaluationMode OldMode;
1117 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1120 HadNoPriorDiags(Info.EvalStatus.Diag &&
1121 Info.EvalStatus.Diag->empty() &&
1122 !Info.EvalStatus.HasSideEffects),
1123 OldMode(Info.EvalMode) {
1125 Info.EvalMode = EvalInfo::EM_ConstantFold;
1127 void keepDiagnostics() { Enabled = false; }
1129 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1130 !Info.EvalStatus.HasSideEffects)
1131 Info.EvalStatus.Diag->clear();
1132 Info.EvalMode = OldMode;
1136 /// RAII object used to set the current evaluation mode to ignore
1138 struct IgnoreSideEffectsRAII {
1140 EvalInfo::EvaluationMode OldMode;
1141 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1142 : Info(Info), OldMode(Info.EvalMode) {
1143 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1146 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1149 /// RAII object used to optionally suppress diagnostics and side-effects from
1150 /// a speculative evaluation.
1151 class SpeculativeEvaluationRAII {
1152 EvalInfo *Info = nullptr;
1153 Expr::EvalStatus OldStatus;
1154 unsigned OldSpeculativeEvaluationDepth;
1156 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1158 OldStatus = Other.OldStatus;
1159 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1160 Other.Info = nullptr;
1163 void maybeRestoreState() {
1167 Info->EvalStatus = OldStatus;
1168 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1172 SpeculativeEvaluationRAII() = default;
1174 SpeculativeEvaluationRAII(
1175 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1176 : Info(&Info), OldStatus(Info.EvalStatus),
1177 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1178 Info.EvalStatus.Diag = NewDiag;
1179 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1182 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1183 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1184 moveFromAndCancel(std::move(Other));
1187 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1188 maybeRestoreState();
1189 moveFromAndCancel(std::move(Other));
1193 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1196 /// RAII object wrapping a full-expression or block scope, and handling
1197 /// the ending of the lifetime of temporaries created within it.
1198 template<bool IsFullExpression>
1201 unsigned OldStackSize;
1203 ScopeRAII(EvalInfo &Info)
1204 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1205 // Push a new temporary version. This is needed to distinguish between
1206 // temporaries created in different iterations of a loop.
1207 Info.CurrentCall->pushTempVersion();
1210 // Body moved to a static method to encourage the compiler to inline away
1211 // instances of this class.
1212 cleanup(Info, OldStackSize);
1213 Info.CurrentCall->popTempVersion();
1216 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1217 unsigned NewEnd = OldStackSize;
1218 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1220 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1221 // Full-expression cleanup of a lifetime-extended temporary: nothing
1222 // to do, just move this cleanup to the right place in the stack.
1223 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1226 // End the lifetime of the object.
1227 Info.CleanupStack[I].endLifetime();
1230 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1231 Info.CleanupStack.end());
1234 typedef ScopeRAII<false> BlockScopeRAII;
1235 typedef ScopeRAII<true> FullExpressionRAII;
1238 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1239 CheckSubobjectKind CSK) {
1242 if (isOnePastTheEnd()) {
1243 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1248 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1249 // must actually be at least one array element; even a VLA cannot have a
1250 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1254 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1256 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1257 // Do not set the designator as invalid: we can represent this situation,
1258 // and correct handling of __builtin_object_size requires us to do so.
1261 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1264 // If we're complaining, we must be able to statically determine the size of
1265 // the most derived array.
1266 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1267 Info.CCEDiag(E, diag::note_constexpr_array_index)
1269 << static_cast<unsigned>(getMostDerivedArraySize());
1271 Info.CCEDiag(E, diag::note_constexpr_array_index)
1272 << N << /*non-array*/ 1;
1276 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1277 const FunctionDecl *Callee, const LValue *This,
1279 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1280 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1281 Info.CurrentCall = this;
1282 ++Info.CallStackDepth;
1285 CallStackFrame::~CallStackFrame() {
1286 assert(Info.CurrentCall == this && "calls retired out of order");
1287 --Info.CallStackDepth;
1288 Info.CurrentCall = Caller;
1291 APValue &CallStackFrame::createTemporary(const void *Key,
1292 bool IsLifetimeExtended) {
1293 unsigned Version = Info.CurrentCall->getTempVersion();
1294 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1295 assert(Result.isAbsent() && "temporary created multiple times");
1296 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1300 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1302 void EvalInfo::addCallStack(unsigned Limit) {
1303 // Determine which calls to skip, if any.
1304 unsigned ActiveCalls = CallStackDepth - 1;
1305 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1306 if (Limit && Limit < ActiveCalls) {
1307 SkipStart = Limit / 2 + Limit % 2;
1308 SkipEnd = ActiveCalls - Limit / 2;
1311 // Walk the call stack and add the diagnostics.
1312 unsigned CallIdx = 0;
1313 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1314 Frame = Frame->Caller, ++CallIdx) {
1316 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1317 if (CallIdx == SkipStart) {
1318 // Note that we're skipping calls.
1319 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1320 << unsigned(ActiveCalls - Limit);
1325 // Use a different note for an inheriting constructor, because from the
1326 // user's perspective it's not really a function at all.
1327 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1328 if (CD->isInheritingConstructor()) {
1329 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1335 SmallVector<char, 128> Buffer;
1336 llvm::raw_svector_ostream Out(Buffer);
1337 describeCall(Frame, Out);
1338 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1342 /// Kinds of access we can perform on an object, for diagnostics. Note that
1343 /// we consider a member function call to be a kind of access, even though
1344 /// it is not formally an access of the object, because it has (largely) the
1345 /// same set of semantic restrictions.
1356 static bool isModification(AccessKinds AK) {
1360 case AK_DynamicCast:
1368 llvm_unreachable("unknown access kind");
1371 /// Is this an access per the C++ definition?
1372 static bool isFormalAccess(AccessKinds AK) {
1373 return AK == AK_Read || isModification(AK);
1377 struct ComplexValue {
1382 APSInt IntReal, IntImag;
1383 APFloat FloatReal, FloatImag;
1385 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1387 void makeComplexFloat() { IsInt = false; }
1388 bool isComplexFloat() const { return !IsInt; }
1389 APFloat &getComplexFloatReal() { return FloatReal; }
1390 APFloat &getComplexFloatImag() { return FloatImag; }
1392 void makeComplexInt() { IsInt = true; }
1393 bool isComplexInt() const { return IsInt; }
1394 APSInt &getComplexIntReal() { return IntReal; }
1395 APSInt &getComplexIntImag() { return IntImag; }
1397 void moveInto(APValue &v) const {
1398 if (isComplexFloat())
1399 v = APValue(FloatReal, FloatImag);
1401 v = APValue(IntReal, IntImag);
1403 void setFrom(const APValue &v) {
1404 assert(v.isComplexFloat() || v.isComplexInt());
1405 if (v.isComplexFloat()) {
1407 FloatReal = v.getComplexFloatReal();
1408 FloatImag = v.getComplexFloatImag();
1411 IntReal = v.getComplexIntReal();
1412 IntImag = v.getComplexIntImag();
1418 APValue::LValueBase Base;
1420 SubobjectDesignator Designator;
1422 bool InvalidBase : 1;
1424 const APValue::LValueBase getLValueBase() const { return Base; }
1425 CharUnits &getLValueOffset() { return Offset; }
1426 const CharUnits &getLValueOffset() const { return Offset; }
1427 SubobjectDesignator &getLValueDesignator() { return Designator; }
1428 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1429 bool isNullPointer() const { return IsNullPtr;}
1431 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1432 unsigned getLValueVersion() const { return Base.getVersion(); }
1434 void moveInto(APValue &V) const {
1435 if (Designator.Invalid)
1436 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1438 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1439 V = APValue(Base, Offset, Designator.Entries,
1440 Designator.IsOnePastTheEnd, IsNullPtr);
1443 void setFrom(ASTContext &Ctx, const APValue &V) {
1444 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1445 Base = V.getLValueBase();
1446 Offset = V.getLValueOffset();
1447 InvalidBase = false;
1448 Designator = SubobjectDesignator(Ctx, V);
1449 IsNullPtr = V.isNullPointer();
1452 void set(APValue::LValueBase B, bool BInvalid = false) {
1454 // We only allow a few types of invalid bases. Enforce that here.
1456 const auto *E = B.get<const Expr *>();
1457 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1458 "Unexpected type of invalid base");
1463 Offset = CharUnits::fromQuantity(0);
1464 InvalidBase = BInvalid;
1465 Designator = SubobjectDesignator(getType(B));
1469 void setNull(QualType PointerTy, uint64_t TargetVal) {
1470 Base = (Expr *)nullptr;
1471 Offset = CharUnits::fromQuantity(TargetVal);
1472 InvalidBase = false;
1473 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1477 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1482 // Check that this LValue is not based on a null pointer. If it is, produce
1483 // a diagnostic and mark the designator as invalid.
1484 template <typename GenDiagType>
1485 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1486 if (Designator.Invalid)
1490 Designator.setInvalid();
1497 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1498 CheckSubobjectKind CSK) {
1499 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1500 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1504 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1506 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1507 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1511 // Check this LValue refers to an object. If not, set the designator to be
1512 // invalid and emit a diagnostic.
1513 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1514 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1515 Designator.checkSubobject(Info, E, CSK);
1518 void addDecl(EvalInfo &Info, const Expr *E,
1519 const Decl *D, bool Virtual = false) {
1520 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1521 Designator.addDeclUnchecked(D, Virtual);
1523 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1524 if (!Designator.Entries.empty()) {
1525 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1526 Designator.setInvalid();
1529 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1530 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1531 Designator.FirstEntryIsAnUnsizedArray = true;
1532 Designator.addUnsizedArrayUnchecked(ElemTy);
1535 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1536 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1537 Designator.addArrayUnchecked(CAT);
1539 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1540 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1541 Designator.addComplexUnchecked(EltTy, Imag);
1543 void clearIsNullPointer() {
1546 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1547 const APSInt &Index, CharUnits ElementSize) {
1548 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1549 // but we're not required to diagnose it and it's valid in C++.)
1553 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1554 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1556 uint64_t Offset64 = Offset.getQuantity();
1557 uint64_t ElemSize64 = ElementSize.getQuantity();
1558 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1559 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1561 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1562 Designator.adjustIndex(Info, E, Index);
1563 clearIsNullPointer();
1565 void adjustOffset(CharUnits N) {
1567 if (N.getQuantity())
1568 clearIsNullPointer();
1574 explicit MemberPtr(const ValueDecl *Decl) :
1575 DeclAndIsDerivedMember(Decl, false), Path() {}
1577 /// The member or (direct or indirect) field referred to by this member
1578 /// pointer, or 0 if this is a null member pointer.
1579 const ValueDecl *getDecl() const {
1580 return DeclAndIsDerivedMember.getPointer();
1582 /// Is this actually a member of some type derived from the relevant class?
1583 bool isDerivedMember() const {
1584 return DeclAndIsDerivedMember.getInt();
1586 /// Get the class which the declaration actually lives in.
1587 const CXXRecordDecl *getContainingRecord() const {
1588 return cast<CXXRecordDecl>(
1589 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1592 void moveInto(APValue &V) const {
1593 V = APValue(getDecl(), isDerivedMember(), Path);
1595 void setFrom(const APValue &V) {
1596 assert(V.isMemberPointer());
1597 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1598 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1600 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1601 Path.insert(Path.end(), P.begin(), P.end());
1604 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1605 /// whether the member is a member of some class derived from the class type
1606 /// of the member pointer.
1607 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1608 /// Path - The path of base/derived classes from the member declaration's
1609 /// class (exclusive) to the class type of the member pointer (inclusive).
1610 SmallVector<const CXXRecordDecl*, 4> Path;
1612 /// Perform a cast towards the class of the Decl (either up or down the
1614 bool castBack(const CXXRecordDecl *Class) {
1615 assert(!Path.empty());
1616 const CXXRecordDecl *Expected;
1617 if (Path.size() >= 2)
1618 Expected = Path[Path.size() - 2];
1620 Expected = getContainingRecord();
1621 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1622 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1623 // if B does not contain the original member and is not a base or
1624 // derived class of the class containing the original member, the result
1625 // of the cast is undefined.
1626 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1627 // (D::*). We consider that to be a language defect.
1633 /// Perform a base-to-derived member pointer cast.
1634 bool castToDerived(const CXXRecordDecl *Derived) {
1637 if (!isDerivedMember()) {
1638 Path.push_back(Derived);
1641 if (!castBack(Derived))
1644 DeclAndIsDerivedMember.setInt(false);
1647 /// Perform a derived-to-base member pointer cast.
1648 bool castToBase(const CXXRecordDecl *Base) {
1652 DeclAndIsDerivedMember.setInt(true);
1653 if (isDerivedMember()) {
1654 Path.push_back(Base);
1657 return castBack(Base);
1661 /// Compare two member pointers, which are assumed to be of the same type.
1662 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1663 if (!LHS.getDecl() || !RHS.getDecl())
1664 return !LHS.getDecl() && !RHS.getDecl();
1665 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1667 return LHS.Path == RHS.Path;
1671 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1672 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1673 const LValue &This, const Expr *E,
1674 bool AllowNonLiteralTypes = false);
1675 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1676 bool InvalidBaseOK = false);
1677 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1678 bool InvalidBaseOK = false);
1679 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1681 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1682 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1683 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1685 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1686 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1687 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1689 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1691 /// Evaluate an integer or fixed point expression into an APResult.
1692 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1695 /// Evaluate only a fixed point expression into an APResult.
1696 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1699 //===----------------------------------------------------------------------===//
1701 //===----------------------------------------------------------------------===//
1703 /// A helper function to create a temporary and set an LValue.
1704 template <class KeyTy>
1705 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1706 LValue &LV, CallStackFrame &Frame) {
1707 LV.set({Key, Frame.Info.CurrentCall->Index,
1708 Frame.Info.CurrentCall->getTempVersion()});
1709 return Frame.createTemporary(Key, IsLifetimeExtended);
1712 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1713 /// preserving its value (by extending by up to one bit as needed).
1714 static void negateAsSigned(APSInt &Int) {
1715 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1716 Int = Int.extend(Int.getBitWidth() + 1);
1717 Int.setIsSigned(true);
1722 /// Produce a string describing the given constexpr call.
1723 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1724 unsigned ArgIndex = 0;
1725 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1726 !isa<CXXConstructorDecl>(Frame->Callee) &&
1727 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1730 Out << *Frame->Callee << '(';
1732 if (Frame->This && IsMemberCall) {
1734 Frame->This->moveInto(Val);
1735 Val.printPretty(Out, Frame->Info.Ctx,
1736 Frame->This->Designator.MostDerivedType);
1737 // FIXME: Add parens around Val if needed.
1738 Out << "->" << *Frame->Callee << '(';
1739 IsMemberCall = false;
1742 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1743 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1744 if (ArgIndex > (unsigned)IsMemberCall)
1747 const ParmVarDecl *Param = *I;
1748 const APValue &Arg = Frame->Arguments[ArgIndex];
1749 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1751 if (ArgIndex == 0 && IsMemberCall)
1752 Out << "->" << *Frame->Callee << '(';
1758 /// Evaluate an expression to see if it had side-effects, and discard its
1760 /// \return \c true if the caller should keep evaluating.
1761 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1763 if (!Evaluate(Scratch, Info, E))
1764 // We don't need the value, but we might have skipped a side effect here.
1765 return Info.noteSideEffect();
1769 /// Should this call expression be treated as a string literal?
1770 static bool IsStringLiteralCall(const CallExpr *E) {
1771 unsigned Builtin = E->getBuiltinCallee();
1772 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1773 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1776 static bool IsGlobalLValue(APValue::LValueBase B) {
1777 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1778 // constant expression of pointer type that evaluates to...
1780 // ... a null pointer value, or a prvalue core constant expression of type
1782 if (!B) return true;
1784 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1785 // ... the address of an object with static storage duration,
1786 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1787 return VD->hasGlobalStorage();
1788 // ... the address of a function,
1789 return isa<FunctionDecl>(D);
1792 if (B.is<TypeInfoLValue>())
1795 const Expr *E = B.get<const Expr*>();
1796 switch (E->getStmtClass()) {
1799 case Expr::CompoundLiteralExprClass: {
1800 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1801 return CLE->isFileScope() && CLE->isLValue();
1803 case Expr::MaterializeTemporaryExprClass:
1804 // A materialized temporary might have been lifetime-extended to static
1805 // storage duration.
1806 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1807 // A string literal has static storage duration.
1808 case Expr::StringLiteralClass:
1809 case Expr::PredefinedExprClass:
1810 case Expr::ObjCStringLiteralClass:
1811 case Expr::ObjCEncodeExprClass:
1812 case Expr::CXXUuidofExprClass:
1814 case Expr::ObjCBoxedExprClass:
1815 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1816 case Expr::CallExprClass:
1817 return IsStringLiteralCall(cast<CallExpr>(E));
1818 // For GCC compatibility, &&label has static storage duration.
1819 case Expr::AddrLabelExprClass:
1821 // A Block literal expression may be used as the initialization value for
1822 // Block variables at global or local static scope.
1823 case Expr::BlockExprClass:
1824 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1825 case Expr::ImplicitValueInitExprClass:
1827 // We can never form an lvalue with an implicit value initialization as its
1828 // base through expression evaluation, so these only appear in one case: the
1829 // implicit variable declaration we invent when checking whether a constexpr
1830 // constructor can produce a constant expression. We must assume that such
1831 // an expression might be a global lvalue.
1836 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1837 return LVal.Base.dyn_cast<const ValueDecl*>();
1840 static bool IsLiteralLValue(const LValue &Value) {
1841 if (Value.getLValueCallIndex())
1843 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1844 return E && !isa<MaterializeTemporaryExpr>(E);
1847 static bool IsWeakLValue(const LValue &Value) {
1848 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1849 return Decl && Decl->isWeak();
1852 static bool isZeroSized(const LValue &Value) {
1853 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1854 if (Decl && isa<VarDecl>(Decl)) {
1855 QualType Ty = Decl->getType();
1856 if (Ty->isArrayType())
1857 return Ty->isIncompleteType() ||
1858 Decl->getASTContext().getTypeSize(Ty) == 0;
1863 static bool HasSameBase(const LValue &A, const LValue &B) {
1864 if (!A.getLValueBase())
1865 return !B.getLValueBase();
1866 if (!B.getLValueBase())
1869 if (A.getLValueBase().getOpaqueValue() !=
1870 B.getLValueBase().getOpaqueValue()) {
1871 const Decl *ADecl = GetLValueBaseDecl(A);
1874 const Decl *BDecl = GetLValueBaseDecl(B);
1875 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1879 return IsGlobalLValue(A.getLValueBase()) ||
1880 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1881 A.getLValueVersion() == B.getLValueVersion());
1884 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1885 assert(Base && "no location for a null lvalue");
1886 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1888 Info.Note(VD->getLocation(), diag::note_declared_at);
1889 else if (const Expr *E = Base.dyn_cast<const Expr*>())
1890 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1891 // We have no information to show for a typeid(T) object.
1894 /// Check that this reference or pointer core constant expression is a valid
1895 /// value for an address or reference constant expression. Return true if we
1896 /// can fold this expression, whether or not it's a constant expression.
1897 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1898 QualType Type, const LValue &LVal,
1899 Expr::ConstExprUsage Usage) {
1900 bool IsReferenceType = Type->isReferenceType();
1902 APValue::LValueBase Base = LVal.getLValueBase();
1903 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1905 // Check that the object is a global. Note that the fake 'this' object we
1906 // manufacture when checking potential constant expressions is conservatively
1907 // assumed to be global here.
1908 if (!IsGlobalLValue(Base)) {
1909 if (Info.getLangOpts().CPlusPlus11) {
1910 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1911 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1912 << IsReferenceType << !Designator.Entries.empty()
1914 NoteLValueLocation(Info, Base);
1918 // Don't allow references to temporaries to escape.
1921 assert((Info.checkingPotentialConstantExpression() ||
1922 LVal.getLValueCallIndex() == 0) &&
1923 "have call index for global lvalue");
1925 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1926 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1927 // Check if this is a thread-local variable.
1928 if (Var->getTLSKind())
1931 // A dllimport variable never acts like a constant.
1932 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1935 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1936 // __declspec(dllimport) must be handled very carefully:
1937 // We must never initialize an expression with the thunk in C++.
1938 // Doing otherwise would allow the same id-expression to yield
1939 // different addresses for the same function in different translation
1940 // units. However, this means that we must dynamically initialize the
1941 // expression with the contents of the import address table at runtime.
1943 // The C language has no notion of ODR; furthermore, it has no notion of
1944 // dynamic initialization. This means that we are permitted to
1945 // perform initialization with the address of the thunk.
1946 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1947 FD->hasAttr<DLLImportAttr>())
1952 // Allow address constant expressions to be past-the-end pointers. This is
1953 // an extension: the standard requires them to point to an object.
1954 if (!IsReferenceType)
1957 // A reference constant expression must refer to an object.
1959 // FIXME: diagnostic
1964 // Does this refer one past the end of some object?
1965 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1966 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1967 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1968 << !Designator.Entries.empty() << !!VD << VD;
1969 NoteLValueLocation(Info, Base);
1975 /// Member pointers are constant expressions unless they point to a
1976 /// non-virtual dllimport member function.
1977 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1980 const APValue &Value,
1981 Expr::ConstExprUsage Usage) {
1982 const ValueDecl *Member = Value.getMemberPointerDecl();
1983 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1986 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1987 !FD->hasAttr<DLLImportAttr>();
1990 /// Check that this core constant expression is of literal type, and if not,
1991 /// produce an appropriate diagnostic.
1992 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1993 const LValue *This = nullptr) {
1994 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1997 // C++1y: A constant initializer for an object o [...] may also invoke
1998 // constexpr constructors for o and its subobjects even if those objects
1999 // are of non-literal class types.
2001 // C++11 missed this detail for aggregates, so classes like this:
2002 // struct foo_t { union { int i; volatile int j; } u; };
2003 // are not (obviously) initializable like so:
2004 // __attribute__((__require_constant_initialization__))
2005 // static const foo_t x = {{0}};
2006 // because "i" is a subobject with non-literal initialization (due to the
2007 // volatile member of the union). See:
2008 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2009 // Therefore, we use the C++1y behavior.
2010 if (This && Info.EvaluatingDecl == This->getLValueBase())
2013 // Prvalue constant expressions must be of literal types.
2014 if (Info.getLangOpts().CPlusPlus11)
2015 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2018 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2022 /// Check that this core constant expression value is a valid value for a
2023 /// constant expression. If not, report an appropriate diagnostic. Does not
2024 /// check that the expression is of literal type.
2026 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2027 const APValue &Value,
2028 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2029 SourceLocation SubobjectLoc = SourceLocation()) {
2030 if (!Value.hasValue()) {
2031 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2033 if (SubobjectLoc.isValid())
2034 Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2038 // We allow _Atomic(T) to be initialized from anything that T can be
2039 // initialized from.
2040 if (const AtomicType *AT = Type->getAs<AtomicType>())
2041 Type = AT->getValueType();
2043 // Core issue 1454: For a literal constant expression of array or class type,
2044 // each subobject of its value shall have been initialized by a constant
2046 if (Value.isArray()) {
2047 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2048 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2049 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2050 Value.getArrayInitializedElt(I), Usage,
2054 if (!Value.hasArrayFiller())
2056 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2057 Usage, SubobjectLoc);
2059 if (Value.isUnion() && Value.getUnionField()) {
2060 return CheckConstantExpression(Info, DiagLoc,
2061 Value.getUnionField()->getType(),
2062 Value.getUnionValue(), Usage,
2063 Value.getUnionField()->getLocation());
2065 if (Value.isStruct()) {
2066 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2067 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2068 unsigned BaseIndex = 0;
2069 for (const CXXBaseSpecifier &BS : CD->bases()) {
2070 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2071 Value.getStructBase(BaseIndex), Usage,
2077 for (const auto *I : RD->fields()) {
2078 if (I->isUnnamedBitfield())
2081 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2082 Value.getStructField(I->getFieldIndex()),
2083 Usage, I->getLocation()))
2088 if (Value.isLValue()) {
2090 LVal.setFrom(Info.Ctx, Value);
2091 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2094 if (Value.isMemberPointer())
2095 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2097 // Everything else is fine.
2101 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2102 // A null base expression indicates a null pointer. These are always
2103 // evaluatable, and they are false unless the offset is zero.
2104 if (!Value.getLValueBase()) {
2105 Result = !Value.getLValueOffset().isZero();
2109 // We have a non-null base. These are generally known to be true, but if it's
2110 // a weak declaration it can be null at runtime.
2112 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2113 return !Decl || !Decl->isWeak();
2116 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2117 switch (Val.getKind()) {
2119 case APValue::Indeterminate:
2122 Result = Val.getInt().getBoolValue();
2124 case APValue::FixedPoint:
2125 Result = Val.getFixedPoint().getBoolValue();
2127 case APValue::Float:
2128 Result = !Val.getFloat().isZero();
2130 case APValue::ComplexInt:
2131 Result = Val.getComplexIntReal().getBoolValue() ||
2132 Val.getComplexIntImag().getBoolValue();
2134 case APValue::ComplexFloat:
2135 Result = !Val.getComplexFloatReal().isZero() ||
2136 !Val.getComplexFloatImag().isZero();
2138 case APValue::LValue:
2139 return EvalPointerValueAsBool(Val, Result);
2140 case APValue::MemberPointer:
2141 Result = Val.getMemberPointerDecl();
2143 case APValue::Vector:
2144 case APValue::Array:
2145 case APValue::Struct:
2146 case APValue::Union:
2147 case APValue::AddrLabelDiff:
2151 llvm_unreachable("unknown APValue kind");
2154 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2156 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2158 if (!Evaluate(Val, Info, E))
2160 return HandleConversionToBool(Val, Result);
2163 template<typename T>
2164 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2165 const T &SrcValue, QualType DestType) {
2166 Info.CCEDiag(E, diag::note_constexpr_overflow)
2167 << SrcValue << DestType;
2168 return Info.noteUndefinedBehavior();
2171 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2172 QualType SrcType, const APFloat &Value,
2173 QualType DestType, APSInt &Result) {
2174 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2175 // Determine whether we are converting to unsigned or signed.
2176 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2178 Result = APSInt(DestWidth, !DestSigned);
2180 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2181 & APFloat::opInvalidOp)
2182 return HandleOverflow(Info, E, Value, DestType);
2186 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2187 QualType SrcType, QualType DestType,
2189 APFloat Value = Result;
2191 Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2192 APFloat::rmNearestTiesToEven, &ignored);
2196 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2197 QualType DestType, QualType SrcType,
2198 const APSInt &Value) {
2199 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2200 // Figure out if this is a truncate, extend or noop cast.
2201 // If the input is signed, do a sign extend, noop, or truncate.
2202 APSInt Result = Value.extOrTrunc(DestWidth);
2203 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2204 if (DestType->isBooleanType())
2205 Result = Value.getBoolValue();
2209 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2210 QualType SrcType, const APSInt &Value,
2211 QualType DestType, APFloat &Result) {
2212 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2213 Result.convertFromAPInt(Value, Value.isSigned(),
2214 APFloat::rmNearestTiesToEven);
2218 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2219 APValue &Value, const FieldDecl *FD) {
2220 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2222 if (!Value.isInt()) {
2223 // Trying to store a pointer-cast-to-integer into a bitfield.
2224 // FIXME: In this case, we should provide the diagnostic for casting
2225 // a pointer to an integer.
2226 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2231 APSInt &Int = Value.getInt();
2232 unsigned OldBitWidth = Int.getBitWidth();
2233 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2234 if (NewBitWidth < OldBitWidth)
2235 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2239 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2242 if (!Evaluate(SVal, Info, E))
2245 Res = SVal.getInt();
2248 if (SVal.isFloat()) {
2249 Res = SVal.getFloat().bitcastToAPInt();
2252 if (SVal.isVector()) {
2253 QualType VecTy = E->getType();
2254 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2255 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2256 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2257 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2258 Res = llvm::APInt::getNullValue(VecSize);
2259 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2260 APValue &Elt = SVal.getVectorElt(i);
2261 llvm::APInt EltAsInt;
2263 EltAsInt = Elt.getInt();
2264 } else if (Elt.isFloat()) {
2265 EltAsInt = Elt.getFloat().bitcastToAPInt();
2267 // Don't try to handle vectors of anything other than int or float
2268 // (not sure if it's possible to hit this case).
2269 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2272 unsigned BaseEltSize = EltAsInt.getBitWidth();
2274 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2276 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2280 // Give up if the input isn't an int, float, or vector. For example, we
2281 // reject "(v4i16)(intptr_t)&a".
2282 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2286 /// Perform the given integer operation, which is known to need at most BitWidth
2287 /// bits, and check for overflow in the original type (if that type was not an
2289 template<typename Operation>
2290 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2291 const APSInt &LHS, const APSInt &RHS,
2292 unsigned BitWidth, Operation Op,
2294 if (LHS.isUnsigned()) {
2295 Result = Op(LHS, RHS);
2299 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2300 Result = Value.trunc(LHS.getBitWidth());
2301 if (Result.extend(BitWidth) != Value) {
2302 if (Info.checkingForUndefinedBehavior())
2303 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2304 diag::warn_integer_constant_overflow)
2305 << Result.toString(10) << E->getType();
2307 return HandleOverflow(Info, E, Value, E->getType());
2312 /// Perform the given binary integer operation.
2313 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2314 BinaryOperatorKind Opcode, APSInt RHS,
2321 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2322 std::multiplies<APSInt>(), Result);
2324 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2325 std::plus<APSInt>(), Result);
2327 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2328 std::minus<APSInt>(), Result);
2329 case BO_And: Result = LHS & RHS; return true;
2330 case BO_Xor: Result = LHS ^ RHS; return true;
2331 case BO_Or: Result = LHS | RHS; return true;
2335 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2338 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2339 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2340 // this operation and gives the two's complement result.
2341 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2342 LHS.isSigned() && LHS.isMinSignedValue())
2343 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2347 if (Info.getLangOpts().OpenCL)
2348 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2349 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2350 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2352 else if (RHS.isSigned() && RHS.isNegative()) {
2353 // During constant-folding, a negative shift is an opposite shift. Such
2354 // a shift is not a constant expression.
2355 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2360 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2361 // the shifted type.
2362 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2364 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2365 << RHS << E->getType() << LHS.getBitWidth();
2366 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2367 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2368 // operand, and must not overflow the corresponding unsigned type.
2369 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2370 // E1 x 2^E2 module 2^N.
2371 if (LHS.isNegative())
2372 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2373 else if (LHS.countLeadingZeros() < SA)
2374 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2380 if (Info.getLangOpts().OpenCL)
2381 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2382 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2383 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2385 else if (RHS.isSigned() && RHS.isNegative()) {
2386 // During constant-folding, a negative shift is an opposite shift. Such a
2387 // shift is not a constant expression.
2388 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2393 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2395 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2397 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2398 << RHS << E->getType() << LHS.getBitWidth();
2403 case BO_LT: Result = LHS < RHS; return true;
2404 case BO_GT: Result = LHS > RHS; return true;
2405 case BO_LE: Result = LHS <= RHS; return true;
2406 case BO_GE: Result = LHS >= RHS; return true;
2407 case BO_EQ: Result = LHS == RHS; return true;
2408 case BO_NE: Result = LHS != RHS; return true;
2410 llvm_unreachable("BO_Cmp should be handled elsewhere");
2414 /// Perform the given binary floating-point operation, in-place, on LHS.
2415 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2416 APFloat &LHS, BinaryOperatorKind Opcode,
2417 const APFloat &RHS) {
2423 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2426 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2429 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2433 // If the second operand of / or % is zero the behavior is undefined.
2435 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2436 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2441 // If during the evaluation of an expression, the result is not
2442 // mathematically defined [...], the behavior is undefined.
2443 // FIXME: C++ rules require us to not conform to IEEE 754 here.
2445 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2446 return Info.noteUndefinedBehavior();
2451 /// Cast an lvalue referring to a base subobject to a derived class, by
2452 /// truncating the lvalue's path to the given length.
2453 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2454 const RecordDecl *TruncatedType,
2455 unsigned TruncatedElements) {
2456 SubobjectDesignator &D = Result.Designator;
2458 // Check we actually point to a derived class object.
2459 if (TruncatedElements == D.Entries.size())
2461 assert(TruncatedElements >= D.MostDerivedPathLength &&
2462 "not casting to a derived class");
2463 if (!Result.checkSubobject(Info, E, CSK_Derived))
2466 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2467 const RecordDecl *RD = TruncatedType;
2468 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2469 if (RD->isInvalidDecl()) return false;
2470 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2471 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2472 if (isVirtualBaseClass(D.Entries[I]))
2473 Result.Offset -= Layout.getVBaseClassOffset(Base);
2475 Result.Offset -= Layout.getBaseClassOffset(Base);
2478 D.Entries.resize(TruncatedElements);
2482 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2483 const CXXRecordDecl *Derived,
2484 const CXXRecordDecl *Base,
2485 const ASTRecordLayout *RL = nullptr) {
2487 if (Derived->isInvalidDecl()) return false;
2488 RL = &Info.Ctx.getASTRecordLayout(Derived);
2491 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2492 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2496 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2497 const CXXRecordDecl *DerivedDecl,
2498 const CXXBaseSpecifier *Base) {
2499 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2501 if (!Base->isVirtual())
2502 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2504 SubobjectDesignator &D = Obj.Designator;
2508 // Extract most-derived object and corresponding type.
2509 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2510 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2513 // Find the virtual base class.
2514 if (DerivedDecl->isInvalidDecl()) return false;
2515 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2516 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2517 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2521 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2522 QualType Type, LValue &Result) {
2523 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2524 PathE = E->path_end();
2525 PathI != PathE; ++PathI) {
2526 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2529 Type = (*PathI)->getType();
2534 /// Cast an lvalue referring to a derived class to a known base subobject.
2535 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2536 const CXXRecordDecl *DerivedRD,
2537 const CXXRecordDecl *BaseRD) {
2538 CXXBasePaths Paths(/*FindAmbiguities=*/false,
2539 /*RecordPaths=*/true, /*DetectVirtual=*/false);
2540 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2541 llvm_unreachable("Class must be derived from the passed in base class!");
2543 for (CXXBasePathElement &Elem : Paths.front())
2544 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2549 /// Update LVal to refer to the given field, which must be a member of the type
2550 /// currently described by LVal.
2551 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2552 const FieldDecl *FD,
2553 const ASTRecordLayout *RL = nullptr) {
2555 if (FD->getParent()->isInvalidDecl()) return false;
2556 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2559 unsigned I = FD->getFieldIndex();
2560 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2561 LVal.addDecl(Info, E, FD);
2565 /// Update LVal to refer to the given indirect field.
2566 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2568 const IndirectFieldDecl *IFD) {
2569 for (const auto *C : IFD->chain())
2570 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2575 /// Get the size of the given type in char units.
2576 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2577 QualType Type, CharUnits &Size) {
2578 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2580 if (Type->isVoidType() || Type->isFunctionType()) {
2581 Size = CharUnits::One();
2585 if (Type->isDependentType()) {
2590 if (!Type->isConstantSizeType()) {
2591 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2592 // FIXME: Better diagnostic.
2597 Size = Info.Ctx.getTypeSizeInChars(Type);
2601 /// Update a pointer value to model pointer arithmetic.
2602 /// \param Info - Information about the ongoing evaluation.
2603 /// \param E - The expression being evaluated, for diagnostic purposes.
2604 /// \param LVal - The pointer value to be updated.
2605 /// \param EltTy - The pointee type represented by LVal.
2606 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2607 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2608 LValue &LVal, QualType EltTy,
2609 APSInt Adjustment) {
2610 CharUnits SizeOfPointee;
2611 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2614 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2618 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2619 LValue &LVal, QualType EltTy,
2620 int64_t Adjustment) {
2621 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2622 APSInt::get(Adjustment));
2625 /// Update an lvalue to refer to a component of a complex number.
2626 /// \param Info - Information about the ongoing evaluation.
2627 /// \param LVal - The lvalue to be updated.
2628 /// \param EltTy - The complex number's component type.
2629 /// \param Imag - False for the real component, true for the imaginary.
2630 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2631 LValue &LVal, QualType EltTy,
2634 CharUnits SizeOfComponent;
2635 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2637 LVal.Offset += SizeOfComponent;
2639 LVal.addComplex(Info, E, EltTy, Imag);
2643 /// Try to evaluate the initializer for a variable declaration.
2645 /// \param Info Information about the ongoing evaluation.
2646 /// \param E An expression to be used when printing diagnostics.
2647 /// \param VD The variable whose initializer should be obtained.
2648 /// \param Frame The frame in which the variable was created. Must be null
2649 /// if this variable is not local to the evaluation.
2650 /// \param Result Filled in with a pointer to the value of the variable.
2651 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2652 const VarDecl *VD, CallStackFrame *Frame,
2653 APValue *&Result, const LValue *LVal) {
2655 // If this is a parameter to an active constexpr function call, perform
2656 // argument substitution.
2657 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2658 // Assume arguments of a potential constant expression are unknown
2659 // constant expressions.
2660 if (Info.checkingPotentialConstantExpression())
2662 if (!Frame || !Frame->Arguments) {
2663 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2666 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2670 // If this is a local variable, dig out its value.
2672 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2673 : Frame->getCurrentTemporary(VD);
2675 // Assume variables referenced within a lambda's call operator that were
2676 // not declared within the call operator are captures and during checking
2677 // of a potential constant expression, assume they are unknown constant
2679 assert(isLambdaCallOperator(Frame->Callee) &&
2680 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2681 "missing value for local variable");
2682 if (Info.checkingPotentialConstantExpression())
2684 // FIXME: implement capture evaluation during constant expr evaluation.
2685 Info.FFDiag(E->getBeginLoc(),
2686 diag::note_unimplemented_constexpr_lambda_feature_ast)
2687 << "captures not currently allowed";
2693 // Dig out the initializer, and use the declaration which it's attached to.
2694 const Expr *Init = VD->getAnyInitializer(VD);
2695 if (!Init || Init->isValueDependent()) {
2696 // If we're checking a potential constant expression, the variable could be
2697 // initialized later.
2698 if (!Info.checkingPotentialConstantExpression())
2699 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2703 // If we're currently evaluating the initializer of this declaration, use that
2705 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2706 Result = Info.EvaluatingDeclValue;
2710 // Never evaluate the initializer of a weak variable. We can't be sure that
2711 // this is the definition which will be used.
2713 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2717 // Check that we can fold the initializer. In C++, we will have already done
2718 // this in the cases where it matters for conformance.
2719 SmallVector<PartialDiagnosticAt, 8> Notes;
2720 if (!VD->evaluateValue(Notes)) {
2721 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2722 Notes.size() + 1) << VD;
2723 Info.Note(VD->getLocation(), diag::note_declared_at);
2724 Info.addNotes(Notes);
2726 } else if (!VD->checkInitIsICE()) {
2727 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2728 Notes.size() + 1) << VD;
2729 Info.Note(VD->getLocation(), diag::note_declared_at);
2730 Info.addNotes(Notes);
2733 Result = VD->getEvaluatedValue();
2737 static bool IsConstNonVolatile(QualType T) {
2738 Qualifiers Quals = T.getQualifiers();
2739 return Quals.hasConst() && !Quals.hasVolatile();
2742 /// Get the base index of the given base class within an APValue representing
2743 /// the given derived class.
2744 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2745 const CXXRecordDecl *Base) {
2746 Base = Base->getCanonicalDecl();
2748 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2749 E = Derived->bases_end(); I != E; ++I, ++Index) {
2750 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2754 llvm_unreachable("base class missing from derived class's bases list");
2757 /// Extract the value of a character from a string literal.
2758 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2760 assert(!isa<SourceLocExpr>(Lit) &&
2761 "SourceLocExpr should have already been converted to a StringLiteral");
2763 // FIXME: Support MakeStringConstant
2764 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2766 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2767 assert(Index <= Str.size() && "Index too large");
2768 return APSInt::getUnsigned(Str.c_str()[Index]);
2771 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2772 Lit = PE->getFunctionName();
2773 const StringLiteral *S = cast<StringLiteral>(Lit);
2774 const ConstantArrayType *CAT =
2775 Info.Ctx.getAsConstantArrayType(S->getType());
2776 assert(CAT && "string literal isn't an array");
2777 QualType CharType = CAT->getElementType();
2778 assert(CharType->isIntegerType() && "unexpected character type");
2780 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2781 CharType->isUnsignedIntegerType());
2782 if (Index < S->getLength())
2783 Value = S->getCodeUnit(Index);
2787 // Expand a string literal into an array of characters.
2789 // FIXME: This is inefficient; we should probably introduce something similar
2790 // to the LLVM ConstantDataArray to make this cheaper.
2791 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2793 const ConstantArrayType *CAT =
2794 Info.Ctx.getAsConstantArrayType(S->getType());
2795 assert(CAT && "string literal isn't an array");
2796 QualType CharType = CAT->getElementType();
2797 assert(CharType->isIntegerType() && "unexpected character type");
2799 unsigned Elts = CAT->getSize().getZExtValue();
2800 Result = APValue(APValue::UninitArray(),
2801 std::min(S->getLength(), Elts), Elts);
2802 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2803 CharType->isUnsignedIntegerType());
2804 if (Result.hasArrayFiller())
2805 Result.getArrayFiller() = APValue(Value);
2806 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2807 Value = S->getCodeUnit(I);
2808 Result.getArrayInitializedElt(I) = APValue(Value);
2812 // Expand an array so that it has more than Index filled elements.
2813 static void expandArray(APValue &Array, unsigned Index) {
2814 unsigned Size = Array.getArraySize();
2815 assert(Index < Size);
2817 // Always at least double the number of elements for which we store a value.
2818 unsigned OldElts = Array.getArrayInitializedElts();
2819 unsigned NewElts = std::max(Index+1, OldElts * 2);
2820 NewElts = std::min(Size, std::max(NewElts, 8u));
2822 // Copy the data across.
2823 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2824 for (unsigned I = 0; I != OldElts; ++I)
2825 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2826 for (unsigned I = OldElts; I != NewElts; ++I)
2827 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2828 if (NewValue.hasArrayFiller())
2829 NewValue.getArrayFiller() = Array.getArrayFiller();
2830 Array.swap(NewValue);
2833 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2834 /// conversion. If it's of class type, we may assume that the copy operation
2835 /// is trivial. Note that this is never true for a union type with fields
2836 /// (because the copy always "reads" the active member) and always true for
2837 /// a non-class type.
2838 static bool isReadByLvalueToRvalueConversion(QualType T) {
2839 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2840 if (!RD || (RD->isUnion() && !RD->field_empty()))
2845 for (auto *Field : RD->fields())
2846 if (isReadByLvalueToRvalueConversion(Field->getType()))
2849 for (auto &BaseSpec : RD->bases())
2850 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2856 /// Diagnose an attempt to read from any unreadable field within the specified
2857 /// type, which might be a class type.
2858 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2860 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2864 if (!RD->hasMutableFields())
2867 for (auto *Field : RD->fields()) {
2868 // If we're actually going to read this field in some way, then it can't
2869 // be mutable. If we're in a union, then assigning to a mutable field
2870 // (even an empty one) can change the active member, so that's not OK.
2871 // FIXME: Add core issue number for the union case.
2872 if (Field->isMutable() &&
2873 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2874 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2875 Info.Note(Field->getLocation(), diag::note_declared_at);
2879 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2883 for (auto &BaseSpec : RD->bases())
2884 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2887 // All mutable fields were empty, and thus not actually read.
2891 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2892 APValue::LValueBase Base) {
2893 // A temporary we created.
2894 if (Base.getCallIndex())
2897 auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2901 // The variable whose initializer we're evaluating.
2902 if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2903 if (declaresSameEntity(Evaluating, BaseD))
2906 // A temporary lifetime-extended by the variable whose initializer we're
2908 if (auto *BaseE = Base.dyn_cast<const Expr *>())
2909 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2910 if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2917 /// A handle to a complete object (an object that is not a subobject of
2918 /// another object).
2919 struct CompleteObject {
2920 /// The identity of the object.
2921 APValue::LValueBase Base;
2922 /// The value of the complete object.
2924 /// The type of the complete object.
2927 CompleteObject() : Value(nullptr) {}
2928 CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2929 : Base(Base), Value(Value), Type(Type) {}
2931 bool mayReadMutableMembers(EvalInfo &Info) const {
2932 // In C++14 onwards, it is permitted to read a mutable member whose
2933 // lifetime began within the evaluation.
2934 // FIXME: Should we also allow this in C++11?
2935 if (!Info.getLangOpts().CPlusPlus14)
2937 return lifetimeStartedInEvaluation(Info, Base);
2940 explicit operator bool() const { return !Type.isNull(); }
2942 } // end anonymous namespace
2944 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2945 bool IsMutable = false) {
2946 // C++ [basic.type.qualifier]p1:
2947 // - A const object is an object of type const T or a non-mutable subobject
2948 // of a const object.
2949 if (ObjType.isConstQualified() && !IsMutable)
2950 SubobjType.addConst();
2951 // - A volatile object is an object of type const T or a subobject of a
2953 if (ObjType.isVolatileQualified())
2954 SubobjType.addVolatile();
2958 /// Find the designated sub-object of an rvalue.
2959 template<typename SubobjectHandler>
2960 typename SubobjectHandler::result_type
2961 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2962 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2964 // A diagnostic will have already been produced.
2965 return handler.failed();
2966 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2967 if (Info.getLangOpts().CPlusPlus11)
2968 Info.FFDiag(E, Sub.isOnePastTheEnd()
2969 ? diag::note_constexpr_access_past_end
2970 : diag::note_constexpr_access_unsized_array)
2971 << handler.AccessKind;
2974 return handler.failed();
2977 APValue *O = Obj.Value;
2978 QualType ObjType = Obj.Type;
2979 const FieldDecl *LastField = nullptr;
2980 const FieldDecl *VolatileField = nullptr;
2982 // Walk the designator's path to find the subobject.
2983 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2984 // Reading an indeterminate value is undefined, but assigning over one is OK.
2985 if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
2986 if (!Info.checkingPotentialConstantExpression())
2987 Info.FFDiag(E, diag::note_constexpr_access_uninit)
2988 << handler.AccessKind << O->isIndeterminate();
2989 return handler.failed();
2992 // C++ [class.ctor]p5:
2993 // const and volatile semantics are not applied on an object under
2995 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2996 ObjType->isRecordType() &&
2997 Info.isEvaluatingConstructor(
2998 Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2999 Sub.Entries.begin() + I)) !=
3000 ConstructionPhase::None) {
3001 ObjType = Info.Ctx.getCanonicalType(ObjType);
3002 ObjType.removeLocalConst();
3003 ObjType.removeLocalVolatile();
3006 // If this is our last pass, check that the final object type is OK.
3007 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3008 // Accesses to volatile objects are prohibited.
3009 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3010 if (Info.getLangOpts().CPlusPlus) {
3013 const NamedDecl *Decl = nullptr;
3014 if (VolatileField) {
3016 Loc = VolatileField->getLocation();
3017 Decl = VolatileField;
3018 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3020 Loc = VD->getLocation();
3024 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3025 Loc = E->getExprLoc();
3027 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3028 << handler.AccessKind << DiagKind << Decl;
3029 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3031 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3033 return handler.failed();
3036 // If we are reading an object of class type, there may still be more
3037 // things we need to check: if there are any mutable subobjects, we
3038 // cannot perform this read. (This only happens when performing a trivial
3039 // copy or assignment.)
3040 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3041 !Obj.mayReadMutableMembers(Info) &&
3042 diagnoseUnreadableFields(Info, E, ObjType))
3043 return handler.failed();
3047 if (!handler.found(*O, ObjType))
3050 // If we modified a bit-field, truncate it to the right width.
3051 if (isModification(handler.AccessKind) &&
3052 LastField && LastField->isBitField() &&
3053 !truncateBitfieldValue(Info, E, *O, LastField))
3059 LastField = nullptr;
3060 if (ObjType->isArrayType()) {
3061 // Next subobject is an array element.
3062 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3063 assert(CAT && "vla in literal type?");
3064 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3065 if (CAT->getSize().ule(Index)) {
3066 // Note, it should not be possible to form a pointer with a valid
3067 // designator which points more than one past the end of the array.
3068 if (Info.getLangOpts().CPlusPlus11)
3069 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3070 << handler.AccessKind;
3073 return handler.failed();
3076 ObjType = CAT->getElementType();
3078 if (O->getArrayInitializedElts() > Index)
3079 O = &O->getArrayInitializedElt(Index);
3080 else if (handler.AccessKind != AK_Read) {
3081 expandArray(*O, Index);
3082 O = &O->getArrayInitializedElt(Index);
3084 O = &O->getArrayFiller();
3085 } else if (ObjType->isAnyComplexType()) {
3086 // Next subobject is a complex number.
3087 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3089 if (Info.getLangOpts().CPlusPlus11)
3090 Info.FFDiag(E, diag::note_constexpr_access_past_end)
3091 << handler.AccessKind;
3094 return handler.failed();
3097 ObjType = getSubobjectType(
3098 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3100 assert(I == N - 1 && "extracting subobject of scalar?");
3101 if (O->isComplexInt()) {
3102 return handler.found(Index ? O->getComplexIntImag()
3103 : O->getComplexIntReal(), ObjType);
3105 assert(O->isComplexFloat());
3106 return handler.found(Index ? O->getComplexFloatImag()
3107 : O->getComplexFloatReal(), ObjType);
3109 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3110 if (Field->isMutable() && handler.AccessKind == AK_Read &&
3111 !Obj.mayReadMutableMembers(Info)) {
3112 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3114 Info.Note(Field->getLocation(), diag::note_declared_at);
3115 return handler.failed();
3118 // Next subobject is a class, struct or union field.
3119 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3120 if (RD->isUnion()) {
3121 const FieldDecl *UnionField = O->getUnionField();
3123 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3124 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3125 << handler.AccessKind << Field << !UnionField << UnionField;
3126 return handler.failed();
3128 O = &O->getUnionValue();
3130 O = &O->getStructField(Field->getFieldIndex());
3132 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3134 if (Field->getType().isVolatileQualified())
3135 VolatileField = Field;
3137 // Next subobject is a base class.
3138 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3139 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3140 O = &O->getStructBase(getBaseIndex(Derived, Base));
3142 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3148 struct ExtractSubobjectHandler {
3152 static const AccessKinds AccessKind = AK_Read;
3154 typedef bool result_type;
3155 bool failed() { return false; }
3156 bool found(APValue &Subobj, QualType SubobjType) {
3160 bool found(APSInt &Value, QualType SubobjType) {
3161 Result = APValue(Value);
3164 bool found(APFloat &Value, QualType SubobjType) {
3165 Result = APValue(Value);
3169 } // end anonymous namespace
3171 const AccessKinds ExtractSubobjectHandler::AccessKind;
3173 /// Extract the designated sub-object of an rvalue.
3174 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3175 const CompleteObject &Obj,
3176 const SubobjectDesignator &Sub,
3178 ExtractSubobjectHandler Handler = { Info, Result };
3179 return findSubobject(Info, E, Obj, Sub, Handler);
3183 struct ModifySubobjectHandler {
3188 typedef bool result_type;
3189 static const AccessKinds AccessKind = AK_Assign;
3191 bool checkConst(QualType QT) {
3192 // Assigning to a const object has undefined behavior.
3193 if (QT.isConstQualified()) {
3194 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3200 bool failed() { return false; }
3201 bool found(APValue &Subobj, QualType SubobjType) {
3202 if (!checkConst(SubobjType))
3204 // We've been given ownership of NewVal, so just swap it in.
3205 Subobj.swap(NewVal);
3208 bool found(APSInt &Value, QualType SubobjType) {
3209 if (!checkConst(SubobjType))
3211 if (!NewVal.isInt()) {
3212 // Maybe trying to write a cast pointer value into a complex?
3216 Value = NewVal.getInt();
3219 bool found(APFloat &Value, QualType SubobjType) {
3220 if (!checkConst(SubobjType))
3222 Value = NewVal.getFloat();
3226 } // end anonymous namespace
3228 const AccessKinds ModifySubobjectHandler::AccessKind;
3230 /// Update the designated sub-object of an rvalue to the given value.
3231 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3232 const CompleteObject &Obj,
3233 const SubobjectDesignator &Sub,
3235 ModifySubobjectHandler Handler = { Info, NewVal, E };
3236 return findSubobject(Info, E, Obj, Sub, Handler);
3239 /// Find the position where two subobject designators diverge, or equivalently
3240 /// the length of the common initial subsequence.
3241 static unsigned FindDesignatorMismatch(QualType ObjType,
3242 const SubobjectDesignator &A,
3243 const SubobjectDesignator &B,
3244 bool &WasArrayIndex) {
3245 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3246 for (/**/; I != N; ++I) {
3247 if (!ObjType.isNull() &&
3248 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3249 // Next subobject is an array element.
3250 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3251 WasArrayIndex = true;
3254 if (ObjType->isAnyComplexType())
3255 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3257 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3259 if (A.Entries[I].getAsBaseOrMember() !=
3260 B.Entries[I].getAsBaseOrMember()) {
3261 WasArrayIndex = false;
3264 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3265 // Next subobject is a field.
3266 ObjType = FD->getType();
3268 // Next subobject is a base class.
3269 ObjType = QualType();
3272 WasArrayIndex = false;
3276 /// Determine whether the given subobject designators refer to elements of the
3277 /// same array object.
3278 static bool AreElementsOfSameArray(QualType ObjType,
3279 const SubobjectDesignator &A,
3280 const SubobjectDesignator &B) {
3281 if (A.Entries.size() != B.Entries.size())
3284 bool IsArray = A.MostDerivedIsArrayElement;
3285 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3286 // A is a subobject of the array element.
3289 // If A (and B) designates an array element, the last entry will be the array
3290 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3291 // of length 1' case, and the entire path must match.
3293 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3294 return CommonLength >= A.Entries.size() - IsArray;
3297 /// Find the complete object to which an LValue refers.
3298 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3299 AccessKinds AK, const LValue &LVal,
3300 QualType LValType) {
3301 if (LVal.InvalidBase) {
3303 return CompleteObject();
3307 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3308 return CompleteObject();
3311 CallStackFrame *Frame = nullptr;
3313 if (LVal.getLValueCallIndex()) {
3314 std::tie(Frame, Depth) =
3315 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3317 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3318 << AK << LVal.Base.is<const ValueDecl*>();
3319 NoteLValueLocation(Info, LVal.Base);
3320 return CompleteObject();
3324 bool IsAccess = isFormalAccess(AK);
3326 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3327 // is not a constant expression (even if the object is non-volatile). We also
3328 // apply this rule to C++98, in order to conform to the expected 'volatile'
3330 if (IsAccess && LValType.isVolatileQualified()) {
3331 if (Info.getLangOpts().CPlusPlus)
3332 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3336 return CompleteObject();
3339 // Compute value storage location and type of base object.
3340 APValue *BaseVal = nullptr;
3341 QualType BaseType = getType(LVal.Base);
3343 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3344 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3345 // In C++11, constexpr, non-volatile variables initialized with constant
3346 // expressions are constant expressions too. Inside constexpr functions,
3347 // parameters are constant expressions even if they're non-const.
3348 // In C++1y, objects local to a constant expression (those with a Frame) are
3349 // both readable and writable inside constant expressions.
3350 // In C, such things can also be folded, although they are not ICEs.
3351 const VarDecl *VD = dyn_cast<VarDecl>(D);
3353 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3356 if (!VD || VD->isInvalidDecl()) {
3358 return CompleteObject();
3361 // Unless we're looking at a local variable or argument in a constexpr call,
3362 // the variable we're reading must be const.
3364 if (Info.getLangOpts().CPlusPlus14 &&
3366 VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3367 // OK, we can read and modify an object if we're in the process of
3368 // evaluating its initializer, because its lifetime began in this
3370 } else if (isModification(AK)) {
3371 // All the remaining cases do not permit modification of the object.
3372 Info.FFDiag(E, diag::note_constexpr_modify_global);
3373 return CompleteObject();
3374 } else if (VD->isConstexpr()) {
3375 // OK, we can read this variable.
3376 } else if (BaseType->isIntegralOrEnumerationType()) {
3377 // In OpenCL if a variable is in constant address space it is a const
3379 if (!(BaseType.isConstQualified() ||
3380 (Info.getLangOpts().OpenCL &&
3381 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3383 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3384 if (Info.getLangOpts().CPlusPlus) {
3385 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3386 Info.Note(VD->getLocation(), diag::note_declared_at);
3390 return CompleteObject();
3392 } else if (!IsAccess) {
3393 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3394 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3395 // We support folding of const floating-point types, in order to make
3396 // static const data members of such types (supported as an extension)
3398 if (Info.getLangOpts().CPlusPlus11) {
3399 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3400 Info.Note(VD->getLocation(), diag::note_declared_at);
3404 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3405 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3406 // Keep evaluating to see what we can do.
3408 // FIXME: Allow folding of values of any literal type in all languages.
3409 if (Info.checkingPotentialConstantExpression() &&
3410 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3411 // The definition of this variable could be constexpr. We can't
3412 // access it right now, but may be able to in future.
3413 } else if (Info.getLangOpts().CPlusPlus11) {
3414 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3415 Info.Note(VD->getLocation(), diag::note_declared_at);
3419 return CompleteObject();
3423 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3424 return CompleteObject();
3426 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3429 if (const MaterializeTemporaryExpr *MTE =
3430 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3431 assert(MTE->getStorageDuration() == SD_Static &&
3432 "should have a frame for a non-global materialized temporary");
3434 // Per C++1y [expr.const]p2:
3435 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3436 // - a [...] glvalue of integral or enumeration type that refers to
3437 // a non-volatile const object [...]
3439 // - a [...] glvalue of literal type that refers to a non-volatile
3440 // object whose lifetime began within the evaluation of e.
3442 // C++11 misses the 'began within the evaluation of e' check and
3443 // instead allows all temporaries, including things like:
3446 // constexpr int k = r;
3447 // Therefore we use the C++14 rules in C++11 too.
3448 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3449 const ValueDecl *ED = MTE->getExtendingDecl();
3450 if (!(BaseType.isConstQualified() &&
3451 BaseType->isIntegralOrEnumerationType()) &&
3452 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3454 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3455 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3456 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3457 return CompleteObject();
3460 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3461 assert(BaseVal && "got reference to unevaluated temporary");
3464 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3467 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3469 << Val.getAsString(Info.Ctx,
3470 Info.Ctx.getLValueReferenceType(LValType));
3471 NoteLValueLocation(Info, LVal.Base);
3472 return CompleteObject();
3475 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3476 assert(BaseVal && "missing value for temporary");
3480 // In C++14, we can't safely access any mutable state when we might be
3481 // evaluating after an unmodeled side effect.
3483 // FIXME: Not all local state is mutable. Allow local constant subobjects
3484 // to be read here (but take care with 'mutable' fields).
3485 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3486 Info.EvalStatus.HasSideEffects) ||
3487 (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3488 return CompleteObject();
3490 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3493 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3494 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3495 /// glvalue referred to by an entity of reference type.
3497 /// \param Info - Information about the ongoing evaluation.
3498 /// \param Conv - The expression for which we are performing the conversion.
3499 /// Used for diagnostics.
3500 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3501 /// case of a non-class type).
3502 /// \param LVal - The glvalue on which we are attempting to perform this action.
3503 /// \param RVal - The produced value will be placed here.
3504 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3506 const LValue &LVal, APValue &RVal) {
3507 if (LVal.Designator.Invalid)
3510 // Check for special cases where there is no existing APValue to look at.
3511 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3513 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3514 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3515 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3516 // initializer until now for such expressions. Such an expression can't be
3517 // an ICE in C, so this only matters for fold.
3518 if (Type.isVolatileQualified()) {
3523 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3525 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3526 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3527 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3528 // Special-case character extraction so we don't have to construct an
3529 // APValue for the whole string.
3530 assert(LVal.Designator.Entries.size() <= 1 &&
3531 "Can only read characters from string literals");
3532 if (LVal.Designator.Entries.empty()) {
3533 // Fail for now for LValue to RValue conversion of an array.
3534 // (This shouldn't show up in C/C++, but it could be triggered by a
3535 // weird EvaluateAsRValue call from a tool.)
3539 if (LVal.Designator.isOnePastTheEnd()) {
3540 if (Info.getLangOpts().CPlusPlus11)
3541 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3546 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3547 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3552 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3553 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3556 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3557 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3558 QualType LValType, APValue &Val) {
3559 if (LVal.Designator.Invalid)
3562 if (!Info.getLangOpts().CPlusPlus14) {
3567 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3568 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3572 struct CompoundAssignSubobjectHandler {
3575 QualType PromotedLHSType;
3576 BinaryOperatorKind Opcode;
3579 static const AccessKinds AccessKind = AK_Assign;
3581 typedef bool result_type;
3583 bool checkConst(QualType QT) {
3584 // Assigning to a const object has undefined behavior.
3585 if (QT.isConstQualified()) {
3586 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3592 bool failed() { return false; }
3593 bool found(APValue &Subobj, QualType SubobjType) {
3594 switch (Subobj.getKind()) {
3596 return found(Subobj.getInt(), SubobjType);
3597 case APValue::Float:
3598 return found(Subobj.getFloat(), SubobjType);
3599 case APValue::ComplexInt:
3600 case APValue::ComplexFloat:
3601 // FIXME: Implement complex compound assignment.
3604 case APValue::LValue:
3605 return foundPointer(Subobj, SubobjType);
3607 // FIXME: can this happen?
3612 bool found(APSInt &Value, QualType SubobjType) {
3613 if (!checkConst(SubobjType))
3616 if (!SubobjType->isIntegerType()) {
3617 // We don't support compound assignment on integer-cast-to-pointer
3625 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3626 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3628 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3630 } else if (RHS.isFloat()) {
3631 APFloat FValue(0.0);
3632 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3634 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3635 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3642 bool found(APFloat &Value, QualType SubobjType) {
3643 return checkConst(SubobjType) &&
3644 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3646 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3647 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3649 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3650 if (!checkConst(SubobjType))
3653 QualType PointeeType;
3654 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3655 PointeeType = PT->getPointeeType();
3657 if (PointeeType.isNull() || !RHS.isInt() ||
3658 (Opcode != BO_Add && Opcode != BO_Sub)) {
3663 APSInt Offset = RHS.getInt();
3664 if (Opcode == BO_Sub)
3665 negateAsSigned(Offset);
3668 LVal.setFrom(Info.Ctx, Subobj);
3669 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3671 LVal.moveInto(Subobj);
3675 } // end anonymous namespace
3677 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3679 /// Perform a compound assignment of LVal <op>= RVal.
3680 static bool handleCompoundAssignment(
3681 EvalInfo &Info, const Expr *E,
3682 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3683 BinaryOperatorKind Opcode, const APValue &RVal) {
3684 if (LVal.Designator.Invalid)
3687 if (!Info.getLangOpts().CPlusPlus14) {
3692 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3693 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3695 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3699 struct IncDecSubobjectHandler {
3701 const UnaryOperator *E;
3702 AccessKinds AccessKind;
3705 typedef bool result_type;
3707 bool checkConst(QualType QT) {
3708 // Assigning to a const object has undefined behavior.
3709 if (QT.isConstQualified()) {
3710 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3716 bool failed() { return false; }
3717 bool found(APValue &Subobj, QualType SubobjType) {
3718 // Stash the old value. Also clear Old, so we don't clobber it later
3719 // if we're post-incrementing a complex.
3725 switch (Subobj.getKind()) {
3727 return found(Subobj.getInt(), SubobjType);
3728 case APValue::Float:
3729 return found(Subobj.getFloat(), SubobjType);
3730 case APValue::ComplexInt:
3731 return found(Subobj.getComplexIntReal(),
3732 SubobjType->castAs<ComplexType>()->getElementType()
3733 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3734 case APValue::ComplexFloat:
3735 return found(Subobj.getComplexFloatReal(),
3736 SubobjType->castAs<ComplexType>()->getElementType()
3737 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3738 case APValue::LValue:
3739 return foundPointer(Subobj, SubobjType);
3741 // FIXME: can this happen?
3746 bool found(APSInt &Value, QualType SubobjType) {
3747 if (!checkConst(SubobjType))
3750 if (!SubobjType->isIntegerType()) {
3751 // We don't support increment / decrement on integer-cast-to-pointer
3757 if (Old) *Old = APValue(Value);
3759 // bool arithmetic promotes to int, and the conversion back to bool
3760 // doesn't reduce mod 2^n, so special-case it.
3761 if (SubobjType->isBooleanType()) {
3762 if (AccessKind == AK_Increment)
3769 bool WasNegative = Value.isNegative();
3770 if (AccessKind == AK_Increment) {
3773 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3774 APSInt ActualValue(Value, /*IsUnsigned*/true);
3775 return HandleOverflow(Info, E, ActualValue, SubobjType);
3780 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3781 unsigned BitWidth = Value.getBitWidth();
3782 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3783 ActualValue.setBit(BitWidth);
3784 return HandleOverflow(Info, E, ActualValue, SubobjType);
3789 bool found(APFloat &Value, QualType SubobjType) {
3790 if (!checkConst(SubobjType))
3793 if (Old) *Old = APValue(Value);
3795 APFloat One(Value.getSemantics(), 1);
3796 if (AccessKind == AK_Increment)
3797 Value.add(One, APFloat::rmNearestTiesToEven);
3799 Value.subtract(One, APFloat::rmNearestTiesToEven);
3802 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3803 if (!checkConst(SubobjType))
3806 QualType PointeeType;
3807 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3808 PointeeType = PT->getPointeeType();
3815 LVal.setFrom(Info.Ctx, Subobj);
3816 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3817 AccessKind == AK_Increment ? 1 : -1))
3819 LVal.moveInto(Subobj);
3823 } // end anonymous namespace
3825 /// Perform an increment or decrement on LVal.
3826 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3827 QualType LValType, bool IsIncrement, APValue *Old) {
3828 if (LVal.Designator.Invalid)
3831 if (!Info.getLangOpts().CPlusPlus14) {
3836 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3837 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3838 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3839 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3842 /// Build an lvalue for the object argument of a member function call.
3843 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3845 if (Object->getType()->isPointerType())
3846 return EvaluatePointer(Object, This, Info);
3848 if (Object->isGLValue())
3849 return EvaluateLValue(Object, This, Info);
3851 if (Object->getType()->isLiteralType(Info.Ctx))
3852 return EvaluateTemporary(Object, This, Info);
3854 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3858 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3859 /// lvalue referring to the result.
3861 /// \param Info - Information about the ongoing evaluation.
3862 /// \param LV - An lvalue referring to the base of the member pointer.
3863 /// \param RHS - The member pointer expression.
3864 /// \param IncludeMember - Specifies whether the member itself is included in
3865 /// the resulting LValue subobject designator. This is not possible when
3866 /// creating a bound member function.
3867 /// \return The field or method declaration to which the member pointer refers,
3868 /// or 0 if evaluation fails.
3869 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3873 bool IncludeMember = true) {
3875 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3878 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3879 // member value, the behavior is undefined.
3880 if (!MemPtr.getDecl()) {
3881 // FIXME: Specific diagnostic.
3886 if (MemPtr.isDerivedMember()) {
3887 // This is a member of some derived class. Truncate LV appropriately.
3888 // The end of the derived-to-base path for the base object must match the
3889 // derived-to-base path for the member pointer.
3890 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3891 LV.Designator.Entries.size()) {
3895 unsigned PathLengthToMember =
3896 LV.Designator.Entries.size() - MemPtr.Path.size();
3897 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3898 const CXXRecordDecl *LVDecl = getAsBaseClass(
3899 LV.Designator.Entries[PathLengthToMember + I]);
3900 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3901 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3907 // Truncate the lvalue to the appropriate derived class.
3908 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3909 PathLengthToMember))
3911 } else if (!MemPtr.Path.empty()) {
3912 // Extend the LValue path with the member pointer's path.
3913 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3914 MemPtr.Path.size() + IncludeMember);
3916 // Walk down to the appropriate base class.
3917 if (const PointerType *PT = LVType->getAs<PointerType>())
3918 LVType = PT->getPointeeType();
3919 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3920 assert(RD && "member pointer access on non-class-type expression");
3921 // The first class in the path is that of the lvalue.
3922 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3923 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3924 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3928 // Finally cast to the class containing the member.
3929 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3930 MemPtr.getContainingRecord()))
3934 // Add the member. Note that we cannot build bound member functions here.
3935 if (IncludeMember) {
3936 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3937 if (!HandleLValueMember(Info, RHS, LV, FD))
3939 } else if (const IndirectFieldDecl *IFD =
3940 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3941 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3944 llvm_unreachable("can't construct reference to bound member function");
3948 return MemPtr.getDecl();
3951 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3952 const BinaryOperator *BO,
3954 bool IncludeMember = true) {
3955 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3957 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3958 if (Info.noteFailure()) {
3960 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3965 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3966 BO->getRHS(), IncludeMember);
3969 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3970 /// the provided lvalue, which currently refers to the base object.
3971 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3973 SubobjectDesignator &D = Result.Designator;
3974 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3977 QualType TargetQT = E->getType();
3978 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3979 TargetQT = PT->getPointeeType();
3981 // Check this cast lands within the final derived-to-base subobject path.
3982 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3983 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3984 << D.MostDerivedType << TargetQT;
3988 // Check the type of the final cast. We don't need to check the path,
3989 // since a cast can only be formed if the path is unique.
3990 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3991 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3992 const CXXRecordDecl *FinalType;
3993 if (NewEntriesSize == D.MostDerivedPathLength)
3994 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3996 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3997 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3998 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3999 << D.MostDerivedType << TargetQT;
4003 // Truncate the lvalue to the appropriate derived class.
4004 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4008 enum EvalStmtResult {
4009 /// Evaluation failed.
4011 /// Hit a 'return' statement.
4013 /// Evaluation succeeded.
4015 /// Hit a 'continue' statement.
4017 /// Hit a 'break' statement.
4019 /// Still scanning for 'case' or 'default' statement.
4024 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4025 // We don't need to evaluate the initializer for a static local.
4026 if (!VD->hasLocalStorage())
4030 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4032 const Expr *InitE = VD->getInit();
4034 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4035 << false << VD->getType();
4040 if (InitE->isValueDependent())
4043 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4044 // Wipe out any partially-computed value, to allow tracking that this
4045 // evaluation failed.
4053 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4056 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4057 OK &= EvaluateVarDecl(Info, VD);
4059 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4060 for (auto *BD : DD->bindings())
4061 if (auto *VD = BD->getHoldingVar())
4062 OK &= EvaluateDecl(Info, VD);
4068 /// Evaluate a condition (either a variable declaration or an expression).
4069 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4070 const Expr *Cond, bool &Result) {
4071 FullExpressionRAII Scope(Info);
4072 if (CondDecl && !EvaluateDecl(Info, CondDecl))
4074 return EvaluateAsBooleanCondition(Cond, Result, Info);
4078 /// A location where the result (returned value) of evaluating a
4079 /// statement should be stored.
4081 /// The APValue that should be filled in with the returned value.
4083 /// The location containing the result, if any (used to support RVO).
4087 struct TempVersionRAII {
4088 CallStackFrame &Frame;
4090 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4091 Frame.pushTempVersion();
4094 ~TempVersionRAII() {
4095 Frame.popTempVersion();
4101 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4103 const SwitchCase *SC = nullptr);
4105 /// Evaluate the body of a loop, and translate the result as appropriate.
4106 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4108 const SwitchCase *Case = nullptr) {
4109 BlockScopeRAII Scope(Info);
4110 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4112 return ESR_Succeeded;
4115 return ESR_Continue;
4118 case ESR_CaseNotFound:
4121 llvm_unreachable("Invalid EvalStmtResult!");
4124 /// Evaluate a switch statement.
4125 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4126 const SwitchStmt *SS) {
4127 BlockScopeRAII Scope(Info);
4129 // Evaluate the switch condition.
4132 FullExpressionRAII Scope(Info);
4133 if (const Stmt *Init = SS->getInit()) {
4134 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4135 if (ESR != ESR_Succeeded)
4138 if (SS->getConditionVariable() &&
4139 !EvaluateDecl(Info, SS->getConditionVariable()))
4141 if (!EvaluateInteger(SS->getCond(), Value, Info))
4145 // Find the switch case corresponding to the value of the condition.
4146 // FIXME: Cache this lookup.
4147 const SwitchCase *Found = nullptr;
4148 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4149 SC = SC->getNextSwitchCase()) {
4150 if (isa<DefaultStmt>(SC)) {
4155 const CaseStmt *CS = cast<CaseStmt>(SC);
4156 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4157 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4159 if (LHS <= Value && Value <= RHS) {
4166 return ESR_Succeeded;
4168 // Search the switch body for the switch case and evaluate it from there.
4169 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4171 return ESR_Succeeded;
4177 case ESR_CaseNotFound:
4178 // This can only happen if the switch case is nested within a statement
4179 // expression. We have no intention of supporting that.
4180 Info.FFDiag(Found->getBeginLoc(),
4181 diag::note_constexpr_stmt_expr_unsupported);
4184 llvm_unreachable("Invalid EvalStmtResult!");
4187 // Evaluate a statement.
4188 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4189 const Stmt *S, const SwitchCase *Case) {
4190 if (!Info.nextStep(S))
4193 // If we're hunting down a 'case' or 'default' label, recurse through
4194 // substatements until we hit the label.
4196 // FIXME: We don't start the lifetime of objects whose initialization we
4197 // jump over. However, such objects must be of class type with a trivial
4198 // default constructor that initialize all subobjects, so must be empty,
4199 // so this almost never matters.
4200 switch (S->getStmtClass()) {
4201 case Stmt::CompoundStmtClass:
4202 // FIXME: Precompute which substatement of a compound statement we
4203 // would jump to, and go straight there rather than performing a
4204 // linear scan each time.
4205 case Stmt::LabelStmtClass:
4206 case Stmt::AttributedStmtClass:
4207 case Stmt::DoStmtClass:
4210 case Stmt::CaseStmtClass:
4211 case Stmt::DefaultStmtClass:
4216 case Stmt::IfStmtClass: {
4217 // FIXME: Precompute which side of an 'if' we would jump to, and go
4218 // straight there rather than scanning both sides.
4219 const IfStmt *IS = cast<IfStmt>(S);
4221 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4222 // preceded by our switch label.
4223 BlockScopeRAII Scope(Info);
4225 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4226 if (ESR != ESR_CaseNotFound || !IS->getElse())
4228 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4231 case Stmt::WhileStmtClass: {
4232 EvalStmtResult ESR =
4233 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4234 if (ESR != ESR_Continue)
4239 case Stmt::ForStmtClass: {
4240 const ForStmt *FS = cast<ForStmt>(S);
4241 EvalStmtResult ESR =
4242 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4243 if (ESR != ESR_Continue)
4246 FullExpressionRAII IncScope(Info);
4247 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4253 case Stmt::DeclStmtClass:
4254 // FIXME: If the variable has initialization that can't be jumped over,
4255 // bail out of any immediately-surrounding compound-statement too.
4257 return ESR_CaseNotFound;
4261 switch (S->getStmtClass()) {
4263 if (const Expr *E = dyn_cast<Expr>(S)) {
4264 // Don't bother evaluating beyond an expression-statement which couldn't
4266 FullExpressionRAII Scope(Info);
4267 if (!EvaluateIgnoredValue(Info, E))
4269 return ESR_Succeeded;
4272 Info.FFDiag(S->getBeginLoc());
4275 case Stmt::NullStmtClass:
4276 return ESR_Succeeded;
4278 case Stmt::DeclStmtClass: {
4279 const DeclStmt *DS = cast<DeclStmt>(S);
4280 for (const auto *DclIt : DS->decls()) {
4281 // Each declaration initialization is its own full-expression.
4282 // FIXME: This isn't quite right; if we're performing aggregate
4283 // initialization, each braced subexpression is its own full-expression.
4284 FullExpressionRAII Scope(Info);
4285 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4288 return ESR_Succeeded;
4291 case Stmt::ReturnStmtClass: {
4292 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4293 FullExpressionRAII Scope(Info);
4296 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4297 : Evaluate(Result.Value, Info, RetExpr)))
4299 return ESR_Returned;
4302 case Stmt::CompoundStmtClass: {
4303 BlockScopeRAII Scope(Info);
4305 const CompoundStmt *CS = cast<CompoundStmt>(S);
4306 for (const auto *BI : CS->body()) {
4307 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4308 if (ESR == ESR_Succeeded)
4310 else if (ESR != ESR_CaseNotFound)
4313 return Case ? ESR_CaseNotFound : ESR_Succeeded;
4316 case Stmt::IfStmtClass: {
4317 const IfStmt *IS = cast<IfStmt>(S);
4319 // Evaluate the condition, as either a var decl or as an expression.
4320 BlockScopeRAII Scope(Info);
4321 if (const Stmt *Init = IS->getInit()) {
4322 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4323 if (ESR != ESR_Succeeded)
4327 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4330 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4331 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4332 if (ESR != ESR_Succeeded)
4335 return ESR_Succeeded;
4338 case Stmt::WhileStmtClass: {
4339 const WhileStmt *WS = cast<WhileStmt>(S);
4341 BlockScopeRAII Scope(Info);
4343 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4349 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4350 if (ESR != ESR_Continue)
4353 return ESR_Succeeded;
4356 case Stmt::DoStmtClass: {
4357 const DoStmt *DS = cast<DoStmt>(S);
4360 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4361 if (ESR != ESR_Continue)
4365 FullExpressionRAII CondScope(Info);
4366 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4369 return ESR_Succeeded;
4372 case Stmt::ForStmtClass: {
4373 const ForStmt *FS = cast<ForStmt>(S);
4374 BlockScopeRAII Scope(Info);
4375 if (FS->getInit()) {
4376 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4377 if (ESR != ESR_Succeeded)
4381 BlockScopeRAII Scope(Info);
4382 bool Continue = true;
4383 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4384 FS->getCond(), Continue))
4389 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4390 if (ESR != ESR_Continue)
4394 FullExpressionRAII IncScope(Info);
4395 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4399 return ESR_Succeeded;
4402 case Stmt::CXXForRangeStmtClass: {
4403 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4404 BlockScopeRAII Scope(Info);
4406 // Evaluate the init-statement if present.
4407 if (FS->getInit()) {
4408 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4409 if (ESR != ESR_Succeeded)
4413 // Initialize the __range variable.
4414 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4415 if (ESR != ESR_Succeeded)
4418 // Create the __begin and __end iterators.
4419 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4420 if (ESR != ESR_Succeeded)
4422 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4423 if (ESR != ESR_Succeeded)
4427 // Condition: __begin != __end.
4429 bool Continue = true;
4430 FullExpressionRAII CondExpr(Info);
4431 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4437 // User's variable declaration, initialized by *__begin.
4438 BlockScopeRAII InnerScope(Info);
4439 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4440 if (ESR != ESR_Succeeded)
4444 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4445 if (ESR != ESR_Continue)
4448 // Increment: ++__begin
4449 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4453 return ESR_Succeeded;
4456 case Stmt::SwitchStmtClass:
4457 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4459 case Stmt::ContinueStmtClass:
4460 return ESR_Continue;
4462 case Stmt::BreakStmtClass:
4465 case Stmt::LabelStmtClass:
4466 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4468 case Stmt::AttributedStmtClass:
4469 // As a general principle, C++11 attributes can be ignored without
4470 // any semantic impact.
4471 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4474 case Stmt::CaseStmtClass:
4475 case Stmt::DefaultStmtClass:
4476 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4477 case Stmt::CXXTryStmtClass:
4478 // Evaluate try blocks by evaluating all sub statements.
4479 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4483 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4484 /// default constructor. If so, we'll fold it whether or not it's marked as
4485 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4486 /// so we need special handling.
4487 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4488 const CXXConstructorDecl *CD,
4489 bool IsValueInitialization) {
4490 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4493 // Value-initialization does not call a trivial default constructor, so such a
4494 // call is a core constant expression whether or not the constructor is
4496 if (!CD->isConstexpr() && !IsValueInitialization) {
4497 if (Info.getLangOpts().CPlusPlus11) {
4498 // FIXME: If DiagDecl is an implicitly-declared special member function,
4499 // we should be much more explicit about why it's not constexpr.
4500 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4501 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4502 Info.Note(CD->getLocation(), diag::note_declared_at);
4504 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4510 /// CheckConstexprFunction - Check that a function can be called in a constant
4512 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4513 const FunctionDecl *Declaration,
4514 const FunctionDecl *Definition,
4516 // Potential constant expressions can contain calls to declared, but not yet
4517 // defined, constexpr functions.
4518 if (Info.checkingPotentialConstantExpression() && !Definition &&
4519 Declaration->isConstexpr())
4522 // Bail out if the function declaration itself is invalid. We will
4523 // have produced a relevant diagnostic while parsing it, so just
4524 // note the problematic sub-expression.
4525 if (Declaration->isInvalidDecl()) {
4526 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4530 // DR1872: An instantiated virtual constexpr function can't be called in a
4531 // constant expression (prior to C++20). We can still constant-fold such a
4533 if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4534 cast<CXXMethodDecl>(Declaration)->isVirtual())
4535 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4537 if (Definition && Definition->isInvalidDecl()) {
4538 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4542 // Can we evaluate this function call?
4543 if (Definition && Definition->isConstexpr() && Body)
4546 if (Info.getLangOpts().CPlusPlus11) {
4547 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4549 // If this function is not constexpr because it is an inherited
4550 // non-constexpr constructor, diagnose that directly.
4551 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4552 if (CD && CD->isInheritingConstructor()) {
4553 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4554 if (!Inherited->isConstexpr())
4555 DiagDecl = CD = Inherited;
4558 // FIXME: If DiagDecl is an implicitly-declared special member function
4559 // or an inheriting constructor, we should be much more explicit about why
4560 // it's not constexpr.
4561 if (CD && CD->isInheritingConstructor())
4562 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4563 << CD->getInheritedConstructor().getConstructor()->getParent();
4565 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4566 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4567 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4569 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4575 struct CheckDynamicTypeHandler {
4576 AccessKinds AccessKind;
4577 typedef bool result_type;
4578 bool failed() { return false; }
4579 bool found(APValue &Subobj, QualType SubobjType) { return true; }
4580 bool found(APSInt &Value, QualType SubobjType) { return true; }
4581 bool found(APFloat &Value, QualType SubobjType) { return true; }
4583 } // end anonymous namespace
4585 /// Check that we can access the notional vptr of an object / determine its
4587 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4588 AccessKinds AK, bool Polymorphic) {
4589 if (This.Designator.Invalid)
4592 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4598 // The object is not usable in constant expressions, so we can't inspect
4599 // its value to see if it's in-lifetime or what the active union members
4600 // are. We can still check for a one-past-the-end lvalue.
4601 if (This.Designator.isOnePastTheEnd() ||
4602 This.Designator.isMostDerivedAnUnsizedArray()) {
4603 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4604 ? diag::note_constexpr_access_past_end
4605 : diag::note_constexpr_access_unsized_array)
4608 } else if (Polymorphic) {
4609 // Conservatively refuse to perform a polymorphic operation if we would
4610 // not be able to read a notional 'vptr' value.
4613 QualType StarThisType =
4614 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4615 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4616 << AK << Val.getAsString(Info.Ctx, StarThisType);
4622 CheckDynamicTypeHandler Handler{AK};
4623 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4626 /// Check that the pointee of the 'this' pointer in a member function call is
4627 /// either within its lifetime or in its period of construction or destruction.
4628 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4629 const LValue &This) {
4630 return checkDynamicType(Info, E, This, AK_MemberCall, false);
4633 struct DynamicType {
4634 /// The dynamic class type of the object.
4635 const CXXRecordDecl *Type;
4636 /// The corresponding path length in the lvalue.
4637 unsigned PathLength;
4640 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4641 unsigned PathLength) {
4642 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4643 Designator.Entries.size() && "invalid path length");
4644 return (PathLength == Designator.MostDerivedPathLength)
4645 ? Designator.MostDerivedType->getAsCXXRecordDecl()
4646 : getAsBaseClass(Designator.Entries[PathLength - 1]);
4649 /// Determine the dynamic type of an object.
4650 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4651 LValue &This, AccessKinds AK) {
4652 // If we don't have an lvalue denoting an object of class type, there is no
4653 // meaningful dynamic type. (We consider objects of non-class type to have no
4655 if (!checkDynamicType(Info, E, This, AK, true))
4658 // Refuse to compute a dynamic type in the presence of virtual bases. This
4659 // shouldn't happen other than in constant-folding situations, since literal
4660 // types can't have virtual bases.
4662 // Note that consumers of DynamicType assume that the type has no virtual
4663 // bases, and will need modifications if this restriction is relaxed.
4664 const CXXRecordDecl *Class =
4665 This.Designator.MostDerivedType->getAsCXXRecordDecl();
4666 if (!Class || Class->getNumVBases()) {
4671 // FIXME: For very deep class hierarchies, it might be beneficial to use a
4672 // binary search here instead. But the overwhelmingly common case is that
4673 // we're not in the middle of a constructor, so it probably doesn't matter
4675 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4676 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4677 PathLength <= Path.size(); ++PathLength) {
4678 switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4679 Path.slice(0, PathLength))) {
4680 case ConstructionPhase::Bases:
4681 // We're constructing a base class. This is not the dynamic type.
4684 case ConstructionPhase::None:
4685 case ConstructionPhase::AfterBases:
4686 // We've finished constructing the base classes, so this is the dynamic
4688 return DynamicType{getBaseClassType(This.Designator, PathLength),
4693 // CWG issue 1517: we're constructing a base class of the object described by
4694 // 'This', so that object has not yet begun its period of construction and
4695 // any polymorphic operation on it results in undefined behavior.
4700 /// Perform virtual dispatch.
4701 static const CXXMethodDecl *HandleVirtualDispatch(
4702 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4703 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4704 Optional<DynamicType> DynType =
4705 ComputeDynamicType(Info, E, This, AK_MemberCall);
4709 // Find the final overrider. It must be declared in one of the classes on the
4710 // path from the dynamic type to the static type.
4711 // FIXME: If we ever allow literal types to have virtual base classes, that
4713 const CXXMethodDecl *Callee = Found;
4714 unsigned PathLength = DynType->PathLength;
4715 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4716 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4717 const CXXMethodDecl *Overrider =
4718 Found->getCorrespondingMethodDeclaredInClass(Class, false);
4725 // C++2a [class.abstract]p6:
4726 // the effect of making a virtual call to a pure virtual function [...] is
4728 if (Callee->isPure()) {
4729 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4730 Info.Note(Callee->getLocation(), diag::note_declared_at);
4734 // If necessary, walk the rest of the path to determine the sequence of
4735 // covariant adjustment steps to apply.
4736 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4737 Found->getReturnType())) {
4738 CovariantAdjustmentPath.push_back(Callee->getReturnType());
4739 for (unsigned CovariantPathLength = PathLength + 1;
4740 CovariantPathLength != This.Designator.Entries.size();
4741 ++CovariantPathLength) {
4742 const CXXRecordDecl *NextClass =
4743 getBaseClassType(This.Designator, CovariantPathLength);
4744 const CXXMethodDecl *Next =
4745 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4746 if (Next && !Info.Ctx.hasSameUnqualifiedType(
4747 Next->getReturnType(), CovariantAdjustmentPath.back()))
4748 CovariantAdjustmentPath.push_back(Next->getReturnType());
4750 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4751 CovariantAdjustmentPath.back()))
4752 CovariantAdjustmentPath.push_back(Found->getReturnType());
4755 // Perform 'this' adjustment.
4756 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4762 /// Perform the adjustment from a value returned by a virtual function to
4763 /// a value of the statically expected type, which may be a pointer or
4764 /// reference to a base class of the returned type.
4765 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4767 ArrayRef<QualType> Path) {
4768 assert(Result.isLValue() &&
4769 "unexpected kind of APValue for covariant return");
4770 if (Result.isNullPointer())
4774 LVal.setFrom(Info.Ctx, Result);
4776 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4777 for (unsigned I = 1; I != Path.size(); ++I) {
4778 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4779 assert(OldClass && NewClass && "unexpected kind of covariant return");
4780 if (OldClass != NewClass &&
4781 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4783 OldClass = NewClass;
4786 LVal.moveInto(Result);
4790 /// Determine whether \p Base, which is known to be a direct base class of
4791 /// \p Derived, is a public base class.
4792 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4793 const CXXRecordDecl *Base) {
4794 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4795 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4796 if (BaseClass && declaresSameEntity(BaseClass, Base))
4797 return BaseSpec.getAccessSpecifier() == AS_public;
4799 llvm_unreachable("Base is not a direct base of Derived");
4802 /// Apply the given dynamic cast operation on the provided lvalue.
4804 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4805 /// to find a suitable target subobject.
4806 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4808 // We can't do anything with a non-symbolic pointer value.
4809 SubobjectDesignator &D = Ptr.Designator;
4813 // C++ [expr.dynamic.cast]p6:
4814 // If v is a null pointer value, the result is a null pointer value.
4815 if (Ptr.isNullPointer() && !E->isGLValue())
4818 // For all the other cases, we need the pointer to point to an object within
4819 // its lifetime / period of construction / destruction, and we need to know
4820 // its dynamic type.
4821 Optional<DynamicType> DynType =
4822 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4826 // C++ [expr.dynamic.cast]p7:
4827 // If T is "pointer to cv void", then the result is a pointer to the most
4829 if (E->getType()->isVoidPointerType())
4830 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4832 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4833 assert(C && "dynamic_cast target is not void pointer nor class");
4834 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4836 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4837 // C++ [expr.dynamic.cast]p9:
4838 if (!E->isGLValue()) {
4839 // The value of a failed cast to pointer type is the null pointer value
4840 // of the required result type.
4841 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4842 Ptr.setNull(E->getType(), TargetVal);
4846 // A failed cast to reference type throws [...] std::bad_cast.
4848 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4849 DynType->Type->isDerivedFrom(C)))
4851 else if (!Paths || Paths->begin() == Paths->end())
4853 else if (Paths->isAmbiguous(CQT))
4856 assert(Paths->front().Access != AS_public && "why did the cast fail?");
4859 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4860 << DiagKind << Ptr.Designator.getType(Info.Ctx)
4861 << Info.Ctx.getRecordType(DynType->Type)
4862 << E->getType().getUnqualifiedType();
4866 // Runtime check, phase 1:
4867 // Walk from the base subobject towards the derived object looking for the
4869 for (int PathLength = Ptr.Designator.Entries.size();
4870 PathLength >= (int)DynType->PathLength; --PathLength) {
4871 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4872 if (declaresSameEntity(Class, C))
4873 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4874 // We can only walk across public inheritance edges.
4875 if (PathLength > (int)DynType->PathLength &&
4876 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4878 return RuntimeCheckFailed(nullptr);
4881 // Runtime check, phase 2:
4882 // Search the dynamic type for an unambiguous public base of type C.
4883 CXXBasePaths Paths(/*FindAmbiguities=*/true,
4884 /*RecordPaths=*/true, /*DetectVirtual=*/false);
4885 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4886 Paths.front().Access == AS_public) {
4887 // Downcast to the dynamic type...
4888 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4890 // ... then upcast to the chosen base class subobject.
4891 for (CXXBasePathElement &Elem : Paths.front())
4892 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4897 // Otherwise, the runtime check fails.
4898 return RuntimeCheckFailed(&Paths);
4902 struct StartLifetimeOfUnionMemberHandler {
4903 const FieldDecl *Field;
4905 static const AccessKinds AccessKind = AK_Assign;
4907 APValue getDefaultInitValue(QualType SubobjType) {
4908 if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4910 return APValue((const FieldDecl*)nullptr);
4912 APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4913 std::distance(RD->field_begin(), RD->field_end()));
4916 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4917 End = RD->bases_end(); I != End; ++I, ++Index)
4918 Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4920 for (const auto *I : RD->fields()) {
4921 if (I->isUnnamedBitfield())
4923 Struct.getStructField(I->getFieldIndex()) =
4924 getDefaultInitValue(I->getType());
4929 if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4930 SubobjType->getAsArrayTypeUnsafe())) {
4931 APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4932 if (Array.hasArrayFiller())
4933 Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4937 return APValue::IndeterminateValue();
4940 typedef bool result_type;
4941 bool failed() { return false; }
4942 bool found(APValue &Subobj, QualType SubobjType) {
4943 // We are supposed to perform no initialization but begin the lifetime of
4944 // the object. We interpret that as meaning to do what default
4945 // initialization of the object would do if all constructors involved were
4947 // * All base, non-variant member, and array element subobjects' lifetimes
4949 // * No variant members' lifetimes begin
4950 // * All scalar subobjects whose lifetimes begin have indeterminate values
4951 assert(SubobjType->isUnionType());
4952 if (!declaresSameEntity(Subobj.getUnionField(), Field))
4953 Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4956 bool found(APSInt &Value, QualType SubobjType) {
4957 llvm_unreachable("wrong value kind for union object");
4959 bool found(APFloat &Value, QualType SubobjType) {
4960 llvm_unreachable("wrong value kind for union object");
4963 } // end anonymous namespace
4965 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4967 /// Handle a builtin simple-assignment or a call to a trivial assignment
4968 /// operator whose left-hand side might involve a union member access. If it
4969 /// does, implicitly start the lifetime of any accessed union elements per
4970 /// C++20 [class.union]5.
4971 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4972 const LValue &LHS) {
4973 if (LHS.InvalidBase || LHS.Designator.Invalid)
4976 llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4977 // C++ [class.union]p5:
4978 // define the set S(E) of subexpressions of E as follows:
4979 unsigned PathLength = LHS.Designator.Entries.size();
4980 for (const Expr *E = LHSExpr; E != nullptr;) {
4981 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
4982 if (auto *ME = dyn_cast<MemberExpr>(E)) {
4983 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
4987 // ... and also contains A.B if B names a union member
4988 if (FD->getParent()->isUnion())
4989 UnionPathLengths.push_back({PathLength - 1, FD});
4993 assert(declaresSameEntity(FD,
4994 LHS.Designator.Entries[PathLength]
4995 .getAsBaseOrMember().getPointer()));
4997 // -- If E is of the form A[B] and is interpreted as a built-in array
4998 // subscripting operator, S(E) is [S(the array operand, if any)].
4999 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5000 // Step over an ArrayToPointerDecay implicit cast.
5001 auto *Base = ASE->getBase()->IgnoreImplicit();
5002 if (!Base->getType()->isArrayType())
5008 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5009 // Step over a derived-to-base conversion.
5010 E = ICE->getSubExpr();
5011 if (ICE->getCastKind() == CK_NoOp)
5013 if (ICE->getCastKind() != CK_DerivedToBase &&
5014 ICE->getCastKind() != CK_UncheckedDerivedToBase)
5016 // Walk path backwards as we walk up from the base to the derived class.
5017 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5020 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5021 LHS.Designator.Entries[PathLength]
5022 .getAsBaseOrMember().getPointer()));
5025 // -- Otherwise, S(E) is empty.
5031 // Common case: no unions' lifetimes are started.
5032 if (UnionPathLengths.empty())
5035 // if modification of X [would access an inactive union member], an object
5036 // of the type of X is implicitly created
5037 CompleteObject Obj =
5038 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5041 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5042 llvm::reverse(UnionPathLengths)) {
5043 // Form a designator for the union object.
5044 SubobjectDesignator D = LHS.Designator;
5045 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5047 StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5048 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5055 /// Determine if a class has any fields that might need to be copied by a
5056 /// trivial copy or move operation.
5057 static bool hasFields(const CXXRecordDecl *RD) {
5058 if (!RD || RD->isEmpty())
5060 for (auto *FD : RD->fields()) {
5061 if (FD->isUnnamedBitfield())
5065 for (auto &Base : RD->bases())
5066 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5072 typedef SmallVector<APValue, 8> ArgVector;
5075 /// EvaluateArgs - Evaluate the arguments to a function call.
5076 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5077 EvalInfo &Info, const FunctionDecl *Callee) {
5078 bool Success = true;
5079 llvm::SmallBitVector ForbiddenNullArgs;
5080 if (Callee->hasAttr<NonNullAttr>()) {
5081 ForbiddenNullArgs.resize(Args.size());
5082 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5083 if (!Attr->args_size()) {
5084 ForbiddenNullArgs.set();
5087 for (auto Idx : Attr->args()) {
5088 unsigned ASTIdx = Idx.getASTIndex();
5089 if (ASTIdx >= Args.size())
5091 ForbiddenNullArgs[ASTIdx] = 1;
5095 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
5097 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5098 // If we're checking for a potential constant expression, evaluate all
5099 // initializers even if some of them fail.
5100 if (!Info.noteFailure())
5103 } else if (!ForbiddenNullArgs.empty() &&
5104 ForbiddenNullArgs[I - Args.begin()] &&
5105 ArgValues[I - Args.begin()].isNullPointer()) {
5106 Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5107 if (!Info.noteFailure())
5115 /// Evaluate a function call.
5116 static bool HandleFunctionCall(SourceLocation CallLoc,
5117 const FunctionDecl *Callee, const LValue *This,
5118 ArrayRef<const Expr*> Args, const Stmt *Body,
5119 EvalInfo &Info, APValue &Result,
5120 const LValue *ResultSlot) {
5121 ArgVector ArgValues(Args.size());
5122 if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5125 if (!Info.CheckCallLimit(CallLoc))
5128 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5130 // For a trivial copy or move assignment, perform an APValue copy. This is
5131 // essential for unions, where the operations performed by the assignment
5132 // operator cannot be represented as statements.
5134 // Skip this for non-union classes with no fields; in that case, the defaulted
5135 // copy/move does not actually read the object.
5136 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5137 if (MD && MD->isDefaulted() &&
5138 (MD->getParent()->isUnion() ||
5139 (MD->isTrivial() && hasFields(MD->getParent())))) {
5141 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5143 RHS.setFrom(Info.Ctx, ArgValues[0]);
5145 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5148 if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5149 !HandleUnionActiveMemberChange(Info, Args[0], *This))
5151 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5154 This->moveInto(Result);
5156 } else if (MD && isLambdaCallOperator(MD)) {
5157 // We're in a lambda; determine the lambda capture field maps unless we're
5158 // just constexpr checking a lambda's call operator. constexpr checking is
5159 // done before the captures have been added to the closure object (unless
5160 // we're inferring constexpr-ness), so we don't have access to them in this
5161 // case. But since we don't need the captures to constexpr check, we can
5162 // just ignore them.
5163 if (!Info.checkingPotentialConstantExpression())
5164 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5165 Frame.LambdaThisCaptureField);
5168 StmtResult Ret = {Result, ResultSlot};
5169 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5170 if (ESR == ESR_Succeeded) {
5171 if (Callee->getReturnType()->isVoidType())
5173 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5175 return ESR == ESR_Returned;
5178 /// Evaluate a constructor call.
5179 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5181 const CXXConstructorDecl *Definition,
5182 EvalInfo &Info, APValue &Result) {
5183 SourceLocation CallLoc = E->getExprLoc();
5184 if (!Info.CheckCallLimit(CallLoc))
5187 const CXXRecordDecl *RD = Definition->getParent();
5188 if (RD->getNumVBases()) {
5189 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5193 EvalInfo::EvaluatingConstructorRAII EvalObj(
5195 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5197 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5199 // FIXME: Creating an APValue just to hold a nonexistent return value is
5202 StmtResult Ret = {RetVal, nullptr};
5204 // If it's a delegating constructor, delegate.
5205 if (Definition->isDelegatingConstructor()) {
5206 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5208 FullExpressionRAII InitScope(Info);
5209 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5212 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5215 // For a trivial copy or move constructor, perform an APValue copy. This is
5216 // essential for unions (or classes with anonymous union members), where the
5217 // operations performed by the constructor cannot be represented by
5218 // ctor-initializers.
5220 // Skip this for empty non-union classes; we should not perform an
5221 // lvalue-to-rvalue conversion on them because their copy constructor does not
5222 // actually read them.
5223 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5224 (Definition->getParent()->isUnion() ||
5225 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5227 RHS.setFrom(Info.Ctx, ArgValues[0]);
5228 return handleLValueToRValueConversion(
5229 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5233 // Reserve space for the struct members.
5234 if (!RD->isUnion() && !Result.hasValue())
5235 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5236 std::distance(RD->field_begin(), RD->field_end()));
5238 if (RD->isInvalidDecl()) return false;
5239 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5241 // A scope for temporaries lifetime-extended by reference members.
5242 BlockScopeRAII LifetimeExtendedScope(Info);
5244 bool Success = true;
5245 unsigned BasesSeen = 0;
5247 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5249 for (const auto *I : Definition->inits()) {
5250 LValue Subobject = This;
5251 LValue SubobjectParent = This;
5252 APValue *Value = &Result;
5254 // Determine the subobject to initialize.
5255 FieldDecl *FD = nullptr;
5256 if (I->isBaseInitializer()) {
5257 QualType BaseType(I->getBaseClass(), 0);
5259 // Non-virtual base classes are initialized in the order in the class
5260 // definition. We have already checked for virtual base classes.
5261 assert(!BaseIt->isVirtual() && "virtual base for literal type");
5262 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5263 "base class initializers not in expected order");
5266 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5267 BaseType->getAsCXXRecordDecl(), &Layout))
5269 Value = &Result.getStructBase(BasesSeen++);
5270 } else if ((FD = I->getMember())) {
5271 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5273 if (RD->isUnion()) {
5274 Result = APValue(FD);
5275 Value = &Result.getUnionValue();
5277 Value = &Result.getStructField(FD->getFieldIndex());
5279 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5280 // Walk the indirect field decl's chain to find the object to initialize,
5281 // and make sure we've initialized every step along it.
5282 auto IndirectFieldChain = IFD->chain();
5283 for (auto *C : IndirectFieldChain) {
5284 FD = cast<FieldDecl>(C);
5285 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5286 // Switch the union field if it differs. This happens if we had
5287 // preceding zero-initialization, and we're now initializing a union
5288 // subobject other than the first.
5289 // FIXME: In this case, the values of the other subobjects are
5290 // specified, since zero-initialization sets all padding bits to zero.
5291 if (!Value->hasValue() ||
5292 (Value->isUnion() && Value->getUnionField() != FD)) {
5294 *Value = APValue(FD);
5296 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5297 std::distance(CD->field_begin(), CD->field_end()));
5299 // Store Subobject as its parent before updating it for the last element
5301 if (C == IndirectFieldChain.back())
5302 SubobjectParent = Subobject;
5303 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5306 Value = &Value->getUnionValue();
5308 Value = &Value->getStructField(FD->getFieldIndex());
5311 llvm_unreachable("unknown base initializer kind");
5314 // Need to override This for implicit field initializers as in this case
5315 // This refers to innermost anonymous struct/union containing initializer,
5316 // not to currently constructed class.
5317 const Expr *Init = I->getInit();
5318 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5319 isa<CXXDefaultInitExpr>(Init));
5320 FullExpressionRAII InitScope(Info);
5321 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5322 (FD && FD->isBitField() &&
5323 !truncateBitfieldValue(Info, Init, *Value, FD))) {
5324 // If we're checking for a potential constant expression, evaluate all
5325 // initializers even if some of them fail.
5326 if (!Info.noteFailure())
5331 // This is the point at which the dynamic type of the object becomes this
5333 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5334 EvalObj.finishedConstructingBases();
5338 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5341 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5342 ArrayRef<const Expr*> Args,
5343 const CXXConstructorDecl *Definition,
5344 EvalInfo &Info, APValue &Result) {
5345 ArgVector ArgValues(Args.size());
5346 if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5349 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5353 //===----------------------------------------------------------------------===//
5354 // Generic Evaluation
5355 //===----------------------------------------------------------------------===//
5358 class BitCastBuffer {
5359 // FIXME: We're going to need bit-level granularity when we support
5361 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5362 // we don't support a host or target where that is the case. Still, we should
5363 // use a more generic type in case we ever do.
5364 SmallVector<Optional<unsigned char>, 32> Bytes;
5366 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5367 "Need at least 8 bit unsigned char");
5369 bool TargetIsLittleEndian;
5372 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5373 : Bytes(Width.getQuantity()),
5374 TargetIsLittleEndian(TargetIsLittleEndian) {}
5377 bool readObject(CharUnits Offset, CharUnits Width,
5378 SmallVectorImpl<unsigned char> &Output) const {
5379 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5380 // If a byte of an integer is uninitialized, then the whole integer is
5382 if (!Bytes[I.getQuantity()])
5384 Output.push_back(*Bytes[I.getQuantity()]);
5386 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5387 std::reverse(Output.begin(), Output.end());
5391 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5392 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5393 std::reverse(Input.begin(), Input.end());
5396 for (unsigned char Byte : Input) {
5397 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5398 Bytes[Offset.getQuantity() + Index] = Byte;
5403 size_t size() { return Bytes.size(); }
5406 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5407 /// target would represent the value at runtime.
5408 class APValueToBufferConverter {
5410 BitCastBuffer Buffer;
5411 const CastExpr *BCE;
5413 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5414 const CastExpr *BCE)
5416 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5419 bool visit(const APValue &Val, QualType Ty) {
5420 return visit(Val, Ty, CharUnits::fromQuantity(0));
5423 // Write out Val with type Ty into Buffer starting at Offset.
5424 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5425 assert((size_t)Offset.getQuantity() <= Buffer.size());
5427 // As a special case, nullptr_t has an indeterminate value.
5428 if (Ty->isNullPtrType())
5431 // Dig through Src to find the byte at SrcOffset.
5432 switch (Val.getKind()) {
5433 case APValue::Indeterminate:
5438 return visitInt(Val.getInt(), Ty, Offset);
5439 case APValue::Float:
5440 return visitFloat(Val.getFloat(), Ty, Offset);
5441 case APValue::Array:
5442 return visitArray(Val, Ty, Offset);
5443 case APValue::Struct:
5444 return visitRecord(Val, Ty, Offset);
5446 case APValue::ComplexInt:
5447 case APValue::ComplexFloat:
5448 case APValue::Vector:
5449 case APValue::FixedPoint:
5450 // FIXME: We should support these.
5452 case APValue::Union:
5453 case APValue::MemberPointer:
5454 case APValue::AddrLabelDiff: {
5455 Info.FFDiag(BCE->getBeginLoc(),
5456 diag::note_constexpr_bit_cast_unsupported_type)
5461 case APValue::LValue:
5462 llvm_unreachable("LValue subobject in bit_cast?");
5464 llvm_unreachable("Unhandled APValue::ValueKind");
5467 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5468 const RecordDecl *RD = Ty->getAsRecordDecl();
5469 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5471 // Visit the base classes.
5472 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5473 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5474 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5475 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5477 if (!visitRecord(Val.getStructBase(I), BS.getType(),
5478 Layout.getBaseClassOffset(BaseDecl) + Offset))
5483 // Visit the fields.
5484 unsigned FieldIdx = 0;
5485 for (FieldDecl *FD : RD->fields()) {
5486 if (FD->isBitField()) {
5487 Info.FFDiag(BCE->getBeginLoc(),
5488 diag::note_constexpr_bit_cast_unsupported_bitfield);
5492 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5494 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5495 "only bit-fields can have sub-char alignment");
5496 CharUnits FieldOffset =
5497 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5498 QualType FieldTy = FD->getType();
5499 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5507 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5509 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5513 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5514 unsigned NumInitializedElts = Val.getArrayInitializedElts();
5515 unsigned ArraySize = Val.getArraySize();
5516 // First, initialize the initialized elements.
5517 for (unsigned I = 0; I != NumInitializedElts; ++I) {
5518 const APValue &SubObj = Val.getArrayInitializedElt(I);
5519 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5523 // Next, initialize the rest of the array using the filler.
5524 if (Val.hasArrayFiller()) {
5525 const APValue &Filler = Val.getArrayFiller();
5526 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5527 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5535 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5536 CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5537 SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5538 llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5539 Buffer.writeObject(Offset, Bytes);
5543 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5544 APSInt AsInt(Val.bitcastToAPInt());
5545 return visitInt(AsInt, Ty, Offset);
5549 static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5550 const CastExpr *BCE) {
5551 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5552 APValueToBufferConverter Converter(Info, DstSize, BCE);
5553 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5555 return Converter.Buffer;
5559 /// Write an BitCastBuffer into an APValue.
5560 class BufferToAPValueConverter {
5562 const BitCastBuffer &Buffer;
5563 const CastExpr *BCE;
5565 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5566 const CastExpr *BCE)
5567 : Info(Info), Buffer(Buffer), BCE(BCE) {}
5569 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5570 // with an invalid type, so anything left is a deficiency on our part (FIXME).
5571 // Ideally this will be unreachable.
5572 llvm::NoneType unsupportedType(QualType Ty) {
5573 Info.FFDiag(BCE->getBeginLoc(),
5574 diag::note_constexpr_bit_cast_unsupported_type)
5579 Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5580 const EnumType *EnumSugar = nullptr) {
5581 if (T->isNullPtrType()) {
5582 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5583 return APValue((Expr *)nullptr,
5584 /*Offset=*/CharUnits::fromQuantity(NullValue),
5585 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5588 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5589 SmallVector<uint8_t, 8> Bytes;
5590 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5591 // If this is std::byte or unsigned char, then its okay to store an
5592 // indeterminate value.
5593 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5595 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5596 T->isSpecificBuiltinType(BuiltinType::Char_U));
5597 if (!IsStdByte && !IsUChar) {
5598 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
5599 Info.FFDiag(BCE->getExprLoc(),
5600 diag::note_constexpr_bit_cast_indet_dest)
5601 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5605 return APValue::IndeterminateValue();
5608 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5609 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5611 if (T->isIntegralOrEnumerationType()) {
5612 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5613 return APValue(Val);
5616 if (T->isRealFloatingType()) {
5617 const llvm::fltSemantics &Semantics =
5618 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5619 return APValue(APFloat(Semantics, Val));
5622 return unsupportedType(QualType(T, 0));
5625 Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5626 const RecordDecl *RD = RTy->getAsRecordDecl();
5627 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5629 unsigned NumBases = 0;
5630 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5631 NumBases = CXXRD->getNumBases();
5633 APValue ResultVal(APValue::UninitStruct(), NumBases,
5634 std::distance(RD->field_begin(), RD->field_end()));
5636 // Visit the base classes.
5637 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5638 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5639 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5640 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5641 if (BaseDecl->isEmpty() ||
5642 Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5645 Optional<APValue> SubObj = visitType(
5646 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5649 ResultVal.getStructBase(I) = *SubObj;
5653 // Visit the fields.
5654 unsigned FieldIdx = 0;
5655 for (FieldDecl *FD : RD->fields()) {
5656 // FIXME: We don't currently support bit-fields. A lot of the logic for
5657 // this is in CodeGen, so we need to factor it around.
5658 if (FD->isBitField()) {
5659 Info.FFDiag(BCE->getBeginLoc(),
5660 diag::note_constexpr_bit_cast_unsupported_bitfield);
5664 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5665 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5667 CharUnits FieldOffset =
5668 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5670 QualType FieldTy = FD->getType();
5671 Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5674 ResultVal.getStructField(FieldIdx) = *SubObj;
5681 Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5682 QualType RepresentationType = Ty->getDecl()->getIntegerType();
5683 assert(!RepresentationType.isNull() &&
5684 "enum forward decl should be caught by Sema");
5685 const BuiltinType *AsBuiltin =
5686 RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5687 assert(AsBuiltin && "non-integral enum underlying type?");
5688 // Recurse into the underlying type. Treat std::byte transparently as
5690 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5693 Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5694 size_t Size = Ty->getSize().getLimitedValue();
5695 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5697 APValue ArrayValue(APValue::UninitArray(), Size, Size);
5698 for (size_t I = 0; I != Size; ++I) {
5699 Optional<APValue> ElementValue =
5700 visitType(Ty->getElementType(), Offset + I * ElementWidth);
5703 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5709 Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5710 return unsupportedType(QualType(Ty, 0));
5713 Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5714 QualType Can = Ty.getCanonicalType();
5716 switch (Can->getTypeClass()) {
5717 #define TYPE(Class, Base) \
5719 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5720 #define ABSTRACT_TYPE(Class, Base)
5721 #define NON_CANONICAL_TYPE(Class, Base) \
5723 llvm_unreachable("non-canonical type should be impossible!");
5724 #define DEPENDENT_TYPE(Class, Base) \
5727 "dependent types aren't supported in the constant evaluator!");
5728 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
5730 llvm_unreachable("either dependent or not canonical!");
5731 #include "clang/AST/TypeNodes.def"
5733 llvm_unreachable("Unhandled Type::TypeClass");
5737 // Pull out a full value of type DstType.
5738 static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5739 const CastExpr *BCE) {
5740 BufferToAPValueConverter Converter(Info, Buffer, BCE);
5741 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5745 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5746 QualType Ty, EvalInfo *Info,
5747 const ASTContext &Ctx,
5748 bool CheckingDest) {
5749 Ty = Ty.getCanonicalType();
5751 auto diag = [&](int Reason) {
5753 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5754 << CheckingDest << (Reason == 4) << Reason;
5757 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5759 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5760 << NoteTy << Construct << Ty;
5764 if (Ty->isUnionType())
5766 if (Ty->isPointerType())
5768 if (Ty->isMemberPointerType())
5770 if (Ty.isVolatileQualified())
5773 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5774 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5775 for (CXXBaseSpecifier &BS : CXXRD->bases())
5776 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5778 return note(1, BS.getType(), BS.getBeginLoc());
5780 for (FieldDecl *FD : Record->fields()) {
5781 if (FD->getType()->isReferenceType())
5783 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5785 return note(0, FD->getType(), FD->getBeginLoc());
5789 if (Ty->isArrayType() &&
5790 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5791 Info, Ctx, CheckingDest))
5797 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5798 const ASTContext &Ctx,
5799 const CastExpr *BCE) {
5800 bool DestOK = checkBitCastConstexprEligibilityType(
5801 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5802 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5804 BCE->getSubExpr()->getType(), Info, Ctx, false);
5808 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5809 APValue &SourceValue,
5810 const CastExpr *BCE) {
5811 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5812 "no host or target supports non 8-bit chars");
5813 assert(SourceValue.isLValue() &&
5814 "LValueToRValueBitcast requires an lvalue operand!");
5816 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5819 LValue SourceLValue;
5820 APValue SourceRValue;
5821 SourceLValue.setFrom(Info.Ctx, SourceValue);
5822 if (!handleLValueToRValueConversion(Info, BCE,
5823 BCE->getSubExpr()->getType().withConst(),
5824 SourceLValue, SourceRValue))
5827 // Read out SourceValue into a char buffer.
5828 Optional<BitCastBuffer> Buffer =
5829 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5833 // Write out the buffer into a new APValue.
5834 Optional<APValue> MaybeDestValue =
5835 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5836 if (!MaybeDestValue)
5839 DestValue = std::move(*MaybeDestValue);
5843 template <class Derived>
5844 class ExprEvaluatorBase
5845 : public ConstStmtVisitor<Derived, bool> {
5847 Derived &getDerived() { return static_cast<Derived&>(*this); }
5848 bool DerivedSuccess(const APValue &V, const Expr *E) {
5849 return getDerived().Success(V, E);
5851 bool DerivedZeroInitialization(const Expr *E) {
5852 return getDerived().ZeroInitialization(E);
5855 // Check whether a conditional operator with a non-constant condition is a
5856 // potential constant expression. If neither arm is a potential constant
5857 // expression, then the conditional operator is not either.
5858 template<typename ConditionalOperator>
5859 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5860 assert(Info.checkingPotentialConstantExpression());
5862 // Speculatively evaluate both arms.
5863 SmallVector<PartialDiagnosticAt, 8> Diag;
5865 SpeculativeEvaluationRAII Speculate(Info, &Diag);
5866 StmtVisitorTy::Visit(E->getFalseExpr());
5872 SpeculativeEvaluationRAII Speculate(Info, &Diag);
5874 StmtVisitorTy::Visit(E->getTrueExpr());
5879 Error(E, diag::note_constexpr_conditional_never_const);
5883 template<typename ConditionalOperator>
5884 bool HandleConditionalOperator(const ConditionalOperator *E) {
5886 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5887 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5888 CheckPotentialConstantConditional(E);
5891 if (Info.noteFailure()) {
5892 StmtVisitorTy::Visit(E->getTrueExpr());
5893 StmtVisitorTy::Visit(E->getFalseExpr());
5898 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5899 return StmtVisitorTy::Visit(EvalExpr);
5904 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5905 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5907 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5908 return Info.CCEDiag(E, D);
5911 bool ZeroInitialization(const Expr *E) { return Error(E); }
5914 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5916 EvalInfo &getEvalInfo() { return Info; }
5918 /// Report an evaluation error. This should only be called when an error is
5919 /// first discovered. When propagating an error, just return false.
5920 bool Error(const Expr *E, diag::kind D) {
5924 bool Error(const Expr *E) {
5925 return Error(E, diag::note_invalid_subexpr_in_const_expr);
5928 bool VisitStmt(const Stmt *) {
5929 llvm_unreachable("Expression evaluator should not be called on stmts");
5931 bool VisitExpr(const Expr *E) {
5935 bool VisitConstantExpr(const ConstantExpr *E)
5936 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5937 bool VisitParenExpr(const ParenExpr *E)
5938 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5939 bool VisitUnaryExtension(const UnaryOperator *E)
5940 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5941 bool VisitUnaryPlus(const UnaryOperator *E)
5942 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5943 bool VisitChooseExpr(const ChooseExpr *E)
5944 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5945 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5946 { return StmtVisitorTy::Visit(E->getResultExpr()); }
5947 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5948 { return StmtVisitorTy::Visit(E->getReplacement()); }
5949 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5950 TempVersionRAII RAII(*Info.CurrentCall);
5951 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5952 return StmtVisitorTy::Visit(E->getExpr());
5954 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5955 TempVersionRAII RAII(*Info.CurrentCall);
5956 // The initializer may not have been parsed yet, or might be erroneous.
5959 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5960 return StmtVisitorTy::Visit(E->getExpr());
5963 // We cannot create any objects for which cleanups are required, so there is
5964 // nothing to do here; all cleanups must come from unevaluated subexpressions.
5965 bool VisitExprWithCleanups(const ExprWithCleanups *E)
5966 { return StmtVisitorTy::Visit(E->getSubExpr()); }
5968 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5969 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5970 return static_cast<Derived*>(this)->VisitCastExpr(E);
5972 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5973 if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5974 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5975 return static_cast<Derived*>(this)->VisitCastExpr(E);
5977 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
5978 return static_cast<Derived*>(this)->VisitCastExpr(E);
5981 bool VisitBinaryOperator(const BinaryOperator *E) {
5982 switch (E->getOpcode()) {
5987 VisitIgnoredValue(E->getLHS());
5988 return StmtVisitorTy::Visit(E->getRHS());
5993 if (!HandleMemberPointerAccess(Info, E, Obj))
5996 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
5998 return DerivedSuccess(Result, E);
6003 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6004 // Evaluate and cache the common expression. We treat it as a temporary,
6005 // even though it's not quite the same thing.
6006 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
6007 Info, E->getCommon()))
6010 return HandleConditionalOperator(E);
6013 bool VisitConditionalOperator(const ConditionalOperator *E) {
6014 bool IsBcpCall = false;
6015 // If the condition (ignoring parens) is a __builtin_constant_p call,
6016 // the result is a constant expression if it can be folded without
6017 // side-effects. This is an important GNU extension. See GCC PR38377
6019 if (const CallExpr *CallCE =
6020 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6021 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6024 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6025 // constant expression; we can't check whether it's potentially foldable.
6026 // FIXME: We should instead treat __builtin_constant_p as non-constant if
6027 // it would return 'false' in this mode.
6028 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6031 FoldConstant Fold(Info, IsBcpCall);
6032 if (!HandleConditionalOperator(E)) {
6033 Fold.keepDiagnostics();
6040 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6041 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6042 return DerivedSuccess(*Value, E);
6044 const Expr *Source = E->getSourceExpr();
6047 if (Source == E) { // sanity checking.
6048 assert(0 && "OpaqueValueExpr recursively refers to itself");
6051 return StmtVisitorTy::Visit(Source);
6054 bool VisitCallExpr(const CallExpr *E) {
6056 if (!handleCallExpr(E, Result, nullptr))
6058 return DerivedSuccess(Result, E);
6061 bool handleCallExpr(const CallExpr *E, APValue &Result,
6062 const LValue *ResultSlot) {
6063 const Expr *Callee = E->getCallee()->IgnoreParens();
6064 QualType CalleeType = Callee->getType();
6066 const FunctionDecl *FD = nullptr;
6067 LValue *This = nullptr, ThisVal;
6068 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6069 bool HasQualifier = false;
6071 // Extract function decl and 'this' pointer from the callee.
6072 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6073 const CXXMethodDecl *Member = nullptr;
6074 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6075 // Explicit bound member calls, such as x.f() or p->g();
6076 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6078 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6080 return Error(Callee);
6082 HasQualifier = ME->hasQualifier();
6083 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6084 // Indirect bound member calls ('.*' or '->*').
6085 Member = dyn_cast_or_null<CXXMethodDecl>(
6086 HandleMemberPointerAccess(Info, BE, ThisVal, false));
6088 return Error(Callee);
6091 return Error(Callee);
6093 } else if (CalleeType->isFunctionPointerType()) {
6095 if (!EvaluatePointer(Callee, Call, Info))
6098 if (!Call.getLValueOffset().isZero())
6099 return Error(Callee);
6100 FD = dyn_cast_or_null<FunctionDecl>(
6101 Call.getLValueBase().dyn_cast<const ValueDecl*>());
6103 return Error(Callee);
6104 // Don't call function pointers which have been cast to some other type.
6105 // Per DR (no number yet), the caller and callee can differ in noexcept.
6106 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6107 CalleeType->getPointeeType(), FD->getType())) {
6111 // Overloaded operator calls to member functions are represented as normal
6112 // calls with '*this' as the first argument.
6113 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6114 if (MD && !MD->isStatic()) {
6115 // FIXME: When selecting an implicit conversion for an overloaded
6116 // operator delete, we sometimes try to evaluate calls to conversion
6117 // operators without a 'this' parameter!
6121 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6124 Args = Args.slice(1);
6125 } else if (MD && MD->isLambdaStaticInvoker()) {
6126 // Map the static invoker for the lambda back to the call operator.
6127 // Conveniently, we don't have to slice out the 'this' argument (as is
6128 // being done for the non-static case), since a static member function
6129 // doesn't have an implicit argument passed in.
6130 const CXXRecordDecl *ClosureClass = MD->getParent();
6132 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6133 "Number of captures must be zero for conversion to function-ptr");
6135 const CXXMethodDecl *LambdaCallOp =
6136 ClosureClass->getLambdaCallOperator();
6138 // Set 'FD', the function that will be called below, to the call
6139 // operator. If the closure object represents a generic lambda, find
6140 // the corresponding specialization of the call operator.
6142 if (ClosureClass->isGenericLambda()) {
6143 assert(MD->isFunctionTemplateSpecialization() &&
6144 "A generic lambda's static-invoker function must be a "
6145 "template specialization");
6146 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6147 FunctionTemplateDecl *CallOpTemplate =
6148 LambdaCallOp->getDescribedFunctionTemplate();
6149 void *InsertPos = nullptr;
6150 FunctionDecl *CorrespondingCallOpSpecialization =
6151 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6152 assert(CorrespondingCallOpSpecialization &&
6153 "We must always have a function call operator specialization "
6154 "that corresponds to our static invoker specialization");
6155 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6162 SmallVector<QualType, 4> CovariantAdjustmentPath;
6164 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
6165 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6166 // Perform virtual dispatch, if necessary.
6167 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6168 CovariantAdjustmentPath);
6172 // Check that the 'this' pointer points to an object of the right type.
6173 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6178 const FunctionDecl *Definition = nullptr;
6179 Stmt *Body = FD->getBody(Definition);
6181 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6182 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
6183 Result, ResultSlot))
6186 if (!CovariantAdjustmentPath.empty() &&
6187 !HandleCovariantReturnAdjustment(Info, E, Result,
6188 CovariantAdjustmentPath))
6194 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6195 return StmtVisitorTy::Visit(E->getInitializer());
6197 bool VisitInitListExpr(const InitListExpr *E) {
6198 if (E->getNumInits() == 0)
6199 return DerivedZeroInitialization(E);
6200 if (E->getNumInits() == 1)
6201 return StmtVisitorTy::Visit(E->getInit(0));
6204 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
6205 return DerivedZeroInitialization(E);
6207 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
6208 return DerivedZeroInitialization(E);
6210 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
6211 return DerivedZeroInitialization(E);
6214 /// A member expression where the object is a prvalue is itself a prvalue.
6215 bool VisitMemberExpr(const MemberExpr *E) {
6216 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6217 "missing temporary materialization conversion");
6218 assert(!E->isArrow() && "missing call to bound member function?");
6221 if (!Evaluate(Val, Info, E->getBase()))
6224 QualType BaseTy = E->getBase()->getType();
6226 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
6227 if (!FD) return Error(E);
6228 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
6229 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6230 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6232 // Note: there is no lvalue base here. But this case should only ever
6233 // happen in C or in C++98, where we cannot be evaluating a constexpr
6234 // constructor, which is the only case the base matters.
6235 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
6236 SubobjectDesignator Designator(BaseTy);
6237 Designator.addDeclUnchecked(FD);
6240 return extractSubobject(Info, E, Obj, Designator, Result) &&
6241 DerivedSuccess(Result, E);
6244 bool VisitCastExpr(const CastExpr *E) {
6245 switch (E->getCastKind()) {
6249 case CK_AtomicToNonAtomic: {
6251 // This does not need to be done in place even for class/array types:
6252 // atomic-to-non-atomic conversion implies copying the object
6254 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
6256 return DerivedSuccess(AtomicVal, E);
6260 case CK_UserDefinedConversion:
6261 return StmtVisitorTy::Visit(E->getSubExpr());
6263 case CK_LValueToRValue: {
6265 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6268 // Note, we use the subexpression's type in order to retain cv-qualifiers.
6269 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6272 return DerivedSuccess(RVal, E);
6274 case CK_LValueToRValueBitCast: {
6275 APValue DestValue, SourceValue;
6276 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6278 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6280 return DerivedSuccess(DestValue, E);
6287 bool VisitUnaryPostInc(const UnaryOperator *UO) {
6288 return VisitUnaryPostIncDec(UO);
6290 bool VisitUnaryPostDec(const UnaryOperator *UO) {
6291 return VisitUnaryPostIncDec(UO);
6293 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
6294 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6298 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6301 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6302 UO->isIncrementOp(), &RVal))
6304 return DerivedSuccess(RVal, UO);
6307 bool VisitStmtExpr(const StmtExpr *E) {
6308 // We will have checked the full-expressions inside the statement expression
6309 // when they were completed, and don't need to check them again now.
6310 if (Info.checkingForUndefinedBehavior())
6313 BlockScopeRAII Scope(Info);
6314 const CompoundStmt *CS = E->getSubStmt();
6315 if (CS->body_empty())
6318 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6319 BE = CS->body_end();
6322 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6324 Info.FFDiag((*BI)->getBeginLoc(),
6325 diag::note_constexpr_stmt_expr_unsupported);
6328 return this->Visit(FinalExpr);
6331 APValue ReturnValue;
6332 StmtResult Result = { ReturnValue, nullptr };
6333 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
6334 if (ESR != ESR_Succeeded) {
6335 // FIXME: If the statement-expression terminated due to 'return',
6336 // 'break', or 'continue', it would be nice to propagate that to
6337 // the outer statement evaluation rather than bailing out.
6338 if (ESR != ESR_Failed)
6339 Info.FFDiag((*BI)->getBeginLoc(),
6340 diag::note_constexpr_stmt_expr_unsupported);
6345 llvm_unreachable("Return from function from the loop above.");
6348 /// Visit a value which is evaluated, but whose value is ignored.
6349 void VisitIgnoredValue(const Expr *E) {
6350 EvaluateIgnoredValue(Info, E);
6353 /// Potentially visit a MemberExpr's base expression.
6354 void VisitIgnoredBaseExpression(const Expr *E) {
6355 // While MSVC doesn't evaluate the base expression, it does diagnose the
6356 // presence of side-effecting behavior.
6357 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6359 VisitIgnoredValue(E);
6365 //===----------------------------------------------------------------------===//
6366 // Common base class for lvalue and temporary evaluation.
6367 //===----------------------------------------------------------------------===//
6369 template<class Derived>
6370 class LValueExprEvaluatorBase
6371 : public ExprEvaluatorBase<Derived> {
6375 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
6376 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
6378 bool Success(APValue::LValueBase B) {
6383 bool evaluatePointer(const Expr *E, LValue &Result) {
6384 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6388 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6389 : ExprEvaluatorBaseTy(Info), Result(Result),
6390 InvalidBaseOK(InvalidBaseOK) {}
6392 bool Success(const APValue &V, const Expr *E) {
6393 Result.setFrom(this->Info.Ctx, V);
6397 bool VisitMemberExpr(const MemberExpr *E) {
6398 // Handle non-static data members.
6402 EvalOK = evaluatePointer(E->getBase(), Result);
6403 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
6404 } else if (E->getBase()->isRValue()) {
6405 assert(E->getBase()->getType()->isRecordType());
6406 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
6407 BaseTy = E->getBase()->getType();
6409 EvalOK = this->Visit(E->getBase());
6410 BaseTy = E->getBase()->getType();
6415 Result.setInvalid(E);
6419 const ValueDecl *MD = E->getMemberDecl();
6420 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6421 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6422 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6424 if (!HandleLValueMember(this->Info, E, Result, FD))
6426 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
6427 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6430 return this->Error(E);
6432 if (MD->getType()->isReferenceType()) {
6434 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
6437 return Success(RefValue, E);
6442 bool VisitBinaryOperator(const BinaryOperator *E) {
6443 switch (E->getOpcode()) {
6445 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6449 return HandleMemberPointerAccess(this->Info, E, Result);
6453 bool VisitCastExpr(const CastExpr *E) {
6454 switch (E->getCastKind()) {
6456 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6458 case CK_DerivedToBase:
6459 case CK_UncheckedDerivedToBase:
6460 if (!this->Visit(E->getSubExpr()))
6463 // Now figure out the necessary offset to add to the base LV to get from
6464 // the derived class to the base class.
6465 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6472 //===----------------------------------------------------------------------===//
6473 // LValue Evaluation
6475 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6476 // function designators (in C), decl references to void objects (in C), and
6477 // temporaries (if building with -Wno-address-of-temporary).
6479 // LValue evaluation produces values comprising a base expression of one of the
6485 // * CompoundLiteralExpr in C (and in global scope in C++)
6488 // * ObjCStringLiteralExpr
6492 // * CallExpr for a MakeStringConstant builtin
6493 // - typeid(T) expressions, as TypeInfoLValues
6494 // - Locals and temporaries
6495 // * MaterializeTemporaryExpr
6496 // * Any Expr, with a CallIndex indicating the function in which the temporary
6497 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
6498 // from the AST (FIXME).
6499 // * A MaterializeTemporaryExpr that has static storage duration, with no
6500 // CallIndex, for a lifetime-extended temporary.
6501 // plus an offset in bytes.
6502 //===----------------------------------------------------------------------===//
6504 class LValueExprEvaluator
6505 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6507 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6508 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6510 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6511 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6513 bool VisitDeclRefExpr(const DeclRefExpr *E);
6514 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6515 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6516 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6517 bool VisitMemberExpr(const MemberExpr *E);
6518 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6519 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6520 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6521 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6522 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6523 bool VisitUnaryDeref(const UnaryOperator *E);
6524 bool VisitUnaryReal(const UnaryOperator *E);
6525 bool VisitUnaryImag(const UnaryOperator *E);
6526 bool VisitUnaryPreInc(const UnaryOperator *UO) {
6527 return VisitUnaryPreIncDec(UO);
6529 bool VisitUnaryPreDec(const UnaryOperator *UO) {
6530 return VisitUnaryPreIncDec(UO);
6532 bool VisitBinAssign(const BinaryOperator *BO);
6533 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6535 bool VisitCastExpr(const CastExpr *E) {
6536 switch (E->getCastKind()) {
6538 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6540 case CK_LValueBitCast:
6541 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6542 if (!Visit(E->getSubExpr()))
6544 Result.Designator.setInvalid();
6547 case CK_BaseToDerived:
6548 if (!Visit(E->getSubExpr()))
6550 return HandleBaseToDerivedCast(Info, E, Result);
6553 if (!Visit(E->getSubExpr()))
6555 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6559 } // end anonymous namespace
6561 /// Evaluate an expression as an lvalue. This can be legitimately called on
6562 /// expressions which are not glvalues, in three cases:
6563 /// * function designators in C, and
6564 /// * "extern void" objects
6565 /// * @selector() expressions in Objective-C
6566 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6567 bool InvalidBaseOK) {
6568 assert(E->isGLValue() || E->getType()->isFunctionType() ||
6569 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6570 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6573 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6574 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6576 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6577 return VisitVarDecl(E, VD);
6578 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6579 return Visit(BD->getBinding());
6584 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6586 // If we are within a lambda's call operator, check whether the 'VD' referred
6587 // to within 'E' actually represents a lambda-capture that maps to a
6588 // data-member/field within the closure object, and if so, evaluate to the
6589 // field or what the field refers to.
6590 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6591 isa<DeclRefExpr>(E) &&
6592 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6593 // We don't always have a complete capture-map when checking or inferring if
6594 // the function call operator meets the requirements of a constexpr function
6595 // - but we don't need to evaluate the captures to determine constexprness
6596 // (dcl.constexpr C++17).
6597 if (Info.checkingPotentialConstantExpression())
6600 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6601 // Start with 'Result' referring to the complete closure object...
6602 Result = *Info.CurrentCall->This;
6603 // ... then update it to refer to the field of the closure object
6604 // that represents the capture.
6605 if (!HandleLValueMember(Info, E, Result, FD))
6607 // And if the field is of reference type, update 'Result' to refer to what
6608 // the field refers to.
6609 if (FD->getType()->isReferenceType()) {
6611 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6614 Result.setFrom(Info.Ctx, RVal);
6619 CallStackFrame *Frame = nullptr;
6620 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6621 // Only if a local variable was declared in the function currently being
6622 // evaluated, do we expect to be able to find its value in the current
6623 // frame. (Otherwise it was likely declared in an enclosing context and
6624 // could either have a valid evaluatable value (for e.g. a constexpr
6625 // variable) or be ill-formed (and trigger an appropriate evaluation
6627 if (Info.CurrentCall->Callee &&
6628 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6629 Frame = Info.CurrentCall;
6633 if (!VD->getType()->isReferenceType()) {
6635 Result.set({VD, Frame->Index,
6636 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6643 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6645 if (!V->hasValue()) {
6646 // FIXME: Is it possible for V to be indeterminate here? If so, we should
6647 // adjust the diagnostic to say that.
6648 if (!Info.checkingPotentialConstantExpression())
6649 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6652 return Success(*V, E);
6655 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6656 const MaterializeTemporaryExpr *E) {
6657 // Walk through the expression to find the materialized temporary itself.
6658 SmallVector<const Expr *, 2> CommaLHSs;
6659 SmallVector<SubobjectAdjustment, 2> Adjustments;
6660 const Expr *Inner = E->GetTemporaryExpr()->
6661 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6663 // If we passed any comma operators, evaluate their LHSs.
6664 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6665 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6668 // A materialized temporary with static storage duration can appear within the
6669 // result of a constant expression evaluation, so we need to preserve its
6670 // value for use outside this evaluation.
6672 if (E->getStorageDuration() == SD_Static) {
6673 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6677 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6681 QualType Type = Inner->getType();
6683 // Materialize the temporary itself.
6684 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6685 (E->getStorageDuration() == SD_Static &&
6686 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6691 // Adjust our lvalue to refer to the desired subobject.
6692 for (unsigned I = Adjustments.size(); I != 0; /**/) {
6694 switch (Adjustments[I].Kind) {
6695 case SubobjectAdjustment::DerivedToBaseAdjustment:
6696 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6699 Type = Adjustments[I].DerivedToBase.BasePath->getType();
6702 case SubobjectAdjustment::FieldAdjustment:
6703 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6705 Type = Adjustments[I].Field->getType();
6708 case SubobjectAdjustment::MemberPointerAdjustment:
6709 if (!HandleMemberPointerAccess(this->Info, Type, Result,
6710 Adjustments[I].Ptr.RHS))
6712 Type = Adjustments[I].Ptr.MPT->getPointeeType();
6721 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6722 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6723 "lvalue compound literal in c++?");
6724 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6725 // only see this when folding in C, so there's no standard to follow here.
6729 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6730 TypeInfoLValue TypeInfo;
6732 if (!E->isPotentiallyEvaluated()) {
6733 if (E->isTypeOperand())
6734 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6736 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6738 if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6739 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6740 << E->getExprOperand()->getType()
6741 << E->getExprOperand()->getSourceRange();
6744 if (!Visit(E->getExprOperand()))
6747 Optional<DynamicType> DynType =
6748 ComputeDynamicType(Info, E, Result, AK_TypeId);
6753 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6756 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6759 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6763 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6764 // Handle static data members.
6765 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6766 VisitIgnoredBaseExpression(E->getBase());
6767 return VisitVarDecl(E, VD);
6770 // Handle static member functions.
6771 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6772 if (MD->isStatic()) {
6773 VisitIgnoredBaseExpression(E->getBase());
6778 // Handle non-static data members.
6779 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6782 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6783 // FIXME: Deal with vectors as array subscript bases.
6784 if (E->getBase()->getType()->isVectorType())
6787 bool Success = true;
6788 if (!evaluatePointer(E->getBase(), Result)) {
6789 if (!Info.noteFailure())
6795 if (!EvaluateInteger(E->getIdx(), Index, Info))
6799 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6802 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6803 return evaluatePointer(E->getSubExpr(), Result);
6806 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6807 if (!Visit(E->getSubExpr()))
6809 // __real is a no-op on scalar lvalues.
6810 if (E->getSubExpr()->getType()->isAnyComplexType())
6811 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6815 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6816 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6817 "lvalue __imag__ on scalar?");
6818 if (!Visit(E->getSubExpr()))
6820 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6824 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6825 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6828 if (!this->Visit(UO->getSubExpr()))
6831 return handleIncDec(
6832 this->Info, UO, Result, UO->getSubExpr()->getType(),
6833 UO->isIncrementOp(), nullptr);
6836 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6837 const CompoundAssignOperator *CAO) {
6838 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6843 // The overall lvalue result is the result of evaluating the LHS.
6844 if (!this->Visit(CAO->getLHS())) {
6845 if (Info.noteFailure())
6846 Evaluate(RHS, this->Info, CAO->getRHS());
6850 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6853 return handleCompoundAssignment(
6855 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6856 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6859 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6860 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6865 if (!this->Visit(E->getLHS())) {
6866 if (Info.noteFailure())
6867 Evaluate(NewVal, this->Info, E->getRHS());
6871 if (!Evaluate(NewVal, this->Info, E->getRHS()))
6874 if (Info.getLangOpts().CPlusPlus2a &&
6875 !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6878 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6882 //===----------------------------------------------------------------------===//
6883 // Pointer Evaluation
6884 //===----------------------------------------------------------------------===//
6886 /// Attempts to compute the number of bytes available at the pointer
6887 /// returned by a function with the alloc_size attribute. Returns true if we
6888 /// were successful. Places an unsigned number into `Result`.
6890 /// This expects the given CallExpr to be a call to a function with an
6891 /// alloc_size attribute.
6892 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6893 const CallExpr *Call,
6894 llvm::APInt &Result) {
6895 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6897 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6898 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6899 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6900 if (Call->getNumArgs() <= SizeArgNo)
6903 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6904 Expr::EvalResult ExprResult;
6905 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6907 Into = ExprResult.Val.getInt();
6908 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6910 Into = Into.zextOrSelf(BitsInSizeT);
6915 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6918 if (!AllocSize->getNumElemsParam().isValid()) {
6919 Result = std::move(SizeOfElem);
6923 APSInt NumberOfElems;
6924 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6925 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6929 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6933 Result = std::move(BytesAvailable);
6937 /// Convenience function. LVal's base must be a call to an alloc_size
6939 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6941 llvm::APInt &Result) {
6942 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6943 "Can't get the size of a non alloc_size function");
6944 const auto *Base = LVal.getLValueBase().get<const Expr *>();
6945 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6946 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6949 /// Attempts to evaluate the given LValueBase as the result of a call to
6950 /// a function with the alloc_size attribute. If it was possible to do so, this
6951 /// function will return true, make Result's Base point to said function call,
6952 /// and mark Result's Base as invalid.
6953 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6958 // Because we do no form of static analysis, we only support const variables.
6960 // Additionally, we can't support parameters, nor can we support static
6961 // variables (in the latter case, use-before-assign isn't UB; in the former,
6962 // we have no clue what they'll be assigned to).
6964 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6965 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6968 const Expr *Init = VD->getAnyInitializer();
6972 const Expr *E = Init->IgnoreParens();
6973 if (!tryUnwrapAllocSizeCall(E))
6976 // Store E instead of E unwrapped so that the type of the LValue's base is
6977 // what the user wanted.
6978 Result.setInvalid(E);
6980 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
6981 Result.addUnsizedArray(Info, E, Pointee);
6986 class PointerExprEvaluator
6987 : public ExprEvaluatorBase<PointerExprEvaluator> {
6991 bool Success(const Expr *E) {
6996 bool evaluateLValue(const Expr *E, LValue &Result) {
6997 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7000 bool evaluatePointer(const Expr *E, LValue &Result) {
7001 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7004 bool visitNonBuiltinCallExpr(const CallExpr *E);
7007 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7008 : ExprEvaluatorBaseTy(info), Result(Result),
7009 InvalidBaseOK(InvalidBaseOK) {}
7011 bool Success(const APValue &V, const Expr *E) {
7012 Result.setFrom(Info.Ctx, V);
7015 bool ZeroInitialization(const Expr *E) {
7016 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7017 Result.setNull(E->getType(), TargetVal);
7021 bool VisitBinaryOperator(const BinaryOperator *E);
7022 bool VisitCastExpr(const CastExpr* E);
7023 bool VisitUnaryAddrOf(const UnaryOperator *E);
7024 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7025 { return Success(E); }
7026 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7027 if (E->isExpressibleAsConstantInitializer())
7029 if (Info.noteFailure())
7030 EvaluateIgnoredValue(Info, E->getSubExpr());
7033 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7034 { return Success(E); }
7035 bool VisitCallExpr(const CallExpr *E);
7036 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7037 bool VisitBlockExpr(const BlockExpr *E) {
7038 if (!E->getBlockDecl()->hasCaptures())
7042 bool VisitCXXThisExpr(const CXXThisExpr *E) {
7043 // Can't look at 'this' when checking a potential constant expression.
7044 if (Info.checkingPotentialConstantExpression())
7046 if (!Info.CurrentCall->This) {
7047 if (Info.getLangOpts().CPlusPlus11)
7048 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7053 Result = *Info.CurrentCall->This;
7054 // If we are inside a lambda's call operator, the 'this' expression refers
7055 // to the enclosing '*this' object (either by value or reference) which is
7056 // either copied into the closure object's field that represents the '*this'
7057 // or refers to '*this'.
7058 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7059 // Update 'Result' to refer to the data member/field of the closure object
7060 // that represents the '*this' capture.
7061 if (!HandleLValueMember(Info, E, Result,
7062 Info.CurrentCall->LambdaThisCaptureField))
7064 // If we captured '*this' by reference, replace the field with its referent.
7065 if (Info.CurrentCall->LambdaThisCaptureField->getType()
7066 ->isPointerType()) {
7068 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7072 Result.setFrom(Info.Ctx, RVal);
7078 bool VisitSourceLocExpr(const SourceLocExpr *E) {
7079 assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7080 APValue LValResult = E->EvaluateInContext(
7081 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7082 Result.setFrom(Info.Ctx, LValResult);
7086 // FIXME: Missing: @protocol, @selector
7088 } // end anonymous namespace
7090 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7091 bool InvalidBaseOK) {
7092 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7093 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7096 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7097 if (E->getOpcode() != BO_Add &&
7098 E->getOpcode() != BO_Sub)
7099 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7101 const Expr *PExp = E->getLHS();
7102 const Expr *IExp = E->getRHS();
7103 if (IExp->getType()->isPointerType())
7104 std::swap(PExp, IExp);
7106 bool EvalPtrOK = evaluatePointer(PExp, Result);
7107 if (!EvalPtrOK && !Info.noteFailure())
7110 llvm::APSInt Offset;
7111 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7114 if (E->getOpcode() == BO_Sub)
7115 negateAsSigned(Offset);
7117 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7118 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7121 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7122 return evaluateLValue(E->getSubExpr(), Result);
7125 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7126 const Expr *SubExpr = E->getSubExpr();
7128 switch (E->getCastKind()) {
7132 case CK_CPointerToObjCPointerCast:
7133 case CK_BlockPointerToObjCPointerCast:
7134 case CK_AnyPointerToBlockPointerCast:
7135 case CK_AddressSpaceConversion:
7136 if (!Visit(SubExpr))
7138 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7139 // permitted in constant expressions in C++11. Bitcasts from cv void* are
7140 // also static_casts, but we disallow them as a resolution to DR1312.
7141 if (!E->getType()->isVoidPointerType()) {
7142 Result.Designator.setInvalid();
7143 if (SubExpr->getType()->isVoidPointerType())
7144 CCEDiag(E, diag::note_constexpr_invalid_cast)
7145 << 3 << SubExpr->getType();
7147 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7149 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7150 ZeroInitialization(E);
7153 case CK_DerivedToBase:
7154 case CK_UncheckedDerivedToBase:
7155 if (!evaluatePointer(E->getSubExpr(), Result))
7157 if (!Result.Base && Result.Offset.isZero())
7160 // Now figure out the necessary offset to add to the base LV to get from
7161 // the derived class to the base class.
7162 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7163 castAs<PointerType>()->getPointeeType(),
7166 case CK_BaseToDerived:
7167 if (!Visit(E->getSubExpr()))
7169 if (!Result.Base && Result.Offset.isZero())
7171 return HandleBaseToDerivedCast(Info, E, Result);
7174 if (!Visit(E->getSubExpr()))
7176 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7178 case CK_NullToPointer:
7179 VisitIgnoredValue(E->getSubExpr());
7180 return ZeroInitialization(E);
7182 case CK_IntegralToPointer: {
7183 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7186 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
7189 if (Value.isInt()) {
7190 unsigned Size = Info.Ctx.getTypeSize(E->getType());
7191 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
7192 Result.Base = (Expr*)nullptr;
7193 Result.InvalidBase = false;
7194 Result.Offset = CharUnits::fromQuantity(N);
7195 Result.Designator.setInvalid();
7196 Result.IsNullPtr = false;
7199 // Cast is of an lvalue, no need to change value.
7200 Result.setFrom(Info.Ctx, Value);
7205 case CK_ArrayToPointerDecay: {
7206 if (SubExpr->isGLValue()) {
7207 if (!evaluateLValue(SubExpr, Result))
7210 APValue &Value = createTemporary(SubExpr, false, Result,
7212 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
7215 // The result is a pointer to the first element of the array.
7216 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7217 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
7218 Result.addArray(Info, E, CAT);
7220 Result.addUnsizedArray(Info, E, AT->getElementType());
7224 case CK_FunctionToPointerDecay:
7225 return evaluateLValue(SubExpr, Result);
7227 case CK_LValueToRValue: {
7229 if (!evaluateLValue(E->getSubExpr(), LVal))
7233 // Note, we use the subexpression's type in order to retain cv-qualifiers.
7234 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7236 return InvalidBaseOK &&
7237 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
7238 return Success(RVal, E);
7242 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7245 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7246 UnaryExprOrTypeTrait ExprKind) {
7247 // C++ [expr.alignof]p3:
7248 // When alignof is applied to a reference type, the result is the
7249 // alignment of the referenced type.
7250 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7251 T = Ref->getPointeeType();
7253 if (T.getQualifiers().hasUnaligned())
7254 return CharUnits::One();
7256 const bool AlignOfReturnsPreferred =
7257 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7259 // __alignof is defined to return the preferred alignment.
7260 // Before 8, clang returned the preferred alignment for alignof and _Alignof
7262 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7263 return Info.Ctx.toCharUnitsFromBits(
7264 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7265 // alignof and _Alignof are defined to return the ABI alignment.
7266 else if (ExprKind == UETT_AlignOf)
7267 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7269 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
7272 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7273 UnaryExprOrTypeTrait ExprKind) {
7274 E = E->IgnoreParens();
7276 // The kinds of expressions that we have special-case logic here for
7277 // should be kept up to date with the special checks for those
7278 // expressions in Sema.
7280 // alignof decl is always accepted, even if it doesn't make sense: we default
7281 // to 1 in those cases.
7282 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7283 return Info.Ctx.getDeclAlign(DRE->getDecl(),
7284 /*RefAsPointee*/true);
7286 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7287 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7288 /*RefAsPointee*/true);
7290 return GetAlignOfType(Info, E->getType(), ExprKind);
7293 // To be clear: this happily visits unsupported builtins. Better name welcomed.
7294 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7295 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7298 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
7301 Result.setInvalid(E);
7302 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
7303 Result.addUnsizedArray(Info, E, PointeeTy);
7307 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
7308 if (IsStringLiteralCall(E))
7311 if (unsigned BuiltinOp = E->getBuiltinCallee())
7312 return VisitBuiltinCallExpr(E, BuiltinOp);
7314 return visitNonBuiltinCallExpr(E);
7317 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7318 unsigned BuiltinOp) {
7319 switch (BuiltinOp) {
7320 case Builtin::BI__builtin_addressof:
7321 return evaluateLValue(E->getArg(0), Result);
7322 case Builtin::BI__builtin_assume_aligned: {
7323 // We need to be very careful here because: if the pointer does not have the
7324 // asserted alignment, then the behavior is undefined, and undefined
7325 // behavior is non-constant.
7326 if (!evaluatePointer(E->getArg(0), Result))
7329 LValue OffsetResult(Result);
7331 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7333 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
7335 if (E->getNumArgs() > 2) {
7337 if (!EvaluateInteger(E->getArg(2), Offset, Info))
7340 int64_t AdditionalOffset = -Offset.getZExtValue();
7341 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7344 // If there is a base object, then it must have the correct alignment.
7345 if (OffsetResult.Base) {
7346 CharUnits BaseAlignment;
7347 if (const ValueDecl *VD =
7348 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7349 BaseAlignment = Info.Ctx.getDeclAlign(VD);
7350 } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7351 BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
7353 BaseAlignment = GetAlignOfType(
7354 Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
7357 if (BaseAlignment < Align) {
7358 Result.Designator.setInvalid();
7359 // FIXME: Add support to Diagnostic for long / long long.
7360 CCEDiag(E->getArg(0),
7361 diag::note_constexpr_baa_insufficient_alignment) << 0
7362 << (unsigned)BaseAlignment.getQuantity()
7363 << (unsigned)Align.getQuantity();
7368 // The offset must also have the correct alignment.
7369 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
7370 Result.Designator.setInvalid();
7373 ? CCEDiag(E->getArg(0),
7374 diag::note_constexpr_baa_insufficient_alignment) << 1
7375 : CCEDiag(E->getArg(0),
7376 diag::note_constexpr_baa_value_insufficient_alignment))
7377 << (int)OffsetResult.Offset.getQuantity()
7378 << (unsigned)Align.getQuantity();
7384 case Builtin::BI__builtin_launder:
7385 return evaluatePointer(E->getArg(0), Result);
7386 case Builtin::BIstrchr:
7387 case Builtin::BIwcschr:
7388 case Builtin::BImemchr:
7389 case Builtin::BIwmemchr:
7390 if (Info.getLangOpts().CPlusPlus11)
7391 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7392 << /*isConstexpr*/0 << /*isConstructor*/0
7393 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7395 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7397 case Builtin::BI__builtin_strchr:
7398 case Builtin::BI__builtin_wcschr:
7399 case Builtin::BI__builtin_memchr:
7400 case Builtin::BI__builtin_char_memchr:
7401 case Builtin::BI__builtin_wmemchr: {
7402 if (!Visit(E->getArg(0)))
7405 if (!EvaluateInteger(E->getArg(1), Desired, Info))
7407 uint64_t MaxLength = uint64_t(-1);
7408 if (BuiltinOp != Builtin::BIstrchr &&
7409 BuiltinOp != Builtin::BIwcschr &&
7410 BuiltinOp != Builtin::BI__builtin_strchr &&
7411 BuiltinOp != Builtin::BI__builtin_wcschr) {
7413 if (!EvaluateInteger(E->getArg(2), N, Info))
7415 MaxLength = N.getExtValue();
7417 // We cannot find the value if there are no candidates to match against.
7418 if (MaxLength == 0u)
7419 return ZeroInitialization(E);
7420 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7421 Result.Designator.Invalid)
7423 QualType CharTy = Result.Designator.getType(Info.Ctx);
7424 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7425 BuiltinOp == Builtin::BI__builtin_memchr;
7427 Info.Ctx.hasSameUnqualifiedType(
7428 CharTy, E->getArg(0)->getType()->getPointeeType()));
7429 // Pointers to const void may point to objects of incomplete type.
7430 if (IsRawByte && CharTy->isIncompleteType()) {
7431 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7434 // Give up on byte-oriented matching against multibyte elements.
7435 // FIXME: We can compare the bytes in the correct order.
7436 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7438 // Figure out what value we're actually looking for (after converting to
7439 // the corresponding unsigned type if necessary).
7440 uint64_t DesiredVal;
7441 bool StopAtNull = false;
7442 switch (BuiltinOp) {
7443 case Builtin::BIstrchr:
7444 case Builtin::BI__builtin_strchr:
7445 // strchr compares directly to the passed integer, and therefore
7446 // always fails if given an int that is not a char.
7447 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7448 E->getArg(1)->getType(),
7451 return ZeroInitialization(E);
7454 case Builtin::BImemchr:
7455 case Builtin::BI__builtin_memchr:
7456 case Builtin::BI__builtin_char_memchr:
7457 // memchr compares by converting both sides to unsigned char. That's also
7458 // correct for strchr if we get this far (to cope with plain char being
7459 // unsigned in the strchr case).
7460 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7463 case Builtin::BIwcschr:
7464 case Builtin::BI__builtin_wcschr:
7467 case Builtin::BIwmemchr:
7468 case Builtin::BI__builtin_wmemchr:
7469 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7470 DesiredVal = Desired.getZExtValue();
7474 for (; MaxLength; --MaxLength) {
7476 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7479 if (Char.getInt().getZExtValue() == DesiredVal)
7481 if (StopAtNull && !Char.getInt())
7483 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7486 // Not found: return nullptr.
7487 return ZeroInitialization(E);
7490 case Builtin::BImemcpy:
7491 case Builtin::BImemmove:
7492 case Builtin::BIwmemcpy:
7493 case Builtin::BIwmemmove:
7494 if (Info.getLangOpts().CPlusPlus11)
7495 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7496 << /*isConstexpr*/0 << /*isConstructor*/0
7497 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7499 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7501 case Builtin::BI__builtin_memcpy:
7502 case Builtin::BI__builtin_memmove:
7503 case Builtin::BI__builtin_wmemcpy:
7504 case Builtin::BI__builtin_wmemmove: {
7505 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7506 BuiltinOp == Builtin::BIwmemmove ||
7507 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7508 BuiltinOp == Builtin::BI__builtin_wmemmove;
7509 bool Move = BuiltinOp == Builtin::BImemmove ||
7510 BuiltinOp == Builtin::BIwmemmove ||
7511 BuiltinOp == Builtin::BI__builtin_memmove ||
7512 BuiltinOp == Builtin::BI__builtin_wmemmove;
7514 // The result of mem* is the first argument.
7515 if (!Visit(E->getArg(0)))
7517 LValue Dest = Result;
7520 if (!EvaluatePointer(E->getArg(1), Src, Info))
7524 if (!EvaluateInteger(E->getArg(2), N, Info))
7526 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7528 // If the size is zero, we treat this as always being a valid no-op.
7529 // (Even if one of the src and dest pointers is null.)
7533 // Otherwise, if either of the operands is null, we can't proceed. Don't
7534 // try to determine the type of the copied objects, because there aren't
7536 if (!Src.Base || !Dest.Base) {
7538 (!Src.Base ? Src : Dest).moveInto(Val);
7539 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7540 << Move << WChar << !!Src.Base
7541 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7544 if (Src.Designator.Invalid || Dest.Designator.Invalid)
7547 // We require that Src and Dest are both pointers to arrays of
7548 // trivially-copyable type. (For the wide version, the designator will be
7549 // invalid if the designated object is not a wchar_t.)
7550 QualType T = Dest.Designator.getType(Info.Ctx);
7551 QualType SrcT = Src.Designator.getType(Info.Ctx);
7552 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7553 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7556 if (T->isIncompleteType()) {
7557 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7560 if (!T.isTriviallyCopyableType(Info.Ctx)) {
7561 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7565 // Figure out how many T's we're copying.
7566 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7569 llvm::APInt OrigN = N;
7570 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7572 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7573 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7579 // Check that the copying will remain within the arrays, just so that we
7580 // can give a more meaningful diagnostic. This implicitly also checks that
7581 // N fits into 64 bits.
7582 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7583 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7584 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7585 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7586 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7587 << N.toString(10, /*Signed*/false);
7590 uint64_t NElems = N.getZExtValue();
7591 uint64_t NBytes = NElems * TSize;
7593 // Check for overlap.
7595 if (HasSameBase(Src, Dest)) {
7596 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7597 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7598 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7599 // Dest is inside the source region.
7601 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7604 // For memmove and friends, copy backwards.
7605 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7606 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7609 } else if (!Move && SrcOffset >= DestOffset &&
7610 SrcOffset - DestOffset < NBytes) {
7611 // Src is inside the destination region for memcpy: invalid.
7612 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7619 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7620 !handleAssignment(Info, E, Dest, T, Val))
7622 // Do not iterate past the last element; if we're copying backwards, that
7623 // might take us off the start of the array.
7626 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7627 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7633 return visitNonBuiltinCallExpr(E);
7637 //===----------------------------------------------------------------------===//
7638 // Member Pointer Evaluation
7639 //===----------------------------------------------------------------------===//
7642 class MemberPointerExprEvaluator
7643 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7646 bool Success(const ValueDecl *D) {
7647 Result = MemberPtr(D);
7652 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7653 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7655 bool Success(const APValue &V, const Expr *E) {
7659 bool ZeroInitialization(const Expr *E) {
7660 return Success((const ValueDecl*)nullptr);
7663 bool VisitCastExpr(const CastExpr *E);
7664 bool VisitUnaryAddrOf(const UnaryOperator *E);
7666 } // end anonymous namespace
7668 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7670 assert(E->isRValue() && E->getType()->isMemberPointerType());
7671 return MemberPointerExprEvaluator(Info, Result).Visit(E);
7674 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7675 switch (E->getCastKind()) {
7677 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7679 case CK_NullToMemberPointer:
7680 VisitIgnoredValue(E->getSubExpr());
7681 return ZeroInitialization(E);
7683 case CK_BaseToDerivedMemberPointer: {
7684 if (!Visit(E->getSubExpr()))
7686 if (E->path_empty())
7688 // Base-to-derived member pointer casts store the path in derived-to-base
7689 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7690 // the wrong end of the derived->base arc, so stagger the path by one class.
7691 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7692 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7693 PathI != PathE; ++PathI) {
7694 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7695 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7696 if (!Result.castToDerived(Derived))
7699 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7700 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7705 case CK_DerivedToBaseMemberPointer:
7706 if (!Visit(E->getSubExpr()))
7708 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7709 PathE = E->path_end(); PathI != PathE; ++PathI) {
7710 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7711 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7712 if (!Result.castToBase(Base))
7719 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7720 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7721 // member can be formed.
7722 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7725 //===----------------------------------------------------------------------===//
7726 // Record Evaluation
7727 //===----------------------------------------------------------------------===//
7730 class RecordExprEvaluator
7731 : public ExprEvaluatorBase<RecordExprEvaluator> {
7736 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7737 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7739 bool Success(const APValue &V, const Expr *E) {
7743 bool ZeroInitialization(const Expr *E) {
7744 return ZeroInitialization(E, E->getType());
7746 bool ZeroInitialization(const Expr *E, QualType T);
7748 bool VisitCallExpr(const CallExpr *E) {
7749 return handleCallExpr(E, Result, &This);
7751 bool VisitCastExpr(const CastExpr *E);
7752 bool VisitInitListExpr(const InitListExpr *E);
7753 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7754 return VisitCXXConstructExpr(E, E->getType());
7756 bool VisitLambdaExpr(const LambdaExpr *E);
7757 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7758 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7759 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7761 bool VisitBinCmp(const BinaryOperator *E);
7765 /// Perform zero-initialization on an object of non-union class type.
7766 /// C++11 [dcl.init]p5:
7767 /// To zero-initialize an object or reference of type T means:
7769 /// -- if T is a (possibly cv-qualified) non-union class type,
7770 /// each non-static data member and each base-class subobject is
7771 /// zero-initialized
7772 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7773 const RecordDecl *RD,
7774 const LValue &This, APValue &Result) {
7775 assert(!RD->isUnion() && "Expected non-union class type");
7776 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7777 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7778 std::distance(RD->field_begin(), RD->field_end()));
7780 if (RD->isInvalidDecl()) return false;
7781 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7785 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7786 End = CD->bases_end(); I != End; ++I, ++Index) {
7787 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7788 LValue Subobject = This;
7789 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7791 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7792 Result.getStructBase(Index)))
7797 for (const auto *I : RD->fields()) {
7798 // -- if T is a reference type, no initialization is performed.
7799 if (I->getType()->isReferenceType())
7802 LValue Subobject = This;
7803 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7806 ImplicitValueInitExpr VIE(I->getType());
7807 if (!EvaluateInPlace(
7808 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7815 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7816 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7817 if (RD->isInvalidDecl()) return false;
7818 if (RD->isUnion()) {
7819 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7820 // object's first non-static named data member is zero-initialized
7821 RecordDecl::field_iterator I = RD->field_begin();
7822 if (I == RD->field_end()) {
7823 Result = APValue((const FieldDecl*)nullptr);
7827 LValue Subobject = This;
7828 if (!HandleLValueMember(Info, E, Subobject, *I))
7830 Result = APValue(*I);
7831 ImplicitValueInitExpr VIE(I->getType());
7832 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7835 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7836 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7840 return HandleClassZeroInitialization(Info, E, RD, This, Result);
7843 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7844 switch (E->getCastKind()) {
7846 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7848 case CK_ConstructorConversion:
7849 return Visit(E->getSubExpr());
7851 case CK_DerivedToBase:
7852 case CK_UncheckedDerivedToBase: {
7853 APValue DerivedObject;
7854 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7856 if (!DerivedObject.isStruct())
7857 return Error(E->getSubExpr());
7859 // Derived-to-base rvalue conversion: just slice off the derived part.
7860 APValue *Value = &DerivedObject;
7861 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7862 for (CastExpr::path_const_iterator PathI = E->path_begin(),
7863 PathE = E->path_end(); PathI != PathE; ++PathI) {
7864 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7865 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7866 Value = &Value->getStructBase(getBaseIndex(RD, Base));
7875 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7876 if (E->isTransparent())
7877 return Visit(E->getInit(0));
7879 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7880 if (RD->isInvalidDecl()) return false;
7881 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7882 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7884 EvalInfo::EvaluatingConstructorRAII EvalObj(
7886 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7887 CXXRD && CXXRD->getNumBases());
7889 if (RD->isUnion()) {
7890 const FieldDecl *Field = E->getInitializedFieldInUnion();
7891 Result = APValue(Field);
7895 // If the initializer list for a union does not contain any elements, the
7896 // first element of the union is value-initialized.
7897 // FIXME: The element should be initialized from an initializer list.
7898 // Is this difference ever observable for initializer lists which
7900 ImplicitValueInitExpr VIE(Field->getType());
7901 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7903 LValue Subobject = This;
7904 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7907 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7908 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7909 isa<CXXDefaultInitExpr>(InitExpr));
7911 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7914 if (!Result.hasValue())
7915 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7916 std::distance(RD->field_begin(), RD->field_end()));
7917 unsigned ElementNo = 0;
7918 bool Success = true;
7920 // Initialize base classes.
7921 if (CXXRD && CXXRD->getNumBases()) {
7922 for (const auto &Base : CXXRD->bases()) {
7923 assert(ElementNo < E->getNumInits() && "missing init for base class");
7924 const Expr *Init = E->getInit(ElementNo);
7926 LValue Subobject = This;
7927 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7930 APValue &FieldVal = Result.getStructBase(ElementNo);
7931 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7932 if (!Info.noteFailure())
7939 EvalObj.finishedConstructingBases();
7942 // Initialize members.
7943 for (const auto *Field : RD->fields()) {
7944 // Anonymous bit-fields are not considered members of the class for
7945 // purposes of aggregate initialization.
7946 if (Field->isUnnamedBitfield())
7949 LValue Subobject = This;
7951 bool HaveInit = ElementNo < E->getNumInits();
7953 // FIXME: Diagnostics here should point to the end of the initializer
7954 // list, not the start.
7955 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7956 Subobject, Field, &Layout))
7959 // Perform an implicit value-initialization for members beyond the end of
7960 // the initializer list.
7961 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7962 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7964 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7965 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7966 isa<CXXDefaultInitExpr>(Init));
7968 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7969 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7970 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7971 FieldVal, Field))) {
7972 if (!Info.noteFailure())
7981 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7983 // Note that E's type is not necessarily the type of our class here; we might
7984 // be initializing an array element instead.
7985 const CXXConstructorDecl *FD = E->getConstructor();
7986 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7988 bool ZeroInit = E->requiresZeroInitialization();
7989 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
7990 // If we've already performed zero-initialization, we're already done.
7991 if (Result.hasValue())
7994 // We can get here in two different ways:
7995 // 1) We're performing value-initialization, and should zero-initialize
7997 // 2) We're performing default-initialization of an object with a trivial
7998 // constexpr default constructor, in which case we should start the
7999 // lifetimes of all the base subobjects (there can be no data member
8000 // subobjects in this case) per [basic.life]p1.
8001 // Either way, ZeroInitialization is appropriate.
8002 return ZeroInitialization(E, T);
8005 const FunctionDecl *Definition = nullptr;
8006 auto Body = FD->getBody(Definition);
8008 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8011 // Avoid materializing a temporary for an elidable copy/move constructor.
8012 if (E->isElidable() && !ZeroInit)
8013 if (const MaterializeTemporaryExpr *ME
8014 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8015 return Visit(ME->GetTemporaryExpr());
8017 if (ZeroInit && !ZeroInitialization(E, T))
8020 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
8021 return HandleConstructorCall(E, This, Args,
8022 cast<CXXConstructorDecl>(Definition), Info,
8026 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8027 const CXXInheritedCtorInitExpr *E) {
8028 if (!Info.CurrentCall) {
8029 assert(Info.checkingPotentialConstantExpression());
8033 const CXXConstructorDecl *FD = E->getConstructor();
8034 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8037 const FunctionDecl *Definition = nullptr;
8038 auto Body = FD->getBody(Definition);
8040 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8043 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
8044 cast<CXXConstructorDecl>(Definition), Info,
8048 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8049 const CXXStdInitializerListExpr *E) {
8050 const ConstantArrayType *ArrayType =
8051 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8054 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8057 // Get a pointer to the first element of the array.
8058 Array.addArray(Info, E, ArrayType);
8060 // FIXME: Perform the checks on the field types in SemaInit.
8061 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8062 RecordDecl::field_iterator Field = Record->field_begin();
8063 if (Field == Record->field_end())
8067 if (!Field->getType()->isPointerType() ||
8068 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8069 ArrayType->getElementType()))
8072 // FIXME: What if the initializer_list type has base classes, etc?
8073 Result = APValue(APValue::UninitStruct(), 0, 2);
8074 Array.moveInto(Result.getStructField(0));
8076 if (++Field == Record->field_end())
8079 if (Field->getType()->isPointerType() &&
8080 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8081 ArrayType->getElementType())) {
8083 if (!HandleLValueArrayAdjustment(Info, E, Array,
8084 ArrayType->getElementType(),
8085 ArrayType->getSize().getZExtValue()))
8087 Array.moveInto(Result.getStructField(1));
8088 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8090 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8094 if (++Field != Record->field_end())
8100 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8101 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8102 if (ClosureClass->isInvalidDecl()) return false;
8104 if (Info.checkingPotentialConstantExpression()) return true;
8106 const size_t NumFields =
8107 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
8109 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8110 E->capture_init_end()) &&
8111 "The number of lambda capture initializers should equal the number of "
8112 "fields within the closure type");
8114 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8115 // Iterate through all the lambda's closure object's fields and initialize
8117 auto *CaptureInitIt = E->capture_init_begin();
8118 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8119 bool Success = true;
8120 for (const auto *Field : ClosureClass->fields()) {
8121 assert(CaptureInitIt != E->capture_init_end());
8122 // Get the initializer for this field
8123 Expr *const CurFieldInit = *CaptureInitIt++;
8125 // If there is no initializer, either this is a VLA or an error has
8130 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8131 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8132 if (!Info.keepEvaluatingAfterFailure())
8141 static bool EvaluateRecord(const Expr *E, const LValue &This,
8142 APValue &Result, EvalInfo &Info) {
8143 assert(E->isRValue() && E->getType()->isRecordType() &&
8144 "can't evaluate expression as a record rvalue");
8145 return RecordExprEvaluator(Info, This, Result).Visit(E);
8148 //===----------------------------------------------------------------------===//
8149 // Temporary Evaluation
8151 // Temporaries are represented in the AST as rvalues, but generally behave like
8152 // lvalues. The full-object of which the temporary is a subobject is implicitly
8153 // materialized so that a reference can bind to it.
8154 //===----------------------------------------------------------------------===//
8156 class TemporaryExprEvaluator
8157 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8159 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
8160 LValueExprEvaluatorBaseTy(Info, Result, false) {}
8162 /// Visit an expression which constructs the value of this temporary.
8163 bool VisitConstructExpr(const Expr *E) {
8164 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8165 return EvaluateInPlace(Value, Info, Result, E);
8168 bool VisitCastExpr(const CastExpr *E) {
8169 switch (E->getCastKind()) {
8171 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8173 case CK_ConstructorConversion:
8174 return VisitConstructExpr(E->getSubExpr());
8177 bool VisitInitListExpr(const InitListExpr *E) {
8178 return VisitConstructExpr(E);
8180 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8181 return VisitConstructExpr(E);
8183 bool VisitCallExpr(const CallExpr *E) {
8184 return VisitConstructExpr(E);
8186 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8187 return VisitConstructExpr(E);
8189 bool VisitLambdaExpr(const LambdaExpr *E) {
8190 return VisitConstructExpr(E);
8193 } // end anonymous namespace
8195 /// Evaluate an expression of record type as a temporary.
8196 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
8197 assert(E->isRValue() && E->getType()->isRecordType());
8198 return TemporaryExprEvaluator(Info, Result).Visit(E);
8201 //===----------------------------------------------------------------------===//
8202 // Vector Evaluation
8203 //===----------------------------------------------------------------------===//
8206 class VectorExprEvaluator
8207 : public ExprEvaluatorBase<VectorExprEvaluator> {
8211 VectorExprEvaluator(EvalInfo &info, APValue &Result)
8212 : ExprEvaluatorBaseTy(info), Result(Result) {}
8214 bool Success(ArrayRef<APValue> V, const Expr *E) {
8215 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8216 // FIXME: remove this APValue copy.
8217 Result = APValue(V.data(), V.size());
8220 bool Success(const APValue &V, const Expr *E) {
8221 assert(V.isVector());
8225 bool ZeroInitialization(const Expr *E);
8227 bool VisitUnaryReal(const UnaryOperator *E)
8228 { return Visit(E->getSubExpr()); }
8229 bool VisitCastExpr(const CastExpr* E);
8230 bool VisitInitListExpr(const InitListExpr *E);
8231 bool VisitUnaryImag(const UnaryOperator *E);
8232 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
8233 // binary comparisons, binary and/or/xor,
8234 // shufflevector, ExtVectorElementExpr
8236 } // end anonymous namespace
8238 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
8239 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
8240 return VectorExprEvaluator(Info, Result).Visit(E);
8243 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
8244 const VectorType *VTy = E->getType()->castAs<VectorType>();
8245 unsigned NElts = VTy->getNumElements();
8247 const Expr *SE = E->getSubExpr();
8248 QualType SETy = SE->getType();
8250 switch (E->getCastKind()) {
8251 case CK_VectorSplat: {
8252 APValue Val = APValue();
8253 if (SETy->isIntegerType()) {
8255 if (!EvaluateInteger(SE, IntResult, Info))
8257 Val = APValue(std::move(IntResult));
8258 } else if (SETy->isRealFloatingType()) {
8259 APFloat FloatResult(0.0);
8260 if (!EvaluateFloat(SE, FloatResult, Info))
8262 Val = APValue(std::move(FloatResult));
8267 // Splat and create vector APValue.
8268 SmallVector<APValue, 4> Elts(NElts, Val);
8269 return Success(Elts, E);
8272 // Evaluate the operand into an APInt we can extract from.
8273 llvm::APInt SValInt;
8274 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8276 // Extract the elements
8277 QualType EltTy = VTy->getElementType();
8278 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8279 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8280 SmallVector<APValue, 4> Elts;
8281 if (EltTy->isRealFloatingType()) {
8282 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
8283 unsigned FloatEltSize = EltSize;
8284 if (&Sem == &APFloat::x87DoubleExtended())
8286 for (unsigned i = 0; i < NElts; i++) {
8289 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8291 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
8292 Elts.push_back(APValue(APFloat(Sem, Elt)));
8294 } else if (EltTy->isIntegerType()) {
8295 for (unsigned i = 0; i < NElts; i++) {
8298 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8300 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8301 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8306 return Success(Elts, E);
8309 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8314 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8315 const VectorType *VT = E->getType()->castAs<VectorType>();
8316 unsigned NumInits = E->getNumInits();
8317 unsigned NumElements = VT->getNumElements();
8319 QualType EltTy = VT->getElementType();
8320 SmallVector<APValue, 4> Elements;
8322 // The number of initializers can be less than the number of
8323 // vector elements. For OpenCL, this can be due to nested vector
8324 // initialization. For GCC compatibility, missing trailing elements
8325 // should be initialized with zeroes.
8326 unsigned CountInits = 0, CountElts = 0;
8327 while (CountElts < NumElements) {
8328 // Handle nested vector initialization.
8329 if (CountInits < NumInits
8330 && E->getInit(CountInits)->getType()->isVectorType()) {
8332 if (!EvaluateVector(E->getInit(CountInits), v, Info))
8334 unsigned vlen = v.getVectorLength();
8335 for (unsigned j = 0; j < vlen; j++)
8336 Elements.push_back(v.getVectorElt(j));
8338 } else if (EltTy->isIntegerType()) {
8339 llvm::APSInt sInt(32);
8340 if (CountInits < NumInits) {
8341 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
8343 } else // trailing integer zero.
8344 sInt = Info.Ctx.MakeIntValue(0, EltTy);
8345 Elements.push_back(APValue(sInt));
8348 llvm::APFloat f(0.0);
8349 if (CountInits < NumInits) {
8350 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
8352 } else // trailing float zero.
8353 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8354 Elements.push_back(APValue(f));
8359 return Success(Elements, E);
8363 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
8364 const VectorType *VT = E->getType()->getAs<VectorType>();
8365 QualType EltTy = VT->getElementType();
8366 APValue ZeroElement;
8367 if (EltTy->isIntegerType())
8368 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8371 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8373 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
8374 return Success(Elements, E);
8377 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8378 VisitIgnoredValue(E->getSubExpr());
8379 return ZeroInitialization(E);
8382 //===----------------------------------------------------------------------===//
8384 //===----------------------------------------------------------------------===//
8387 class ArrayExprEvaluator
8388 : public ExprEvaluatorBase<ArrayExprEvaluator> {
8393 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8394 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
8396 bool Success(const APValue &V, const Expr *E) {
8397 assert(V.isArray() && "expected array");
8402 bool ZeroInitialization(const Expr *E) {
8403 const ConstantArrayType *CAT =
8404 Info.Ctx.getAsConstantArrayType(E->getType());
8408 Result = APValue(APValue::UninitArray(), 0,
8409 CAT->getSize().getZExtValue());
8410 if (!Result.hasArrayFiller()) return true;
8412 // Zero-initialize all elements.
8413 LValue Subobject = This;
8414 Subobject.addArray(Info, E, CAT);
8415 ImplicitValueInitExpr VIE(CAT->getElementType());
8416 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
8419 bool VisitCallExpr(const CallExpr *E) {
8420 return handleCallExpr(E, Result, &This);
8422 bool VisitInitListExpr(const InitListExpr *E);
8423 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
8424 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
8425 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8426 const LValue &Subobject,
8427 APValue *Value, QualType Type);
8428 bool VisitStringLiteral(const StringLiteral *E) {
8429 expandStringLiteral(Info, E, Result);
8433 } // end anonymous namespace
8435 static bool EvaluateArray(const Expr *E, const LValue &This,
8436 APValue &Result, EvalInfo &Info) {
8437 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
8438 return ArrayExprEvaluator(Info, This, Result).Visit(E);
8441 // Return true iff the given array filler may depend on the element index.
8442 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8443 // For now, just whitelist non-class value-initialization and initialization
8444 // lists comprised of them.
8445 if (isa<ImplicitValueInitExpr>(FillerExpr))
8447 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8448 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8449 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8457 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8458 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8462 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8463 // an appropriately-typed string literal enclosed in braces.
8464 if (E->isStringLiteralInit())
8465 return Visit(E->getInit(0));
8467 bool Success = true;
8469 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8470 "zero-initialized array shouldn't have any initialized elts");
8472 if (Result.isArray() && Result.hasArrayFiller())
8473 Filler = Result.getArrayFiller();
8475 unsigned NumEltsToInit = E->getNumInits();
8476 unsigned NumElts = CAT->getSize().getZExtValue();
8477 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8479 // If the initializer might depend on the array index, run it for each
8481 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8482 NumEltsToInit = NumElts;
8484 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8485 << NumEltsToInit << ".\n");
8487 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8489 // If the array was previously zero-initialized, preserve the
8490 // zero-initialized values.
8491 if (Filler.hasValue()) {
8492 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8493 Result.getArrayInitializedElt(I) = Filler;
8494 if (Result.hasArrayFiller())
8495 Result.getArrayFiller() = Filler;
8498 LValue Subobject = This;
8499 Subobject.addArray(Info, E, CAT);
8500 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8502 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8503 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8504 Info, Subobject, Init) ||
8505 !HandleLValueArrayAdjustment(Info, Init, Subobject,
8506 CAT->getElementType(), 1)) {
8507 if (!Info.noteFailure())
8513 if (!Result.hasArrayFiller())
8516 // If we get here, we have a trivial filler, which we can just evaluate
8517 // once and splat over the rest of the array elements.
8518 assert(FillerExpr && "no array filler for incomplete init list");
8519 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8520 FillerExpr) && Success;
8523 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8524 if (E->getCommonExpr() &&
8525 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8526 Info, E->getCommonExpr()->getSourceExpr()))
8529 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8531 uint64_t Elements = CAT->getSize().getZExtValue();
8532 Result = APValue(APValue::UninitArray(), Elements, Elements);
8534 LValue Subobject = This;
8535 Subobject.addArray(Info, E, CAT);
8537 bool Success = true;
8538 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8539 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8540 Info, Subobject, E->getSubExpr()) ||
8541 !HandleLValueArrayAdjustment(Info, E, Subobject,
8542 CAT->getElementType(), 1)) {
8543 if (!Info.noteFailure())
8552 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8553 return VisitCXXConstructExpr(E, This, &Result, E->getType());
8556 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8557 const LValue &Subobject,
8560 bool HadZeroInit = Value->hasValue();
8562 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8563 unsigned N = CAT->getSize().getZExtValue();
8565 // Preserve the array filler if we had prior zero-initialization.
8567 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8570 *Value = APValue(APValue::UninitArray(), N, N);
8573 for (unsigned I = 0; I != N; ++I)
8574 Value->getArrayInitializedElt(I) = Filler;
8576 // Initialize the elements.
8577 LValue ArrayElt = Subobject;
8578 ArrayElt.addArray(Info, E, CAT);
8579 for (unsigned I = 0; I != N; ++I)
8580 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8581 CAT->getElementType()) ||
8582 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8583 CAT->getElementType(), 1))
8589 if (!Type->isRecordType())
8592 return RecordExprEvaluator(Info, Subobject, *Value)
8593 .VisitCXXConstructExpr(E, Type);
8596 //===----------------------------------------------------------------------===//
8597 // Integer Evaluation
8599 // As a GNU extension, we support casting pointers to sufficiently-wide integer
8600 // types and back in constant folding. Integer values are thus represented
8601 // either as an integer-valued APValue, or as an lvalue-valued APValue.
8602 //===----------------------------------------------------------------------===//
8605 class IntExprEvaluator
8606 : public ExprEvaluatorBase<IntExprEvaluator> {
8609 IntExprEvaluator(EvalInfo &info, APValue &result)
8610 : ExprEvaluatorBaseTy(info), Result(result) {}
8612 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8613 assert(E->getType()->isIntegralOrEnumerationType() &&
8614 "Invalid evaluation result.");
8615 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8616 "Invalid evaluation result.");
8617 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8618 "Invalid evaluation result.");
8619 Result = APValue(SI);
8622 bool Success(const llvm::APSInt &SI, const Expr *E) {
8623 return Success(SI, E, Result);
8626 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8627 assert(E->getType()->isIntegralOrEnumerationType() &&
8628 "Invalid evaluation result.");
8629 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8630 "Invalid evaluation result.");
8631 Result = APValue(APSInt(I));
8632 Result.getInt().setIsUnsigned(
8633 E->getType()->isUnsignedIntegerOrEnumerationType());
8636 bool Success(const llvm::APInt &I, const Expr *E) {
8637 return Success(I, E, Result);
8640 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8641 assert(E->getType()->isIntegralOrEnumerationType() &&
8642 "Invalid evaluation result.");
8643 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8646 bool Success(uint64_t Value, const Expr *E) {
8647 return Success(Value, E, Result);
8650 bool Success(CharUnits Size, const Expr *E) {
8651 return Success(Size.getQuantity(), E);
8654 bool Success(const APValue &V, const Expr *E) {
8655 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
8659 return Success(V.getInt(), E);
8662 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8664 //===--------------------------------------------------------------------===//
8666 //===--------------------------------------------------------------------===//
8668 bool VisitConstantExpr(const ConstantExpr *E);
8670 bool VisitIntegerLiteral(const IntegerLiteral *E) {
8671 return Success(E->getValue(), E);
8673 bool VisitCharacterLiteral(const CharacterLiteral *E) {
8674 return Success(E->getValue(), E);
8677 bool CheckReferencedDecl(const Expr *E, const Decl *D);
8678 bool VisitDeclRefExpr(const DeclRefExpr *E) {
8679 if (CheckReferencedDecl(E, E->getDecl()))
8682 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8684 bool VisitMemberExpr(const MemberExpr *E) {
8685 if (CheckReferencedDecl(E, E->getMemberDecl())) {
8686 VisitIgnoredBaseExpression(E->getBase());
8690 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8693 bool VisitCallExpr(const CallExpr *E);
8694 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8695 bool VisitBinaryOperator(const BinaryOperator *E);
8696 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8697 bool VisitUnaryOperator(const UnaryOperator *E);
8699 bool VisitCastExpr(const CastExpr* E);
8700 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8702 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8703 return Success(E->getValue(), E);
8706 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8707 return Success(E->getValue(), E);
8710 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8711 if (Info.ArrayInitIndex == uint64_t(-1)) {
8712 // We were asked to evaluate this subexpression independent of the
8713 // enclosing ArrayInitLoopExpr. We can't do that.
8717 return Success(Info.ArrayInitIndex, E);
8720 // Note, GNU defines __null as an integer, not a pointer.
8721 bool VisitGNUNullExpr(const GNUNullExpr *E) {
8722 return ZeroInitialization(E);
8725 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8726 return Success(E->getValue(), E);
8729 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8730 return Success(E->getValue(), E);
8733 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8734 return Success(E->getValue(), E);
8737 bool VisitUnaryReal(const UnaryOperator *E);
8738 bool VisitUnaryImag(const UnaryOperator *E);
8740 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8741 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8742 bool VisitSourceLocExpr(const SourceLocExpr *E);
8743 // FIXME: Missing: array subscript of vector, member of vector
8746 class FixedPointExprEvaluator
8747 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8751 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8752 : ExprEvaluatorBaseTy(info), Result(result) {}
8754 bool Success(const llvm::APInt &I, const Expr *E) {
8756 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8759 bool Success(uint64_t Value, const Expr *E) {
8761 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8764 bool Success(const APValue &V, const Expr *E) {
8765 return Success(V.getFixedPoint(), E);
8768 bool Success(const APFixedPoint &V, const Expr *E) {
8769 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8770 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8771 "Invalid evaluation result.");
8772 Result = APValue(V);
8776 //===--------------------------------------------------------------------===//
8778 //===--------------------------------------------------------------------===//
8780 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8781 return Success(E->getValue(), E);
8784 bool VisitCastExpr(const CastExpr *E);
8785 bool VisitUnaryOperator(const UnaryOperator *E);
8786 bool VisitBinaryOperator(const BinaryOperator *E);
8788 } // end anonymous namespace
8790 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8791 /// produce either the integer value or a pointer.
8793 /// GCC has a heinous extension which folds casts between pointer types and
8794 /// pointer-sized integral types. We support this by allowing the evaluation of
8795 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8796 /// Some simple arithmetic on such values is supported (they are treated much
8798 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8800 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8801 return IntExprEvaluator(Info, Result).Visit(E);
8804 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8806 if (!EvaluateIntegerOrLValue(E, Val, Info))
8809 // FIXME: It would be better to produce the diagnostic for casting
8810 // a pointer to an integer.
8811 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8814 Result = Val.getInt();
8818 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8819 APValue Evaluated = E->EvaluateInContext(
8820 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8821 return Success(Evaluated, E);
8824 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8826 if (E->getType()->isFixedPointType()) {
8828 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8830 if (!Val.isFixedPoint())
8833 Result = Val.getFixedPoint();
8839 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8841 if (E->getType()->isIntegerType()) {
8842 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8844 if (!EvaluateInteger(E, Val, Info))
8846 Result = APFixedPoint(Val, FXSema);
8848 } else if (E->getType()->isFixedPointType()) {
8849 return EvaluateFixedPoint(E, Result, Info);
8854 /// Check whether the given declaration can be directly converted to an integral
8855 /// rvalue. If not, no diagnostic is produced; there are other things we can
8857 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8858 // Enums are integer constant exprs.
8859 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8860 // Check for signedness/width mismatches between E type and ECD value.
8861 bool SameSign = (ECD->getInitVal().isSigned()
8862 == E->getType()->isSignedIntegerOrEnumerationType());
8863 bool SameWidth = (ECD->getInitVal().getBitWidth()
8864 == Info.Ctx.getIntWidth(E->getType()));
8865 if (SameSign && SameWidth)
8866 return Success(ECD->getInitVal(), E);
8868 // Get rid of mismatch (otherwise Success assertions will fail)
8869 // by computing a new value matching the type of E.
8870 llvm::APSInt Val = ECD->getInitVal();
8872 Val.setIsSigned(!ECD->getInitVal().isSigned());
8874 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8875 return Success(Val, E);
8881 /// Values returned by __builtin_classify_type, chosen to match the values
8882 /// produced by GCC's builtin.
8883 enum class GCCTypeClass {
8887 // GCC reserves 2 for character types, but instead classifies them as
8892 // GCC reserves 6 for references, but appears to never use it (because
8893 // expressions never have reference type, presumably).
8894 PointerToDataMember = 7,
8897 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8898 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8899 // GCC claims to reserve 11 for pointers to member functions, but *actually*
8900 // uses 12 for that purpose, same as for a class or struct. Maybe it
8901 // internally implements a pointer to member as a struct? Who knows.
8902 PointerToMemberFunction = 12, // Not a bug, see above.
8905 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8906 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8907 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8911 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8914 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8915 assert(!T->isDependentType() && "unexpected dependent type");
8917 QualType CanTy = T.getCanonicalType();
8918 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8920 switch (CanTy->getTypeClass()) {
8921 #define TYPE(ID, BASE)
8922 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8923 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8924 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8925 #include "clang/AST/TypeNodes.def"
8927 case Type::DeducedTemplateSpecialization:
8928 llvm_unreachable("unexpected non-canonical or dependent type");
8931 switch (BT->getKind()) {
8932 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8933 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8934 case BuiltinType::ID: return GCCTypeClass::Integer;
8935 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8936 case BuiltinType::ID: return GCCTypeClass::RealFloat;
8937 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8938 case BuiltinType::ID: break;
8939 #include "clang/AST/BuiltinTypes.def"
8940 case BuiltinType::Void:
8941 return GCCTypeClass::Void;
8943 case BuiltinType::Bool:
8944 return GCCTypeClass::Bool;
8946 case BuiltinType::Char_U:
8947 case BuiltinType::UChar:
8948 case BuiltinType::WChar_U:
8949 case BuiltinType::Char8:
8950 case BuiltinType::Char16:
8951 case BuiltinType::Char32:
8952 case BuiltinType::UShort:
8953 case BuiltinType::UInt:
8954 case BuiltinType::ULong:
8955 case BuiltinType::ULongLong:
8956 case BuiltinType::UInt128:
8957 return GCCTypeClass::Integer;
8959 case BuiltinType::UShortAccum:
8960 case BuiltinType::UAccum:
8961 case BuiltinType::ULongAccum:
8962 case BuiltinType::UShortFract:
8963 case BuiltinType::UFract:
8964 case BuiltinType::ULongFract:
8965 case BuiltinType::SatUShortAccum:
8966 case BuiltinType::SatUAccum:
8967 case BuiltinType::SatULongAccum:
8968 case BuiltinType::SatUShortFract:
8969 case BuiltinType::SatUFract:
8970 case BuiltinType::SatULongFract:
8971 return GCCTypeClass::None;
8973 case BuiltinType::NullPtr:
8975 case BuiltinType::ObjCId:
8976 case BuiltinType::ObjCClass:
8977 case BuiltinType::ObjCSel:
8978 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8979 case BuiltinType::Id:
8980 #include "clang/Basic/OpenCLImageTypes.def"
8981 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8982 case BuiltinType::Id:
8983 #include "clang/Basic/OpenCLExtensionTypes.def"
8984 case BuiltinType::OCLSampler:
8985 case BuiltinType::OCLEvent:
8986 case BuiltinType::OCLClkEvent:
8987 case BuiltinType::OCLQueue:
8988 case BuiltinType::OCLReserveID:
8989 return GCCTypeClass::None;
8991 case BuiltinType::Dependent:
8992 llvm_unreachable("unexpected dependent type");
8994 llvm_unreachable("unexpected placeholder type");
8997 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
9000 case Type::ConstantArray:
9001 case Type::VariableArray:
9002 case Type::IncompleteArray:
9003 case Type::FunctionNoProto:
9004 case Type::FunctionProto:
9005 return GCCTypeClass::Pointer;
9007 case Type::MemberPointer:
9008 return CanTy->isMemberDataPointerType()
9009 ? GCCTypeClass::PointerToDataMember
9010 : GCCTypeClass::PointerToMemberFunction;
9013 return GCCTypeClass::Complex;
9016 return CanTy->isUnionType() ? GCCTypeClass::Union
9017 : GCCTypeClass::ClassOrStruct;
9020 // GCC classifies _Atomic T the same as T.
9021 return EvaluateBuiltinClassifyType(
9022 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
9024 case Type::BlockPointer:
9026 case Type::ExtVector:
9027 case Type::ObjCObject:
9028 case Type::ObjCInterface:
9029 case Type::ObjCObjectPointer:
9031 // GCC classifies vectors as None. We follow its lead and classify all
9032 // other types that don't fit into the regular classification the same way.
9033 return GCCTypeClass::None;
9035 case Type::LValueReference:
9036 case Type::RValueReference:
9037 llvm_unreachable("invalid type for expression");
9040 llvm_unreachable("unexpected type class");
9043 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9046 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9047 // If no argument was supplied, default to None. This isn't
9048 // ideal, however it is what gcc does.
9049 if (E->getNumArgs() == 0)
9050 return GCCTypeClass::None;
9052 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9053 // being an ICE, but still folds it to a constant using the type of the first
9055 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
9058 /// EvaluateBuiltinConstantPForLValue - Determine the result of
9059 /// __builtin_constant_p when applied to the given pointer.
9061 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
9062 /// or it points to the first character of a string literal.
9063 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9064 APValue::LValueBase Base = LV.getLValueBase();
9065 if (Base.isNull()) {
9066 // A null base is acceptable.
9068 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9069 if (!isa<StringLiteral>(E))
9071 return LV.getLValueOffset().isZero();
9072 } else if (Base.is<TypeInfoLValue>()) {
9073 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9074 // evaluate to true.
9077 // Any other base is not constant enough for GCC.
9082 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9083 /// GCC as we can manage.
9084 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9085 // This evaluation is not permitted to have side-effects, so evaluate it in
9086 // a speculative evaluation context.
9087 SpeculativeEvaluationRAII SpeculativeEval(Info);
9089 // Constant-folding is always enabled for the operand of __builtin_constant_p
9090 // (even when the enclosing evaluation context otherwise requires a strict
9091 // language-specific constant expression).
9092 FoldConstant Fold(Info, true);
9094 QualType ArgType = Arg->getType();
9096 // __builtin_constant_p always has one operand. The rules which gcc follows
9097 // are not precisely documented, but are as follows:
9099 // - If the operand is of integral, floating, complex or enumeration type,
9100 // and can be folded to a known value of that type, it returns 1.
9101 // - If the operand can be folded to a pointer to the first character
9102 // of a string literal (or such a pointer cast to an integral type)
9103 // or to a null pointer or an integer cast to a pointer, it returns 1.
9105 // Otherwise, it returns 0.
9107 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9108 // its support for this did not work prior to GCC 9 and is not yet well
9110 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9111 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9112 ArgType->isNullPtrType()) {
9114 if (!::EvaluateAsRValue(Info, Arg, V)) {
9115 Fold.keepDiagnostics();
9119 // For a pointer (possibly cast to integer), there are special rules.
9120 if (V.getKind() == APValue::LValue)
9121 return EvaluateBuiltinConstantPForLValue(V);
9123 // Otherwise, any constant value is good enough.
9124 return V.hasValue();
9127 // Anything else isn't considered to be sufficiently constant.
9131 /// Retrieves the "underlying object type" of the given expression,
9132 /// as used by __builtin_object_size.
9133 static QualType getObjectType(APValue::LValueBase B) {
9134 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9135 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9136 return VD->getType();
9137 } else if (const Expr *E = B.get<const Expr*>()) {
9138 if (isa<CompoundLiteralExpr>(E))
9139 return E->getType();
9140 } else if (B.is<TypeInfoLValue>()) {
9141 return B.getTypeInfoType();
9147 /// A more selective version of E->IgnoreParenCasts for
9148 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9149 /// to change the type of E.
9150 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9152 /// Always returns an RValue with a pointer representation.
9153 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9154 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9156 auto *NoParens = E->IgnoreParens();
9157 auto *Cast = dyn_cast<CastExpr>(NoParens);
9158 if (Cast == nullptr)
9161 // We only conservatively allow a few kinds of casts, because this code is
9162 // inherently a simple solution that seeks to support the common case.
9163 auto CastKind = Cast->getCastKind();
9164 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9165 CastKind != CK_AddressSpaceConversion)
9168 auto *SubExpr = Cast->getSubExpr();
9169 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9171 return ignorePointerCastsAndParens(SubExpr);
9174 /// Checks to see if the given LValue's Designator is at the end of the LValue's
9175 /// record layout. e.g.
9176 /// struct { struct { int a, b; } fst, snd; } obj;
9182 /// obj.snd.b // yes
9184 /// Please note: this function is specialized for how __builtin_object_size
9185 /// views "objects".
9187 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
9188 /// correct result, it will always return true.
9189 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9190 assert(!LVal.Designator.Invalid);
9192 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9193 const RecordDecl *Parent = FD->getParent();
9194 Invalid = Parent->isInvalidDecl();
9195 if (Invalid || Parent->isUnion())
9197 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9198 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9201 auto &Base = LVal.getLValueBase();
9202 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9203 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9205 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9207 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9208 for (auto *FD : IFD->chain()) {
9210 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9217 QualType BaseType = getType(Base);
9218 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9219 // If we don't know the array bound, conservatively assume we're looking at
9220 // the final array element.
9222 if (BaseType->isIncompleteArrayType())
9223 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9225 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9228 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9229 const auto &Entry = LVal.Designator.Entries[I];
9230 if (BaseType->isArrayType()) {
9231 // Because __builtin_object_size treats arrays as objects, we can ignore
9232 // the index iff this is the last array in the Designator.
9235 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9236 uint64_t Index = Entry.getAsArrayIndex();
9237 if (Index + 1 != CAT->getSize())
9239 BaseType = CAT->getElementType();
9240 } else if (BaseType->isAnyComplexType()) {
9241 const auto *CT = BaseType->castAs<ComplexType>();
9242 uint64_t Index = Entry.getAsArrayIndex();
9245 BaseType = CT->getElementType();
9246 } else if (auto *FD = getAsField(Entry)) {
9248 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9250 BaseType = FD->getType();
9252 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
9259 /// Tests to see if the LValue has a user-specified designator (that isn't
9260 /// necessarily valid). Note that this always returns 'true' if the LValue has
9261 /// an unsized array as its first designator entry, because there's currently no
9262 /// way to tell if the user typed *foo or foo[0].
9263 static bool refersToCompleteObject(const LValue &LVal) {
9264 if (LVal.Designator.Invalid)
9267 if (!LVal.Designator.Entries.empty())
9268 return LVal.Designator.isMostDerivedAnUnsizedArray();
9270 if (!LVal.InvalidBase)
9273 // If `E` is a MemberExpr, then the first part of the designator is hiding in
9275 const auto *E = LVal.Base.dyn_cast<const Expr *>();
9276 return !E || !isa<MemberExpr>(E);
9279 /// Attempts to detect a user writing into a piece of memory that's impossible
9280 /// to figure out the size of by just using types.
9281 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9282 const SubobjectDesignator &Designator = LVal.Designator;
9284 // - Users can only write off of the end when we have an invalid base. Invalid
9285 // bases imply we don't know where the memory came from.
9286 // - We used to be a bit more aggressive here; we'd only be conservative if
9287 // the array at the end was flexible, or if it had 0 or 1 elements. This
9288 // broke some common standard library extensions (PR30346), but was
9289 // otherwise seemingly fine. It may be useful to reintroduce this behavior
9290 // with some sort of whitelist. OTOH, it seems that GCC is always
9291 // conservative with the last element in structs (if it's an array), so our
9292 // current behavior is more compatible than a whitelisting approach would
9294 return LVal.InvalidBase &&
9295 Designator.Entries.size() == Designator.MostDerivedPathLength &&
9296 Designator.MostDerivedIsArrayElement &&
9297 isDesignatorAtObjectEnd(Ctx, LVal);
9300 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9301 /// Fails if the conversion would cause loss of precision.
9302 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9303 CharUnits &Result) {
9304 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9305 if (Int.ugt(CharUnitsMax))
9307 Result = CharUnits::fromQuantity(Int.getZExtValue());
9311 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9312 /// determine how many bytes exist from the beginning of the object to either
9313 /// the end of the current subobject, or the end of the object itself, depending
9314 /// on what the LValue looks like + the value of Type.
9316 /// If this returns false, the value of Result is undefined.
9317 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9318 unsigned Type, const LValue &LVal,
9319 CharUnits &EndOffset) {
9320 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
9322 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9323 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9325 return HandleSizeof(Info, ExprLoc, Ty, Result);
9328 // We want to evaluate the size of the entire object. This is a valid fallback
9329 // for when Type=1 and the designator is invalid, because we're asked for an
9331 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9332 // Type=3 wants a lower bound, so we can't fall back to this.
9333 if (Type == 3 && !DetermineForCompleteObject)
9336 llvm::APInt APEndOffset;
9337 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9338 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9339 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9341 if (LVal.InvalidBase)
9344 QualType BaseTy = getObjectType(LVal.getLValueBase());
9345 return CheckedHandleSizeof(BaseTy, EndOffset);
9348 // We want to evaluate the size of a subobject.
9349 const SubobjectDesignator &Designator = LVal.Designator;
9351 // The following is a moderately common idiom in C:
9353 // struct Foo { int a; char c[1]; };
9354 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9355 // strcpy(&F->c[0], Bar);
9357 // In order to not break too much legacy code, we need to support it.
9358 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9359 // If we can resolve this to an alloc_size call, we can hand that back,
9360 // because we know for certain how many bytes there are to write to.
9361 llvm::APInt APEndOffset;
9362 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9363 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9364 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9366 // If we cannot determine the size of the initial allocation, then we can't
9367 // given an accurate upper-bound. However, we are still able to give
9368 // conservative lower-bounds for Type=3.
9373 CharUnits BytesPerElem;
9374 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
9377 // According to the GCC documentation, we want the size of the subobject
9378 // denoted by the pointer. But that's not quite right -- what we actually
9379 // want is the size of the immediately-enclosing array, if there is one.
9380 int64_t ElemsRemaining;
9381 if (Designator.MostDerivedIsArrayElement &&
9382 Designator.Entries.size() == Designator.MostDerivedPathLength) {
9383 uint64_t ArraySize = Designator.getMostDerivedArraySize();
9384 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
9385 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9387 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9390 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9394 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
9395 /// returns true and stores the result in @p Size.
9397 /// If @p WasError is non-null, this will report whether the failure to evaluate
9398 /// is to be treated as an Error in IntExprEvaluator.
9399 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9400 EvalInfo &Info, uint64_t &Size) {
9401 // Determine the denoted object.
9404 // The operand of __builtin_object_size is never evaluated for side-effects.
9405 // If there are any, but we can determine the pointed-to object anyway, then
9406 // ignore the side-effects.
9407 SpeculativeEvaluationRAII SpeculativeEval(Info);
9408 IgnoreSideEffectsRAII Fold(Info);
9410 if (E->isGLValue()) {
9411 // It's possible for us to be given GLValues if we're called via
9412 // Expr::tryEvaluateObjectSize.
9414 if (!EvaluateAsRValue(Info, E, RVal))
9416 LVal.setFrom(Info.Ctx, RVal);
9417 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9418 /*InvalidBaseOK=*/true))
9422 // If we point to before the start of the object, there are no accessible
9424 if (LVal.getLValueOffset().isNegative()) {
9429 CharUnits EndOffset;
9430 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9433 // If we've fallen outside of the end offset, just pretend there's nothing to
9434 // write to/read from.
9435 if (EndOffset <= LVal.getLValueOffset())
9438 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9442 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9443 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
9444 if (E->getResultAPValueKind() != APValue::None)
9445 return Success(E->getAPValueResult(), E);
9446 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9449 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
9450 if (unsigned BuiltinOp = E->getBuiltinCallee())
9451 return VisitBuiltinCallExpr(E, BuiltinOp);
9453 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9456 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9457 unsigned BuiltinOp) {
9458 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9460 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9462 case Builtin::BI__builtin_dynamic_object_size:
9463 case Builtin::BI__builtin_object_size: {
9464 // The type was checked when we built the expression.
9466 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9467 assert(Type <= 3 && "unexpected type");
9470 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9471 return Success(Size, E);
9473 if (E->getArg(0)->HasSideEffects(Info.Ctx))
9474 return Success((Type & 2) ? 0 : -1, E);
9476 // Expression had no side effects, but we couldn't statically determine the
9477 // size of the referenced object.
9478 switch (Info.EvalMode) {
9479 case EvalInfo::EM_ConstantExpression:
9480 case EvalInfo::EM_ConstantFold:
9481 case EvalInfo::EM_IgnoreSideEffects:
9482 // Leave it to IR generation.
9484 case EvalInfo::EM_ConstantExpressionUnevaluated:
9485 // Reduce it to a constant now.
9486 return Success((Type & 2) ? 0 : -1, E);
9489 llvm_unreachable("unexpected EvalMode");
9492 case Builtin::BI__builtin_os_log_format_buffer_size: {
9493 analyze_os_log::OSLogBufferLayout Layout;
9494 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9495 return Success(Layout.size().getQuantity(), E);
9498 case Builtin::BI__builtin_bswap16:
9499 case Builtin::BI__builtin_bswap32:
9500 case Builtin::BI__builtin_bswap64: {
9502 if (!EvaluateInteger(E->getArg(0), Val, Info))
9505 return Success(Val.byteSwap(), E);
9508 case Builtin::BI__builtin_classify_type:
9509 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9511 case Builtin::BI__builtin_clrsb:
9512 case Builtin::BI__builtin_clrsbl:
9513 case Builtin::BI__builtin_clrsbll: {
9515 if (!EvaluateInteger(E->getArg(0), Val, Info))
9518 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9521 case Builtin::BI__builtin_clz:
9522 case Builtin::BI__builtin_clzl:
9523 case Builtin::BI__builtin_clzll:
9524 case Builtin::BI__builtin_clzs: {
9526 if (!EvaluateInteger(E->getArg(0), Val, Info))
9531 return Success(Val.countLeadingZeros(), E);
9534 case Builtin::BI__builtin_constant_p: {
9535 const Expr *Arg = E->getArg(0);
9536 if (EvaluateBuiltinConstantP(Info, Arg))
9537 return Success(true, E);
9538 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9539 // Outside a constant context, eagerly evaluate to false in the presence
9540 // of side-effects in order to avoid -Wunsequenced false-positives in
9541 // a branch on __builtin_constant_p(expr).
9542 return Success(false, E);
9544 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9548 case Builtin::BI__builtin_is_constant_evaluated:
9549 return Success(Info.InConstantContext, E);
9551 case Builtin::BI__builtin_ctz:
9552 case Builtin::BI__builtin_ctzl:
9553 case Builtin::BI__builtin_ctzll:
9554 case Builtin::BI__builtin_ctzs: {
9556 if (!EvaluateInteger(E->getArg(0), Val, Info))
9561 return Success(Val.countTrailingZeros(), E);
9564 case Builtin::BI__builtin_eh_return_data_regno: {
9565 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9566 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9567 return Success(Operand, E);
9570 case Builtin::BI__builtin_expect:
9571 return Visit(E->getArg(0));
9573 case Builtin::BI__builtin_ffs:
9574 case Builtin::BI__builtin_ffsl:
9575 case Builtin::BI__builtin_ffsll: {
9577 if (!EvaluateInteger(E->getArg(0), Val, Info))
9580 unsigned N = Val.countTrailingZeros();
9581 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9584 case Builtin::BI__builtin_fpclassify: {
9586 if (!EvaluateFloat(E->getArg(5), Val, Info))
9589 switch (Val.getCategory()) {
9590 case APFloat::fcNaN: Arg = 0; break;
9591 case APFloat::fcInfinity: Arg = 1; break;
9592 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9593 case APFloat::fcZero: Arg = 4; break;
9595 return Visit(E->getArg(Arg));
9598 case Builtin::BI__builtin_isinf_sign: {
9600 return EvaluateFloat(E->getArg(0), Val, Info) &&
9601 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9604 case Builtin::BI__builtin_isinf: {
9606 return EvaluateFloat(E->getArg(0), Val, Info) &&
9607 Success(Val.isInfinity() ? 1 : 0, E);
9610 case Builtin::BI__builtin_isfinite: {
9612 return EvaluateFloat(E->getArg(0), Val, Info) &&
9613 Success(Val.isFinite() ? 1 : 0, E);
9616 case Builtin::BI__builtin_isnan: {
9618 return EvaluateFloat(E->getArg(0), Val, Info) &&
9619 Success(Val.isNaN() ? 1 : 0, E);
9622 case Builtin::BI__builtin_isnormal: {
9624 return EvaluateFloat(E->getArg(0), Val, Info) &&
9625 Success(Val.isNormal() ? 1 : 0, E);
9628 case Builtin::BI__builtin_parity:
9629 case Builtin::BI__builtin_parityl:
9630 case Builtin::BI__builtin_parityll: {
9632 if (!EvaluateInteger(E->getArg(0), Val, Info))
9635 return Success(Val.countPopulation() % 2, E);
9638 case Builtin::BI__builtin_popcount:
9639 case Builtin::BI__builtin_popcountl:
9640 case Builtin::BI__builtin_popcountll: {
9642 if (!EvaluateInteger(E->getArg(0), Val, Info))
9645 return Success(Val.countPopulation(), E);
9648 case Builtin::BIstrlen:
9649 case Builtin::BIwcslen:
9650 // A call to strlen is not a constant expression.
9651 if (Info.getLangOpts().CPlusPlus11)
9652 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9653 << /*isConstexpr*/0 << /*isConstructor*/0
9654 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9656 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9658 case Builtin::BI__builtin_strlen:
9659 case Builtin::BI__builtin_wcslen: {
9660 // As an extension, we support __builtin_strlen() as a constant expression,
9661 // and support folding strlen() to a constant.
9663 if (!EvaluatePointer(E->getArg(0), String, Info))
9666 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9668 // Fast path: if it's a string literal, search the string value.
9669 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9670 String.getLValueBase().dyn_cast<const Expr *>())) {
9671 // The string literal may have embedded null characters. Find the first
9672 // one and truncate there.
9673 StringRef Str = S->getBytes();
9674 int64_t Off = String.Offset.getQuantity();
9675 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9676 S->getCharByteWidth() == 1 &&
9677 // FIXME: Add fast-path for wchar_t too.
9678 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9679 Str = Str.substr(Off);
9681 StringRef::size_type Pos = Str.find(0);
9682 if (Pos != StringRef::npos)
9683 Str = Str.substr(0, Pos);
9685 return Success(Str.size(), E);
9688 // Fall through to slow path to issue appropriate diagnostic.
9691 // Slow path: scan the bytes of the string looking for the terminating 0.
9692 for (uint64_t Strlen = 0; /**/; ++Strlen) {
9694 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9698 return Success(Strlen, E);
9699 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9704 case Builtin::BIstrcmp:
9705 case Builtin::BIwcscmp:
9706 case Builtin::BIstrncmp:
9707 case Builtin::BIwcsncmp:
9708 case Builtin::BImemcmp:
9709 case Builtin::BIbcmp:
9710 case Builtin::BIwmemcmp:
9711 // A call to strlen is not a constant expression.
9712 if (Info.getLangOpts().CPlusPlus11)
9713 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9714 << /*isConstexpr*/0 << /*isConstructor*/0
9715 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9717 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9719 case Builtin::BI__builtin_strcmp:
9720 case Builtin::BI__builtin_wcscmp:
9721 case Builtin::BI__builtin_strncmp:
9722 case Builtin::BI__builtin_wcsncmp:
9723 case Builtin::BI__builtin_memcmp:
9724 case Builtin::BI__builtin_bcmp:
9725 case Builtin::BI__builtin_wmemcmp: {
9726 LValue String1, String2;
9727 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9728 !EvaluatePointer(E->getArg(1), String2, Info))
9731 uint64_t MaxLength = uint64_t(-1);
9732 if (BuiltinOp != Builtin::BIstrcmp &&
9733 BuiltinOp != Builtin::BIwcscmp &&
9734 BuiltinOp != Builtin::BI__builtin_strcmp &&
9735 BuiltinOp != Builtin::BI__builtin_wcscmp) {
9737 if (!EvaluateInteger(E->getArg(2), N, Info))
9739 MaxLength = N.getExtValue();
9742 // Empty substrings compare equal by definition.
9743 if (MaxLength == 0u)
9744 return Success(0, E);
9746 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9747 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9748 String1.Designator.Invalid || String2.Designator.Invalid)
9751 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9752 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9754 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9755 BuiltinOp == Builtin::BIbcmp ||
9756 BuiltinOp == Builtin::BI__builtin_memcmp ||
9757 BuiltinOp == Builtin::BI__builtin_bcmp;
9760 (Info.Ctx.hasSameUnqualifiedType(
9761 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9762 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9764 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9765 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9766 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9767 Char1.isInt() && Char2.isInt();
9769 const auto &AdvanceElems = [&] {
9770 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9771 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9775 uint64_t BytesRemaining = MaxLength;
9776 // Pointers to const void may point to objects of incomplete type.
9777 if (CharTy1->isIncompleteType()) {
9778 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9781 if (CharTy2->isIncompleteType()) {
9782 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9785 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9786 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9787 // Give up on comparing between elements with disparate widths.
9788 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9790 uint64_t BytesPerElement = CharTy1Size.getQuantity();
9791 assert(BytesRemaining && "BytesRemaining should not be zero: the "
9792 "following loop considers at least one element");
9794 APValue Char1, Char2;
9795 if (!ReadCurElems(Char1, Char2))
9797 // We have compatible in-memory widths, but a possible type and
9798 // (for `bool`) internal representation mismatch.
9799 // Assuming two's complement representation, including 0 for `false` and
9800 // 1 for `true`, we can check an appropriate number of elements for
9801 // equality even if they are not byte-sized.
9802 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9803 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9804 if (Char1InMem.ne(Char2InMem)) {
9805 // If the elements are byte-sized, then we can produce a three-way
9806 // comparison result in a straightforward manner.
9807 if (BytesPerElement == 1u) {
9808 // memcmp always compares unsigned chars.
9809 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9811 // The result is byte-order sensitive, and we have multibyte elements.
9812 // FIXME: We can compare the remaining bytes in the correct order.
9815 if (!AdvanceElems())
9817 if (BytesRemaining <= BytesPerElement)
9819 BytesRemaining -= BytesPerElement;
9821 // Enough elements are equal to account for the memcmp limit.
9822 return Success(0, E);
9826 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9827 BuiltinOp != Builtin::BIwmemcmp &&
9828 BuiltinOp != Builtin::BI__builtin_memcmp &&
9829 BuiltinOp != Builtin::BI__builtin_bcmp &&
9830 BuiltinOp != Builtin::BI__builtin_wmemcmp);
9831 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9832 BuiltinOp == Builtin::BIwcsncmp ||
9833 BuiltinOp == Builtin::BIwmemcmp ||
9834 BuiltinOp == Builtin::BI__builtin_wcscmp ||
9835 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9836 BuiltinOp == Builtin::BI__builtin_wmemcmp;
9838 for (; MaxLength; --MaxLength) {
9839 APValue Char1, Char2;
9840 if (!ReadCurElems(Char1, Char2))
9842 if (Char1.getInt() != Char2.getInt()) {
9843 if (IsWide) // wmemcmp compares with wchar_t signedness.
9844 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9845 // memcmp always compares unsigned chars.
9846 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9848 if (StopAtNull && !Char1.getInt())
9849 return Success(0, E);
9850 assert(!(StopAtNull && !Char2.getInt()));
9851 if (!AdvanceElems())
9854 // We hit the strncmp / memcmp limit.
9855 return Success(0, E);
9858 case Builtin::BI__atomic_always_lock_free:
9859 case Builtin::BI__atomic_is_lock_free:
9860 case Builtin::BI__c11_atomic_is_lock_free: {
9862 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9865 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9866 // of two less than the maximum inline atomic width, we know it is
9867 // lock-free. If the size isn't a power of two, or greater than the
9868 // maximum alignment where we promote atomics, we know it is not lock-free
9869 // (at least not in the sense of atomic_is_lock_free). Otherwise,
9870 // the answer can only be determined at runtime; for example, 16-byte
9871 // atomics have lock-free implementations on some, but not all,
9872 // x86-64 processors.
9874 // Check power-of-two.
9875 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9876 if (Size.isPowerOfTwo()) {
9877 // Check against inlining width.
9878 unsigned InlineWidthBits =
9879 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9880 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9881 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9882 Size == CharUnits::One() ||
9883 E->getArg(1)->isNullPointerConstant(Info.Ctx,
9884 Expr::NPC_NeverValueDependent))
9885 // OK, we will inline appropriately-aligned operations of this size,
9886 // and _Atomic(T) is appropriately-aligned.
9887 return Success(1, E);
9889 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9890 castAs<PointerType>()->getPointeeType();
9891 if (!PointeeType->isIncompleteType() &&
9892 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9893 // OK, we will inline operations on this object.
9894 return Success(1, E);
9899 // Avoid emiting call for runtime decision on PowerPC 32-bit
9900 // The lock free possibilities on this platform are covered by the lines
9901 // above and we know in advance other cases require lock
9902 if (Info.Ctx.getTargetInfo().getTriple().getArch() == llvm::Triple::ppc) {
9903 return Success(0, E);
9906 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9907 Success(0, E) : Error(E);
9909 case Builtin::BIomp_is_initial_device:
9910 // We can decide statically which value the runtime would return if called.
9911 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9912 case Builtin::BI__builtin_add_overflow:
9913 case Builtin::BI__builtin_sub_overflow:
9914 case Builtin::BI__builtin_mul_overflow:
9915 case Builtin::BI__builtin_sadd_overflow:
9916 case Builtin::BI__builtin_uadd_overflow:
9917 case Builtin::BI__builtin_uaddl_overflow:
9918 case Builtin::BI__builtin_uaddll_overflow:
9919 case Builtin::BI__builtin_usub_overflow:
9920 case Builtin::BI__builtin_usubl_overflow:
9921 case Builtin::BI__builtin_usubll_overflow:
9922 case Builtin::BI__builtin_umul_overflow:
9923 case Builtin::BI__builtin_umull_overflow:
9924 case Builtin::BI__builtin_umulll_overflow:
9925 case Builtin::BI__builtin_saddl_overflow:
9926 case Builtin::BI__builtin_saddll_overflow:
9927 case Builtin::BI__builtin_ssub_overflow:
9928 case Builtin::BI__builtin_ssubl_overflow:
9929 case Builtin::BI__builtin_ssubll_overflow:
9930 case Builtin::BI__builtin_smul_overflow:
9931 case Builtin::BI__builtin_smull_overflow:
9932 case Builtin::BI__builtin_smulll_overflow: {
9933 LValue ResultLValue;
9936 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9937 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9938 !EvaluateInteger(E->getArg(1), RHS, Info) ||
9939 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9943 bool DidOverflow = false;
9945 // If the types don't have to match, enlarge all 3 to the largest of them.
9946 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9947 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9948 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9949 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9950 ResultType->isSignedIntegerOrEnumerationType();
9951 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9952 ResultType->isSignedIntegerOrEnumerationType();
9953 uint64_t LHSSize = LHS.getBitWidth();
9954 uint64_t RHSSize = RHS.getBitWidth();
9955 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9956 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9958 // Add an additional bit if the signedness isn't uniformly agreed to. We
9959 // could do this ONLY if there is a signed and an unsigned that both have
9960 // MaxBits, but the code to check that is pretty nasty. The issue will be
9961 // caught in the shrink-to-result later anyway.
9962 if (IsSigned && !AllSigned)
9965 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9966 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9967 Result = APSInt(MaxBits, !IsSigned);
9970 // Find largest int.
9971 switch (BuiltinOp) {
9973 llvm_unreachable("Invalid value for BuiltinOp");
9974 case Builtin::BI__builtin_add_overflow:
9975 case Builtin::BI__builtin_sadd_overflow:
9976 case Builtin::BI__builtin_saddl_overflow:
9977 case Builtin::BI__builtin_saddll_overflow:
9978 case Builtin::BI__builtin_uadd_overflow:
9979 case Builtin::BI__builtin_uaddl_overflow:
9980 case Builtin::BI__builtin_uaddll_overflow:
9981 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9982 : LHS.uadd_ov(RHS, DidOverflow);
9984 case Builtin::BI__builtin_sub_overflow:
9985 case Builtin::BI__builtin_ssub_overflow:
9986 case Builtin::BI__builtin_ssubl_overflow:
9987 case Builtin::BI__builtin_ssubll_overflow:
9988 case Builtin::BI__builtin_usub_overflow:
9989 case Builtin::BI__builtin_usubl_overflow:
9990 case Builtin::BI__builtin_usubll_overflow:
9991 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9992 : LHS.usub_ov(RHS, DidOverflow);
9994 case Builtin::BI__builtin_mul_overflow:
9995 case Builtin::BI__builtin_smul_overflow:
9996 case Builtin::BI__builtin_smull_overflow:
9997 case Builtin::BI__builtin_smulll_overflow:
9998 case Builtin::BI__builtin_umul_overflow:
9999 case Builtin::BI__builtin_umull_overflow:
10000 case Builtin::BI__builtin_umulll_overflow:
10001 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10002 : LHS.umul_ov(RHS, DidOverflow);
10006 // In the case where multiple sizes are allowed, truncate and see if
10007 // the values are the same.
10008 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10009 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10010 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10011 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10012 // since it will give us the behavior of a TruncOrSelf in the case where
10013 // its parameter <= its size. We previously set Result to be at least the
10014 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10015 // will work exactly like TruncOrSelf.
10016 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10017 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10019 if (!APSInt::isSameValue(Temp, Result))
10020 DidOverflow = true;
10024 APValue APV{Result};
10025 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10027 return Success(DidOverflow, E);
10032 /// Determine whether this is a pointer past the end of the complete
10033 /// object referred to by the lvalue.
10034 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10035 const LValue &LV) {
10036 // A null pointer can be viewed as being "past the end" but we don't
10037 // choose to look at it that way here.
10038 if (!LV.getLValueBase())
10041 // If the designator is valid and refers to a subobject, we're not pointing
10043 if (!LV.getLValueDesignator().Invalid &&
10044 !LV.getLValueDesignator().isOnePastTheEnd())
10047 // A pointer to an incomplete type might be past-the-end if the type's size is
10048 // zero. We cannot tell because the type is incomplete.
10049 QualType Ty = getType(LV.getLValueBase());
10050 if (Ty->isIncompleteType())
10053 // We're a past-the-end pointer if we point to the byte after the object,
10054 // no matter what our type or path is.
10055 auto Size = Ctx.getTypeSizeInChars(Ty);
10056 return LV.getLValueOffset() == Size;
10061 /// Data recursive integer evaluator of certain binary operators.
10063 /// We use a data recursive algorithm for binary operators so that we are able
10064 /// to handle extreme cases of chained binary operators without causing stack
10066 class DataRecursiveIntBinOpEvaluator {
10067 struct EvalResult {
10071 EvalResult() : Failed(false) { }
10073 void swap(EvalResult &RHS) {
10075 Failed = RHS.Failed;
10076 RHS.Failed = false;
10082 EvalResult LHSResult; // meaningful only for binary operator expression.
10083 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10086 Job(Job &&) = default;
10088 void startSpeculativeEval(EvalInfo &Info) {
10089 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10093 SpeculativeEvaluationRAII SpecEvalRAII;
10096 SmallVector<Job, 16> Queue;
10098 IntExprEvaluator &IntEval;
10100 APValue &FinalResult;
10103 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10104 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10106 /// True if \param E is a binary operator that we are going to handle
10107 /// data recursively.
10108 /// We handle binary operators that are comma, logical, or that have operands
10109 /// with integral or enumeration type.
10110 static bool shouldEnqueue(const BinaryOperator *E) {
10111 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10112 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10113 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10114 E->getRHS()->getType()->isIntegralOrEnumerationType());
10117 bool Traverse(const BinaryOperator *E) {
10119 EvalResult PrevResult;
10120 while (!Queue.empty())
10121 process(PrevResult);
10123 if (PrevResult.Failed) return false;
10125 FinalResult.swap(PrevResult.Val);
10130 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10131 return IntEval.Success(Value, E, Result);
10133 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10134 return IntEval.Success(Value, E, Result);
10136 bool Error(const Expr *E) {
10137 return IntEval.Error(E);
10139 bool Error(const Expr *E, diag::kind D) {
10140 return IntEval.Error(E, D);
10143 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10144 return Info.CCEDiag(E, D);
10147 // Returns true if visiting the RHS is necessary, false otherwise.
10148 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10149 bool &SuppressRHSDiags);
10151 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10152 const BinaryOperator *E, APValue &Result);
10154 void EvaluateExpr(const Expr *E, EvalResult &Result) {
10155 Result.Failed = !Evaluate(Result.Val, Info, E);
10157 Result.Val = APValue();
10160 void process(EvalResult &Result);
10162 void enqueue(const Expr *E) {
10163 E = E->IgnoreParens();
10164 Queue.resize(Queue.size()+1);
10165 Queue.back().E = E;
10166 Queue.back().Kind = Job::AnyExprKind;
10172 bool DataRecursiveIntBinOpEvaluator::
10173 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10174 bool &SuppressRHSDiags) {
10175 if (E->getOpcode() == BO_Comma) {
10176 // Ignore LHS but note if we could not evaluate it.
10177 if (LHSResult.Failed)
10178 return Info.noteSideEffect();
10182 if (E->isLogicalOp()) {
10184 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10185 // We were able to evaluate the LHS, see if we can get away with not
10186 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10187 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10188 Success(LHSAsBool, E, LHSResult.Val);
10189 return false; // Ignore RHS
10192 LHSResult.Failed = true;
10194 // Since we weren't able to evaluate the left hand side, it
10195 // might have had side effects.
10196 if (!Info.noteSideEffect())
10199 // We can't evaluate the LHS; however, sometimes the result
10200 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10201 // Don't ignore RHS and suppress diagnostics from this arm.
10202 SuppressRHSDiags = true;
10208 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10209 E->getRHS()->getType()->isIntegralOrEnumerationType());
10211 if (LHSResult.Failed && !Info.noteFailure())
10212 return false; // Ignore RHS;
10217 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10219 // Compute the new offset in the appropriate width, wrapping at 64 bits.
10220 // FIXME: When compiling for a 32-bit target, we should use 32-bit
10222 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10223 CharUnits &Offset = LVal.getLValueOffset();
10224 uint64_t Offset64 = Offset.getQuantity();
10225 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10226 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10227 : Offset64 + Index64);
10230 bool DataRecursiveIntBinOpEvaluator::
10231 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10232 const BinaryOperator *E, APValue &Result) {
10233 if (E->getOpcode() == BO_Comma) {
10234 if (RHSResult.Failed)
10236 Result = RHSResult.Val;
10240 if (E->isLogicalOp()) {
10241 bool lhsResult, rhsResult;
10242 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10243 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10247 if (E->getOpcode() == BO_LOr)
10248 return Success(lhsResult || rhsResult, E, Result);
10250 return Success(lhsResult && rhsResult, E, Result);
10254 // We can't evaluate the LHS; however, sometimes the result
10255 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10256 if (rhsResult == (E->getOpcode() == BO_LOr))
10257 return Success(rhsResult, E, Result);
10264 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10265 E->getRHS()->getType()->isIntegralOrEnumerationType());
10267 if (LHSResult.Failed || RHSResult.Failed)
10270 const APValue &LHSVal = LHSResult.Val;
10271 const APValue &RHSVal = RHSResult.Val;
10273 // Handle cases like (unsigned long)&a + 4.
10274 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10276 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10280 // Handle cases like 4 + (unsigned long)&a
10281 if (E->getOpcode() == BO_Add &&
10282 RHSVal.isLValue() && LHSVal.isInt()) {
10284 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10288 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10289 // Handle (intptr_t)&&A - (intptr_t)&&B.
10290 if (!LHSVal.getLValueOffset().isZero() ||
10291 !RHSVal.getLValueOffset().isZero())
10293 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10294 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10295 if (!LHSExpr || !RHSExpr)
10297 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10298 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10299 if (!LHSAddrExpr || !RHSAddrExpr)
10301 // Make sure both labels come from the same function.
10302 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10303 RHSAddrExpr->getLabel()->getDeclContext())
10305 Result = APValue(LHSAddrExpr, RHSAddrExpr);
10309 // All the remaining cases expect both operands to be an integer
10310 if (!LHSVal.isInt() || !RHSVal.isInt())
10313 // Set up the width and signedness manually, in case it can't be deduced
10314 // from the operation we're performing.
10315 // FIXME: Don't do this in the cases where we can deduce it.
10316 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10317 E->getType()->isUnsignedIntegerOrEnumerationType());
10318 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10319 RHSVal.getInt(), Value))
10321 return Success(Value, E, Result);
10324 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
10325 Job &job = Queue.back();
10327 switch (job.Kind) {
10328 case Job::AnyExprKind: {
10329 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10330 if (shouldEnqueue(Bop)) {
10331 job.Kind = Job::BinOpKind;
10332 enqueue(Bop->getLHS());
10337 EvaluateExpr(job.E, Result);
10342 case Job::BinOpKind: {
10343 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10344 bool SuppressRHSDiags = false;
10345 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
10349 if (SuppressRHSDiags)
10350 job.startSpeculativeEval(Info);
10351 job.LHSResult.swap(Result);
10352 job.Kind = Job::BinOpVisitedLHSKind;
10353 enqueue(Bop->getRHS());
10357 case Job::BinOpVisitedLHSKind: {
10358 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10361 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
10367 llvm_unreachable("Invalid Job::Kind!");
10371 /// Used when we determine that we should fail, but can keep evaluating prior to
10372 /// noting that we had a failure.
10373 class DelayedNoteFailureRAII {
10378 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10379 : Info(Info), NoteFailure(NoteFailure) {}
10380 ~DelayedNoteFailureRAII() {
10382 bool ContinueAfterFailure = Info.noteFailure();
10383 (void)ContinueAfterFailure;
10384 assert(ContinueAfterFailure &&
10385 "Shouldn't have kept evaluating on failure.");
10391 template <class SuccessCB, class AfterCB>
10393 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10394 SuccessCB &&Success, AfterCB &&DoAfter) {
10395 assert(E->isComparisonOp() && "expected comparison operator");
10396 assert((E->getOpcode() == BO_Cmp ||
10397 E->getType()->isIntegralOrEnumerationType()) &&
10398 "unsupported binary expression evaluation");
10399 auto Error = [&](const Expr *E) {
10400 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10404 using CCR = ComparisonCategoryResult;
10405 bool IsRelational = E->isRelationalOp();
10406 bool IsEquality = E->isEqualityOp();
10407 if (E->getOpcode() == BO_Cmp) {
10408 const ComparisonCategoryInfo &CmpInfo =
10409 Info.Ctx.CompCategories.getInfoForType(E->getType());
10410 IsRelational = CmpInfo.isOrdered();
10411 IsEquality = CmpInfo.isEquality();
10414 QualType LHSTy = E->getLHS()->getType();
10415 QualType RHSTy = E->getRHS()->getType();
10417 if (LHSTy->isIntegralOrEnumerationType() &&
10418 RHSTy->isIntegralOrEnumerationType()) {
10420 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10421 if (!LHSOK && !Info.noteFailure())
10423 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10426 return Success(CCR::Less, E);
10428 return Success(CCR::Greater, E);
10429 return Success(CCR::Equal, E);
10432 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10433 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10434 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10436 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10437 if (!LHSOK && !Info.noteFailure())
10439 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10442 return Success(CCR::Less, E);
10444 return Success(CCR::Greater, E);
10445 return Success(CCR::Equal, E);
10448 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10449 ComplexValue LHS, RHS;
10451 if (E->isAssignmentOp()) {
10453 EvaluateLValue(E->getLHS(), LV, Info);
10455 } else if (LHSTy->isRealFloatingType()) {
10456 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10458 LHS.makeComplexFloat();
10459 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10462 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10464 if (!LHSOK && !Info.noteFailure())
10467 if (E->getRHS()->getType()->isRealFloatingType()) {
10468 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10470 RHS.makeComplexFloat();
10471 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10472 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10475 if (LHS.isComplexFloat()) {
10476 APFloat::cmpResult CR_r =
10477 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10478 APFloat::cmpResult CR_i =
10479 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10480 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10481 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10483 assert(IsEquality && "invalid complex comparison");
10484 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10485 LHS.getComplexIntImag() == RHS.getComplexIntImag();
10486 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10490 if (LHSTy->isRealFloatingType() &&
10491 RHSTy->isRealFloatingType()) {
10492 APFloat RHS(0.0), LHS(0.0);
10494 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10495 if (!LHSOK && !Info.noteFailure())
10498 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10501 assert(E->isComparisonOp() && "Invalid binary operator!");
10502 auto GetCmpRes = [&]() {
10503 switch (LHS.compare(RHS)) {
10504 case APFloat::cmpEqual:
10506 case APFloat::cmpLessThan:
10508 case APFloat::cmpGreaterThan:
10509 return CCR::Greater;
10510 case APFloat::cmpUnordered:
10511 return CCR::Unordered;
10513 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10515 return Success(GetCmpRes(), E);
10518 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10519 LValue LHSValue, RHSValue;
10521 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10522 if (!LHSOK && !Info.noteFailure())
10525 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10528 // Reject differing bases from the normal codepath; we special-case
10529 // comparisons to null.
10530 if (!HasSameBase(LHSValue, RHSValue)) {
10531 // Inequalities and subtractions between unrelated pointers have
10532 // unspecified or undefined behavior.
10535 // A constant address may compare equal to the address of a symbol.
10536 // The one exception is that address of an object cannot compare equal
10537 // to a null pointer constant.
10538 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10539 (!RHSValue.Base && !RHSValue.Offset.isZero()))
10541 // It's implementation-defined whether distinct literals will have
10542 // distinct addresses. In clang, the result of such a comparison is
10543 // unspecified, so it is not a constant expression. However, we do know
10544 // that the address of a literal will be non-null.
10545 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10546 LHSValue.Base && RHSValue.Base)
10548 // We can't tell whether weak symbols will end up pointing to the same
10550 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10552 // We can't compare the address of the start of one object with the
10553 // past-the-end address of another object, per C++ DR1652.
10554 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10555 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10556 (RHSValue.Base && RHSValue.Offset.isZero() &&
10557 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10559 // We can't tell whether an object is at the same address as another
10560 // zero sized object.
10561 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10562 (LHSValue.Base && isZeroSized(RHSValue)))
10564 return Success(CCR::Nonequal, E);
10567 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10568 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10570 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10571 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10573 // C++11 [expr.rel]p3:
10574 // Pointers to void (after pointer conversions) can be compared, with a
10575 // result defined as follows: If both pointers represent the same
10576 // address or are both the null pointer value, the result is true if the
10577 // operator is <= or >= and false otherwise; otherwise the result is
10579 // We interpret this as applying to pointers to *cv* void.
10580 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10581 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10583 // C++11 [expr.rel]p2:
10584 // - If two pointers point to non-static data members of the same object,
10585 // or to subobjects or array elements fo such members, recursively, the
10586 // pointer to the later declared member compares greater provided the
10587 // two members have the same access control and provided their class is
10590 // - Otherwise pointer comparisons are unspecified.
10591 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10592 bool WasArrayIndex;
10593 unsigned Mismatch = FindDesignatorMismatch(
10594 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10595 // At the point where the designators diverge, the comparison has a
10596 // specified value if:
10597 // - we are comparing array indices
10598 // - we are comparing fields of a union, or fields with the same access
10599 // Otherwise, the result is unspecified and thus the comparison is not a
10600 // constant expression.
10601 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10602 Mismatch < RHSDesignator.Entries.size()) {
10603 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10604 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10606 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10608 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10609 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10610 << RF->getParent() << RF;
10612 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10613 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10614 << LF->getParent() << LF;
10615 else if (!LF->getParent()->isUnion() &&
10616 LF->getAccess() != RF->getAccess())
10618 diag::note_constexpr_pointer_comparison_differing_access)
10619 << LF << LF->getAccess() << RF << RF->getAccess()
10620 << LF->getParent();
10624 // The comparison here must be unsigned, and performed with the same
10625 // width as the pointer.
10626 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10627 uint64_t CompareLHS = LHSOffset.getQuantity();
10628 uint64_t CompareRHS = RHSOffset.getQuantity();
10629 assert(PtrSize <= 64 && "Unexpected pointer width");
10630 uint64_t Mask = ~0ULL >> (64 - PtrSize);
10631 CompareLHS &= Mask;
10632 CompareRHS &= Mask;
10634 // If there is a base and this is a relational operator, we can only
10635 // compare pointers within the object in question; otherwise, the result
10636 // depends on where the object is located in memory.
10637 if (!LHSValue.Base.isNull() && IsRelational) {
10638 QualType BaseTy = getType(LHSValue.Base);
10639 if (BaseTy->isIncompleteType())
10641 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10642 uint64_t OffsetLimit = Size.getQuantity();
10643 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10647 if (CompareLHS < CompareRHS)
10648 return Success(CCR::Less, E);
10649 if (CompareLHS > CompareRHS)
10650 return Success(CCR::Greater, E);
10651 return Success(CCR::Equal, E);
10654 if (LHSTy->isMemberPointerType()) {
10655 assert(IsEquality && "unexpected member pointer operation");
10656 assert(RHSTy->isMemberPointerType() && "invalid comparison");
10658 MemberPtr LHSValue, RHSValue;
10660 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10661 if (!LHSOK && !Info.noteFailure())
10664 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10667 // C++11 [expr.eq]p2:
10668 // If both operands are null, they compare equal. Otherwise if only one is
10669 // null, they compare unequal.
10670 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10671 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10672 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10675 // Otherwise if either is a pointer to a virtual member function, the
10676 // result is unspecified.
10677 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10678 if (MD->isVirtual())
10679 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10680 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10681 if (MD->isVirtual())
10682 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10684 // Otherwise they compare equal if and only if they would refer to the
10685 // same member of the same most derived object or the same subobject if
10686 // they were dereferenced with a hypothetical object of the associated
10688 bool Equal = LHSValue == RHSValue;
10689 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10692 if (LHSTy->isNullPtrType()) {
10693 assert(E->isComparisonOp() && "unexpected nullptr operation");
10694 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10695 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10696 // are compared, the result is true of the operator is <=, >= or ==, and
10697 // false otherwise.
10698 return Success(CCR::Equal, E);
10704 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10705 if (!CheckLiteralType(Info, E))
10708 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10709 const BinaryOperator *E) {
10710 // Evaluation succeeded. Lookup the information for the comparison category
10711 // type and fetch the VarDecl for the result.
10712 const ComparisonCategoryInfo &CmpInfo =
10713 Info.Ctx.CompCategories.getInfoForType(E->getType());
10714 const VarDecl *VD =
10715 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10716 // Check and evaluate the result as a constant expression.
10719 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10721 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10723 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10724 return ExprEvaluatorBaseTy::VisitBinCmp(E);
10728 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10729 // We don't call noteFailure immediately because the assignment happens after
10730 // we evaluate LHS and RHS.
10731 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10734 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10735 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10736 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10738 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10739 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10740 "DataRecursiveIntBinOpEvaluator should have handled integral types");
10742 if (E->isComparisonOp()) {
10743 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10744 // comparisons and then translating the result.
10745 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10746 const BinaryOperator *E) {
10747 using CCR = ComparisonCategoryResult;
10748 bool IsEqual = ResKind == CCR::Equal,
10749 IsLess = ResKind == CCR::Less,
10750 IsGreater = ResKind == CCR::Greater;
10751 auto Op = E->getOpcode();
10754 llvm_unreachable("unsupported binary operator");
10757 return Success(IsEqual == (Op == BO_EQ), E);
10758 case BO_LT: return Success(IsLess, E);
10759 case BO_GT: return Success(IsGreater, E);
10760 case BO_LE: return Success(IsEqual || IsLess, E);
10761 case BO_GE: return Success(IsEqual || IsGreater, E);
10764 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10765 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10769 QualType LHSTy = E->getLHS()->getType();
10770 QualType RHSTy = E->getRHS()->getType();
10772 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10773 E->getOpcode() == BO_Sub) {
10774 LValue LHSValue, RHSValue;
10776 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10777 if (!LHSOK && !Info.noteFailure())
10780 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10783 // Reject differing bases from the normal codepath; we special-case
10784 // comparisons to null.
10785 if (!HasSameBase(LHSValue, RHSValue)) {
10786 // Handle &&A - &&B.
10787 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10789 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10790 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10791 if (!LHSExpr || !RHSExpr)
10793 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10794 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10795 if (!LHSAddrExpr || !RHSAddrExpr)
10797 // Make sure both labels come from the same function.
10798 if (LHSAddrExpr->getLabel()->getDeclContext() !=
10799 RHSAddrExpr->getLabel()->getDeclContext())
10801 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10803 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10804 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10806 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10807 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10809 // C++11 [expr.add]p6:
10810 // Unless both pointers point to elements of the same array object, or
10811 // one past the last element of the array object, the behavior is
10813 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10814 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10816 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10818 QualType Type = E->getLHS()->getType();
10819 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10821 CharUnits ElementSize;
10822 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10825 // As an extension, a type may have zero size (empty struct or union in
10826 // C, array of zero length). Pointer subtraction in such cases has
10827 // undefined behavior, so is not constant.
10828 if (ElementSize.isZero()) {
10829 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10834 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10835 // and produce incorrect results when it overflows. Such behavior
10836 // appears to be non-conforming, but is common, so perhaps we should
10837 // assume the standard intended for such cases to be undefined behavior
10838 // and check for them.
10840 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10841 // overflow in the final conversion to ptrdiff_t.
10842 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10843 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10844 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10846 APSInt TrueResult = (LHS - RHS) / ElemSize;
10847 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10849 if (Result.extend(65) != TrueResult &&
10850 !HandleOverflow(Info, E, TrueResult, E->getType()))
10852 return Success(Result, E);
10855 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10858 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10859 /// a result as the expression's type.
10860 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10861 const UnaryExprOrTypeTraitExpr *E) {
10862 switch(E->getKind()) {
10863 case UETT_PreferredAlignOf:
10864 case UETT_AlignOf: {
10865 if (E->isArgumentType())
10866 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10869 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10873 case UETT_VecStep: {
10874 QualType Ty = E->getTypeOfArgument();
10876 if (Ty->isVectorType()) {
10877 unsigned n = Ty->castAs<VectorType>()->getNumElements();
10879 // The vec_step built-in functions that take a 3-component
10880 // vector return 4. (OpenCL 1.1 spec 6.11.12)
10884 return Success(n, E);
10886 return Success(1, E);
10889 case UETT_SizeOf: {
10890 QualType SrcTy = E->getTypeOfArgument();
10891 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10892 // the result is the size of the referenced type."
10893 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10894 SrcTy = Ref->getPointeeType();
10897 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10899 return Success(Sizeof, E);
10901 case UETT_OpenMPRequiredSimdAlign:
10902 assert(E->isArgumentType());
10904 Info.Ctx.toCharUnitsFromBits(
10905 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10910 llvm_unreachable("unknown expr/type trait");
10913 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10915 unsigned n = OOE->getNumComponents();
10918 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10919 for (unsigned i = 0; i != n; ++i) {
10920 OffsetOfNode ON = OOE->getComponent(i);
10921 switch (ON.getKind()) {
10922 case OffsetOfNode::Array: {
10923 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10925 if (!EvaluateInteger(Idx, IdxResult, Info))
10927 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10930 CurrentType = AT->getElementType();
10931 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10932 Result += IdxResult.getSExtValue() * ElementSize;
10936 case OffsetOfNode::Field: {
10937 FieldDecl *MemberDecl = ON.getField();
10938 const RecordType *RT = CurrentType->getAs<RecordType>();
10941 RecordDecl *RD = RT->getDecl();
10942 if (RD->isInvalidDecl()) return false;
10943 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10944 unsigned i = MemberDecl->getFieldIndex();
10945 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10946 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10947 CurrentType = MemberDecl->getType().getNonReferenceType();
10951 case OffsetOfNode::Identifier:
10952 llvm_unreachable("dependent __builtin_offsetof");
10954 case OffsetOfNode::Base: {
10955 CXXBaseSpecifier *BaseSpec = ON.getBase();
10956 if (BaseSpec->isVirtual())
10959 // Find the layout of the class whose base we are looking into.
10960 const RecordType *RT = CurrentType->getAs<RecordType>();
10963 RecordDecl *RD = RT->getDecl();
10964 if (RD->isInvalidDecl()) return false;
10965 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10967 // Find the base class itself.
10968 CurrentType = BaseSpec->getType();
10969 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10973 // Add the offset to the base.
10974 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10979 return Success(Result, OOE);
10982 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10983 switch (E->getOpcode()) {
10985 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10989 // FIXME: Should extension allow i-c-e extension expressions in its scope?
10990 // If so, we could clear the diagnostic ID.
10991 return Visit(E->getSubExpr());
10993 // The result is just the value.
10994 return Visit(E->getSubExpr());
10996 if (!Visit(E->getSubExpr()))
10998 if (!Result.isInt()) return Error(E);
10999 const APSInt &Value = Result.getInt();
11000 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11001 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11004 return Success(-Value, E);
11007 if (!Visit(E->getSubExpr()))
11009 if (!Result.isInt()) return Error(E);
11010 return Success(~Result.getInt(), E);
11014 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11016 return Success(!bres, E);
11021 /// HandleCast - This is used to evaluate implicit or explicit casts where the
11022 /// result type is integer.
11023 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11024 const Expr *SubExpr = E->getSubExpr();
11025 QualType DestType = E->getType();
11026 QualType SrcType = SubExpr->getType();
11028 switch (E->getCastKind()) {
11029 case CK_BaseToDerived:
11030 case CK_DerivedToBase:
11031 case CK_UncheckedDerivedToBase:
11034 case CK_ArrayToPointerDecay:
11035 case CK_FunctionToPointerDecay:
11036 case CK_NullToPointer:
11037 case CK_NullToMemberPointer:
11038 case CK_BaseToDerivedMemberPointer:
11039 case CK_DerivedToBaseMemberPointer:
11040 case CK_ReinterpretMemberPointer:
11041 case CK_ConstructorConversion:
11042 case CK_IntegralToPointer:
11044 case CK_VectorSplat:
11045 case CK_IntegralToFloating:
11046 case CK_FloatingCast:
11047 case CK_CPointerToObjCPointerCast:
11048 case CK_BlockPointerToObjCPointerCast:
11049 case CK_AnyPointerToBlockPointerCast:
11050 case CK_ObjCObjectLValueCast:
11051 case CK_FloatingRealToComplex:
11052 case CK_FloatingComplexToReal:
11053 case CK_FloatingComplexCast:
11054 case CK_FloatingComplexToIntegralComplex:
11055 case CK_IntegralRealToComplex:
11056 case CK_IntegralComplexCast:
11057 case CK_IntegralComplexToFloatingComplex:
11058 case CK_BuiltinFnToFnPtr:
11059 case CK_ZeroToOCLOpaqueType:
11060 case CK_NonAtomicToAtomic:
11061 case CK_AddressSpaceConversion:
11062 case CK_IntToOCLSampler:
11063 case CK_FixedPointCast:
11064 case CK_IntegralToFixedPoint:
11065 llvm_unreachable("invalid cast kind for integral value");
11069 case CK_LValueBitCast:
11070 case CK_ARCProduceObject:
11071 case CK_ARCConsumeObject:
11072 case CK_ARCReclaimReturnedObject:
11073 case CK_ARCExtendBlockObject:
11074 case CK_CopyAndAutoreleaseBlockObject:
11077 case CK_UserDefinedConversion:
11078 case CK_LValueToRValue:
11079 case CK_AtomicToNonAtomic:
11081 case CK_LValueToRValueBitCast:
11082 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11084 case CK_MemberPointerToBoolean:
11085 case CK_PointerToBoolean:
11086 case CK_IntegralToBoolean:
11087 case CK_FloatingToBoolean:
11088 case CK_BooleanToSignedIntegral:
11089 case CK_FloatingComplexToBoolean:
11090 case CK_IntegralComplexToBoolean: {
11092 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11094 uint64_t IntResult = BoolResult;
11095 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11096 IntResult = (uint64_t)-1;
11097 return Success(IntResult, E);
11100 case CK_FixedPointToIntegral: {
11101 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11102 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11105 llvm::APSInt Result = Src.convertToInt(
11106 Info.Ctx.getIntWidth(DestType),
11107 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11108 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11110 return Success(Result, E);
11113 case CK_FixedPointToBoolean: {
11114 // Unsigned padding does not affect this.
11116 if (!Evaluate(Val, Info, SubExpr))
11118 return Success(Val.getFixedPoint().getBoolValue(), E);
11121 case CK_IntegralCast: {
11122 if (!Visit(SubExpr))
11125 if (!Result.isInt()) {
11126 // Allow casts of address-of-label differences if they are no-ops
11127 // or narrowing. (The narrowing case isn't actually guaranteed to
11128 // be constant-evaluatable except in some narrow cases which are hard
11129 // to detect here. We let it through on the assumption the user knows
11130 // what they are doing.)
11131 if (Result.isAddrLabelDiff())
11132 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11133 // Only allow casts of lvalues if they are lossless.
11134 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11137 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11138 Result.getInt()), E);
11141 case CK_PointerToIntegral: {
11142 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11145 if (!EvaluatePointer(SubExpr, LV, Info))
11148 if (LV.getLValueBase()) {
11149 // Only allow based lvalue casts if they are lossless.
11150 // FIXME: Allow a larger integer size than the pointer size, and allow
11151 // narrowing back down to pointer width in subsequent integral casts.
11152 // FIXME: Check integer type's active bits, not its type size.
11153 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11156 LV.Designator.setInvalid();
11157 LV.moveInto(Result);
11164 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11165 llvm_unreachable("Can't cast this!");
11167 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11170 case CK_IntegralComplexToReal: {
11172 if (!EvaluateComplex(SubExpr, C, Info))
11174 return Success(C.getComplexIntReal(), E);
11177 case CK_FloatingToIntegral: {
11179 if (!EvaluateFloat(SubExpr, F, Info))
11183 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11185 return Success(Value, E);
11189 llvm_unreachable("unknown cast resulting in integral value");
11192 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11193 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11195 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11197 if (!LV.isComplexInt())
11199 return Success(LV.getComplexIntReal(), E);
11202 return Visit(E->getSubExpr());
11205 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11206 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11208 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11210 if (!LV.isComplexInt())
11212 return Success(LV.getComplexIntImag(), E);
11215 VisitIgnoredValue(E->getSubExpr());
11216 return Success(0, E);
11219 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11220 return Success(E->getPackLength(), E);
11223 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11224 return Success(E->getValue(), E);
11227 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11228 switch (E->getOpcode()) {
11230 // Invalid unary operators
11233 // The result is just the value.
11234 return Visit(E->getSubExpr());
11236 if (!Visit(E->getSubExpr())) return false;
11237 if (!Result.isFixedPoint())
11240 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11241 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11243 return Success(Negated, E);
11247 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11249 return Success(!bres, E);
11254 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11255 const Expr *SubExpr = E->getSubExpr();
11256 QualType DestType = E->getType();
11257 assert(DestType->isFixedPointType() &&
11258 "Expected destination type to be a fixed point type");
11259 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11261 switch (E->getCastKind()) {
11262 case CK_FixedPointCast: {
11263 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11264 if (!EvaluateFixedPoint(SubExpr, Src, Info))
11267 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11268 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11270 return Success(Result, E);
11272 case CK_IntegralToFixedPoint: {
11274 if (!EvaluateInteger(SubExpr, Src, Info))
11278 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11279 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11281 if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11284 return Success(IntResult, E);
11287 case CK_LValueToRValue:
11288 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11294 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11295 const Expr *LHS = E->getLHS();
11296 const Expr *RHS = E->getRHS();
11297 FixedPointSemantics ResultFXSema =
11298 Info.Ctx.getFixedPointSemantics(E->getType());
11300 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11301 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11303 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11304 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11307 switch (E->getOpcode()) {
11309 bool AddOverflow, ConversionOverflow;
11310 APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11311 .convert(ResultFXSema, &ConversionOverflow);
11312 if ((AddOverflow || ConversionOverflow) &&
11313 !HandleOverflow(Info, E, Result, E->getType()))
11315 return Success(Result, E);
11320 llvm_unreachable("Should've exited before this");
11323 //===----------------------------------------------------------------------===//
11324 // Float Evaluation
11325 //===----------------------------------------------------------------------===//
11328 class FloatExprEvaluator
11329 : public ExprEvaluatorBase<FloatExprEvaluator> {
11332 FloatExprEvaluator(EvalInfo &info, APFloat &result)
11333 : ExprEvaluatorBaseTy(info), Result(result) {}
11335 bool Success(const APValue &V, const Expr *e) {
11336 Result = V.getFloat();
11340 bool ZeroInitialization(const Expr *E) {
11341 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11345 bool VisitCallExpr(const CallExpr *E);
11347 bool VisitUnaryOperator(const UnaryOperator *E);
11348 bool VisitBinaryOperator(const BinaryOperator *E);
11349 bool VisitFloatingLiteral(const FloatingLiteral *E);
11350 bool VisitCastExpr(const CastExpr *E);
11352 bool VisitUnaryReal(const UnaryOperator *E);
11353 bool VisitUnaryImag(const UnaryOperator *E);
11355 // FIXME: Missing: array subscript of vector, member of vector
11357 } // end anonymous namespace
11359 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
11360 assert(E->isRValue() && E->getType()->isRealFloatingType());
11361 return FloatExprEvaluator(Info, Result).Visit(E);
11364 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11368 llvm::APFloat &Result) {
11369 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11370 if (!S) return false;
11372 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11376 // Treat empty strings as if they were zero.
11377 if (S->getString().empty())
11378 fill = llvm::APInt(32, 0);
11379 else if (S->getString().getAsInteger(0, fill))
11382 if (Context.getTargetInfo().isNan2008()) {
11384 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11386 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11388 // Prior to IEEE 754-2008, architectures were allowed to choose whether
11389 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11390 // a different encoding to what became a standard in 2008, and for pre-
11391 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11392 // sNaN. This is now known as "legacy NaN" encoding.
11394 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11396 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11402 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11403 switch (E->getBuiltinCallee()) {
11405 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11407 case Builtin::BI__builtin_huge_val:
11408 case Builtin::BI__builtin_huge_valf:
11409 case Builtin::BI__builtin_huge_vall:
11410 case Builtin::BI__builtin_huge_valf128:
11411 case Builtin::BI__builtin_inf:
11412 case Builtin::BI__builtin_inff:
11413 case Builtin::BI__builtin_infl:
11414 case Builtin::BI__builtin_inff128: {
11415 const llvm::fltSemantics &Sem =
11416 Info.Ctx.getFloatTypeSemantics(E->getType());
11417 Result = llvm::APFloat::getInf(Sem);
11421 case Builtin::BI__builtin_nans:
11422 case Builtin::BI__builtin_nansf:
11423 case Builtin::BI__builtin_nansl:
11424 case Builtin::BI__builtin_nansf128:
11425 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11430 case Builtin::BI__builtin_nan:
11431 case Builtin::BI__builtin_nanf:
11432 case Builtin::BI__builtin_nanl:
11433 case Builtin::BI__builtin_nanf128:
11434 // If this is __builtin_nan() turn this into a nan, otherwise we
11435 // can't constant fold it.
11436 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11441 case Builtin::BI__builtin_fabs:
11442 case Builtin::BI__builtin_fabsf:
11443 case Builtin::BI__builtin_fabsl:
11444 case Builtin::BI__builtin_fabsf128:
11445 if (!EvaluateFloat(E->getArg(0), Result, Info))
11448 if (Result.isNegative())
11449 Result.changeSign();
11452 // FIXME: Builtin::BI__builtin_powi
11453 // FIXME: Builtin::BI__builtin_powif
11454 // FIXME: Builtin::BI__builtin_powil
11456 case Builtin::BI__builtin_copysign:
11457 case Builtin::BI__builtin_copysignf:
11458 case Builtin::BI__builtin_copysignl:
11459 case Builtin::BI__builtin_copysignf128: {
11461 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11462 !EvaluateFloat(E->getArg(1), RHS, Info))
11464 Result.copySign(RHS);
11470 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11471 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11473 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11475 Result = CV.FloatReal;
11479 return Visit(E->getSubExpr());
11482 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11483 if (E->getSubExpr()->getType()->isAnyComplexType()) {
11485 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11487 Result = CV.FloatImag;
11491 VisitIgnoredValue(E->getSubExpr());
11492 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11493 Result = llvm::APFloat::getZero(Sem);
11497 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11498 switch (E->getOpcode()) {
11499 default: return Error(E);
11501 return EvaluateFloat(E->getSubExpr(), Result, Info);
11503 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11505 Result.changeSign();
11510 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11511 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11512 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11515 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11516 if (!LHSOK && !Info.noteFailure())
11518 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11519 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11522 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11523 Result = E->getValue();
11527 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11528 const Expr* SubExpr = E->getSubExpr();
11530 switch (E->getCastKind()) {
11532 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11534 case CK_IntegralToFloating: {
11536 return EvaluateInteger(SubExpr, IntResult, Info) &&
11537 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11538 E->getType(), Result);
11541 case CK_FloatingCast: {
11542 if (!Visit(SubExpr))
11544 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11548 case CK_FloatingComplexToReal: {
11550 if (!EvaluateComplex(SubExpr, V, Info))
11552 Result = V.getComplexFloatReal();
11558 //===----------------------------------------------------------------------===//
11559 // Complex Evaluation (for float and integer)
11560 //===----------------------------------------------------------------------===//
11563 class ComplexExprEvaluator
11564 : public ExprEvaluatorBase<ComplexExprEvaluator> {
11565 ComplexValue &Result;
11568 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11569 : ExprEvaluatorBaseTy(info), Result(Result) {}
11571 bool Success(const APValue &V, const Expr *e) {
11576 bool ZeroInitialization(const Expr *E);
11578 //===--------------------------------------------------------------------===//
11580 //===--------------------------------------------------------------------===//
11582 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11583 bool VisitCastExpr(const CastExpr *E);
11584 bool VisitBinaryOperator(const BinaryOperator *E);
11585 bool VisitUnaryOperator(const UnaryOperator *E);
11586 bool VisitInitListExpr(const InitListExpr *E);
11588 } // end anonymous namespace
11590 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11592 assert(E->isRValue() && E->getType()->isAnyComplexType());
11593 return ComplexExprEvaluator(Info, Result).Visit(E);
11596 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11597 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11598 if (ElemTy->isRealFloatingType()) {
11599 Result.makeComplexFloat();
11600 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11601 Result.FloatReal = Zero;
11602 Result.FloatImag = Zero;
11604 Result.makeComplexInt();
11605 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11606 Result.IntReal = Zero;
11607 Result.IntImag = Zero;
11612 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11613 const Expr* SubExpr = E->getSubExpr();
11615 if (SubExpr->getType()->isRealFloatingType()) {
11616 Result.makeComplexFloat();
11617 APFloat &Imag = Result.FloatImag;
11618 if (!EvaluateFloat(SubExpr, Imag, Info))
11621 Result.FloatReal = APFloat(Imag.getSemantics());
11624 assert(SubExpr->getType()->isIntegerType() &&
11625 "Unexpected imaginary literal.");
11627 Result.makeComplexInt();
11628 APSInt &Imag = Result.IntImag;
11629 if (!EvaluateInteger(SubExpr, Imag, Info))
11632 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11637 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11639 switch (E->getCastKind()) {
11641 case CK_BaseToDerived:
11642 case CK_DerivedToBase:
11643 case CK_UncheckedDerivedToBase:
11646 case CK_ArrayToPointerDecay:
11647 case CK_FunctionToPointerDecay:
11648 case CK_NullToPointer:
11649 case CK_NullToMemberPointer:
11650 case CK_BaseToDerivedMemberPointer:
11651 case CK_DerivedToBaseMemberPointer:
11652 case CK_MemberPointerToBoolean:
11653 case CK_ReinterpretMemberPointer:
11654 case CK_ConstructorConversion:
11655 case CK_IntegralToPointer:
11656 case CK_PointerToIntegral:
11657 case CK_PointerToBoolean:
11659 case CK_VectorSplat:
11660 case CK_IntegralCast:
11661 case CK_BooleanToSignedIntegral:
11662 case CK_IntegralToBoolean:
11663 case CK_IntegralToFloating:
11664 case CK_FloatingToIntegral:
11665 case CK_FloatingToBoolean:
11666 case CK_FloatingCast:
11667 case CK_CPointerToObjCPointerCast:
11668 case CK_BlockPointerToObjCPointerCast:
11669 case CK_AnyPointerToBlockPointerCast:
11670 case CK_ObjCObjectLValueCast:
11671 case CK_FloatingComplexToReal:
11672 case CK_FloatingComplexToBoolean:
11673 case CK_IntegralComplexToReal:
11674 case CK_IntegralComplexToBoolean:
11675 case CK_ARCProduceObject:
11676 case CK_ARCConsumeObject:
11677 case CK_ARCReclaimReturnedObject:
11678 case CK_ARCExtendBlockObject:
11679 case CK_CopyAndAutoreleaseBlockObject:
11680 case CK_BuiltinFnToFnPtr:
11681 case CK_ZeroToOCLOpaqueType:
11682 case CK_NonAtomicToAtomic:
11683 case CK_AddressSpaceConversion:
11684 case CK_IntToOCLSampler:
11685 case CK_FixedPointCast:
11686 case CK_FixedPointToBoolean:
11687 case CK_FixedPointToIntegral:
11688 case CK_IntegralToFixedPoint:
11689 llvm_unreachable("invalid cast kind for complex value");
11691 case CK_LValueToRValue:
11692 case CK_AtomicToNonAtomic:
11694 case CK_LValueToRValueBitCast:
11695 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11698 case CK_LValueBitCast:
11699 case CK_UserDefinedConversion:
11702 case CK_FloatingRealToComplex: {
11703 APFloat &Real = Result.FloatReal;
11704 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11707 Result.makeComplexFloat();
11708 Result.FloatImag = APFloat(Real.getSemantics());
11712 case CK_FloatingComplexCast: {
11713 if (!Visit(E->getSubExpr()))
11716 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11718 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11720 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11721 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11724 case CK_FloatingComplexToIntegralComplex: {
11725 if (!Visit(E->getSubExpr()))
11728 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11730 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11731 Result.makeComplexInt();
11732 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11733 To, Result.IntReal) &&
11734 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11735 To, Result.IntImag);
11738 case CK_IntegralRealToComplex: {
11739 APSInt &Real = Result.IntReal;
11740 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11743 Result.makeComplexInt();
11744 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11748 case CK_IntegralComplexCast: {
11749 if (!Visit(E->getSubExpr()))
11752 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11754 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11756 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11757 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11761 case CK_IntegralComplexToFloatingComplex: {
11762 if (!Visit(E->getSubExpr()))
11765 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11767 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11768 Result.makeComplexFloat();
11769 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11770 To, Result.FloatReal) &&
11771 HandleIntToFloatCast(Info, E, From, Result.IntImag,
11772 To, Result.FloatImag);
11776 llvm_unreachable("unknown cast resulting in complex value");
11779 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11780 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11781 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11783 // Track whether the LHS or RHS is real at the type system level. When this is
11784 // the case we can simplify our evaluation strategy.
11785 bool LHSReal = false, RHSReal = false;
11788 if (E->getLHS()->getType()->isRealFloatingType()) {
11790 APFloat &Real = Result.FloatReal;
11791 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11793 Result.makeComplexFloat();
11794 Result.FloatImag = APFloat(Real.getSemantics());
11797 LHSOK = Visit(E->getLHS());
11799 if (!LHSOK && !Info.noteFailure())
11803 if (E->getRHS()->getType()->isRealFloatingType()) {
11805 APFloat &Real = RHS.FloatReal;
11806 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11808 RHS.makeComplexFloat();
11809 RHS.FloatImag = APFloat(Real.getSemantics());
11810 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11813 assert(!(LHSReal && RHSReal) &&
11814 "Cannot have both operands of a complex operation be real.");
11815 switch (E->getOpcode()) {
11816 default: return Error(E);
11818 if (Result.isComplexFloat()) {
11819 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11820 APFloat::rmNearestTiesToEven);
11822 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11824 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11825 APFloat::rmNearestTiesToEven);
11827 Result.getComplexIntReal() += RHS.getComplexIntReal();
11828 Result.getComplexIntImag() += RHS.getComplexIntImag();
11832 if (Result.isComplexFloat()) {
11833 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11834 APFloat::rmNearestTiesToEven);
11836 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11837 Result.getComplexFloatImag().changeSign();
11838 } else if (!RHSReal) {
11839 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11840 APFloat::rmNearestTiesToEven);
11843 Result.getComplexIntReal() -= RHS.getComplexIntReal();
11844 Result.getComplexIntImag() -= RHS.getComplexIntImag();
11848 if (Result.isComplexFloat()) {
11849 // This is an implementation of complex multiplication according to the
11850 // constraints laid out in C11 Annex G. The implementation uses the
11851 // following naming scheme:
11852 // (a + ib) * (c + id)
11853 ComplexValue LHS = Result;
11854 APFloat &A = LHS.getComplexFloatReal();
11855 APFloat &B = LHS.getComplexFloatImag();
11856 APFloat &C = RHS.getComplexFloatReal();
11857 APFloat &D = RHS.getComplexFloatImag();
11858 APFloat &ResR = Result.getComplexFloatReal();
11859 APFloat &ResI = Result.getComplexFloatImag();
11861 assert(!RHSReal && "Cannot have two real operands for a complex op!");
11864 } else if (RHSReal) {
11868 // In the fully general case, we need to handle NaNs and infinities
11870 APFloat AC = A * C;
11871 APFloat BD = B * D;
11872 APFloat AD = A * D;
11873 APFloat BC = B * C;
11876 if (ResR.isNaN() && ResI.isNaN()) {
11877 bool Recalc = false;
11878 if (A.isInfinity() || B.isInfinity()) {
11879 A = APFloat::copySign(
11880 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11881 B = APFloat::copySign(
11882 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11884 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11886 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11889 if (C.isInfinity() || D.isInfinity()) {
11890 C = APFloat::copySign(
11891 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11892 D = APFloat::copySign(
11893 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11895 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11897 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11900 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11901 AD.isInfinity() || BC.isInfinity())) {
11903 A = APFloat::copySign(APFloat(A.getSemantics()), A);
11905 B = APFloat::copySign(APFloat(B.getSemantics()), B);
11907 C = APFloat::copySign(APFloat(C.getSemantics()), C);
11909 D = APFloat::copySign(APFloat(D.getSemantics()), D);
11913 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11914 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11919 ComplexValue LHS = Result;
11920 Result.getComplexIntReal() =
11921 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11922 LHS.getComplexIntImag() * RHS.getComplexIntImag());
11923 Result.getComplexIntImag() =
11924 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11925 LHS.getComplexIntImag() * RHS.getComplexIntReal());
11929 if (Result.isComplexFloat()) {
11930 // This is an implementation of complex division according to the
11931 // constraints laid out in C11 Annex G. The implementation uses the
11932 // following naming scheme:
11933 // (a + ib) / (c + id)
11934 ComplexValue LHS = Result;
11935 APFloat &A = LHS.getComplexFloatReal();
11936 APFloat &B = LHS.getComplexFloatImag();
11937 APFloat &C = RHS.getComplexFloatReal();
11938 APFloat &D = RHS.getComplexFloatImag();
11939 APFloat &ResR = Result.getComplexFloatReal();
11940 APFloat &ResI = Result.getComplexFloatImag();
11946 // No real optimizations we can do here, stub out with zero.
11947 B = APFloat::getZero(A.getSemantics());
11950 APFloat MaxCD = maxnum(abs(C), abs(D));
11951 if (MaxCD.isFinite()) {
11952 DenomLogB = ilogb(MaxCD);
11953 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11954 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11956 APFloat Denom = C * C + D * D;
11957 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11958 APFloat::rmNearestTiesToEven);
11959 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11960 APFloat::rmNearestTiesToEven);
11961 if (ResR.isNaN() && ResI.isNaN()) {
11962 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11963 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11964 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11965 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11967 A = APFloat::copySign(
11968 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11969 B = APFloat::copySign(
11970 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11971 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11972 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11973 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11974 C = APFloat::copySign(
11975 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11976 D = APFloat::copySign(
11977 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11978 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11979 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11984 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11985 return Error(E, diag::note_expr_divide_by_zero);
11987 ComplexValue LHS = Result;
11988 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11989 RHS.getComplexIntImag() * RHS.getComplexIntImag();
11990 Result.getComplexIntReal() =
11991 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11992 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11993 Result.getComplexIntImag() =
11994 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11995 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
12003 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12004 // Get the operand value into 'Result'.
12005 if (!Visit(E->getSubExpr()))
12008 switch (E->getOpcode()) {
12014 // The result is always just the subexpr.
12017 if (Result.isComplexFloat()) {
12018 Result.getComplexFloatReal().changeSign();
12019 Result.getComplexFloatImag().changeSign();
12022 Result.getComplexIntReal() = -Result.getComplexIntReal();
12023 Result.getComplexIntImag() = -Result.getComplexIntImag();
12027 if (Result.isComplexFloat())
12028 Result.getComplexFloatImag().changeSign();
12030 Result.getComplexIntImag() = -Result.getComplexIntImag();
12035 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12036 if (E->getNumInits() == 2) {
12037 if (E->getType()->isComplexType()) {
12038 Result.makeComplexFloat();
12039 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12041 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12044 Result.makeComplexInt();
12045 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12047 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12052 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12055 //===----------------------------------------------------------------------===//
12056 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12057 // implicit conversion.
12058 //===----------------------------------------------------------------------===//
12061 class AtomicExprEvaluator :
12062 public ExprEvaluatorBase<AtomicExprEvaluator> {
12063 const LValue *This;
12066 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12067 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12069 bool Success(const APValue &V, const Expr *E) {
12074 bool ZeroInitialization(const Expr *E) {
12075 ImplicitValueInitExpr VIE(
12076 E->getType()->castAs<AtomicType>()->getValueType());
12077 // For atomic-qualified class (and array) types in C++, initialize the
12078 // _Atomic-wrapped subobject directly, in-place.
12079 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12080 : Evaluate(Result, Info, &VIE);
12083 bool VisitCastExpr(const CastExpr *E) {
12084 switch (E->getCastKind()) {
12086 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12087 case CK_NonAtomicToAtomic:
12088 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12089 : Evaluate(Result, Info, E->getSubExpr());
12093 } // end anonymous namespace
12095 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12097 assert(E->isRValue() && E->getType()->isAtomicType());
12098 return AtomicExprEvaluator(Info, This, Result).Visit(E);
12101 //===----------------------------------------------------------------------===//
12102 // Void expression evaluation, primarily for a cast to void on the LHS of a
12104 //===----------------------------------------------------------------------===//
12107 class VoidExprEvaluator
12108 : public ExprEvaluatorBase<VoidExprEvaluator> {
12110 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12112 bool Success(const APValue &V, const Expr *e) { return true; }
12114 bool ZeroInitialization(const Expr *E) { return true; }
12116 bool VisitCastExpr(const CastExpr *E) {
12117 switch (E->getCastKind()) {
12119 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12121 VisitIgnoredValue(E->getSubExpr());
12126 bool VisitCallExpr(const CallExpr *E) {
12127 switch (E->getBuiltinCallee()) {
12129 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12130 case Builtin::BI__assume:
12131 case Builtin::BI__builtin_assume:
12132 // The argument is not evaluated!
12137 } // end anonymous namespace
12139 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12140 assert(E->isRValue() && E->getType()->isVoidType());
12141 return VoidExprEvaluator(Info).Visit(E);
12144 //===----------------------------------------------------------------------===//
12145 // Top level Expr::EvaluateAsRValue method.
12146 //===----------------------------------------------------------------------===//
12148 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12149 // In C, function designators are not lvalues, but we evaluate them as if they
12151 QualType T = E->getType();
12152 if (E->isGLValue() || T->isFunctionType()) {
12154 if (!EvaluateLValue(E, LV, Info))
12156 LV.moveInto(Result);
12157 } else if (T->isVectorType()) {
12158 if (!EvaluateVector(E, Result, Info))
12160 } else if (T->isIntegralOrEnumerationType()) {
12161 if (!IntExprEvaluator(Info, Result).Visit(E))
12163 } else if (T->hasPointerRepresentation()) {
12165 if (!EvaluatePointer(E, LV, Info))
12167 LV.moveInto(Result);
12168 } else if (T->isRealFloatingType()) {
12169 llvm::APFloat F(0.0);
12170 if (!EvaluateFloat(E, F, Info))
12172 Result = APValue(F);
12173 } else if (T->isAnyComplexType()) {
12175 if (!EvaluateComplex(E, C, Info))
12177 C.moveInto(Result);
12178 } else if (T->isFixedPointType()) {
12179 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12180 } else if (T->isMemberPointerType()) {
12182 if (!EvaluateMemberPointer(E, P, Info))
12184 P.moveInto(Result);
12186 } else if (T->isArrayType()) {
12188 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12189 if (!EvaluateArray(E, LV, Value, Info))
12192 } else if (T->isRecordType()) {
12194 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12195 if (!EvaluateRecord(E, LV, Value, Info))
12198 } else if (T->isVoidType()) {
12199 if (!Info.getLangOpts().CPlusPlus11)
12200 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
12202 if (!EvaluateVoid(E, Info))
12204 } else if (T->isAtomicType()) {
12205 QualType Unqual = T.getAtomicUnqualifiedType();
12206 if (Unqual->isArrayType() || Unqual->isRecordType()) {
12208 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12209 if (!EvaluateAtomic(E, &LV, Value, Info))
12212 if (!EvaluateAtomic(E, nullptr, Result, Info))
12215 } else if (Info.getLangOpts().CPlusPlus11) {
12216 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
12219 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12226 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12227 /// cases, the in-place evaluation is essential, since later initializers for
12228 /// an object can indirectly refer to subobjects which were initialized earlier.
12229 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
12230 const Expr *E, bool AllowNonLiteralTypes) {
12231 assert(!E->isValueDependent());
12233 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
12236 if (E->isRValue()) {
12237 // Evaluate arrays and record types in-place, so that later initializers can
12238 // refer to earlier-initialized members of the object.
12239 QualType T = E->getType();
12240 if (T->isArrayType())
12241 return EvaluateArray(E, This, Result, Info);
12242 else if (T->isRecordType())
12243 return EvaluateRecord(E, This, Result, Info);
12244 else if (T->isAtomicType()) {
12245 QualType Unqual = T.getAtomicUnqualifiedType();
12246 if (Unqual->isArrayType() || Unqual->isRecordType())
12247 return EvaluateAtomic(E, &This, Result, Info);
12251 // For any other type, in-place evaluation is unimportant.
12252 return Evaluate(Result, Info, E);
12255 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12256 /// lvalue-to-rvalue cast if it is an lvalue.
12257 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
12258 if (E->getType().isNull())
12261 if (!CheckLiteralType(Info, E))
12264 if (!::Evaluate(Result, Info, E))
12267 if (E->isGLValue()) {
12269 LV.setFrom(Info.Ctx, Result);
12270 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12274 // Check this core constant expression is a constant expression.
12275 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12278 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
12279 const ASTContext &Ctx, bool &IsConst) {
12280 // Fast-path evaluations of integer literals, since we sometimes see files
12281 // containing vast quantities of these.
12282 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12283 Result.Val = APValue(APSInt(L->getValue(),
12284 L->getType()->isUnsignedIntegerType()));
12289 // This case should be rare, but we need to check it before we check on
12291 if (Exp->getType().isNull()) {
12296 // FIXME: Evaluating values of large array and record types can cause
12297 // performance problems. Only do so in C++11 for now.
12298 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12299 Exp->getType()->isRecordType()) &&
12300 !Ctx.getLangOpts().CPlusPlus11) {
12307 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12308 Expr::SideEffectsKind SEK) {
12309 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12310 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12313 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12314 const ASTContext &Ctx, EvalInfo &Info) {
12316 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12319 return EvaluateAsRValue(Info, E, Result.Val);
12322 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12323 const ASTContext &Ctx,
12324 Expr::SideEffectsKind AllowSideEffects,
12326 if (!E->getType()->isIntegralOrEnumerationType())
12329 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12330 !ExprResult.Val.isInt() ||
12331 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12337 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12338 const ASTContext &Ctx,
12339 Expr::SideEffectsKind AllowSideEffects,
12341 if (!E->getType()->isFixedPointType())
12344 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12347 if (!ExprResult.Val.isFixedPoint() ||
12348 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12354 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
12355 /// any crazy technique (that has nothing to do with language standards) that
12356 /// we want to. If this function returns true, it returns the folded constant
12357 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12358 /// will be applied to the result.
12359 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12360 bool InConstantContext) const {
12361 assert(!isValueDependent() &&
12362 "Expression evaluator can't be called on a dependent expression.");
12363 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12364 Info.InConstantContext = InConstantContext;
12365 return ::EvaluateAsRValue(this, Result, Ctx, Info);
12368 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12369 bool InConstantContext) const {
12370 assert(!isValueDependent() &&
12371 "Expression evaluator can't be called on a dependent expression.");
12372 EvalResult Scratch;
12373 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
12374 HandleConversionToBool(Scratch.Val, Result);
12377 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12378 SideEffectsKind AllowSideEffects,
12379 bool InConstantContext) const {
12380 assert(!isValueDependent() &&
12381 "Expression evaluator can't be called on a dependent expression.");
12382 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12383 Info.InConstantContext = InConstantContext;
12384 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12387 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
12388 SideEffectsKind AllowSideEffects,
12389 bool InConstantContext) const {
12390 assert(!isValueDependent() &&
12391 "Expression evaluator can't be called on a dependent expression.");
12392 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12393 Info.InConstantContext = InConstantContext;
12394 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12397 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12398 SideEffectsKind AllowSideEffects,
12399 bool InConstantContext) const {
12400 assert(!isValueDependent() &&
12401 "Expression evaluator can't be called on a dependent expression.");
12403 if (!getType()->isRealFloatingType())
12406 EvalResult ExprResult;
12407 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12408 !ExprResult.Val.isFloat() ||
12409 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12412 Result = ExprResult.Val.getFloat();
12416 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12417 bool InConstantContext) const {
12418 assert(!isValueDependent() &&
12419 "Expression evaluator can't be called on a dependent expression.");
12421 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12422 Info.InConstantContext = InConstantContext;
12424 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12425 !CheckLValueConstantExpression(Info, getExprLoc(),
12426 Ctx.getLValueReferenceType(getType()), LV,
12427 Expr::EvaluateForCodeGen))
12430 LV.moveInto(Result.Val);
12434 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12435 const ASTContext &Ctx) const {
12436 assert(!isValueDependent() &&
12437 "Expression evaluator can't be called on a dependent expression.");
12439 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12440 EvalInfo Info(Ctx, Result, EM);
12441 Info.InConstantContext = true;
12443 if (!::Evaluate(Result.Val, Info, this))
12446 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12450 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12452 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12453 assert(!isValueDependent() &&
12454 "Expression evaluator can't be called on a dependent expression.");
12456 // FIXME: Evaluating initializers for large array and record types can cause
12457 // performance problems. Only do so in C++11 for now.
12458 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12459 !Ctx.getLangOpts().CPlusPlus11)
12462 Expr::EvalStatus EStatus;
12463 EStatus.Diag = &Notes;
12465 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12466 ? EvalInfo::EM_ConstantExpression
12467 : EvalInfo::EM_ConstantFold);
12468 InitInfo.setEvaluatingDecl(VD, Value);
12469 InitInfo.InConstantContext = true;
12474 // C++11 [basic.start.init]p2:
12475 // Variables with static storage duration or thread storage duration shall be
12476 // zero-initialized before any other initialization takes place.
12477 // This behavior is not present in C.
12478 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12479 !VD->getType()->isReferenceType()) {
12480 ImplicitValueInitExpr VIE(VD->getType());
12481 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12482 /*AllowNonLiteralTypes=*/true))
12486 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12487 /*AllowNonLiteralTypes=*/true) ||
12488 EStatus.HasSideEffects)
12491 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12495 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12496 /// constant folded, but discard the result.
12497 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12498 assert(!isValueDependent() &&
12499 "Expression evaluator can't be called on a dependent expression.");
12502 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12503 !hasUnacceptableSideEffect(Result, SEK);
12506 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12507 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12508 assert(!isValueDependent() &&
12509 "Expression evaluator can't be called on a dependent expression.");
12511 EvalResult EVResult;
12512 EVResult.Diag = Diag;
12513 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12514 Info.InConstantContext = true;
12516 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12518 assert(Result && "Could not evaluate expression");
12519 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12521 return EVResult.Val.getInt();
12524 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12525 const ASTContext &Ctx, 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;
12533 Info.CheckingForUndefinedBehavior = true;
12535 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12537 assert(Result && "Could not evaluate expression");
12538 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12540 return EVResult.Val.getInt();
12543 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12544 assert(!isValueDependent() &&
12545 "Expression evaluator can't be called on a dependent expression.");
12548 EvalResult EVResult;
12549 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12550 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12551 Info.CheckingForUndefinedBehavior = true;
12552 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12556 bool Expr::EvalResult::isGlobalLValue() const {
12557 assert(Val.isLValue());
12558 return IsGlobalLValue(Val.getLValueBase());
12562 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12563 /// an integer constant expression.
12565 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12568 // CheckICE - This function does the fundamental ICE checking: the returned
12569 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12570 // and a (possibly null) SourceLocation indicating the location of the problem.
12572 // Note that to reduce code duplication, this helper does no evaluation
12573 // itself; the caller checks whether the expression is evaluatable, and
12574 // in the rare cases where CheckICE actually cares about the evaluated
12575 // value, it calls into Evaluate.
12580 /// This expression is an ICE.
12582 /// This expression is not an ICE, but if it isn't evaluated, it's
12583 /// a legal subexpression for an ICE. This return value is used to handle
12584 /// the comma operator in C99 mode, and non-constant subexpressions.
12585 IK_ICEIfUnevaluated,
12586 /// This expression is not an ICE, and is not a legal subexpression for one.
12592 SourceLocation Loc;
12594 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12599 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12601 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12603 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12604 Expr::EvalResult EVResult;
12605 Expr::EvalStatus Status;
12606 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12608 Info.InConstantContext = true;
12609 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12610 !EVResult.Val.isInt())
12611 return ICEDiag(IK_NotICE, E->getBeginLoc());
12616 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12617 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12618 if (!E->getType()->isIntegralOrEnumerationType())
12619 return ICEDiag(IK_NotICE, E->getBeginLoc());
12621 switch (E->getStmtClass()) {
12622 #define ABSTRACT_STMT(Node)
12623 #define STMT(Node, Base) case Expr::Node##Class:
12624 #define EXPR(Node, Base)
12625 #include "clang/AST/StmtNodes.inc"
12626 case Expr::PredefinedExprClass:
12627 case Expr::FloatingLiteralClass:
12628 case Expr::ImaginaryLiteralClass:
12629 case Expr::StringLiteralClass:
12630 case Expr::ArraySubscriptExprClass:
12631 case Expr::OMPArraySectionExprClass:
12632 case Expr::MemberExprClass:
12633 case Expr::CompoundAssignOperatorClass:
12634 case Expr::CompoundLiteralExprClass:
12635 case Expr::ExtVectorElementExprClass:
12636 case Expr::DesignatedInitExprClass:
12637 case Expr::ArrayInitLoopExprClass:
12638 case Expr::ArrayInitIndexExprClass:
12639 case Expr::NoInitExprClass:
12640 case Expr::DesignatedInitUpdateExprClass:
12641 case Expr::ImplicitValueInitExprClass:
12642 case Expr::ParenListExprClass:
12643 case Expr::VAArgExprClass:
12644 case Expr::AddrLabelExprClass:
12645 case Expr::StmtExprClass:
12646 case Expr::CXXMemberCallExprClass:
12647 case Expr::CUDAKernelCallExprClass:
12648 case Expr::CXXDynamicCastExprClass:
12649 case Expr::CXXTypeidExprClass:
12650 case Expr::CXXUuidofExprClass:
12651 case Expr::MSPropertyRefExprClass:
12652 case Expr::MSPropertySubscriptExprClass:
12653 case Expr::CXXNullPtrLiteralExprClass:
12654 case Expr::UserDefinedLiteralClass:
12655 case Expr::CXXThisExprClass:
12656 case Expr::CXXThrowExprClass:
12657 case Expr::CXXNewExprClass:
12658 case Expr::CXXDeleteExprClass:
12659 case Expr::CXXPseudoDestructorExprClass:
12660 case Expr::UnresolvedLookupExprClass:
12661 case Expr::TypoExprClass:
12662 case Expr::DependentScopeDeclRefExprClass:
12663 case Expr::CXXConstructExprClass:
12664 case Expr::CXXInheritedCtorInitExprClass:
12665 case Expr::CXXStdInitializerListExprClass:
12666 case Expr::CXXBindTemporaryExprClass:
12667 case Expr::ExprWithCleanupsClass:
12668 case Expr::CXXTemporaryObjectExprClass:
12669 case Expr::CXXUnresolvedConstructExprClass:
12670 case Expr::CXXDependentScopeMemberExprClass:
12671 case Expr::UnresolvedMemberExprClass:
12672 case Expr::ObjCStringLiteralClass:
12673 case Expr::ObjCBoxedExprClass:
12674 case Expr::ObjCArrayLiteralClass:
12675 case Expr::ObjCDictionaryLiteralClass:
12676 case Expr::ObjCEncodeExprClass:
12677 case Expr::ObjCMessageExprClass:
12678 case Expr::ObjCSelectorExprClass:
12679 case Expr::ObjCProtocolExprClass:
12680 case Expr::ObjCIvarRefExprClass:
12681 case Expr::ObjCPropertyRefExprClass:
12682 case Expr::ObjCSubscriptRefExprClass:
12683 case Expr::ObjCIsaExprClass:
12684 case Expr::ObjCAvailabilityCheckExprClass:
12685 case Expr::ShuffleVectorExprClass:
12686 case Expr::ConvertVectorExprClass:
12687 case Expr::BlockExprClass:
12688 case Expr::NoStmtClass:
12689 case Expr::OpaqueValueExprClass:
12690 case Expr::PackExpansionExprClass:
12691 case Expr::SubstNonTypeTemplateParmPackExprClass:
12692 case Expr::FunctionParmPackExprClass:
12693 case Expr::AsTypeExprClass:
12694 case Expr::ObjCIndirectCopyRestoreExprClass:
12695 case Expr::MaterializeTemporaryExprClass:
12696 case Expr::PseudoObjectExprClass:
12697 case Expr::AtomicExprClass:
12698 case Expr::LambdaExprClass:
12699 case Expr::CXXFoldExprClass:
12700 case Expr::CoawaitExprClass:
12701 case Expr::DependentCoawaitExprClass:
12702 case Expr::CoyieldExprClass:
12703 return ICEDiag(IK_NotICE, E->getBeginLoc());
12705 case Expr::InitListExprClass: {
12706 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12707 // form "T x = { a };" is equivalent to "T x = a;".
12708 // Unless we're initializing a reference, T is a scalar as it is known to be
12709 // of integral or enumeration type.
12711 if (cast<InitListExpr>(E)->getNumInits() == 1)
12712 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12713 return ICEDiag(IK_NotICE, E->getBeginLoc());
12716 case Expr::SizeOfPackExprClass:
12717 case Expr::GNUNullExprClass:
12718 case Expr::SourceLocExprClass:
12721 case Expr::SubstNonTypeTemplateParmExprClass:
12723 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12725 case Expr::ConstantExprClass:
12726 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12728 case Expr::ParenExprClass:
12729 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12730 case Expr::GenericSelectionExprClass:
12731 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12732 case Expr::IntegerLiteralClass:
12733 case Expr::FixedPointLiteralClass:
12734 case Expr::CharacterLiteralClass:
12735 case Expr::ObjCBoolLiteralExprClass:
12736 case Expr::CXXBoolLiteralExprClass:
12737 case Expr::CXXScalarValueInitExprClass:
12738 case Expr::TypeTraitExprClass:
12739 case Expr::ArrayTypeTraitExprClass:
12740 case Expr::ExpressionTraitExprClass:
12741 case Expr::CXXNoexceptExprClass:
12743 case Expr::CallExprClass:
12744 case Expr::CXXOperatorCallExprClass: {
12745 // C99 6.6/3 allows function calls within unevaluated subexpressions of
12746 // constant expressions, but they can never be ICEs because an ICE cannot
12747 // contain an operand of (pointer to) function type.
12748 const CallExpr *CE = cast<CallExpr>(E);
12749 if (CE->getBuiltinCallee())
12750 return CheckEvalInICE(E, Ctx);
12751 return ICEDiag(IK_NotICE, E->getBeginLoc());
12753 case Expr::DeclRefExprClass: {
12754 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12756 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12757 if (Ctx.getLangOpts().CPlusPlus &&
12758 D && IsConstNonVolatile(D->getType())) {
12759 // Parameter variables are never constants. Without this check,
12760 // getAnyInitializer() can find a default argument, which leads
12762 if (isa<ParmVarDecl>(D))
12763 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12766 // A variable of non-volatile const-qualified integral or enumeration
12767 // type initialized by an ICE can be used in ICEs.
12768 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12769 if (!Dcl->getType()->isIntegralOrEnumerationType())
12770 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12773 // Look for a declaration of this variable that has an initializer, and
12774 // check whether it is an ICE.
12775 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12778 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12781 return ICEDiag(IK_NotICE, E->getBeginLoc());
12783 case Expr::UnaryOperatorClass: {
12784 const UnaryOperator *Exp = cast<UnaryOperator>(E);
12785 switch (Exp->getOpcode()) {
12793 // C99 6.6/3 allows increment and decrement within unevaluated
12794 // subexpressions of constant expressions, but they can never be ICEs
12795 // because an ICE cannot contain an lvalue operand.
12796 return ICEDiag(IK_NotICE, E->getBeginLoc());
12804 return CheckICE(Exp->getSubExpr(), Ctx);
12806 llvm_unreachable("invalid unary operator class");
12808 case Expr::OffsetOfExprClass: {
12809 // Note that per C99, offsetof must be an ICE. And AFAIK, using
12810 // EvaluateAsRValue matches the proposed gcc behavior for cases like
12811 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
12812 // compliance: we should warn earlier for offsetof expressions with
12813 // array subscripts that aren't ICEs, and if the array subscripts
12814 // are ICEs, the value of the offsetof must be an integer constant.
12815 return CheckEvalInICE(E, Ctx);
12817 case Expr::UnaryExprOrTypeTraitExprClass: {
12818 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12819 if ((Exp->getKind() == UETT_SizeOf) &&
12820 Exp->getTypeOfArgument()->isVariableArrayType())
12821 return ICEDiag(IK_NotICE, E->getBeginLoc());
12824 case Expr::BinaryOperatorClass: {
12825 const BinaryOperator *Exp = cast<BinaryOperator>(E);
12826 switch (Exp->getOpcode()) {
12840 // C99 6.6/3 allows assignments within unevaluated subexpressions of
12841 // constant expressions, but they can never be ICEs because an ICE cannot
12842 // contain an lvalue operand.
12843 return ICEDiag(IK_NotICE, E->getBeginLoc());
12863 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12864 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12865 if (Exp->getOpcode() == BO_Div ||
12866 Exp->getOpcode() == BO_Rem) {
12867 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12868 // we don't evaluate one.
12869 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12870 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12872 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12873 if (REval.isSigned() && REval.isAllOnesValue()) {
12874 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12875 if (LEval.isMinSignedValue())
12876 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12880 if (Exp->getOpcode() == BO_Comma) {
12881 if (Ctx.getLangOpts().C99) {
12882 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12883 // if it isn't evaluated.
12884 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12885 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12887 // In both C89 and C++, commas in ICEs are illegal.
12888 return ICEDiag(IK_NotICE, E->getBeginLoc());
12891 return Worst(LHSResult, RHSResult);
12895 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12896 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12897 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12898 // Rare case where the RHS has a comma "side-effect"; we need
12899 // to actually check the condition to see whether the side
12900 // with the comma is evaluated.
12901 if ((Exp->getOpcode() == BO_LAnd) !=
12902 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12907 return Worst(LHSResult, RHSResult);
12910 llvm_unreachable("invalid binary operator kind");
12912 case Expr::ImplicitCastExprClass:
12913 case Expr::CStyleCastExprClass:
12914 case Expr::CXXFunctionalCastExprClass:
12915 case Expr::CXXStaticCastExprClass:
12916 case Expr::CXXReinterpretCastExprClass:
12917 case Expr::CXXConstCastExprClass:
12918 case Expr::ObjCBridgedCastExprClass: {
12919 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12920 if (isa<ExplicitCastExpr>(E)) {
12921 if (const FloatingLiteral *FL
12922 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12923 unsigned DestWidth = Ctx.getIntWidth(E->getType());
12924 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12925 APSInt IgnoredVal(DestWidth, !DestSigned);
12927 // If the value does not fit in the destination type, the behavior is
12928 // undefined, so we are not required to treat it as a constant
12930 if (FL->getValue().convertToInteger(IgnoredVal,
12931 llvm::APFloat::rmTowardZero,
12932 &Ignored) & APFloat::opInvalidOp)
12933 return ICEDiag(IK_NotICE, E->getBeginLoc());
12937 switch (cast<CastExpr>(E)->getCastKind()) {
12938 case CK_LValueToRValue:
12939 case CK_AtomicToNonAtomic:
12940 case CK_NonAtomicToAtomic:
12942 case CK_IntegralToBoolean:
12943 case CK_IntegralCast:
12944 return CheckICE(SubExpr, Ctx);
12946 return ICEDiag(IK_NotICE, E->getBeginLoc());
12949 case Expr::BinaryConditionalOperatorClass: {
12950 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12951 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12952 if (CommonResult.Kind == IK_NotICE) return CommonResult;
12953 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12954 if (FalseResult.Kind == IK_NotICE) return FalseResult;
12955 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12956 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12957 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12958 return FalseResult;
12960 case Expr::ConditionalOperatorClass: {
12961 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12962 // If the condition (ignoring parens) is a __builtin_constant_p call,
12963 // then only the true side is actually considered in an integer constant
12964 // expression, and it is fully evaluated. This is an important GNU
12965 // extension. See GCC PR38377 for discussion.
12966 if (const CallExpr *CallCE
12967 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12968 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12969 return CheckEvalInICE(E, Ctx);
12970 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12971 if (CondResult.Kind == IK_NotICE)
12974 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12975 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12977 if (TrueResult.Kind == IK_NotICE)
12979 if (FalseResult.Kind == IK_NotICE)
12980 return FalseResult;
12981 if (CondResult.Kind == IK_ICEIfUnevaluated)
12983 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12985 // Rare case where the diagnostics depend on which side is evaluated
12986 // Note that if we get here, CondResult is 0, and at least one of
12987 // TrueResult and FalseResult is non-zero.
12988 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12989 return FalseResult;
12992 case Expr::CXXDefaultArgExprClass:
12993 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12994 case Expr::CXXDefaultInitExprClass:
12995 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12996 case Expr::ChooseExprClass: {
12997 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12999 case Expr::BuiltinBitCastExprClass: {
13000 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13001 return ICEDiag(IK_NotICE, E->getBeginLoc());
13002 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13006 llvm_unreachable("Invalid StmtClass!");
13009 /// Evaluate an expression as a C++11 integral constant expression.
13010 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
13012 llvm::APSInt *Value,
13013 SourceLocation *Loc) {
13014 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13015 if (Loc) *Loc = E->getExprLoc();
13020 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
13023 if (!Result.isInt()) {
13024 if (Loc) *Loc = E->getExprLoc();
13028 if (Value) *Value = Result.getInt();
13032 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13033 SourceLocation *Loc) const {
13034 assert(!isValueDependent() &&
13035 "Expression evaluator can't be called on a dependent expression.");
13037 if (Ctx.getLangOpts().CPlusPlus11)
13038 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
13040 ICEDiag D = CheckICE(this, Ctx);
13041 if (D.Kind != IK_ICE) {
13042 if (Loc) *Loc = D.Loc;
13048 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
13049 SourceLocation *Loc, bool isEvaluated) 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, &Value, Loc);
13056 if (!isIntegerConstantExpr(Ctx, Loc))
13059 // The only possible side-effects here are due to UB discovered in the
13060 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13061 // required to treat the expression as an ICE, so we produce the folded
13063 EvalResult ExprResult;
13064 Expr::EvalStatus Status;
13065 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13066 Info.InConstantContext = true;
13068 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13069 llvm_unreachable("ICE cannot be evaluated!");
13071 Value = ExprResult.Val.getInt();
13075 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
13076 assert(!isValueDependent() &&
13077 "Expression evaluator can't be called on a dependent expression.");
13079 return CheckICE(this, Ctx).Kind == IK_ICE;
13082 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
13083 SourceLocation *Loc) const {
13084 assert(!isValueDependent() &&
13085 "Expression evaluator can't be called on a dependent expression.");
13087 // We support this checking in C++98 mode in order to diagnose compatibility
13089 assert(Ctx.getLangOpts().CPlusPlus);
13091 // Build evaluation settings.
13092 Expr::EvalStatus Status;
13093 SmallVector<PartialDiagnosticAt, 8> Diags;
13094 Status.Diag = &Diags;
13095 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13098 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13100 if (!Diags.empty()) {
13101 IsConstExpr = false;
13102 if (Loc) *Loc = Diags[0].first;
13103 } else if (!IsConstExpr) {
13104 // FIXME: This shouldn't happen.
13105 if (Loc) *Loc = getExprLoc();
13108 return IsConstExpr;
13111 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13112 const FunctionDecl *Callee,
13113 ArrayRef<const Expr*> Args,
13114 const Expr *This) const {
13115 assert(!isValueDependent() &&
13116 "Expression evaluator can't be called on a dependent expression.");
13118 Expr::EvalStatus Status;
13119 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
13120 Info.InConstantContext = true;
13123 const LValue *ThisPtr = nullptr;
13126 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13127 assert(MD && "Don't provide `this` for non-methods.");
13128 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13130 if (EvaluateObjectArgument(Info, This, ThisVal))
13131 ThisPtr = &ThisVal;
13132 if (Info.EvalStatus.HasSideEffects)
13136 ArgVector ArgValues(Args.size());
13137 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13139 if ((*I)->isValueDependent() ||
13140 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
13141 // If evaluation fails, throw away the argument entirely.
13142 ArgValues[I - Args.begin()] = APValue();
13143 if (Info.EvalStatus.HasSideEffects)
13147 // Build fake call to Callee.
13148 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
13150 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13153 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
13155 PartialDiagnosticAt> &Diags) {
13156 // FIXME: It would be useful to check constexpr function templates, but at the
13157 // moment the constant expression evaluator cannot cope with the non-rigorous
13158 // ASTs which we build for dependent expressions.
13159 if (FD->isDependentContext())
13162 Expr::EvalStatus Status;
13163 Status.Diag = &Diags;
13165 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
13166 Info.InConstantContext = true;
13167 Info.CheckingPotentialConstantExpression = true;
13169 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13170 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
13172 // Fabricate an arbitrary expression on the stack and pretend that it
13173 // is a temporary being used as the 'this' pointer.
13175 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
13176 This.set({&VIE, Info.CurrentCall->Index});
13178 ArrayRef<const Expr*> Args;
13181 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13182 // Evaluate the call as a constant initializer, to allow the construction
13183 // of objects of non-literal types.
13184 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
13185 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13187 SourceLocation Loc = FD->getLocation();
13188 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
13189 Args, FD->getBody(), Info, Scratch, nullptr);
13192 return Diags.empty();
13195 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13196 const FunctionDecl *FD,
13198 PartialDiagnosticAt> &Diags) {
13199 assert(!E->isValueDependent() &&
13200 "Expression evaluator can't be called on a dependent expression.");
13202 Expr::EvalStatus Status;
13203 Status.Diag = &Diags;
13205 EvalInfo Info(FD->getASTContext(), Status,
13206 EvalInfo::EM_ConstantExpressionUnevaluated);
13207 Info.InConstantContext = true;
13208 Info.CheckingPotentialConstantExpression = true;
13210 // Fabricate a call stack frame to give the arguments a plausible cover story.
13211 ArrayRef<const Expr*> Args;
13212 ArgVector ArgValues(0);
13213 bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
13216 "Failed to set up arguments for potential constant evaluation");
13217 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
13219 APValue ResultScratch;
13220 Evaluate(ResultScratch, Info, E);
13221 return Diags.empty();
13224 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13225 unsigned Type) const {
13226 if (!getType()->isPointerType())
13229 Expr::EvalStatus Status;
13230 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
13231 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);