1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr constant evaluator.
12 // Constant expression evaluation produces four main results:
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
19 // * An evaluated result, valid only if constant folding has not failed.
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
34 //===----------------------------------------------------------------------===//
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
55 static bool IsGlobalLValue(APValue::LValueBase B);
59 struct CallStackFrame;
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67 const Expr *Base = B.get<const Expr*>();
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 // Keep any cv-qualifiers from the reference if we generated a temporary
81 return Inner->getType();
84 return Base->getType();
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field or base class.
90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
106 /// Determine whether this LValue path entry for a base class names a virtual
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return getAsBaseOrMember(E).getInt();
112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type,
119 unsigned MostDerivedLength = 0;
121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
133 MostDerivedLength = I + 1;
135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
138 MostDerivedLength = I + 1;
141 // Path[I] describes a base class.
146 return MostDerivedLength;
149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
152 CSK_This, CSK_Real, CSK_Imag
155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
162 /// Is this a pointer one past the end of an object?
163 bool IsOnePastTheEnd : 1;
165 /// Indicator of whether the most-derived object is an array element.
166 bool MostDerivedIsArrayElement : 1;
168 /// The length of the path to the most-derived object of which this is a
170 unsigned MostDerivedPathLength : 29;
172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
176 uint64_t MostDerivedArraySize;
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
181 typedef APValue::LValuePathEntry PathEntry;
183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
186 SubobjectDesignator() : Invalid(true) {}
188 explicit SubobjectDesignator(QualType T)
189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
201 if (V.getLValueBase()) {
202 bool IsArray = false;
203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
222 if (MostDerivedIsArrayElement &&
223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
232 return !isOnePastTheEnd();
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
241 Entry.ArrayIndex = 0;
242 Entries.push_back(Entry);
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
246 MostDerivedIsArrayElement = true;
247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
250 /// Update this designator to refer to the given base or member of this
252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
256 Entries.push_back(Entry);
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
261 MostDerivedIsArrayElement = false;
262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
275 MostDerivedIsArrayElement = true;
276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
280 /// Add N to the address of this subobject.
281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
285 Entries.back().ArrayIndex += N;
286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
310 /// Parent - The caller of this stack frame.
311 CallStackFrame *Caller;
313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
319 /// Index - The call index of this call.
322 /// This - The binding for the this pointer in this call, if any.
325 /// Arguments - Parameter bindings for this function call, indexed by
326 /// parameters' function scope indices.
329 // Note that we intentionally use std::map here so that references to
330 // values are stable.
331 typedef std::map<const void*, APValue> MapTy;
332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
343 return I == Temporaries.end() ? nullptr : &I->second;
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
354 Frame.This = NewThis;
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
360 CallStackFrame &Frame;
361 const LValue *OldThis;
364 /// A partial diagnostic which we might know in advance that we are not going
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
374 OptionalDiagnostic &operator<<(const T &v) {
380 OptionalDiagnostic &operator<<(const APSInt &I) {
382 SmallVector<char, 32> Buffer;
384 *Diag << StringRef(Buffer.data(), Buffer.size());
389 OptionalDiagnostic &operator<<(const APFloat &F) {
391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
400 SmallVector<char, 32> Buffer;
401 F.toString(Buffer, precision);
402 *Diag << StringRef(Buffer.data(), Buffer.size());
408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
416 bool isLifetimeExtended() const { return Value.getInt(); }
418 *Value.getPointer() = APValue();
422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
456 /// BottomFrame - The frame in which evaluation started. This must be
457 /// initialized after CurrentCall and CallStackDepth.
458 CallStackFrame BottomFrame;
460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
466 APValue::LValueBase EvaluatingDecl;
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473 /// notes attached to it will also be stored, otherwise they will not be.
474 bool HasActiveDiagnostic;
476 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
477 /// fold (not just why it's not strictly a constant expression)?
478 bool HasFoldFailureDiagnostic;
480 enum EvaluationMode {
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression.
483 EM_ConstantExpression,
485 /// Evaluate as a potential constant expression. Keep going if we hit a
486 /// construct that we can't evaluate yet (because we don't yet know the
487 /// value of something) but stop if we hit something that could never be
488 /// a constant expression.
489 EM_PotentialConstantExpression,
491 /// Fold the expression to a constant. Stop if we hit a side-effect that
495 /// Evaluate the expression looking for integer overflow and similar
496 /// issues. Don't worry about side-effects, and try to visit all
498 EM_EvaluateForOverflow,
500 /// Evaluate in any way we know how. Don't worry about side-effects that
501 /// can't be modeled.
502 EM_IgnoreSideEffects,
504 /// Evaluate as a constant expression. Stop if we find that the expression
505 /// is not a constant expression. Some expressions can be retried in the
506 /// optimizer if we don't constant fold them here, but in an unevaluated
507 /// context we try to fold them immediately since the optimizer never
508 /// gets a chance to look at it.
509 EM_ConstantExpressionUnevaluated,
511 /// Evaluate as a potential constant expression. Keep going if we hit a
512 /// construct that we can't evaluate yet (because we don't yet know the
513 /// value of something) but stop if we hit something that could never be
514 /// a constant expression. Some expressions can be retried in the
515 /// optimizer if we don't constant fold them here, but in an unevaluated
516 /// context we try to fold them immediately since the optimizer never
517 /// gets a chance to look at it.
518 EM_PotentialConstantExpressionUnevaluated,
520 /// Evaluate as a constant expression. Continue evaluating if we find a
521 /// MemberExpr with a base that can't be evaluated.
525 /// Are we checking whether the expression is a potential constant
527 bool checkingPotentialConstantExpression() const {
528 return EvalMode == EM_PotentialConstantExpression ||
529 EvalMode == EM_PotentialConstantExpressionUnevaluated;
532 /// Are we checking an expression for overflow?
533 // FIXME: We should check for any kind of undefined or suspicious behavior
534 // in such constructs, not just overflow.
535 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
537 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
538 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
539 CallStackDepth(0), NextCallIndex(1),
540 StepsLeft(getLangOpts().ConstexprStepLimit),
541 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
542 EvaluatingDecl((const ValueDecl *)nullptr),
543 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
544 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
546 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
547 EvaluatingDecl = Base;
548 EvaluatingDeclValue = &Value;
551 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
553 bool CheckCallLimit(SourceLocation Loc) {
554 // Don't perform any constexpr calls (other than the call we're checking)
555 // when checking a potential constant expression.
556 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
558 if (NextCallIndex == 0) {
559 // NextCallIndex has wrapped around.
560 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
563 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
565 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
566 << getLangOpts().ConstexprCallDepth;
570 CallStackFrame *getCallFrame(unsigned CallIndex) {
571 assert(CallIndex && "no call index in getCallFrame");
572 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
573 // be null in this loop.
574 CallStackFrame *Frame = CurrentCall;
575 while (Frame->Index > CallIndex)
576 Frame = Frame->Caller;
577 return (Frame->Index == CallIndex) ? Frame : nullptr;
580 bool nextStep(const Stmt *S) {
582 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
590 /// Add a diagnostic to the diagnostics list.
591 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
592 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
593 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
594 return EvalStatus.Diag->back().second;
597 /// Add notes containing a call stack to the current point of evaluation.
598 void addCallStack(unsigned Limit);
601 /// Diagnose that the evaluation cannot be folded.
602 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
603 = diag::note_invalid_subexpr_in_const_expr,
604 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
605 if (EvalStatus.Diag) {
606 // If we have a prior diagnostic, it will be noting that the expression
607 // isn't a constant expression. This diagnostic is more important,
608 // unless we require this evaluation to produce a constant expression.
610 // FIXME: We might want to show both diagnostics to the user in
611 // EM_ConstantFold mode.
612 if (!EvalStatus.Diag->empty()) {
614 case EM_ConstantFold:
615 case EM_IgnoreSideEffects:
616 case EM_EvaluateForOverflow:
617 if (!HasFoldFailureDiagnostic)
619 // We've already failed to fold something. Keep that diagnostic.
620 case EM_ConstantExpression:
621 case EM_PotentialConstantExpression:
622 case EM_ConstantExpressionUnevaluated:
623 case EM_PotentialConstantExpressionUnevaluated:
624 case EM_DesignatorFold:
625 HasActiveDiagnostic = false;
626 return OptionalDiagnostic();
630 unsigned CallStackNotes = CallStackDepth - 1;
631 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
633 CallStackNotes = std::min(CallStackNotes, Limit + 1);
634 if (checkingPotentialConstantExpression())
637 HasActiveDiagnostic = true;
638 HasFoldFailureDiagnostic = !IsCCEDiag;
639 EvalStatus.Diag->clear();
640 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
641 addDiag(Loc, DiagId);
642 if (!checkingPotentialConstantExpression())
644 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
646 HasActiveDiagnostic = false;
647 return OptionalDiagnostic();
650 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
651 = diag::note_invalid_subexpr_in_const_expr,
652 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
654 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
655 HasActiveDiagnostic = false;
656 return OptionalDiagnostic();
659 /// Diagnose that the evaluation does not produce a C++11 core constant
662 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
663 /// EM_PotentialConstantExpression mode and we produce one of these.
664 template<typename LocArg>
665 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
666 = diag::note_invalid_subexpr_in_const_expr,
667 unsigned ExtraNotes = 0) {
668 // Don't override a previous diagnostic. Don't bother collecting
669 // diagnostics if we're evaluating for overflow.
670 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
671 HasActiveDiagnostic = false;
672 return OptionalDiagnostic();
674 return Diag(Loc, DiagId, ExtraNotes, true);
677 /// Add a note to a prior diagnostic.
678 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
679 if (!HasActiveDiagnostic)
680 return OptionalDiagnostic();
681 return OptionalDiagnostic(&addDiag(Loc, DiagId));
684 /// Add a stack of notes to a prior diagnostic.
685 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
686 if (HasActiveDiagnostic) {
687 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
688 Diags.begin(), Diags.end());
692 /// Should we continue evaluation after encountering a side-effect that we
694 bool keepEvaluatingAfterSideEffect() {
696 case EM_PotentialConstantExpression:
697 case EM_PotentialConstantExpressionUnevaluated:
698 case EM_EvaluateForOverflow:
699 case EM_IgnoreSideEffects:
702 case EM_ConstantExpression:
703 case EM_ConstantExpressionUnevaluated:
704 case EM_ConstantFold:
705 case EM_DesignatorFold:
708 llvm_unreachable("Missed EvalMode case");
711 /// Note that we have had a side-effect, and determine whether we should
713 bool noteSideEffect() {
714 EvalStatus.HasSideEffects = true;
715 return keepEvaluatingAfterSideEffect();
718 /// Should we continue evaluation after encountering undefined behavior?
719 bool keepEvaluatingAfterUndefinedBehavior() {
721 case EM_EvaluateForOverflow:
722 case EM_IgnoreSideEffects:
723 case EM_ConstantFold:
724 case EM_DesignatorFold:
727 case EM_PotentialConstantExpression:
728 case EM_PotentialConstantExpressionUnevaluated:
729 case EM_ConstantExpression:
730 case EM_ConstantExpressionUnevaluated:
733 llvm_unreachable("Missed EvalMode case");
736 /// Note that we hit something that was technically undefined behavior, but
737 /// that we can evaluate past it (such as signed overflow or floating-point
738 /// division by zero.)
739 bool noteUndefinedBehavior() {
740 EvalStatus.HasUndefinedBehavior = true;
741 return keepEvaluatingAfterUndefinedBehavior();
744 /// Should we continue evaluation as much as possible after encountering a
745 /// construct which can't be reduced to a value?
746 bool keepEvaluatingAfterFailure() {
751 case EM_PotentialConstantExpression:
752 case EM_PotentialConstantExpressionUnevaluated:
753 case EM_EvaluateForOverflow:
756 case EM_ConstantExpression:
757 case EM_ConstantExpressionUnevaluated:
758 case EM_ConstantFold:
759 case EM_IgnoreSideEffects:
760 case EM_DesignatorFold:
763 llvm_unreachable("Missed EvalMode case");
766 bool allowInvalidBaseExpr() const {
767 return EvalMode == EM_DesignatorFold;
771 /// Object used to treat all foldable expressions as constant expressions.
772 struct FoldConstant {
775 bool HadNoPriorDiags;
776 EvalInfo::EvaluationMode OldMode;
778 explicit FoldConstant(EvalInfo &Info, bool Enabled)
781 HadNoPriorDiags(Info.EvalStatus.Diag &&
782 Info.EvalStatus.Diag->empty() &&
783 !Info.EvalStatus.HasSideEffects),
784 OldMode(Info.EvalMode) {
786 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
787 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
788 Info.EvalMode = EvalInfo::EM_ConstantFold;
790 void keepDiagnostics() { Enabled = false; }
792 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
793 !Info.EvalStatus.HasSideEffects)
794 Info.EvalStatus.Diag->clear();
795 Info.EvalMode = OldMode;
799 /// RAII object used to treat the current evaluation as the correct pointer
800 /// offset fold for the current EvalMode
801 struct FoldOffsetRAII {
803 EvalInfo::EvaluationMode OldMode;
804 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
805 : Info(Info), OldMode(Info.EvalMode) {
806 if (!Info.checkingPotentialConstantExpression())
807 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
808 : EvalInfo::EM_ConstantFold;
811 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
814 /// RAII object used to suppress diagnostics and side-effects from a
815 /// speculative evaluation.
816 class SpeculativeEvaluationRAII {
818 Expr::EvalStatus Old;
821 SpeculativeEvaluationRAII(EvalInfo &Info,
822 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
823 : Info(Info), Old(Info.EvalStatus) {
824 Info.EvalStatus.Diag = NewDiag;
825 // If we're speculatively evaluating, we may have skipped over some
826 // evaluations and missed out a side effect.
827 Info.EvalStatus.HasSideEffects = true;
829 ~SpeculativeEvaluationRAII() {
830 Info.EvalStatus = Old;
834 /// RAII object wrapping a full-expression or block scope, and handling
835 /// the ending of the lifetime of temporaries created within it.
836 template<bool IsFullExpression>
839 unsigned OldStackSize;
841 ScopeRAII(EvalInfo &Info)
842 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
844 // Body moved to a static method to encourage the compiler to inline away
845 // instances of this class.
846 cleanup(Info, OldStackSize);
849 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
850 unsigned NewEnd = OldStackSize;
851 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
853 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
854 // Full-expression cleanup of a lifetime-extended temporary: nothing
855 // to do, just move this cleanup to the right place in the stack.
856 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
859 // End the lifetime of the object.
860 Info.CleanupStack[I].endLifetime();
863 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
864 Info.CleanupStack.end());
867 typedef ScopeRAII<false> BlockScopeRAII;
868 typedef ScopeRAII<true> FullExpressionRAII;
871 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
872 CheckSubobjectKind CSK) {
875 if (isOnePastTheEnd()) {
876 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
884 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
885 const Expr *E, uint64_t N) {
886 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
887 Info.CCEDiag(E, diag::note_constexpr_array_index)
888 << static_cast<int>(N) << /*array*/ 0
889 << static_cast<unsigned>(MostDerivedArraySize);
891 Info.CCEDiag(E, diag::note_constexpr_array_index)
892 << static_cast<int>(N) << /*non-array*/ 1;
896 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
897 const FunctionDecl *Callee, const LValue *This,
899 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
900 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
901 Info.CurrentCall = this;
902 ++Info.CallStackDepth;
905 CallStackFrame::~CallStackFrame() {
906 assert(Info.CurrentCall == this && "calls retired out of order");
907 --Info.CallStackDepth;
908 Info.CurrentCall = Caller;
911 APValue &CallStackFrame::createTemporary(const void *Key,
912 bool IsLifetimeExtended) {
913 APValue &Result = Temporaries[Key];
914 assert(Result.isUninit() && "temporary created multiple times");
915 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
919 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
921 void EvalInfo::addCallStack(unsigned Limit) {
922 // Determine which calls to skip, if any.
923 unsigned ActiveCalls = CallStackDepth - 1;
924 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
925 if (Limit && Limit < ActiveCalls) {
926 SkipStart = Limit / 2 + Limit % 2;
927 SkipEnd = ActiveCalls - Limit / 2;
930 // Walk the call stack and add the diagnostics.
931 unsigned CallIdx = 0;
932 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
933 Frame = Frame->Caller, ++CallIdx) {
935 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
936 if (CallIdx == SkipStart) {
937 // Note that we're skipping calls.
938 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
939 << unsigned(ActiveCalls - Limit);
944 SmallVector<char, 128> Buffer;
945 llvm::raw_svector_ostream Out(Buffer);
946 describeCall(Frame, Out);
947 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
952 struct ComplexValue {
957 APSInt IntReal, IntImag;
958 APFloat FloatReal, FloatImag;
960 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
962 void makeComplexFloat() { IsInt = false; }
963 bool isComplexFloat() const { return !IsInt; }
964 APFloat &getComplexFloatReal() { return FloatReal; }
965 APFloat &getComplexFloatImag() { return FloatImag; }
967 void makeComplexInt() { IsInt = true; }
968 bool isComplexInt() const { return IsInt; }
969 APSInt &getComplexIntReal() { return IntReal; }
970 APSInt &getComplexIntImag() { return IntImag; }
972 void moveInto(APValue &v) const {
973 if (isComplexFloat())
974 v = APValue(FloatReal, FloatImag);
976 v = APValue(IntReal, IntImag);
978 void setFrom(const APValue &v) {
979 assert(v.isComplexFloat() || v.isComplexInt());
980 if (v.isComplexFloat()) {
982 FloatReal = v.getComplexFloatReal();
983 FloatImag = v.getComplexFloatImag();
986 IntReal = v.getComplexIntReal();
987 IntImag = v.getComplexIntImag();
993 APValue::LValueBase Base;
995 bool InvalidBase : 1;
996 unsigned CallIndex : 31;
997 SubobjectDesignator Designator;
999 const APValue::LValueBase getLValueBase() const { return Base; }
1000 CharUnits &getLValueOffset() { return Offset; }
1001 const CharUnits &getLValueOffset() const { return Offset; }
1002 unsigned getLValueCallIndex() const { return CallIndex; }
1003 SubobjectDesignator &getLValueDesignator() { return Designator; }
1004 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1006 void moveInto(APValue &V) const {
1007 if (Designator.Invalid)
1008 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1010 V = APValue(Base, Offset, Designator.Entries,
1011 Designator.IsOnePastTheEnd, CallIndex);
1013 void setFrom(ASTContext &Ctx, const APValue &V) {
1014 assert(V.isLValue());
1015 Base = V.getLValueBase();
1016 Offset = V.getLValueOffset();
1017 InvalidBase = false;
1018 CallIndex = V.getLValueCallIndex();
1019 Designator = SubobjectDesignator(Ctx, V);
1022 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1024 Offset = CharUnits::Zero();
1025 InvalidBase = BInvalid;
1027 Designator = SubobjectDesignator(getType(B));
1030 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1034 // Check that this LValue is not based on a null pointer. If it is, produce
1035 // a diagnostic and mark the designator as invalid.
1036 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1037 CheckSubobjectKind CSK) {
1038 if (Designator.Invalid)
1041 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1043 Designator.setInvalid();
1049 // Check this LValue refers to an object. If not, set the designator to be
1050 // invalid and emit a diagnostic.
1051 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1052 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1053 Designator.checkSubobject(Info, E, CSK);
1056 void addDecl(EvalInfo &Info, const Expr *E,
1057 const Decl *D, bool Virtual = false) {
1058 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1059 Designator.addDeclUnchecked(D, Virtual);
1061 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1062 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1063 Designator.addArrayUnchecked(CAT);
1065 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1066 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1067 Designator.addComplexUnchecked(EltTy, Imag);
1069 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
1070 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
1071 Designator.adjustIndex(Info, E, N);
1077 explicit MemberPtr(const ValueDecl *Decl) :
1078 DeclAndIsDerivedMember(Decl, false), Path() {}
1080 /// The member or (direct or indirect) field referred to by this member
1081 /// pointer, or 0 if this is a null member pointer.
1082 const ValueDecl *getDecl() const {
1083 return DeclAndIsDerivedMember.getPointer();
1085 /// Is this actually a member of some type derived from the relevant class?
1086 bool isDerivedMember() const {
1087 return DeclAndIsDerivedMember.getInt();
1089 /// Get the class which the declaration actually lives in.
1090 const CXXRecordDecl *getContainingRecord() const {
1091 return cast<CXXRecordDecl>(
1092 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1095 void moveInto(APValue &V) const {
1096 V = APValue(getDecl(), isDerivedMember(), Path);
1098 void setFrom(const APValue &V) {
1099 assert(V.isMemberPointer());
1100 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1101 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1103 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1104 Path.insert(Path.end(), P.begin(), P.end());
1107 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1108 /// whether the member is a member of some class derived from the class type
1109 /// of the member pointer.
1110 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1111 /// Path - The path of base/derived classes from the member declaration's
1112 /// class (exclusive) to the class type of the member pointer (inclusive).
1113 SmallVector<const CXXRecordDecl*, 4> Path;
1115 /// Perform a cast towards the class of the Decl (either up or down the
1117 bool castBack(const CXXRecordDecl *Class) {
1118 assert(!Path.empty());
1119 const CXXRecordDecl *Expected;
1120 if (Path.size() >= 2)
1121 Expected = Path[Path.size() - 2];
1123 Expected = getContainingRecord();
1124 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1125 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1126 // if B does not contain the original member and is not a base or
1127 // derived class of the class containing the original member, the result
1128 // of the cast is undefined.
1129 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1130 // (D::*). We consider that to be a language defect.
1136 /// Perform a base-to-derived member pointer cast.
1137 bool castToDerived(const CXXRecordDecl *Derived) {
1140 if (!isDerivedMember()) {
1141 Path.push_back(Derived);
1144 if (!castBack(Derived))
1147 DeclAndIsDerivedMember.setInt(false);
1150 /// Perform a derived-to-base member pointer cast.
1151 bool castToBase(const CXXRecordDecl *Base) {
1155 DeclAndIsDerivedMember.setInt(true);
1156 if (isDerivedMember()) {
1157 Path.push_back(Base);
1160 return castBack(Base);
1164 /// Compare two member pointers, which are assumed to be of the same type.
1165 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1166 if (!LHS.getDecl() || !RHS.getDecl())
1167 return !LHS.getDecl() && !RHS.getDecl();
1168 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1170 return LHS.Path == RHS.Path;
1174 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1175 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1176 const LValue &This, const Expr *E,
1177 bool AllowNonLiteralTypes = false);
1178 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1179 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1180 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1182 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1183 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1184 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1186 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1187 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1188 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1189 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1191 //===----------------------------------------------------------------------===//
1193 //===----------------------------------------------------------------------===//
1195 /// Produce a string describing the given constexpr call.
1196 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1197 unsigned ArgIndex = 0;
1198 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1199 !isa<CXXConstructorDecl>(Frame->Callee) &&
1200 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1203 Out << *Frame->Callee << '(';
1205 if (Frame->This && IsMemberCall) {
1207 Frame->This->moveInto(Val);
1208 Val.printPretty(Out, Frame->Info.Ctx,
1209 Frame->This->Designator.MostDerivedType);
1210 // FIXME: Add parens around Val if needed.
1211 Out << "->" << *Frame->Callee << '(';
1212 IsMemberCall = false;
1215 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1216 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1217 if (ArgIndex > (unsigned)IsMemberCall)
1220 const ParmVarDecl *Param = *I;
1221 const APValue &Arg = Frame->Arguments[ArgIndex];
1222 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1224 if (ArgIndex == 0 && IsMemberCall)
1225 Out << "->" << *Frame->Callee << '(';
1231 /// Evaluate an expression to see if it had side-effects, and discard its
1233 /// \return \c true if the caller should keep evaluating.
1234 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1236 if (!Evaluate(Scratch, Info, E))
1237 // We don't need the value, but we might have skipped a side effect here.
1238 return Info.noteSideEffect();
1242 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1243 /// return its existing value.
1244 static int64_t getExtValue(const APSInt &Value) {
1245 return Value.isSigned() ? Value.getSExtValue()
1246 : static_cast<int64_t>(Value.getZExtValue());
1249 /// Should this call expression be treated as a string literal?
1250 static bool IsStringLiteralCall(const CallExpr *E) {
1251 unsigned Builtin = E->getBuiltinCallee();
1252 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1253 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1256 static bool IsGlobalLValue(APValue::LValueBase B) {
1257 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1258 // constant expression of pointer type that evaluates to...
1260 // ... a null pointer value, or a prvalue core constant expression of type
1262 if (!B) return true;
1264 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1265 // ... the address of an object with static storage duration,
1266 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1267 return VD->hasGlobalStorage();
1268 // ... the address of a function,
1269 return isa<FunctionDecl>(D);
1272 const Expr *E = B.get<const Expr*>();
1273 switch (E->getStmtClass()) {
1276 case Expr::CompoundLiteralExprClass: {
1277 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1278 return CLE->isFileScope() && CLE->isLValue();
1280 case Expr::MaterializeTemporaryExprClass:
1281 // A materialized temporary might have been lifetime-extended to static
1282 // storage duration.
1283 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1284 // A string literal has static storage duration.
1285 case Expr::StringLiteralClass:
1286 case Expr::PredefinedExprClass:
1287 case Expr::ObjCStringLiteralClass:
1288 case Expr::ObjCEncodeExprClass:
1289 case Expr::CXXTypeidExprClass:
1290 case Expr::CXXUuidofExprClass:
1292 case Expr::CallExprClass:
1293 return IsStringLiteralCall(cast<CallExpr>(E));
1294 // For GCC compatibility, &&label has static storage duration.
1295 case Expr::AddrLabelExprClass:
1297 // A Block literal expression may be used as the initialization value for
1298 // Block variables at global or local static scope.
1299 case Expr::BlockExprClass:
1300 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1301 case Expr::ImplicitValueInitExprClass:
1303 // We can never form an lvalue with an implicit value initialization as its
1304 // base through expression evaluation, so these only appear in one case: the
1305 // implicit variable declaration we invent when checking whether a constexpr
1306 // constructor can produce a constant expression. We must assume that such
1307 // an expression might be a global lvalue.
1312 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1313 assert(Base && "no location for a null lvalue");
1314 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1316 Info.Note(VD->getLocation(), diag::note_declared_at);
1318 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1319 diag::note_constexpr_temporary_here);
1322 /// Check that this reference or pointer core constant expression is a valid
1323 /// value for an address or reference constant expression. Return true if we
1324 /// can fold this expression, whether or not it's a constant expression.
1325 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1326 QualType Type, const LValue &LVal) {
1327 bool IsReferenceType = Type->isReferenceType();
1329 APValue::LValueBase Base = LVal.getLValueBase();
1330 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1332 // Check that the object is a global. Note that the fake 'this' object we
1333 // manufacture when checking potential constant expressions is conservatively
1334 // assumed to be global here.
1335 if (!IsGlobalLValue(Base)) {
1336 if (Info.getLangOpts().CPlusPlus11) {
1337 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1338 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1339 << IsReferenceType << !Designator.Entries.empty()
1341 NoteLValueLocation(Info, Base);
1345 // Don't allow references to temporaries to escape.
1348 assert((Info.checkingPotentialConstantExpression() ||
1349 LVal.getLValueCallIndex() == 0) &&
1350 "have call index for global lvalue");
1352 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1353 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1354 // Check if this is a thread-local variable.
1355 if (Var->getTLSKind())
1358 // A dllimport variable never acts like a constant.
1359 if (Var->hasAttr<DLLImportAttr>())
1362 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1363 // __declspec(dllimport) must be handled very carefully:
1364 // We must never initialize an expression with the thunk in C++.
1365 // Doing otherwise would allow the same id-expression to yield
1366 // different addresses for the same function in different translation
1367 // units. However, this means that we must dynamically initialize the
1368 // expression with the contents of the import address table at runtime.
1370 // The C language has no notion of ODR; furthermore, it has no notion of
1371 // dynamic initialization. This means that we are permitted to
1372 // perform initialization with the address of the thunk.
1373 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1378 // Allow address constant expressions to be past-the-end pointers. This is
1379 // an extension: the standard requires them to point to an object.
1380 if (!IsReferenceType)
1383 // A reference constant expression must refer to an object.
1385 // FIXME: diagnostic
1390 // Does this refer one past the end of some object?
1391 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1392 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1393 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1394 << !Designator.Entries.empty() << !!VD << VD;
1395 NoteLValueLocation(Info, Base);
1401 /// Check that this core constant expression is of literal type, and if not,
1402 /// produce an appropriate diagnostic.
1403 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1404 const LValue *This = nullptr) {
1405 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1408 // C++1y: A constant initializer for an object o [...] may also invoke
1409 // constexpr constructors for o and its subobjects even if those objects
1410 // are of non-literal class types.
1411 if (Info.getLangOpts().CPlusPlus14 && This &&
1412 Info.EvaluatingDecl == This->getLValueBase())
1415 // Prvalue constant expressions must be of literal types.
1416 if (Info.getLangOpts().CPlusPlus11)
1417 Info.Diag(E, diag::note_constexpr_nonliteral)
1420 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1424 /// Check that this core constant expression value is a valid value for a
1425 /// constant expression. If not, report an appropriate diagnostic. Does not
1426 /// check that the expression is of literal type.
1427 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1428 QualType Type, const APValue &Value) {
1429 if (Value.isUninit()) {
1430 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1435 // We allow _Atomic(T) to be initialized from anything that T can be
1436 // initialized from.
1437 if (const AtomicType *AT = Type->getAs<AtomicType>())
1438 Type = AT->getValueType();
1440 // Core issue 1454: For a literal constant expression of array or class type,
1441 // each subobject of its value shall have been initialized by a constant
1443 if (Value.isArray()) {
1444 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1445 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1446 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1447 Value.getArrayInitializedElt(I)))
1450 if (!Value.hasArrayFiller())
1452 return CheckConstantExpression(Info, DiagLoc, EltTy,
1453 Value.getArrayFiller());
1455 if (Value.isUnion() && Value.getUnionField()) {
1456 return CheckConstantExpression(Info, DiagLoc,
1457 Value.getUnionField()->getType(),
1458 Value.getUnionValue());
1460 if (Value.isStruct()) {
1461 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1462 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1463 unsigned BaseIndex = 0;
1464 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1465 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1466 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1467 Value.getStructBase(BaseIndex)))
1471 for (const auto *I : RD->fields()) {
1472 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1473 Value.getStructField(I->getFieldIndex())))
1478 if (Value.isLValue()) {
1480 LVal.setFrom(Info.Ctx, Value);
1481 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1484 // Everything else is fine.
1488 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1489 return LVal.Base.dyn_cast<const ValueDecl*>();
1492 static bool IsLiteralLValue(const LValue &Value) {
1493 if (Value.CallIndex)
1495 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1496 return E && !isa<MaterializeTemporaryExpr>(E);
1499 static bool IsWeakLValue(const LValue &Value) {
1500 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1501 return Decl && Decl->isWeak();
1504 static bool isZeroSized(const LValue &Value) {
1505 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1506 if (Decl && isa<VarDecl>(Decl)) {
1507 QualType Ty = Decl->getType();
1508 if (Ty->isArrayType())
1509 return Ty->isIncompleteType() ||
1510 Decl->getASTContext().getTypeSize(Ty) == 0;
1515 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1516 // A null base expression indicates a null pointer. These are always
1517 // evaluatable, and they are false unless the offset is zero.
1518 if (!Value.getLValueBase()) {
1519 Result = !Value.getLValueOffset().isZero();
1523 // We have a non-null base. These are generally known to be true, but if it's
1524 // a weak declaration it can be null at runtime.
1526 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1527 return !Decl || !Decl->isWeak();
1530 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1531 switch (Val.getKind()) {
1532 case APValue::Uninitialized:
1535 Result = Val.getInt().getBoolValue();
1537 case APValue::Float:
1538 Result = !Val.getFloat().isZero();
1540 case APValue::ComplexInt:
1541 Result = Val.getComplexIntReal().getBoolValue() ||
1542 Val.getComplexIntImag().getBoolValue();
1544 case APValue::ComplexFloat:
1545 Result = !Val.getComplexFloatReal().isZero() ||
1546 !Val.getComplexFloatImag().isZero();
1548 case APValue::LValue:
1549 return EvalPointerValueAsBool(Val, Result);
1550 case APValue::MemberPointer:
1551 Result = Val.getMemberPointerDecl();
1553 case APValue::Vector:
1554 case APValue::Array:
1555 case APValue::Struct:
1556 case APValue::Union:
1557 case APValue::AddrLabelDiff:
1561 llvm_unreachable("unknown APValue kind");
1564 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1566 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1568 if (!Evaluate(Val, Info, E))
1570 return HandleConversionToBool(Val, Result);
1573 template<typename T>
1574 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1575 const T &SrcValue, QualType DestType) {
1576 Info.CCEDiag(E, diag::note_constexpr_overflow)
1577 << SrcValue << DestType;
1578 return Info.noteUndefinedBehavior();
1581 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1582 QualType SrcType, const APFloat &Value,
1583 QualType DestType, APSInt &Result) {
1584 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1585 // Determine whether we are converting to unsigned or signed.
1586 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1588 Result = APSInt(DestWidth, !DestSigned);
1590 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1591 & APFloat::opInvalidOp)
1592 return HandleOverflow(Info, E, Value, DestType);
1596 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1597 QualType SrcType, QualType DestType,
1599 APFloat Value = Result;
1601 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1602 APFloat::rmNearestTiesToEven, &ignored)
1603 & APFloat::opOverflow)
1604 return HandleOverflow(Info, E, Value, DestType);
1608 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1609 QualType DestType, QualType SrcType,
1610 const APSInt &Value) {
1611 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1612 APSInt Result = Value;
1613 // Figure out if this is a truncate, extend or noop cast.
1614 // If the input is signed, do a sign extend, noop, or truncate.
1615 Result = Result.extOrTrunc(DestWidth);
1616 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1620 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1621 QualType SrcType, const APSInt &Value,
1622 QualType DestType, APFloat &Result) {
1623 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1624 if (Result.convertFromAPInt(Value, Value.isSigned(),
1625 APFloat::rmNearestTiesToEven)
1626 & APFloat::opOverflow)
1627 return HandleOverflow(Info, E, Value, DestType);
1631 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1632 APValue &Value, const FieldDecl *FD) {
1633 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1635 if (!Value.isInt()) {
1636 // Trying to store a pointer-cast-to-integer into a bitfield.
1637 // FIXME: In this case, we should provide the diagnostic for casting
1638 // a pointer to an integer.
1639 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1644 APSInt &Int = Value.getInt();
1645 unsigned OldBitWidth = Int.getBitWidth();
1646 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1647 if (NewBitWidth < OldBitWidth)
1648 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1652 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1655 if (!Evaluate(SVal, Info, E))
1658 Res = SVal.getInt();
1661 if (SVal.isFloat()) {
1662 Res = SVal.getFloat().bitcastToAPInt();
1665 if (SVal.isVector()) {
1666 QualType VecTy = E->getType();
1667 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1668 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1669 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1670 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1671 Res = llvm::APInt::getNullValue(VecSize);
1672 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1673 APValue &Elt = SVal.getVectorElt(i);
1674 llvm::APInt EltAsInt;
1676 EltAsInt = Elt.getInt();
1677 } else if (Elt.isFloat()) {
1678 EltAsInt = Elt.getFloat().bitcastToAPInt();
1680 // Don't try to handle vectors of anything other than int or float
1681 // (not sure if it's possible to hit this case).
1682 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1685 unsigned BaseEltSize = EltAsInt.getBitWidth();
1687 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1689 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1693 // Give up if the input isn't an int, float, or vector. For example, we
1694 // reject "(v4i16)(intptr_t)&a".
1695 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1699 /// Perform the given integer operation, which is known to need at most BitWidth
1700 /// bits, and check for overflow in the original type (if that type was not an
1702 template<typename Operation>
1703 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1704 const APSInt &LHS, const APSInt &RHS,
1705 unsigned BitWidth, Operation Op,
1707 if (LHS.isUnsigned()) {
1708 Result = Op(LHS, RHS);
1712 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1713 Result = Value.trunc(LHS.getBitWidth());
1714 if (Result.extend(BitWidth) != Value) {
1715 if (Info.checkingForOverflow())
1716 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1717 diag::warn_integer_constant_overflow)
1718 << Result.toString(10) << E->getType();
1720 return HandleOverflow(Info, E, Value, E->getType());
1725 /// Perform the given binary integer operation.
1726 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1727 BinaryOperatorKind Opcode, APSInt RHS,
1734 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1735 std::multiplies<APSInt>(), Result);
1737 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1738 std::plus<APSInt>(), Result);
1740 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1741 std::minus<APSInt>(), Result);
1742 case BO_And: Result = LHS & RHS; return true;
1743 case BO_Xor: Result = LHS ^ RHS; return true;
1744 case BO_Or: Result = LHS | RHS; return true;
1748 Info.Diag(E, diag::note_expr_divide_by_zero);
1751 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1752 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1753 // this operation and gives the two's complement result.
1754 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1755 LHS.isSigned() && LHS.isMinSignedValue())
1756 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1760 if (Info.getLangOpts().OpenCL)
1761 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1762 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1763 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1765 else if (RHS.isSigned() && RHS.isNegative()) {
1766 // During constant-folding, a negative shift is an opposite shift. Such
1767 // a shift is not a constant expression.
1768 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1773 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1774 // the shifted type.
1775 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1777 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1778 << RHS << E->getType() << LHS.getBitWidth();
1779 } else if (LHS.isSigned()) {
1780 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1781 // operand, and must not overflow the corresponding unsigned type.
1782 if (LHS.isNegative())
1783 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1784 else if (LHS.countLeadingZeros() < SA)
1785 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1791 if (Info.getLangOpts().OpenCL)
1792 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1793 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1794 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1796 else if (RHS.isSigned() && RHS.isNegative()) {
1797 // During constant-folding, a negative shift is an opposite shift. Such a
1798 // shift is not a constant expression.
1799 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1804 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1806 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1808 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1809 << RHS << E->getType() << LHS.getBitWidth();
1814 case BO_LT: Result = LHS < RHS; return true;
1815 case BO_GT: Result = LHS > RHS; return true;
1816 case BO_LE: Result = LHS <= RHS; return true;
1817 case BO_GE: Result = LHS >= RHS; return true;
1818 case BO_EQ: Result = LHS == RHS; return true;
1819 case BO_NE: Result = LHS != RHS; return true;
1823 /// Perform the given binary floating-point operation, in-place, on LHS.
1824 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1825 APFloat &LHS, BinaryOperatorKind Opcode,
1826 const APFloat &RHS) {
1832 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1835 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1838 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1841 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1845 if (LHS.isInfinity() || LHS.isNaN()) {
1846 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1847 return Info.noteUndefinedBehavior();
1852 /// Cast an lvalue referring to a base subobject to a derived class, by
1853 /// truncating the lvalue's path to the given length.
1854 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1855 const RecordDecl *TruncatedType,
1856 unsigned TruncatedElements) {
1857 SubobjectDesignator &D = Result.Designator;
1859 // Check we actually point to a derived class object.
1860 if (TruncatedElements == D.Entries.size())
1862 assert(TruncatedElements >= D.MostDerivedPathLength &&
1863 "not casting to a derived class");
1864 if (!Result.checkSubobject(Info, E, CSK_Derived))
1867 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1868 const RecordDecl *RD = TruncatedType;
1869 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1870 if (RD->isInvalidDecl()) return false;
1871 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1872 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1873 if (isVirtualBaseClass(D.Entries[I]))
1874 Result.Offset -= Layout.getVBaseClassOffset(Base);
1876 Result.Offset -= Layout.getBaseClassOffset(Base);
1879 D.Entries.resize(TruncatedElements);
1883 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1884 const CXXRecordDecl *Derived,
1885 const CXXRecordDecl *Base,
1886 const ASTRecordLayout *RL = nullptr) {
1888 if (Derived->isInvalidDecl()) return false;
1889 RL = &Info.Ctx.getASTRecordLayout(Derived);
1892 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1893 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1897 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1898 const CXXRecordDecl *DerivedDecl,
1899 const CXXBaseSpecifier *Base) {
1900 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1902 if (!Base->isVirtual())
1903 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1905 SubobjectDesignator &D = Obj.Designator;
1909 // Extract most-derived object and corresponding type.
1910 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1911 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1914 // Find the virtual base class.
1915 if (DerivedDecl->isInvalidDecl()) return false;
1916 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1917 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1918 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1922 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1923 QualType Type, LValue &Result) {
1924 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1925 PathE = E->path_end();
1926 PathI != PathE; ++PathI) {
1927 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1930 Type = (*PathI)->getType();
1935 /// Update LVal to refer to the given field, which must be a member of the type
1936 /// currently described by LVal.
1937 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1938 const FieldDecl *FD,
1939 const ASTRecordLayout *RL = nullptr) {
1941 if (FD->getParent()->isInvalidDecl()) return false;
1942 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1945 unsigned I = FD->getFieldIndex();
1946 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1947 LVal.addDecl(Info, E, FD);
1951 /// Update LVal to refer to the given indirect field.
1952 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1954 const IndirectFieldDecl *IFD) {
1955 for (const auto *C : IFD->chain())
1956 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
1961 /// Get the size of the given type in char units.
1962 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1963 QualType Type, CharUnits &Size) {
1964 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1966 if (Type->isVoidType() || Type->isFunctionType()) {
1967 Size = CharUnits::One();
1971 if (!Type->isConstantSizeType()) {
1972 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1973 // FIXME: Better diagnostic.
1978 Size = Info.Ctx.getTypeSizeInChars(Type);
1982 /// Update a pointer value to model pointer arithmetic.
1983 /// \param Info - Information about the ongoing evaluation.
1984 /// \param E - The expression being evaluated, for diagnostic purposes.
1985 /// \param LVal - The pointer value to be updated.
1986 /// \param EltTy - The pointee type represented by LVal.
1987 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1988 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1989 LValue &LVal, QualType EltTy,
1990 int64_t Adjustment) {
1991 CharUnits SizeOfPointee;
1992 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1995 // Compute the new offset in the appropriate width.
1996 LVal.Offset += Adjustment * SizeOfPointee;
1997 LVal.adjustIndex(Info, E, Adjustment);
2001 /// Update an lvalue to refer to a component of a complex number.
2002 /// \param Info - Information about the ongoing evaluation.
2003 /// \param LVal - The lvalue to be updated.
2004 /// \param EltTy - The complex number's component type.
2005 /// \param Imag - False for the real component, true for the imaginary.
2006 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2007 LValue &LVal, QualType EltTy,
2010 CharUnits SizeOfComponent;
2011 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2013 LVal.Offset += SizeOfComponent;
2015 LVal.addComplex(Info, E, EltTy, Imag);
2019 /// Try to evaluate the initializer for a variable declaration.
2021 /// \param Info Information about the ongoing evaluation.
2022 /// \param E An expression to be used when printing diagnostics.
2023 /// \param VD The variable whose initializer should be obtained.
2024 /// \param Frame The frame in which the variable was created. Must be null
2025 /// if this variable is not local to the evaluation.
2026 /// \param Result Filled in with a pointer to the value of the variable.
2027 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2028 const VarDecl *VD, CallStackFrame *Frame,
2030 // If this is a parameter to an active constexpr function call, perform
2031 // argument substitution.
2032 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2033 // Assume arguments of a potential constant expression are unknown
2034 // constant expressions.
2035 if (Info.checkingPotentialConstantExpression())
2037 if (!Frame || !Frame->Arguments) {
2038 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2041 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2045 // If this is a local variable, dig out its value.
2047 Result = Frame->getTemporary(VD);
2048 assert(Result && "missing value for local variable");
2052 // Dig out the initializer, and use the declaration which it's attached to.
2053 const Expr *Init = VD->getAnyInitializer(VD);
2054 if (!Init || Init->isValueDependent()) {
2055 // If we're checking a potential constant expression, the variable could be
2056 // initialized later.
2057 if (!Info.checkingPotentialConstantExpression())
2058 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2062 // If we're currently evaluating the initializer of this declaration, use that
2064 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2065 Result = Info.EvaluatingDeclValue;
2069 // Never evaluate the initializer of a weak variable. We can't be sure that
2070 // this is the definition which will be used.
2072 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2076 // Check that we can fold the initializer. In C++, we will have already done
2077 // this in the cases where it matters for conformance.
2078 SmallVector<PartialDiagnosticAt, 8> Notes;
2079 if (!VD->evaluateValue(Notes)) {
2080 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
2081 Notes.size() + 1) << VD;
2082 Info.Note(VD->getLocation(), diag::note_declared_at);
2083 Info.addNotes(Notes);
2085 } else if (!VD->checkInitIsICE()) {
2086 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2087 Notes.size() + 1) << VD;
2088 Info.Note(VD->getLocation(), diag::note_declared_at);
2089 Info.addNotes(Notes);
2092 Result = VD->getEvaluatedValue();
2096 static bool IsConstNonVolatile(QualType T) {
2097 Qualifiers Quals = T.getQualifiers();
2098 return Quals.hasConst() && !Quals.hasVolatile();
2101 /// Get the base index of the given base class within an APValue representing
2102 /// the given derived class.
2103 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2104 const CXXRecordDecl *Base) {
2105 Base = Base->getCanonicalDecl();
2107 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2108 E = Derived->bases_end(); I != E; ++I, ++Index) {
2109 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2113 llvm_unreachable("base class missing from derived class's bases list");
2116 /// Extract the value of a character from a string literal.
2117 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2119 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2120 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2121 Lit = PE->getFunctionName();
2122 const StringLiteral *S = cast<StringLiteral>(Lit);
2123 const ConstantArrayType *CAT =
2124 Info.Ctx.getAsConstantArrayType(S->getType());
2125 assert(CAT && "string literal isn't an array");
2126 QualType CharType = CAT->getElementType();
2127 assert(CharType->isIntegerType() && "unexpected character type");
2129 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2130 CharType->isUnsignedIntegerType());
2131 if (Index < S->getLength())
2132 Value = S->getCodeUnit(Index);
2136 // Expand a string literal into an array of characters.
2137 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2139 const StringLiteral *S = cast<StringLiteral>(Lit);
2140 const ConstantArrayType *CAT =
2141 Info.Ctx.getAsConstantArrayType(S->getType());
2142 assert(CAT && "string literal isn't an array");
2143 QualType CharType = CAT->getElementType();
2144 assert(CharType->isIntegerType() && "unexpected character type");
2146 unsigned Elts = CAT->getSize().getZExtValue();
2147 Result = APValue(APValue::UninitArray(),
2148 std::min(S->getLength(), Elts), Elts);
2149 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2150 CharType->isUnsignedIntegerType());
2151 if (Result.hasArrayFiller())
2152 Result.getArrayFiller() = APValue(Value);
2153 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2154 Value = S->getCodeUnit(I);
2155 Result.getArrayInitializedElt(I) = APValue(Value);
2159 // Expand an array so that it has more than Index filled elements.
2160 static void expandArray(APValue &Array, unsigned Index) {
2161 unsigned Size = Array.getArraySize();
2162 assert(Index < Size);
2164 // Always at least double the number of elements for which we store a value.
2165 unsigned OldElts = Array.getArrayInitializedElts();
2166 unsigned NewElts = std::max(Index+1, OldElts * 2);
2167 NewElts = std::min(Size, std::max(NewElts, 8u));
2169 // Copy the data across.
2170 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2171 for (unsigned I = 0; I != OldElts; ++I)
2172 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2173 for (unsigned I = OldElts; I != NewElts; ++I)
2174 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2175 if (NewValue.hasArrayFiller())
2176 NewValue.getArrayFiller() = Array.getArrayFiller();
2177 Array.swap(NewValue);
2180 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2181 /// conversion. If it's of class type, we may assume that the copy operation
2182 /// is trivial. Note that this is never true for a union type with fields
2183 /// (because the copy always "reads" the active member) and always true for
2184 /// a non-class type.
2185 static bool isReadByLvalueToRvalueConversion(QualType T) {
2186 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2187 if (!RD || (RD->isUnion() && !RD->field_empty()))
2192 for (auto *Field : RD->fields())
2193 if (isReadByLvalueToRvalueConversion(Field->getType()))
2196 for (auto &BaseSpec : RD->bases())
2197 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2203 /// Diagnose an attempt to read from any unreadable field within the specified
2204 /// type, which might be a class type.
2205 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2207 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2211 if (!RD->hasMutableFields())
2214 for (auto *Field : RD->fields()) {
2215 // If we're actually going to read this field in some way, then it can't
2216 // be mutable. If we're in a union, then assigning to a mutable field
2217 // (even an empty one) can change the active member, so that's not OK.
2218 // FIXME: Add core issue number for the union case.
2219 if (Field->isMutable() &&
2220 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2221 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2222 Info.Note(Field->getLocation(), diag::note_declared_at);
2226 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2230 for (auto &BaseSpec : RD->bases())
2231 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2234 // All mutable fields were empty, and thus not actually read.
2238 /// Kinds of access we can perform on an object, for diagnostics.
2247 /// A handle to a complete object (an object that is not a subobject of
2248 /// another object).
2249 struct CompleteObject {
2250 /// The value of the complete object.
2252 /// The type of the complete object.
2255 CompleteObject() : Value(nullptr) {}
2256 CompleteObject(APValue *Value, QualType Type)
2257 : Value(Value), Type(Type) {
2258 assert(Value && "missing value for complete object");
2261 explicit operator bool() const { return Value; }
2263 } // end anonymous namespace
2265 /// Find the designated sub-object of an rvalue.
2266 template<typename SubobjectHandler>
2267 typename SubobjectHandler::result_type
2268 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2269 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2271 // A diagnostic will have already been produced.
2272 return handler.failed();
2273 if (Sub.isOnePastTheEnd()) {
2274 if (Info.getLangOpts().CPlusPlus11)
2275 Info.Diag(E, diag::note_constexpr_access_past_end)
2276 << handler.AccessKind;
2279 return handler.failed();
2282 APValue *O = Obj.Value;
2283 QualType ObjType = Obj.Type;
2284 const FieldDecl *LastField = nullptr;
2286 // Walk the designator's path to find the subobject.
2287 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2288 if (O->isUninit()) {
2289 if (!Info.checkingPotentialConstantExpression())
2290 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2291 return handler.failed();
2295 // If we are reading an object of class type, there may still be more
2296 // things we need to check: if there are any mutable subobjects, we
2297 // cannot perform this read. (This only happens when performing a trivial
2298 // copy or assignment.)
2299 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2300 diagnoseUnreadableFields(Info, E, ObjType))
2301 return handler.failed();
2303 if (!handler.found(*O, ObjType))
2306 // If we modified a bit-field, truncate it to the right width.
2307 if (handler.AccessKind != AK_Read &&
2308 LastField && LastField->isBitField() &&
2309 !truncateBitfieldValue(Info, E, *O, LastField))
2315 LastField = nullptr;
2316 if (ObjType->isArrayType()) {
2317 // Next subobject is an array element.
2318 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2319 assert(CAT && "vla in literal type?");
2320 uint64_t Index = Sub.Entries[I].ArrayIndex;
2321 if (CAT->getSize().ule(Index)) {
2322 // Note, it should not be possible to form a pointer with a valid
2323 // designator which points more than one past the end of the array.
2324 if (Info.getLangOpts().CPlusPlus11)
2325 Info.Diag(E, diag::note_constexpr_access_past_end)
2326 << handler.AccessKind;
2329 return handler.failed();
2332 ObjType = CAT->getElementType();
2334 // An array object is represented as either an Array APValue or as an
2335 // LValue which refers to a string literal.
2336 if (O->isLValue()) {
2337 assert(I == N - 1 && "extracting subobject of character?");
2338 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2339 if (handler.AccessKind != AK_Read)
2340 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2343 return handler.foundString(*O, ObjType, Index);
2346 if (O->getArrayInitializedElts() > Index)
2347 O = &O->getArrayInitializedElt(Index);
2348 else if (handler.AccessKind != AK_Read) {
2349 expandArray(*O, Index);
2350 O = &O->getArrayInitializedElt(Index);
2352 O = &O->getArrayFiller();
2353 } else if (ObjType->isAnyComplexType()) {
2354 // Next subobject is a complex number.
2355 uint64_t Index = Sub.Entries[I].ArrayIndex;
2357 if (Info.getLangOpts().CPlusPlus11)
2358 Info.Diag(E, diag::note_constexpr_access_past_end)
2359 << handler.AccessKind;
2362 return handler.failed();
2365 bool WasConstQualified = ObjType.isConstQualified();
2366 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2367 if (WasConstQualified)
2370 assert(I == N - 1 && "extracting subobject of scalar?");
2371 if (O->isComplexInt()) {
2372 return handler.found(Index ? O->getComplexIntImag()
2373 : O->getComplexIntReal(), ObjType);
2375 assert(O->isComplexFloat());
2376 return handler.found(Index ? O->getComplexFloatImag()
2377 : O->getComplexFloatReal(), ObjType);
2379 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2380 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2381 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2383 Info.Note(Field->getLocation(), diag::note_declared_at);
2384 return handler.failed();
2387 // Next subobject is a class, struct or union field.
2388 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2389 if (RD->isUnion()) {
2390 const FieldDecl *UnionField = O->getUnionField();
2392 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2393 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2394 << handler.AccessKind << Field << !UnionField << UnionField;
2395 return handler.failed();
2397 O = &O->getUnionValue();
2399 O = &O->getStructField(Field->getFieldIndex());
2401 bool WasConstQualified = ObjType.isConstQualified();
2402 ObjType = Field->getType();
2403 if (WasConstQualified && !Field->isMutable())
2406 if (ObjType.isVolatileQualified()) {
2407 if (Info.getLangOpts().CPlusPlus) {
2408 // FIXME: Include a description of the path to the volatile subobject.
2409 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2410 << handler.AccessKind << 2 << Field;
2411 Info.Note(Field->getLocation(), diag::note_declared_at);
2413 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2415 return handler.failed();
2420 // Next subobject is a base class.
2421 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2422 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2423 O = &O->getStructBase(getBaseIndex(Derived, Base));
2425 bool WasConstQualified = ObjType.isConstQualified();
2426 ObjType = Info.Ctx.getRecordType(Base);
2427 if (WasConstQualified)
2434 struct ExtractSubobjectHandler {
2438 static const AccessKinds AccessKind = AK_Read;
2440 typedef bool result_type;
2441 bool failed() { return false; }
2442 bool found(APValue &Subobj, QualType SubobjType) {
2446 bool found(APSInt &Value, QualType SubobjType) {
2447 Result = APValue(Value);
2450 bool found(APFloat &Value, QualType SubobjType) {
2451 Result = APValue(Value);
2454 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2455 Result = APValue(extractStringLiteralCharacter(
2456 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2460 } // end anonymous namespace
2462 const AccessKinds ExtractSubobjectHandler::AccessKind;
2464 /// Extract the designated sub-object of an rvalue.
2465 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2466 const CompleteObject &Obj,
2467 const SubobjectDesignator &Sub,
2469 ExtractSubobjectHandler Handler = { Info, Result };
2470 return findSubobject(Info, E, Obj, Sub, Handler);
2474 struct ModifySubobjectHandler {
2479 typedef bool result_type;
2480 static const AccessKinds AccessKind = AK_Assign;
2482 bool checkConst(QualType QT) {
2483 // Assigning to a const object has undefined behavior.
2484 if (QT.isConstQualified()) {
2485 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2491 bool failed() { return false; }
2492 bool found(APValue &Subobj, QualType SubobjType) {
2493 if (!checkConst(SubobjType))
2495 // We've been given ownership of NewVal, so just swap it in.
2496 Subobj.swap(NewVal);
2499 bool found(APSInt &Value, QualType SubobjType) {
2500 if (!checkConst(SubobjType))
2502 if (!NewVal.isInt()) {
2503 // Maybe trying to write a cast pointer value into a complex?
2507 Value = NewVal.getInt();
2510 bool found(APFloat &Value, QualType SubobjType) {
2511 if (!checkConst(SubobjType))
2513 Value = NewVal.getFloat();
2516 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2517 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2520 } // end anonymous namespace
2522 const AccessKinds ModifySubobjectHandler::AccessKind;
2524 /// Update the designated sub-object of an rvalue to the given value.
2525 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2526 const CompleteObject &Obj,
2527 const SubobjectDesignator &Sub,
2529 ModifySubobjectHandler Handler = { Info, NewVal, E };
2530 return findSubobject(Info, E, Obj, Sub, Handler);
2533 /// Find the position where two subobject designators diverge, or equivalently
2534 /// the length of the common initial subsequence.
2535 static unsigned FindDesignatorMismatch(QualType ObjType,
2536 const SubobjectDesignator &A,
2537 const SubobjectDesignator &B,
2538 bool &WasArrayIndex) {
2539 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2540 for (/**/; I != N; ++I) {
2541 if (!ObjType.isNull() &&
2542 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2543 // Next subobject is an array element.
2544 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2545 WasArrayIndex = true;
2548 if (ObjType->isAnyComplexType())
2549 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2551 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2553 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2554 WasArrayIndex = false;
2557 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2558 // Next subobject is a field.
2559 ObjType = FD->getType();
2561 // Next subobject is a base class.
2562 ObjType = QualType();
2565 WasArrayIndex = false;
2569 /// Determine whether the given subobject designators refer to elements of the
2570 /// same array object.
2571 static bool AreElementsOfSameArray(QualType ObjType,
2572 const SubobjectDesignator &A,
2573 const SubobjectDesignator &B) {
2574 if (A.Entries.size() != B.Entries.size())
2577 bool IsArray = A.MostDerivedIsArrayElement;
2578 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2579 // A is a subobject of the array element.
2582 // If A (and B) designates an array element, the last entry will be the array
2583 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2584 // of length 1' case, and the entire path must match.
2586 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2587 return CommonLength >= A.Entries.size() - IsArray;
2590 /// Find the complete object to which an LValue refers.
2591 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2592 AccessKinds AK, const LValue &LVal,
2593 QualType LValType) {
2595 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2596 return CompleteObject();
2599 CallStackFrame *Frame = nullptr;
2600 if (LVal.CallIndex) {
2601 Frame = Info.getCallFrame(LVal.CallIndex);
2603 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2604 << AK << LVal.Base.is<const ValueDecl*>();
2605 NoteLValueLocation(Info, LVal.Base);
2606 return CompleteObject();
2610 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2611 // is not a constant expression (even if the object is non-volatile). We also
2612 // apply this rule to C++98, in order to conform to the expected 'volatile'
2614 if (LValType.isVolatileQualified()) {
2615 if (Info.getLangOpts().CPlusPlus)
2616 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2620 return CompleteObject();
2623 // Compute value storage location and type of base object.
2624 APValue *BaseVal = nullptr;
2625 QualType BaseType = getType(LVal.Base);
2627 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2628 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2629 // In C++11, constexpr, non-volatile variables initialized with constant
2630 // expressions are constant expressions too. Inside constexpr functions,
2631 // parameters are constant expressions even if they're non-const.
2632 // In C++1y, objects local to a constant expression (those with a Frame) are
2633 // both readable and writable inside constant expressions.
2634 // In C, such things can also be folded, although they are not ICEs.
2635 const VarDecl *VD = dyn_cast<VarDecl>(D);
2637 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2640 if (!VD || VD->isInvalidDecl()) {
2642 return CompleteObject();
2645 // Accesses of volatile-qualified objects are not allowed.
2646 if (BaseType.isVolatileQualified()) {
2647 if (Info.getLangOpts().CPlusPlus) {
2648 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2650 Info.Note(VD->getLocation(), diag::note_declared_at);
2654 return CompleteObject();
2657 // Unless we're looking at a local variable or argument in a constexpr call,
2658 // the variable we're reading must be const.
2660 if (Info.getLangOpts().CPlusPlus14 &&
2661 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2662 // OK, we can read and modify an object if we're in the process of
2663 // evaluating its initializer, because its lifetime began in this
2665 } else if (AK != AK_Read) {
2666 // All the remaining cases only permit reading.
2667 Info.Diag(E, diag::note_constexpr_modify_global);
2668 return CompleteObject();
2669 } else if (VD->isConstexpr()) {
2670 // OK, we can read this variable.
2671 } else if (BaseType->isIntegralOrEnumerationType()) {
2672 if (!BaseType.isConstQualified()) {
2673 if (Info.getLangOpts().CPlusPlus) {
2674 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2675 Info.Note(VD->getLocation(), diag::note_declared_at);
2679 return CompleteObject();
2681 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2682 // We support folding of const floating-point types, in order to make
2683 // static const data members of such types (supported as an extension)
2685 if (Info.getLangOpts().CPlusPlus11) {
2686 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2687 Info.Note(VD->getLocation(), diag::note_declared_at);
2692 // FIXME: Allow folding of values of any literal type in all languages.
2693 if (Info.getLangOpts().CPlusPlus11) {
2694 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2695 Info.Note(VD->getLocation(), diag::note_declared_at);
2699 return CompleteObject();
2703 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2704 return CompleteObject();
2706 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2709 if (const MaterializeTemporaryExpr *MTE =
2710 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2711 assert(MTE->getStorageDuration() == SD_Static &&
2712 "should have a frame for a non-global materialized temporary");
2714 // Per C++1y [expr.const]p2:
2715 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2716 // - a [...] glvalue of integral or enumeration type that refers to
2717 // a non-volatile const object [...]
2719 // - a [...] glvalue of literal type that refers to a non-volatile
2720 // object whose lifetime began within the evaluation of e.
2722 // C++11 misses the 'began within the evaluation of e' check and
2723 // instead allows all temporaries, including things like:
2726 // constexpr int k = r;
2727 // Therefore we use the C++1y rules in C++11 too.
2728 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2729 const ValueDecl *ED = MTE->getExtendingDecl();
2730 if (!(BaseType.isConstQualified() &&
2731 BaseType->isIntegralOrEnumerationType()) &&
2732 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2733 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2734 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2735 return CompleteObject();
2738 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2739 assert(BaseVal && "got reference to unevaluated temporary");
2742 return CompleteObject();
2745 BaseVal = Frame->getTemporary(Base);
2746 assert(BaseVal && "missing value for temporary");
2749 // Volatile temporary objects cannot be accessed in constant expressions.
2750 if (BaseType.isVolatileQualified()) {
2751 if (Info.getLangOpts().CPlusPlus) {
2752 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2754 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2758 return CompleteObject();
2762 // During the construction of an object, it is not yet 'const'.
2763 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2764 // and this doesn't do quite the right thing for const subobjects of the
2765 // object under construction.
2766 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2767 BaseType = Info.Ctx.getCanonicalType(BaseType);
2768 BaseType.removeLocalConst();
2771 // In C++1y, we can't safely access any mutable state when we might be
2772 // evaluating after an unmodeled side effect or an evaluation failure.
2774 // FIXME: Not all local state is mutable. Allow local constant subobjects
2775 // to be read here (but take care with 'mutable' fields).
2776 if (Frame && Info.getLangOpts().CPlusPlus14 &&
2777 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2778 return CompleteObject();
2780 return CompleteObject(BaseVal, BaseType);
2783 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2784 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2785 /// glvalue referred to by an entity of reference type.
2787 /// \param Info - Information about the ongoing evaluation.
2788 /// \param Conv - The expression for which we are performing the conversion.
2789 /// Used for diagnostics.
2790 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2791 /// case of a non-class type).
2792 /// \param LVal - The glvalue on which we are attempting to perform this action.
2793 /// \param RVal - The produced value will be placed here.
2794 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2796 const LValue &LVal, APValue &RVal) {
2797 if (LVal.Designator.Invalid)
2800 // Check for special cases where there is no existing APValue to look at.
2801 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2802 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
2803 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2804 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2805 // initializer until now for such expressions. Such an expression can't be
2806 // an ICE in C, so this only matters for fold.
2807 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2808 if (Type.isVolatileQualified()) {
2813 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2815 CompleteObject LitObj(&Lit, Base->getType());
2816 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2817 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
2818 // We represent a string literal array as an lvalue pointing at the
2819 // corresponding expression, rather than building an array of chars.
2820 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2821 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2822 CompleteObject StrObj(&Str, Base->getType());
2823 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2827 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2828 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2831 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2832 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2833 QualType LValType, APValue &Val) {
2834 if (LVal.Designator.Invalid)
2837 if (!Info.getLangOpts().CPlusPlus14) {
2842 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2843 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2846 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2847 return T->isSignedIntegerType() &&
2848 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2852 struct CompoundAssignSubobjectHandler {
2855 QualType PromotedLHSType;
2856 BinaryOperatorKind Opcode;
2859 static const AccessKinds AccessKind = AK_Assign;
2861 typedef bool result_type;
2863 bool checkConst(QualType QT) {
2864 // Assigning to a const object has undefined behavior.
2865 if (QT.isConstQualified()) {
2866 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2872 bool failed() { return false; }
2873 bool found(APValue &Subobj, QualType SubobjType) {
2874 switch (Subobj.getKind()) {
2876 return found(Subobj.getInt(), SubobjType);
2877 case APValue::Float:
2878 return found(Subobj.getFloat(), SubobjType);
2879 case APValue::ComplexInt:
2880 case APValue::ComplexFloat:
2881 // FIXME: Implement complex compound assignment.
2884 case APValue::LValue:
2885 return foundPointer(Subobj, SubobjType);
2887 // FIXME: can this happen?
2892 bool found(APSInt &Value, QualType SubobjType) {
2893 if (!checkConst(SubobjType))
2896 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2897 // We don't support compound assignment on integer-cast-to-pointer
2903 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2905 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2907 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2910 bool found(APFloat &Value, QualType SubobjType) {
2911 return checkConst(SubobjType) &&
2912 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2914 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2915 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2917 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2918 if (!checkConst(SubobjType))
2921 QualType PointeeType;
2922 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2923 PointeeType = PT->getPointeeType();
2925 if (PointeeType.isNull() || !RHS.isInt() ||
2926 (Opcode != BO_Add && Opcode != BO_Sub)) {
2931 int64_t Offset = getExtValue(RHS.getInt());
2932 if (Opcode == BO_Sub)
2936 LVal.setFrom(Info.Ctx, Subobj);
2937 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2939 LVal.moveInto(Subobj);
2942 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2943 llvm_unreachable("shouldn't encounter string elements here");
2946 } // end anonymous namespace
2948 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2950 /// Perform a compound assignment of LVal <op>= RVal.
2951 static bool handleCompoundAssignment(
2952 EvalInfo &Info, const Expr *E,
2953 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2954 BinaryOperatorKind Opcode, const APValue &RVal) {
2955 if (LVal.Designator.Invalid)
2958 if (!Info.getLangOpts().CPlusPlus14) {
2963 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2964 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2966 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2970 struct IncDecSubobjectHandler {
2973 AccessKinds AccessKind;
2976 typedef bool result_type;
2978 bool checkConst(QualType QT) {
2979 // Assigning to a const object has undefined behavior.
2980 if (QT.isConstQualified()) {
2981 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2987 bool failed() { return false; }
2988 bool found(APValue &Subobj, QualType SubobjType) {
2989 // Stash the old value. Also clear Old, so we don't clobber it later
2990 // if we're post-incrementing a complex.
2996 switch (Subobj.getKind()) {
2998 return found(Subobj.getInt(), SubobjType);
2999 case APValue::Float:
3000 return found(Subobj.getFloat(), SubobjType);
3001 case APValue::ComplexInt:
3002 return found(Subobj.getComplexIntReal(),
3003 SubobjType->castAs<ComplexType>()->getElementType()
3004 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3005 case APValue::ComplexFloat:
3006 return found(Subobj.getComplexFloatReal(),
3007 SubobjType->castAs<ComplexType>()->getElementType()
3008 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3009 case APValue::LValue:
3010 return foundPointer(Subobj, SubobjType);
3012 // FIXME: can this happen?
3017 bool found(APSInt &Value, QualType SubobjType) {
3018 if (!checkConst(SubobjType))
3021 if (!SubobjType->isIntegerType()) {
3022 // We don't support increment / decrement on integer-cast-to-pointer
3028 if (Old) *Old = APValue(Value);
3030 // bool arithmetic promotes to int, and the conversion back to bool
3031 // doesn't reduce mod 2^n, so special-case it.
3032 if (SubobjType->isBooleanType()) {
3033 if (AccessKind == AK_Increment)
3040 bool WasNegative = Value.isNegative();
3041 if (AccessKind == AK_Increment) {
3044 if (!WasNegative && Value.isNegative() &&
3045 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3046 APSInt ActualValue(Value, /*IsUnsigned*/true);
3047 return HandleOverflow(Info, E, ActualValue, SubobjType);
3052 if (WasNegative && !Value.isNegative() &&
3053 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3054 unsigned BitWidth = Value.getBitWidth();
3055 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3056 ActualValue.setBit(BitWidth);
3057 return HandleOverflow(Info, E, ActualValue, SubobjType);
3062 bool found(APFloat &Value, QualType SubobjType) {
3063 if (!checkConst(SubobjType))
3066 if (Old) *Old = APValue(Value);
3068 APFloat One(Value.getSemantics(), 1);
3069 if (AccessKind == AK_Increment)
3070 Value.add(One, APFloat::rmNearestTiesToEven);
3072 Value.subtract(One, APFloat::rmNearestTiesToEven);
3075 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3076 if (!checkConst(SubobjType))
3079 QualType PointeeType;
3080 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3081 PointeeType = PT->getPointeeType();
3088 LVal.setFrom(Info.Ctx, Subobj);
3089 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3090 AccessKind == AK_Increment ? 1 : -1))
3092 LVal.moveInto(Subobj);
3095 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3096 llvm_unreachable("shouldn't encounter string elements here");
3099 } // end anonymous namespace
3101 /// Perform an increment or decrement on LVal.
3102 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3103 QualType LValType, bool IsIncrement, APValue *Old) {
3104 if (LVal.Designator.Invalid)
3107 if (!Info.getLangOpts().CPlusPlus14) {
3112 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3113 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3114 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3115 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3118 /// Build an lvalue for the object argument of a member function call.
3119 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3121 if (Object->getType()->isPointerType())
3122 return EvaluatePointer(Object, This, Info);
3124 if (Object->isGLValue())
3125 return EvaluateLValue(Object, This, Info);
3127 if (Object->getType()->isLiteralType(Info.Ctx))
3128 return EvaluateTemporary(Object, This, Info);
3130 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3134 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3135 /// lvalue referring to the result.
3137 /// \param Info - Information about the ongoing evaluation.
3138 /// \param LV - An lvalue referring to the base of the member pointer.
3139 /// \param RHS - The member pointer expression.
3140 /// \param IncludeMember - Specifies whether the member itself is included in
3141 /// the resulting LValue subobject designator. This is not possible when
3142 /// creating a bound member function.
3143 /// \return The field or method declaration to which the member pointer refers,
3144 /// or 0 if evaluation fails.
3145 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3149 bool IncludeMember = true) {
3151 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3154 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3155 // member value, the behavior is undefined.
3156 if (!MemPtr.getDecl()) {
3157 // FIXME: Specific diagnostic.
3162 if (MemPtr.isDerivedMember()) {
3163 // This is a member of some derived class. Truncate LV appropriately.
3164 // The end of the derived-to-base path for the base object must match the
3165 // derived-to-base path for the member pointer.
3166 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3167 LV.Designator.Entries.size()) {
3171 unsigned PathLengthToMember =
3172 LV.Designator.Entries.size() - MemPtr.Path.size();
3173 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3174 const CXXRecordDecl *LVDecl = getAsBaseClass(
3175 LV.Designator.Entries[PathLengthToMember + I]);
3176 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3177 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3183 // Truncate the lvalue to the appropriate derived class.
3184 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3185 PathLengthToMember))
3187 } else if (!MemPtr.Path.empty()) {
3188 // Extend the LValue path with the member pointer's path.
3189 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3190 MemPtr.Path.size() + IncludeMember);
3192 // Walk down to the appropriate base class.
3193 if (const PointerType *PT = LVType->getAs<PointerType>())
3194 LVType = PT->getPointeeType();
3195 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3196 assert(RD && "member pointer access on non-class-type expression");
3197 // The first class in the path is that of the lvalue.
3198 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3199 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3200 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3204 // Finally cast to the class containing the member.
3205 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3206 MemPtr.getContainingRecord()))
3210 // Add the member. Note that we cannot build bound member functions here.
3211 if (IncludeMember) {
3212 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3213 if (!HandleLValueMember(Info, RHS, LV, FD))
3215 } else if (const IndirectFieldDecl *IFD =
3216 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3217 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3220 llvm_unreachable("can't construct reference to bound member function");
3224 return MemPtr.getDecl();
3227 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3228 const BinaryOperator *BO,
3230 bool IncludeMember = true) {
3231 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3233 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3234 if (Info.keepEvaluatingAfterFailure()) {
3236 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3241 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3242 BO->getRHS(), IncludeMember);
3245 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3246 /// the provided lvalue, which currently refers to the base object.
3247 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3249 SubobjectDesignator &D = Result.Designator;
3250 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3253 QualType TargetQT = E->getType();
3254 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3255 TargetQT = PT->getPointeeType();
3257 // Check this cast lands within the final derived-to-base subobject path.
3258 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3259 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3260 << D.MostDerivedType << TargetQT;
3264 // Check the type of the final cast. We don't need to check the path,
3265 // since a cast can only be formed if the path is unique.
3266 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3267 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3268 const CXXRecordDecl *FinalType;
3269 if (NewEntriesSize == D.MostDerivedPathLength)
3270 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3272 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3273 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3274 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3275 << D.MostDerivedType << TargetQT;
3279 // Truncate the lvalue to the appropriate derived class.
3280 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3284 enum EvalStmtResult {
3285 /// Evaluation failed.
3287 /// Hit a 'return' statement.
3289 /// Evaluation succeeded.
3291 /// Hit a 'continue' statement.
3293 /// Hit a 'break' statement.
3295 /// Still scanning for 'case' or 'default' statement.
3300 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3301 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3302 // We don't need to evaluate the initializer for a static local.
3303 if (!VD->hasLocalStorage())
3307 Result.set(VD, Info.CurrentCall->Index);
3308 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3310 const Expr *InitE = VD->getInit();
3312 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3313 << false << VD->getType();
3318 if (InitE->isValueDependent())
3321 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3322 // Wipe out any partially-computed value, to allow tracking that this
3323 // evaluation failed.
3332 /// Evaluate a condition (either a variable declaration or an expression).
3333 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3334 const Expr *Cond, bool &Result) {
3335 FullExpressionRAII Scope(Info);
3336 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3338 return EvaluateAsBooleanCondition(Cond, Result, Info);
3341 /// \brief A location where the result (returned value) of evaluating a
3342 /// statement should be stored.
3344 /// The APValue that should be filled in with the returned value.
3346 /// The location containing the result, if any (used to support RVO).
3350 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3352 const SwitchCase *SC = nullptr);
3354 /// Evaluate the body of a loop, and translate the result as appropriate.
3355 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3357 const SwitchCase *Case = nullptr) {
3358 BlockScopeRAII Scope(Info);
3359 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3361 return ESR_Succeeded;
3364 return ESR_Continue;
3367 case ESR_CaseNotFound:
3370 llvm_unreachable("Invalid EvalStmtResult!");
3373 /// Evaluate a switch statement.
3374 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3375 const SwitchStmt *SS) {
3376 BlockScopeRAII Scope(Info);
3378 // Evaluate the switch condition.
3381 FullExpressionRAII Scope(Info);
3382 if (SS->getConditionVariable() &&
3383 !EvaluateDecl(Info, SS->getConditionVariable()))
3385 if (!EvaluateInteger(SS->getCond(), Value, Info))
3389 // Find the switch case corresponding to the value of the condition.
3390 // FIXME: Cache this lookup.
3391 const SwitchCase *Found = nullptr;
3392 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3393 SC = SC->getNextSwitchCase()) {
3394 if (isa<DefaultStmt>(SC)) {
3399 const CaseStmt *CS = cast<CaseStmt>(SC);
3400 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3401 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3403 if (LHS <= Value && Value <= RHS) {
3410 return ESR_Succeeded;
3412 // Search the switch body for the switch case and evaluate it from there.
3413 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3415 return ESR_Succeeded;
3421 case ESR_CaseNotFound:
3422 // This can only happen if the switch case is nested within a statement
3423 // expression. We have no intention of supporting that.
3424 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3427 llvm_unreachable("Invalid EvalStmtResult!");
3430 // Evaluate a statement.
3431 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3432 const Stmt *S, const SwitchCase *Case) {
3433 if (!Info.nextStep(S))
3436 // If we're hunting down a 'case' or 'default' label, recurse through
3437 // substatements until we hit the label.
3439 // FIXME: We don't start the lifetime of objects whose initialization we
3440 // jump over. However, such objects must be of class type with a trivial
3441 // default constructor that initialize all subobjects, so must be empty,
3442 // so this almost never matters.
3443 switch (S->getStmtClass()) {
3444 case Stmt::CompoundStmtClass:
3445 // FIXME: Precompute which substatement of a compound statement we
3446 // would jump to, and go straight there rather than performing a
3447 // linear scan each time.
3448 case Stmt::LabelStmtClass:
3449 case Stmt::AttributedStmtClass:
3450 case Stmt::DoStmtClass:
3453 case Stmt::CaseStmtClass:
3454 case Stmt::DefaultStmtClass:
3459 case Stmt::IfStmtClass: {
3460 // FIXME: Precompute which side of an 'if' we would jump to, and go
3461 // straight there rather than scanning both sides.
3462 const IfStmt *IS = cast<IfStmt>(S);
3464 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3465 // preceded by our switch label.
3466 BlockScopeRAII Scope(Info);
3468 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3469 if (ESR != ESR_CaseNotFound || !IS->getElse())
3471 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3474 case Stmt::WhileStmtClass: {
3475 EvalStmtResult ESR =
3476 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3477 if (ESR != ESR_Continue)
3482 case Stmt::ForStmtClass: {
3483 const ForStmt *FS = cast<ForStmt>(S);
3484 EvalStmtResult ESR =
3485 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3486 if (ESR != ESR_Continue)
3489 FullExpressionRAII IncScope(Info);
3490 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3496 case Stmt::DeclStmtClass:
3497 // FIXME: If the variable has initialization that can't be jumped over,
3498 // bail out of any immediately-surrounding compound-statement too.
3500 return ESR_CaseNotFound;
3504 switch (S->getStmtClass()) {
3506 if (const Expr *E = dyn_cast<Expr>(S)) {
3507 // Don't bother evaluating beyond an expression-statement which couldn't
3509 FullExpressionRAII Scope(Info);
3510 if (!EvaluateIgnoredValue(Info, E))
3512 return ESR_Succeeded;
3515 Info.Diag(S->getLocStart());
3518 case Stmt::NullStmtClass:
3519 return ESR_Succeeded;
3521 case Stmt::DeclStmtClass: {
3522 const DeclStmt *DS = cast<DeclStmt>(S);
3523 for (const auto *DclIt : DS->decls()) {
3524 // Each declaration initialization is its own full-expression.
3525 // FIXME: This isn't quite right; if we're performing aggregate
3526 // initialization, each braced subexpression is its own full-expression.
3527 FullExpressionRAII Scope(Info);
3528 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3531 return ESR_Succeeded;
3534 case Stmt::ReturnStmtClass: {
3535 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3536 FullExpressionRAII Scope(Info);
3539 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3540 : Evaluate(Result.Value, Info, RetExpr)))
3542 return ESR_Returned;
3545 case Stmt::CompoundStmtClass: {
3546 BlockScopeRAII Scope(Info);
3548 const CompoundStmt *CS = cast<CompoundStmt>(S);
3549 for (const auto *BI : CS->body()) {
3550 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3551 if (ESR == ESR_Succeeded)
3553 else if (ESR != ESR_CaseNotFound)
3556 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3559 case Stmt::IfStmtClass: {
3560 const IfStmt *IS = cast<IfStmt>(S);
3562 // Evaluate the condition, as either a var decl or as an expression.
3563 BlockScopeRAII Scope(Info);
3565 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3568 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3569 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3570 if (ESR != ESR_Succeeded)
3573 return ESR_Succeeded;
3576 case Stmt::WhileStmtClass: {
3577 const WhileStmt *WS = cast<WhileStmt>(S);
3579 BlockScopeRAII Scope(Info);
3581 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3587 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3588 if (ESR != ESR_Continue)
3591 return ESR_Succeeded;
3594 case Stmt::DoStmtClass: {
3595 const DoStmt *DS = cast<DoStmt>(S);
3598 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3599 if (ESR != ESR_Continue)
3603 FullExpressionRAII CondScope(Info);
3604 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3607 return ESR_Succeeded;
3610 case Stmt::ForStmtClass: {
3611 const ForStmt *FS = cast<ForStmt>(S);
3612 BlockScopeRAII Scope(Info);
3613 if (FS->getInit()) {
3614 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3615 if (ESR != ESR_Succeeded)
3619 BlockScopeRAII Scope(Info);
3620 bool Continue = true;
3621 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3622 FS->getCond(), Continue))
3627 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3628 if (ESR != ESR_Continue)
3632 FullExpressionRAII IncScope(Info);
3633 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3637 return ESR_Succeeded;
3640 case Stmt::CXXForRangeStmtClass: {
3641 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3642 BlockScopeRAII Scope(Info);
3644 // Initialize the __range variable.
3645 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3646 if (ESR != ESR_Succeeded)
3649 // Create the __begin and __end iterators.
3650 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3651 if (ESR != ESR_Succeeded)
3655 // Condition: __begin != __end.
3657 bool Continue = true;
3658 FullExpressionRAII CondExpr(Info);
3659 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3665 // User's variable declaration, initialized by *__begin.
3666 BlockScopeRAII InnerScope(Info);
3667 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3668 if (ESR != ESR_Succeeded)
3672 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3673 if (ESR != ESR_Continue)
3676 // Increment: ++__begin
3677 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3681 return ESR_Succeeded;
3684 case Stmt::SwitchStmtClass:
3685 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3687 case Stmt::ContinueStmtClass:
3688 return ESR_Continue;
3690 case Stmt::BreakStmtClass:
3693 case Stmt::LabelStmtClass:
3694 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3696 case Stmt::AttributedStmtClass:
3697 // As a general principle, C++11 attributes can be ignored without
3698 // any semantic impact.
3699 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3702 case Stmt::CaseStmtClass:
3703 case Stmt::DefaultStmtClass:
3704 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3708 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3709 /// default constructor. If so, we'll fold it whether or not it's marked as
3710 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3711 /// so we need special handling.
3712 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3713 const CXXConstructorDecl *CD,
3714 bool IsValueInitialization) {
3715 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3718 // Value-initialization does not call a trivial default constructor, so such a
3719 // call is a core constant expression whether or not the constructor is
3721 if (!CD->isConstexpr() && !IsValueInitialization) {
3722 if (Info.getLangOpts().CPlusPlus11) {
3723 // FIXME: If DiagDecl is an implicitly-declared special member function,
3724 // we should be much more explicit about why it's not constexpr.
3725 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3726 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3727 Info.Note(CD->getLocation(), diag::note_declared_at);
3729 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3735 /// CheckConstexprFunction - Check that a function can be called in a constant
3737 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3738 const FunctionDecl *Declaration,
3739 const FunctionDecl *Definition) {
3740 // Potential constant expressions can contain calls to declared, but not yet
3741 // defined, constexpr functions.
3742 if (Info.checkingPotentialConstantExpression() && !Definition &&
3743 Declaration->isConstexpr())
3746 // Bail out with no diagnostic if the function declaration itself is invalid.
3747 // We will have produced a relevant diagnostic while parsing it.
3748 if (Declaration->isInvalidDecl())
3751 // Can we evaluate this function call?
3752 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3755 if (Info.getLangOpts().CPlusPlus11) {
3756 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3757 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3758 // should be much more explicit about why it's not constexpr.
3759 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3760 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3762 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3764 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3769 /// Determine if a class has any fields that might need to be copied by a
3770 /// trivial copy or move operation.
3771 static bool hasFields(const CXXRecordDecl *RD) {
3772 if (!RD || RD->isEmpty())
3774 for (auto *FD : RD->fields()) {
3775 if (FD->isUnnamedBitfield())
3779 for (auto &Base : RD->bases())
3780 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3786 typedef SmallVector<APValue, 8> ArgVector;
3789 /// EvaluateArgs - Evaluate the arguments to a function call.
3790 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3792 bool Success = true;
3793 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3795 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3796 // If we're checking for a potential constant expression, evaluate all
3797 // initializers even if some of them fail.
3798 if (!Info.keepEvaluatingAfterFailure())
3806 /// Evaluate a function call.
3807 static bool HandleFunctionCall(SourceLocation CallLoc,
3808 const FunctionDecl *Callee, const LValue *This,
3809 ArrayRef<const Expr*> Args, const Stmt *Body,
3810 EvalInfo &Info, APValue &Result,
3811 const LValue *ResultSlot) {
3812 ArgVector ArgValues(Args.size());
3813 if (!EvaluateArgs(Args, ArgValues, Info))
3816 if (!Info.CheckCallLimit(CallLoc))
3819 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3821 // For a trivial copy or move assignment, perform an APValue copy. This is
3822 // essential for unions, where the operations performed by the assignment
3823 // operator cannot be represented as statements.
3825 // Skip this for non-union classes with no fields; in that case, the defaulted
3826 // copy/move does not actually read the object.
3827 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3828 if (MD && MD->isDefaulted() &&
3829 (MD->getParent()->isUnion() ||
3830 (MD->isTrivial() && hasFields(MD->getParent())))) {
3832 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3834 RHS.setFrom(Info.Ctx, ArgValues[0]);
3836 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3839 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3842 This->moveInto(Result);
3846 StmtResult Ret = {Result, ResultSlot};
3847 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
3848 if (ESR == ESR_Succeeded) {
3849 if (Callee->getReturnType()->isVoidType())
3851 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3853 return ESR == ESR_Returned;
3856 /// Evaluate a constructor call.
3857 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3858 ArrayRef<const Expr*> Args,
3859 const CXXConstructorDecl *Definition,
3860 EvalInfo &Info, APValue &Result) {
3861 ArgVector ArgValues(Args.size());
3862 if (!EvaluateArgs(Args, ArgValues, Info))
3865 if (!Info.CheckCallLimit(CallLoc))
3868 const CXXRecordDecl *RD = Definition->getParent();
3869 if (RD->getNumVBases()) {
3870 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3874 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3876 // FIXME: Creating an APValue just to hold a nonexistent return value is
3879 StmtResult Ret = {RetVal, nullptr};
3881 // If it's a delegating constructor, just delegate.
3882 if (Definition->isDelegatingConstructor()) {
3883 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3885 FullExpressionRAII InitScope(Info);
3886 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3889 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
3892 // For a trivial copy or move constructor, perform an APValue copy. This is
3893 // essential for unions (or classes with anonymous union members), where the
3894 // operations performed by the constructor cannot be represented by
3895 // ctor-initializers.
3897 // Skip this for empty non-union classes; we should not perform an
3898 // lvalue-to-rvalue conversion on them because their copy constructor does not
3899 // actually read them.
3900 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
3901 (Definition->getParent()->isUnion() ||
3902 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
3904 RHS.setFrom(Info.Ctx, ArgValues[0]);
3905 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3909 // Reserve space for the struct members.
3910 if (!RD->isUnion() && Result.isUninit())
3911 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3912 std::distance(RD->field_begin(), RD->field_end()));
3914 if (RD->isInvalidDecl()) return false;
3915 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3917 // A scope for temporaries lifetime-extended by reference members.
3918 BlockScopeRAII LifetimeExtendedScope(Info);
3920 bool Success = true;
3921 unsigned BasesSeen = 0;
3923 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3925 for (const auto *I : Definition->inits()) {
3926 LValue Subobject = This;
3927 APValue *Value = &Result;
3929 // Determine the subobject to initialize.
3930 FieldDecl *FD = nullptr;
3931 if (I->isBaseInitializer()) {
3932 QualType BaseType(I->getBaseClass(), 0);
3934 // Non-virtual base classes are initialized in the order in the class
3935 // definition. We have already checked for virtual base classes.
3936 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3937 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3938 "base class initializers not in expected order");
3941 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
3942 BaseType->getAsCXXRecordDecl(), &Layout))
3944 Value = &Result.getStructBase(BasesSeen++);
3945 } else if ((FD = I->getMember())) {
3946 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
3948 if (RD->isUnion()) {
3949 Result = APValue(FD);
3950 Value = &Result.getUnionValue();
3952 Value = &Result.getStructField(FD->getFieldIndex());
3954 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
3955 // Walk the indirect field decl's chain to find the object to initialize,
3956 // and make sure we've initialized every step along it.
3957 for (auto *C : IFD->chain()) {
3958 FD = cast<FieldDecl>(C);
3959 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3960 // Switch the union field if it differs. This happens if we had
3961 // preceding zero-initialization, and we're now initializing a union
3962 // subobject other than the first.
3963 // FIXME: In this case, the values of the other subobjects are
3964 // specified, since zero-initialization sets all padding bits to zero.
3965 if (Value->isUninit() ||
3966 (Value->isUnion() && Value->getUnionField() != FD)) {
3968 *Value = APValue(FD);
3970 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3971 std::distance(CD->field_begin(), CD->field_end()));
3973 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
3976 Value = &Value->getUnionValue();
3978 Value = &Value->getStructField(FD->getFieldIndex());
3981 llvm_unreachable("unknown base initializer kind");
3984 FullExpressionRAII InitScope(Info);
3985 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3986 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
3988 // If we're checking for a potential constant expression, evaluate all
3989 // initializers even if some of them fail.
3990 if (!Info.keepEvaluatingAfterFailure())
3997 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4000 //===----------------------------------------------------------------------===//
4001 // Generic Evaluation
4002 //===----------------------------------------------------------------------===//
4005 template <class Derived>
4006 class ExprEvaluatorBase
4007 : public ConstStmtVisitor<Derived, bool> {
4009 Derived &getDerived() { return static_cast<Derived&>(*this); }
4010 bool DerivedSuccess(const APValue &V, const Expr *E) {
4011 return getDerived().Success(V, E);
4013 bool DerivedZeroInitialization(const Expr *E) {
4014 return getDerived().ZeroInitialization(E);
4017 // Check whether a conditional operator with a non-constant condition is a
4018 // potential constant expression. If neither arm is a potential constant
4019 // expression, then the conditional operator is not either.
4020 template<typename ConditionalOperator>
4021 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4022 assert(Info.checkingPotentialConstantExpression());
4024 // Speculatively evaluate both arms.
4026 SmallVector<PartialDiagnosticAt, 8> Diag;
4027 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4029 StmtVisitorTy::Visit(E->getFalseExpr());
4034 StmtVisitorTy::Visit(E->getTrueExpr());
4039 Error(E, diag::note_constexpr_conditional_never_const);
4043 template<typename ConditionalOperator>
4044 bool HandleConditionalOperator(const ConditionalOperator *E) {
4046 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4047 if (Info.checkingPotentialConstantExpression())
4048 CheckPotentialConstantConditional(E);
4052 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4053 return StmtVisitorTy::Visit(EvalExpr);
4058 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4059 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4061 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4062 return Info.CCEDiag(E, D);
4065 bool ZeroInitialization(const Expr *E) { return Error(E); }
4068 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4070 EvalInfo &getEvalInfo() { return Info; }
4072 /// Report an evaluation error. This should only be called when an error is
4073 /// first discovered. When propagating an error, just return false.
4074 bool Error(const Expr *E, diag::kind D) {
4078 bool Error(const Expr *E) {
4079 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4082 bool VisitStmt(const Stmt *) {
4083 llvm_unreachable("Expression evaluator should not be called on stmts");
4085 bool VisitExpr(const Expr *E) {
4089 bool VisitParenExpr(const ParenExpr *E)
4090 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4091 bool VisitUnaryExtension(const UnaryOperator *E)
4092 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4093 bool VisitUnaryPlus(const UnaryOperator *E)
4094 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4095 bool VisitChooseExpr(const ChooseExpr *E)
4096 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4097 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4098 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4099 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4100 { return StmtVisitorTy::Visit(E->getReplacement()); }
4101 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4102 { return StmtVisitorTy::Visit(E->getExpr()); }
4103 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4104 // The initializer may not have been parsed yet, or might be erroneous.
4107 return StmtVisitorTy::Visit(E->getExpr());
4109 // We cannot create any objects for which cleanups are required, so there is
4110 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4111 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4112 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4114 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4115 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4116 return static_cast<Derived*>(this)->VisitCastExpr(E);
4118 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4119 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4120 return static_cast<Derived*>(this)->VisitCastExpr(E);
4123 bool VisitBinaryOperator(const BinaryOperator *E) {
4124 switch (E->getOpcode()) {
4129 VisitIgnoredValue(E->getLHS());
4130 return StmtVisitorTy::Visit(E->getRHS());
4135 if (!HandleMemberPointerAccess(Info, E, Obj))
4138 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4140 return DerivedSuccess(Result, E);
4145 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4146 // Evaluate and cache the common expression. We treat it as a temporary,
4147 // even though it's not quite the same thing.
4148 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4149 Info, E->getCommon()))
4152 return HandleConditionalOperator(E);
4155 bool VisitConditionalOperator(const ConditionalOperator *E) {
4156 bool IsBcpCall = false;
4157 // If the condition (ignoring parens) is a __builtin_constant_p call,
4158 // the result is a constant expression if it can be folded without
4159 // side-effects. This is an important GNU extension. See GCC PR38377
4161 if (const CallExpr *CallCE =
4162 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4163 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4166 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4167 // constant expression; we can't check whether it's potentially foldable.
4168 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4171 FoldConstant Fold(Info, IsBcpCall);
4172 if (!HandleConditionalOperator(E)) {
4173 Fold.keepDiagnostics();
4180 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4181 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4182 return DerivedSuccess(*Value, E);
4184 const Expr *Source = E->getSourceExpr();
4187 if (Source == E) { // sanity checking.
4188 assert(0 && "OpaqueValueExpr recursively refers to itself");
4191 return StmtVisitorTy::Visit(Source);
4194 bool VisitCallExpr(const CallExpr *E) {
4196 if (!handleCallExpr(E, Result, nullptr))
4198 return DerivedSuccess(Result, E);
4201 bool handleCallExpr(const CallExpr *E, APValue &Result,
4202 const LValue *ResultSlot) {
4203 const Expr *Callee = E->getCallee()->IgnoreParens();
4204 QualType CalleeType = Callee->getType();
4206 const FunctionDecl *FD = nullptr;
4207 LValue *This = nullptr, ThisVal;
4208 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4209 bool HasQualifier = false;
4211 // Extract function decl and 'this' pointer from the callee.
4212 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4213 const ValueDecl *Member = nullptr;
4214 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4215 // Explicit bound member calls, such as x.f() or p->g();
4216 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4218 Member = ME->getMemberDecl();
4220 HasQualifier = ME->hasQualifier();
4221 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4222 // Indirect bound member calls ('.*' or '->*').
4223 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4224 if (!Member) return false;
4227 return Error(Callee);
4229 FD = dyn_cast<FunctionDecl>(Member);
4231 return Error(Callee);
4232 } else if (CalleeType->isFunctionPointerType()) {
4234 if (!EvaluatePointer(Callee, Call, Info))
4237 if (!Call.getLValueOffset().isZero())
4238 return Error(Callee);
4239 FD = dyn_cast_or_null<FunctionDecl>(
4240 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4242 return Error(Callee);
4244 // Overloaded operator calls to member functions are represented as normal
4245 // calls with '*this' as the first argument.
4246 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4247 if (MD && !MD->isStatic()) {
4248 // FIXME: When selecting an implicit conversion for an overloaded
4249 // operator delete, we sometimes try to evaluate calls to conversion
4250 // operators without a 'this' parameter!
4254 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4257 Args = Args.slice(1);
4260 // Don't call function pointers which have been cast to some other type.
4261 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4266 if (This && !This->checkSubobject(Info, E, CSK_This))
4269 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4270 // calls to such functions in constant expressions.
4271 if (This && !HasQualifier &&
4272 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4273 return Error(E, diag::note_constexpr_virtual_call);
4275 const FunctionDecl *Definition = nullptr;
4276 Stmt *Body = FD->getBody(Definition);
4278 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4279 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4280 Result, ResultSlot))
4286 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4287 return StmtVisitorTy::Visit(E->getInitializer());
4289 bool VisitInitListExpr(const InitListExpr *E) {
4290 if (E->getNumInits() == 0)
4291 return DerivedZeroInitialization(E);
4292 if (E->getNumInits() == 1)
4293 return StmtVisitorTy::Visit(E->getInit(0));
4296 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4297 return DerivedZeroInitialization(E);
4299 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4300 return DerivedZeroInitialization(E);
4302 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4303 return DerivedZeroInitialization(E);
4306 /// A member expression where the object is a prvalue is itself a prvalue.
4307 bool VisitMemberExpr(const MemberExpr *E) {
4308 assert(!E->isArrow() && "missing call to bound member function?");
4311 if (!Evaluate(Val, Info, E->getBase()))
4314 QualType BaseTy = E->getBase()->getType();
4316 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4317 if (!FD) return Error(E);
4318 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4319 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4320 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4322 CompleteObject Obj(&Val, BaseTy);
4323 SubobjectDesignator Designator(BaseTy);
4324 Designator.addDeclUnchecked(FD);
4327 return extractSubobject(Info, E, Obj, Designator, Result) &&
4328 DerivedSuccess(Result, E);
4331 bool VisitCastExpr(const CastExpr *E) {
4332 switch (E->getCastKind()) {
4336 case CK_AtomicToNonAtomic: {
4338 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4340 return DerivedSuccess(AtomicVal, E);
4344 case CK_UserDefinedConversion:
4345 return StmtVisitorTy::Visit(E->getSubExpr());
4347 case CK_LValueToRValue: {
4349 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4352 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4353 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4356 return DerivedSuccess(RVal, E);
4363 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4364 return VisitUnaryPostIncDec(UO);
4366 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4367 return VisitUnaryPostIncDec(UO);
4369 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4370 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4374 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4377 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4378 UO->isIncrementOp(), &RVal))
4380 return DerivedSuccess(RVal, UO);
4383 bool VisitStmtExpr(const StmtExpr *E) {
4384 // We will have checked the full-expressions inside the statement expression
4385 // when they were completed, and don't need to check them again now.
4386 if (Info.checkingForOverflow())
4389 BlockScopeRAII Scope(Info);
4390 const CompoundStmt *CS = E->getSubStmt();
4391 if (CS->body_empty())
4394 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4395 BE = CS->body_end();
4398 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4400 Info.Diag((*BI)->getLocStart(),
4401 diag::note_constexpr_stmt_expr_unsupported);
4404 return this->Visit(FinalExpr);
4407 APValue ReturnValue;
4408 StmtResult Result = { ReturnValue, nullptr };
4409 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4410 if (ESR != ESR_Succeeded) {
4411 // FIXME: If the statement-expression terminated due to 'return',
4412 // 'break', or 'continue', it would be nice to propagate that to
4413 // the outer statement evaluation rather than bailing out.
4414 if (ESR != ESR_Failed)
4415 Info.Diag((*BI)->getLocStart(),
4416 diag::note_constexpr_stmt_expr_unsupported);
4421 llvm_unreachable("Return from function from the loop above.");
4424 /// Visit a value which is evaluated, but whose value is ignored.
4425 void VisitIgnoredValue(const Expr *E) {
4426 EvaluateIgnoredValue(Info, E);
4432 //===----------------------------------------------------------------------===//
4433 // Common base class for lvalue and temporary evaluation.
4434 //===----------------------------------------------------------------------===//
4436 template<class Derived>
4437 class LValueExprEvaluatorBase
4438 : public ExprEvaluatorBase<Derived> {
4441 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4442 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4444 bool Success(APValue::LValueBase B) {
4450 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4451 ExprEvaluatorBaseTy(Info), Result(Result) {}
4453 bool Success(const APValue &V, const Expr *E) {
4454 Result.setFrom(this->Info.Ctx, V);
4458 bool VisitMemberExpr(const MemberExpr *E) {
4459 // Handle non-static data members.
4463 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
4464 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4465 } else if (E->getBase()->isRValue()) {
4466 assert(E->getBase()->getType()->isRecordType());
4467 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4468 BaseTy = E->getBase()->getType();
4470 EvalOK = this->Visit(E->getBase());
4471 BaseTy = E->getBase()->getType();
4474 if (!this->Info.allowInvalidBaseExpr())
4476 Result.setInvalid(E);
4480 const ValueDecl *MD = E->getMemberDecl();
4481 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4482 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4483 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4485 if (!HandleLValueMember(this->Info, E, Result, FD))
4487 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4488 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4491 return this->Error(E);
4493 if (MD->getType()->isReferenceType()) {
4495 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4498 return Success(RefValue, E);
4503 bool VisitBinaryOperator(const BinaryOperator *E) {
4504 switch (E->getOpcode()) {
4506 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4510 return HandleMemberPointerAccess(this->Info, E, Result);
4514 bool VisitCastExpr(const CastExpr *E) {
4515 switch (E->getCastKind()) {
4517 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4519 case CK_DerivedToBase:
4520 case CK_UncheckedDerivedToBase:
4521 if (!this->Visit(E->getSubExpr()))
4524 // Now figure out the necessary offset to add to the base LV to get from
4525 // the derived class to the base class.
4526 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4533 //===----------------------------------------------------------------------===//
4534 // LValue Evaluation
4536 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4537 // function designators (in C), decl references to void objects (in C), and
4538 // temporaries (if building with -Wno-address-of-temporary).
4540 // LValue evaluation produces values comprising a base expression of one of the
4546 // * CompoundLiteralExpr in C
4550 // * ObjCStringLiteralExpr
4554 // * CallExpr for a MakeStringConstant builtin
4555 // - Locals and temporaries
4556 // * MaterializeTemporaryExpr
4557 // * Any Expr, with a CallIndex indicating the function in which the temporary
4558 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4559 // from the AST (FIXME).
4560 // * A MaterializeTemporaryExpr that has static storage duration, with no
4561 // CallIndex, for a lifetime-extended temporary.
4562 // plus an offset in bytes.
4563 //===----------------------------------------------------------------------===//
4565 class LValueExprEvaluator
4566 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4568 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4569 LValueExprEvaluatorBaseTy(Info, Result) {}
4571 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4572 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4574 bool VisitDeclRefExpr(const DeclRefExpr *E);
4575 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4576 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4577 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4578 bool VisitMemberExpr(const MemberExpr *E);
4579 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4580 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4581 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4582 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4583 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4584 bool VisitUnaryDeref(const UnaryOperator *E);
4585 bool VisitUnaryReal(const UnaryOperator *E);
4586 bool VisitUnaryImag(const UnaryOperator *E);
4587 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4588 return VisitUnaryPreIncDec(UO);
4590 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4591 return VisitUnaryPreIncDec(UO);
4593 bool VisitBinAssign(const BinaryOperator *BO);
4594 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4596 bool VisitCastExpr(const CastExpr *E) {
4597 switch (E->getCastKind()) {
4599 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4601 case CK_LValueBitCast:
4602 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4603 if (!Visit(E->getSubExpr()))
4605 Result.Designator.setInvalid();
4608 case CK_BaseToDerived:
4609 if (!Visit(E->getSubExpr()))
4611 return HandleBaseToDerivedCast(Info, E, Result);
4615 } // end anonymous namespace
4617 /// Evaluate an expression as an lvalue. This can be legitimately called on
4618 /// expressions which are not glvalues, in three cases:
4619 /// * function designators in C, and
4620 /// * "extern void" objects
4621 /// * @selector() expressions in Objective-C
4622 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4623 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4624 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4625 return LValueExprEvaluator(Info, Result).Visit(E);
4628 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4629 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4631 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4632 return VisitVarDecl(E, VD);
4636 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4637 CallStackFrame *Frame = nullptr;
4638 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4639 Frame = Info.CurrentCall;
4641 if (!VD->getType()->isReferenceType()) {
4643 Result.set(VD, Frame->Index);
4650 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4652 if (V->isUninit()) {
4653 if (!Info.checkingPotentialConstantExpression())
4654 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4657 return Success(*V, E);
4660 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4661 const MaterializeTemporaryExpr *E) {
4662 // Walk through the expression to find the materialized temporary itself.
4663 SmallVector<const Expr *, 2> CommaLHSs;
4664 SmallVector<SubobjectAdjustment, 2> Adjustments;
4665 const Expr *Inner = E->GetTemporaryExpr()->
4666 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4668 // If we passed any comma operators, evaluate their LHSs.
4669 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4670 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4673 // A materialized temporary with static storage duration can appear within the
4674 // result of a constant expression evaluation, so we need to preserve its
4675 // value for use outside this evaluation.
4677 if (E->getStorageDuration() == SD_Static) {
4678 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4682 Value = &Info.CurrentCall->
4683 createTemporary(E, E->getStorageDuration() == SD_Automatic);
4684 Result.set(E, Info.CurrentCall->Index);
4687 QualType Type = Inner->getType();
4689 // Materialize the temporary itself.
4690 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4691 (E->getStorageDuration() == SD_Static &&
4692 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4697 // Adjust our lvalue to refer to the desired subobject.
4698 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4700 switch (Adjustments[I].Kind) {
4701 case SubobjectAdjustment::DerivedToBaseAdjustment:
4702 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4705 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4708 case SubobjectAdjustment::FieldAdjustment:
4709 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4711 Type = Adjustments[I].Field->getType();
4714 case SubobjectAdjustment::MemberPointerAdjustment:
4715 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4716 Adjustments[I].Ptr.RHS))
4718 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4727 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4728 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4729 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4730 // only see this when folding in C, so there's no standard to follow here.
4734 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4735 if (!E->isPotentiallyEvaluated())
4738 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4739 << E->getExprOperand()->getType()
4740 << E->getExprOperand()->getSourceRange();
4744 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4748 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4749 // Handle static data members.
4750 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4751 VisitIgnoredValue(E->getBase());
4752 return VisitVarDecl(E, VD);
4755 // Handle static member functions.
4756 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4757 if (MD->isStatic()) {
4758 VisitIgnoredValue(E->getBase());
4763 // Handle non-static data members.
4764 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4767 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4768 // FIXME: Deal with vectors as array subscript bases.
4769 if (E->getBase()->getType()->isVectorType())
4772 if (!EvaluatePointer(E->getBase(), Result, Info))
4776 if (!EvaluateInteger(E->getIdx(), Index, Info))
4779 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4780 getExtValue(Index));
4783 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4784 return EvaluatePointer(E->getSubExpr(), Result, Info);
4787 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4788 if (!Visit(E->getSubExpr()))
4790 // __real is a no-op on scalar lvalues.
4791 if (E->getSubExpr()->getType()->isAnyComplexType())
4792 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4796 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4797 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4798 "lvalue __imag__ on scalar?");
4799 if (!Visit(E->getSubExpr()))
4801 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4805 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4806 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4809 if (!this->Visit(UO->getSubExpr()))
4812 return handleIncDec(
4813 this->Info, UO, Result, UO->getSubExpr()->getType(),
4814 UO->isIncrementOp(), nullptr);
4817 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4818 const CompoundAssignOperator *CAO) {
4819 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4824 // The overall lvalue result is the result of evaluating the LHS.
4825 if (!this->Visit(CAO->getLHS())) {
4826 if (Info.keepEvaluatingAfterFailure())
4827 Evaluate(RHS, this->Info, CAO->getRHS());
4831 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4834 return handleCompoundAssignment(
4836 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4837 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4840 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4841 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4846 if (!this->Visit(E->getLHS())) {
4847 if (Info.keepEvaluatingAfterFailure())
4848 Evaluate(NewVal, this->Info, E->getRHS());
4852 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4855 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4859 //===----------------------------------------------------------------------===//
4860 // Pointer Evaluation
4861 //===----------------------------------------------------------------------===//
4864 class PointerExprEvaluator
4865 : public ExprEvaluatorBase<PointerExprEvaluator> {
4868 bool Success(const Expr *E) {
4874 PointerExprEvaluator(EvalInfo &info, LValue &Result)
4875 : ExprEvaluatorBaseTy(info), Result(Result) {}
4877 bool Success(const APValue &V, const Expr *E) {
4878 Result.setFrom(Info.Ctx, V);
4881 bool ZeroInitialization(const Expr *E) {
4882 return Success((Expr*)nullptr);
4885 bool VisitBinaryOperator(const BinaryOperator *E);
4886 bool VisitCastExpr(const CastExpr* E);
4887 bool VisitUnaryAddrOf(const UnaryOperator *E);
4888 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4889 { return Success(E); }
4890 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4891 { return Success(E); }
4892 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4893 { return Success(E); }
4894 bool VisitCallExpr(const CallExpr *E);
4895 bool VisitBlockExpr(const BlockExpr *E) {
4896 if (!E->getBlockDecl()->hasCaptures())
4900 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4901 // Can't look at 'this' when checking a potential constant expression.
4902 if (Info.checkingPotentialConstantExpression())
4904 if (!Info.CurrentCall->This) {
4905 if (Info.getLangOpts().CPlusPlus11)
4906 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4911 Result = *Info.CurrentCall->This;
4915 // FIXME: Missing: @protocol, @selector
4917 } // end anonymous namespace
4919 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4920 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4921 return PointerExprEvaluator(Info, Result).Visit(E);
4924 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4925 if (E->getOpcode() != BO_Add &&
4926 E->getOpcode() != BO_Sub)
4927 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4929 const Expr *PExp = E->getLHS();
4930 const Expr *IExp = E->getRHS();
4931 if (IExp->getType()->isPointerType())
4932 std::swap(PExp, IExp);
4934 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4935 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4938 llvm::APSInt Offset;
4939 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4942 int64_t AdditionalOffset = getExtValue(Offset);
4943 if (E->getOpcode() == BO_Sub)
4944 AdditionalOffset = -AdditionalOffset;
4946 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4947 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4951 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4952 return EvaluateLValue(E->getSubExpr(), Result, Info);
4955 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4956 const Expr* SubExpr = E->getSubExpr();
4958 switch (E->getCastKind()) {
4963 case CK_CPointerToObjCPointerCast:
4964 case CK_BlockPointerToObjCPointerCast:
4965 case CK_AnyPointerToBlockPointerCast:
4966 case CK_AddressSpaceConversion:
4967 if (!Visit(SubExpr))
4969 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4970 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4971 // also static_casts, but we disallow them as a resolution to DR1312.
4972 if (!E->getType()->isVoidPointerType()) {
4973 Result.Designator.setInvalid();
4974 if (SubExpr->getType()->isVoidPointerType())
4975 CCEDiag(E, diag::note_constexpr_invalid_cast)
4976 << 3 << SubExpr->getType();
4978 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4982 case CK_DerivedToBase:
4983 case CK_UncheckedDerivedToBase:
4984 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4986 if (!Result.Base && Result.Offset.isZero())
4989 // Now figure out the necessary offset to add to the base LV to get from
4990 // the derived class to the base class.
4991 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4992 castAs<PointerType>()->getPointeeType(),
4995 case CK_BaseToDerived:
4996 if (!Visit(E->getSubExpr()))
4998 if (!Result.Base && Result.Offset.isZero())
5000 return HandleBaseToDerivedCast(Info, E, Result);
5002 case CK_NullToPointer:
5003 VisitIgnoredValue(E->getSubExpr());
5004 return ZeroInitialization(E);
5006 case CK_IntegralToPointer: {
5007 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5010 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5013 if (Value.isInt()) {
5014 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5015 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5016 Result.Base = (Expr*)nullptr;
5017 Result.InvalidBase = false;
5018 Result.Offset = CharUnits::fromQuantity(N);
5019 Result.CallIndex = 0;
5020 Result.Designator.setInvalid();
5023 // Cast is of an lvalue, no need to change value.
5024 Result.setFrom(Info.Ctx, Value);
5028 case CK_ArrayToPointerDecay:
5029 if (SubExpr->isGLValue()) {
5030 if (!EvaluateLValue(SubExpr, Result, Info))
5033 Result.set(SubExpr, Info.CurrentCall->Index);
5034 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5035 Info, Result, SubExpr))
5038 // The result is a pointer to the first element of the array.
5039 if (const ConstantArrayType *CAT
5040 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5041 Result.addArray(Info, E, CAT);
5043 Result.Designator.setInvalid();
5046 case CK_FunctionToPointerDecay:
5047 return EvaluateLValue(SubExpr, Result, Info);
5050 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5053 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5054 // C++ [expr.alignof]p3:
5055 // When alignof is applied to a reference type, the result is the
5056 // alignment of the referenced type.
5057 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5058 T = Ref->getPointeeType();
5060 // __alignof is defined to return the preferred alignment.
5061 return Info.Ctx.toCharUnitsFromBits(
5062 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5065 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5066 E = E->IgnoreParens();
5068 // The kinds of expressions that we have special-case logic here for
5069 // should be kept up to date with the special checks for those
5070 // expressions in Sema.
5072 // alignof decl is always accepted, even if it doesn't make sense: we default
5073 // to 1 in those cases.
5074 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5075 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5076 /*RefAsPointee*/true);
5078 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5079 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5080 /*RefAsPointee*/true);
5082 return GetAlignOfType(Info, E->getType());
5085 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5086 if (IsStringLiteralCall(E))
5089 switch (E->getBuiltinCallee()) {
5090 case Builtin::BI__builtin_addressof:
5091 return EvaluateLValue(E->getArg(0), Result, Info);
5092 case Builtin::BI__builtin_assume_aligned: {
5093 // We need to be very careful here because: if the pointer does not have the
5094 // asserted alignment, then the behavior is undefined, and undefined
5095 // behavior is non-constant.
5096 if (!EvaluatePointer(E->getArg(0), Result, Info))
5099 LValue OffsetResult(Result);
5101 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5103 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5105 if (E->getNumArgs() > 2) {
5107 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5110 int64_t AdditionalOffset = -getExtValue(Offset);
5111 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5114 // If there is a base object, then it must have the correct alignment.
5115 if (OffsetResult.Base) {
5116 CharUnits BaseAlignment;
5117 if (const ValueDecl *VD =
5118 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5119 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5122 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5125 if (BaseAlignment < Align) {
5126 Result.Designator.setInvalid();
5127 // FIXME: Quantities here cast to integers because the plural modifier
5128 // does not work on APSInts yet.
5129 CCEDiag(E->getArg(0),
5130 diag::note_constexpr_baa_insufficient_alignment) << 0
5131 << (int) BaseAlignment.getQuantity()
5132 << (unsigned) getExtValue(Alignment);
5137 // The offset must also have the correct alignment.
5138 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5139 Result.Designator.setInvalid();
5140 APSInt Offset(64, false);
5141 Offset = OffsetResult.Offset.getQuantity();
5143 if (OffsetResult.Base)
5144 CCEDiag(E->getArg(0),
5145 diag::note_constexpr_baa_insufficient_alignment) << 1
5146 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5148 CCEDiag(E->getArg(0),
5149 diag::note_constexpr_baa_value_insufficient_alignment)
5150 << Offset << (unsigned) getExtValue(Alignment);
5158 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5162 //===----------------------------------------------------------------------===//
5163 // Member Pointer Evaluation
5164 //===----------------------------------------------------------------------===//
5167 class MemberPointerExprEvaluator
5168 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5171 bool Success(const ValueDecl *D) {
5172 Result = MemberPtr(D);
5177 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5178 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5180 bool Success(const APValue &V, const Expr *E) {
5184 bool ZeroInitialization(const Expr *E) {
5185 return Success((const ValueDecl*)nullptr);
5188 bool VisitCastExpr(const CastExpr *E);
5189 bool VisitUnaryAddrOf(const UnaryOperator *E);
5191 } // end anonymous namespace
5193 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5195 assert(E->isRValue() && E->getType()->isMemberPointerType());
5196 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5199 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5200 switch (E->getCastKind()) {
5202 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5204 case CK_NullToMemberPointer:
5205 VisitIgnoredValue(E->getSubExpr());
5206 return ZeroInitialization(E);
5208 case CK_BaseToDerivedMemberPointer: {
5209 if (!Visit(E->getSubExpr()))
5211 if (E->path_empty())
5213 // Base-to-derived member pointer casts store the path in derived-to-base
5214 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5215 // the wrong end of the derived->base arc, so stagger the path by one class.
5216 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5217 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5218 PathI != PathE; ++PathI) {
5219 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5220 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5221 if (!Result.castToDerived(Derived))
5224 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5225 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5230 case CK_DerivedToBaseMemberPointer:
5231 if (!Visit(E->getSubExpr()))
5233 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5234 PathE = E->path_end(); PathI != PathE; ++PathI) {
5235 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5236 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5237 if (!Result.castToBase(Base))
5244 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5245 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5246 // member can be formed.
5247 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5250 //===----------------------------------------------------------------------===//
5251 // Record Evaluation
5252 //===----------------------------------------------------------------------===//
5255 class RecordExprEvaluator
5256 : public ExprEvaluatorBase<RecordExprEvaluator> {
5261 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5262 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5264 bool Success(const APValue &V, const Expr *E) {
5268 bool ZeroInitialization(const Expr *E);
5270 bool VisitCallExpr(const CallExpr *E) {
5271 return handleCallExpr(E, Result, &This);
5273 bool VisitCastExpr(const CastExpr *E);
5274 bool VisitInitListExpr(const InitListExpr *E);
5275 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5276 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5280 /// Perform zero-initialization on an object of non-union class type.
5281 /// C++11 [dcl.init]p5:
5282 /// To zero-initialize an object or reference of type T means:
5284 /// -- if T is a (possibly cv-qualified) non-union class type,
5285 /// each non-static data member and each base-class subobject is
5286 /// zero-initialized
5287 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5288 const RecordDecl *RD,
5289 const LValue &This, APValue &Result) {
5290 assert(!RD->isUnion() && "Expected non-union class type");
5291 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5292 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5293 std::distance(RD->field_begin(), RD->field_end()));
5295 if (RD->isInvalidDecl()) return false;
5296 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5300 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5301 End = CD->bases_end(); I != End; ++I, ++Index) {
5302 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5303 LValue Subobject = This;
5304 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5306 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5307 Result.getStructBase(Index)))
5312 for (const auto *I : RD->fields()) {
5313 // -- if T is a reference type, no initialization is performed.
5314 if (I->getType()->isReferenceType())
5317 LValue Subobject = This;
5318 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5321 ImplicitValueInitExpr VIE(I->getType());
5322 if (!EvaluateInPlace(
5323 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5330 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5331 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5332 if (RD->isInvalidDecl()) return false;
5333 if (RD->isUnion()) {
5334 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5335 // object's first non-static named data member is zero-initialized
5336 RecordDecl::field_iterator I = RD->field_begin();
5337 if (I == RD->field_end()) {
5338 Result = APValue((const FieldDecl*)nullptr);
5342 LValue Subobject = This;
5343 if (!HandleLValueMember(Info, E, Subobject, *I))
5345 Result = APValue(*I);
5346 ImplicitValueInitExpr VIE(I->getType());
5347 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5350 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5351 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5355 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5358 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5359 switch (E->getCastKind()) {
5361 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5363 case CK_ConstructorConversion:
5364 return Visit(E->getSubExpr());
5366 case CK_DerivedToBase:
5367 case CK_UncheckedDerivedToBase: {
5368 APValue DerivedObject;
5369 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5371 if (!DerivedObject.isStruct())
5372 return Error(E->getSubExpr());
5374 // Derived-to-base rvalue conversion: just slice off the derived part.
5375 APValue *Value = &DerivedObject;
5376 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5377 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5378 PathE = E->path_end(); PathI != PathE; ++PathI) {
5379 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5380 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5381 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5390 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5391 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5392 if (RD->isInvalidDecl()) return false;
5393 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5395 if (RD->isUnion()) {
5396 const FieldDecl *Field = E->getInitializedFieldInUnion();
5397 Result = APValue(Field);
5401 // If the initializer list for a union does not contain any elements, the
5402 // first element of the union is value-initialized.
5403 // FIXME: The element should be initialized from an initializer list.
5404 // Is this difference ever observable for initializer lists which
5406 ImplicitValueInitExpr VIE(Field->getType());
5407 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5409 LValue Subobject = This;
5410 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5413 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5414 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5415 isa<CXXDefaultInitExpr>(InitExpr));
5417 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5420 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5421 "initializer list for class with base classes");
5422 Result = APValue(APValue::UninitStruct(), 0,
5423 std::distance(RD->field_begin(), RD->field_end()));
5424 unsigned ElementNo = 0;
5425 bool Success = true;
5426 for (const auto *Field : RD->fields()) {
5427 // Anonymous bit-fields are not considered members of the class for
5428 // purposes of aggregate initialization.
5429 if (Field->isUnnamedBitfield())
5432 LValue Subobject = This;
5434 bool HaveInit = ElementNo < E->getNumInits();
5436 // FIXME: Diagnostics here should point to the end of the initializer
5437 // list, not the start.
5438 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5439 Subobject, Field, &Layout))
5442 // Perform an implicit value-initialization for members beyond the end of
5443 // the initializer list.
5444 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5445 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5447 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5448 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5449 isa<CXXDefaultInitExpr>(Init));
5451 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5452 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5453 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5454 FieldVal, Field))) {
5455 if (!Info.keepEvaluatingAfterFailure())
5464 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5465 const CXXConstructorDecl *FD = E->getConstructor();
5466 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5468 bool ZeroInit = E->requiresZeroInitialization();
5469 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5470 // If we've already performed zero-initialization, we're already done.
5471 if (!Result.isUninit())
5474 // We can get here in two different ways:
5475 // 1) We're performing value-initialization, and should zero-initialize
5477 // 2) We're performing default-initialization of an object with a trivial
5478 // constexpr default constructor, in which case we should start the
5479 // lifetimes of all the base subobjects (there can be no data member
5480 // subobjects in this case) per [basic.life]p1.
5481 // Either way, ZeroInitialization is appropriate.
5482 return ZeroInitialization(E);
5485 const FunctionDecl *Definition = nullptr;
5486 FD->getBody(Definition);
5488 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5491 // Avoid materializing a temporary for an elidable copy/move constructor.
5492 if (E->isElidable() && !ZeroInit)
5493 if (const MaterializeTemporaryExpr *ME
5494 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5495 return Visit(ME->GetTemporaryExpr());
5497 if (ZeroInit && !ZeroInitialization(E))
5500 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5501 return HandleConstructorCall(E->getExprLoc(), This, Args,
5502 cast<CXXConstructorDecl>(Definition), Info,
5506 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5507 const CXXStdInitializerListExpr *E) {
5508 const ConstantArrayType *ArrayType =
5509 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5512 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5515 // Get a pointer to the first element of the array.
5516 Array.addArray(Info, E, ArrayType);
5518 // FIXME: Perform the checks on the field types in SemaInit.
5519 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5520 RecordDecl::field_iterator Field = Record->field_begin();
5521 if (Field == Record->field_end())
5525 if (!Field->getType()->isPointerType() ||
5526 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5527 ArrayType->getElementType()))
5530 // FIXME: What if the initializer_list type has base classes, etc?
5531 Result = APValue(APValue::UninitStruct(), 0, 2);
5532 Array.moveInto(Result.getStructField(0));
5534 if (++Field == Record->field_end())
5537 if (Field->getType()->isPointerType() &&
5538 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5539 ArrayType->getElementType())) {
5541 if (!HandleLValueArrayAdjustment(Info, E, Array,
5542 ArrayType->getElementType(),
5543 ArrayType->getSize().getZExtValue()))
5545 Array.moveInto(Result.getStructField(1));
5546 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5548 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5552 if (++Field != Record->field_end())
5558 static bool EvaluateRecord(const Expr *E, const LValue &This,
5559 APValue &Result, EvalInfo &Info) {
5560 assert(E->isRValue() && E->getType()->isRecordType() &&
5561 "can't evaluate expression as a record rvalue");
5562 return RecordExprEvaluator(Info, This, Result).Visit(E);
5565 //===----------------------------------------------------------------------===//
5566 // Temporary Evaluation
5568 // Temporaries are represented in the AST as rvalues, but generally behave like
5569 // lvalues. The full-object of which the temporary is a subobject is implicitly
5570 // materialized so that a reference can bind to it.
5571 //===----------------------------------------------------------------------===//
5573 class TemporaryExprEvaluator
5574 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5576 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5577 LValueExprEvaluatorBaseTy(Info, Result) {}
5579 /// Visit an expression which constructs the value of this temporary.
5580 bool VisitConstructExpr(const Expr *E) {
5581 Result.set(E, Info.CurrentCall->Index);
5582 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5586 bool VisitCastExpr(const CastExpr *E) {
5587 switch (E->getCastKind()) {
5589 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5591 case CK_ConstructorConversion:
5592 return VisitConstructExpr(E->getSubExpr());
5595 bool VisitInitListExpr(const InitListExpr *E) {
5596 return VisitConstructExpr(E);
5598 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5599 return VisitConstructExpr(E);
5601 bool VisitCallExpr(const CallExpr *E) {
5602 return VisitConstructExpr(E);
5604 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5605 return VisitConstructExpr(E);
5608 } // end anonymous namespace
5610 /// Evaluate an expression of record type as a temporary.
5611 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5612 assert(E->isRValue() && E->getType()->isRecordType());
5613 return TemporaryExprEvaluator(Info, Result).Visit(E);
5616 //===----------------------------------------------------------------------===//
5617 // Vector Evaluation
5618 //===----------------------------------------------------------------------===//
5621 class VectorExprEvaluator
5622 : public ExprEvaluatorBase<VectorExprEvaluator> {
5626 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5627 : ExprEvaluatorBaseTy(info), Result(Result) {}
5629 bool Success(ArrayRef<APValue> V, const Expr *E) {
5630 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5631 // FIXME: remove this APValue copy.
5632 Result = APValue(V.data(), V.size());
5635 bool Success(const APValue &V, const Expr *E) {
5636 assert(V.isVector());
5640 bool ZeroInitialization(const Expr *E);
5642 bool VisitUnaryReal(const UnaryOperator *E)
5643 { return Visit(E->getSubExpr()); }
5644 bool VisitCastExpr(const CastExpr* E);
5645 bool VisitInitListExpr(const InitListExpr *E);
5646 bool VisitUnaryImag(const UnaryOperator *E);
5647 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5648 // binary comparisons, binary and/or/xor,
5649 // shufflevector, ExtVectorElementExpr
5651 } // end anonymous namespace
5653 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5654 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5655 return VectorExprEvaluator(Info, Result).Visit(E);
5658 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
5659 const VectorType *VTy = E->getType()->castAs<VectorType>();
5660 unsigned NElts = VTy->getNumElements();
5662 const Expr *SE = E->getSubExpr();
5663 QualType SETy = SE->getType();
5665 switch (E->getCastKind()) {
5666 case CK_VectorSplat: {
5667 APValue Val = APValue();
5668 if (SETy->isIntegerType()) {
5670 if (!EvaluateInteger(SE, IntResult, Info))
5672 Val = APValue(std::move(IntResult));
5673 } else if (SETy->isRealFloatingType()) {
5674 APFloat FloatResult(0.0);
5675 if (!EvaluateFloat(SE, FloatResult, Info))
5677 Val = APValue(std::move(FloatResult));
5682 // Splat and create vector APValue.
5683 SmallVector<APValue, 4> Elts(NElts, Val);
5684 return Success(Elts, E);
5687 // Evaluate the operand into an APInt we can extract from.
5688 llvm::APInt SValInt;
5689 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5691 // Extract the elements
5692 QualType EltTy = VTy->getElementType();
5693 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5694 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5695 SmallVector<APValue, 4> Elts;
5696 if (EltTy->isRealFloatingType()) {
5697 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5698 unsigned FloatEltSize = EltSize;
5699 if (&Sem == &APFloat::x87DoubleExtended)
5701 for (unsigned i = 0; i < NElts; i++) {
5704 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5706 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5707 Elts.push_back(APValue(APFloat(Sem, Elt)));
5709 } else if (EltTy->isIntegerType()) {
5710 for (unsigned i = 0; i < NElts; i++) {
5713 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5715 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5716 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5721 return Success(Elts, E);
5724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5729 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5730 const VectorType *VT = E->getType()->castAs<VectorType>();
5731 unsigned NumInits = E->getNumInits();
5732 unsigned NumElements = VT->getNumElements();
5734 QualType EltTy = VT->getElementType();
5735 SmallVector<APValue, 4> Elements;
5737 // The number of initializers can be less than the number of
5738 // vector elements. For OpenCL, this can be due to nested vector
5739 // initialization. For GCC compatibility, missing trailing elements
5740 // should be initialized with zeroes.
5741 unsigned CountInits = 0, CountElts = 0;
5742 while (CountElts < NumElements) {
5743 // Handle nested vector initialization.
5744 if (CountInits < NumInits
5745 && E->getInit(CountInits)->getType()->isVectorType()) {
5747 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5749 unsigned vlen = v.getVectorLength();
5750 for (unsigned j = 0; j < vlen; j++)
5751 Elements.push_back(v.getVectorElt(j));
5753 } else if (EltTy->isIntegerType()) {
5754 llvm::APSInt sInt(32);
5755 if (CountInits < NumInits) {
5756 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5758 } else // trailing integer zero.
5759 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5760 Elements.push_back(APValue(sInt));
5763 llvm::APFloat f(0.0);
5764 if (CountInits < NumInits) {
5765 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5767 } else // trailing float zero.
5768 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5769 Elements.push_back(APValue(f));
5774 return Success(Elements, E);
5778 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5779 const VectorType *VT = E->getType()->getAs<VectorType>();
5780 QualType EltTy = VT->getElementType();
5781 APValue ZeroElement;
5782 if (EltTy->isIntegerType())
5783 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5786 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5788 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5789 return Success(Elements, E);
5792 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5793 VisitIgnoredValue(E->getSubExpr());
5794 return ZeroInitialization(E);
5797 //===----------------------------------------------------------------------===//
5799 //===----------------------------------------------------------------------===//
5802 class ArrayExprEvaluator
5803 : public ExprEvaluatorBase<ArrayExprEvaluator> {
5808 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5809 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5811 bool Success(const APValue &V, const Expr *E) {
5812 assert((V.isArray() || V.isLValue()) &&
5813 "expected array or string literal");
5818 bool ZeroInitialization(const Expr *E) {
5819 const ConstantArrayType *CAT =
5820 Info.Ctx.getAsConstantArrayType(E->getType());
5824 Result = APValue(APValue::UninitArray(), 0,
5825 CAT->getSize().getZExtValue());
5826 if (!Result.hasArrayFiller()) return true;
5828 // Zero-initialize all elements.
5829 LValue Subobject = This;
5830 Subobject.addArray(Info, E, CAT);
5831 ImplicitValueInitExpr VIE(CAT->getElementType());
5832 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5835 bool VisitCallExpr(const CallExpr *E) {
5836 return handleCallExpr(E, Result, &This);
5838 bool VisitInitListExpr(const InitListExpr *E);
5839 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5840 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5841 const LValue &Subobject,
5842 APValue *Value, QualType Type);
5844 } // end anonymous namespace
5846 static bool EvaluateArray(const Expr *E, const LValue &This,
5847 APValue &Result, EvalInfo &Info) {
5848 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5849 return ArrayExprEvaluator(Info, This, Result).Visit(E);
5852 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5853 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5857 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5858 // an appropriately-typed string literal enclosed in braces.
5859 if (E->isStringLiteralInit()) {
5861 if (!EvaluateLValue(E->getInit(0), LV, Info))
5865 return Success(Val, E);
5868 bool Success = true;
5870 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5871 "zero-initialized array shouldn't have any initialized elts");
5873 if (Result.isArray() && Result.hasArrayFiller())
5874 Filler = Result.getArrayFiller();
5876 unsigned NumEltsToInit = E->getNumInits();
5877 unsigned NumElts = CAT->getSize().getZExtValue();
5878 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5880 // If the initializer might depend on the array index, run it for each
5881 // array element. For now, just whitelist non-class value-initialization.
5882 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5883 NumEltsToInit = NumElts;
5885 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5887 // If the array was previously zero-initialized, preserve the
5888 // zero-initialized values.
5889 if (!Filler.isUninit()) {
5890 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5891 Result.getArrayInitializedElt(I) = Filler;
5892 if (Result.hasArrayFiller())
5893 Result.getArrayFiller() = Filler;
5896 LValue Subobject = This;
5897 Subobject.addArray(Info, E, CAT);
5898 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5900 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5901 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5902 Info, Subobject, Init) ||
5903 !HandleLValueArrayAdjustment(Info, Init, Subobject,
5904 CAT->getElementType(), 1)) {
5905 if (!Info.keepEvaluatingAfterFailure())
5911 if (!Result.hasArrayFiller())
5914 // If we get here, we have a trivial filler, which we can just evaluate
5915 // once and splat over the rest of the array elements.
5916 assert(FillerExpr && "no array filler for incomplete init list");
5917 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5918 FillerExpr) && Success;
5921 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5922 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5925 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5926 const LValue &Subobject,
5929 bool HadZeroInit = !Value->isUninit();
5931 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5932 unsigned N = CAT->getSize().getZExtValue();
5934 // Preserve the array filler if we had prior zero-initialization.
5936 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5939 *Value = APValue(APValue::UninitArray(), N, N);
5942 for (unsigned I = 0; I != N; ++I)
5943 Value->getArrayInitializedElt(I) = Filler;
5945 // Initialize the elements.
5946 LValue ArrayElt = Subobject;
5947 ArrayElt.addArray(Info, E, CAT);
5948 for (unsigned I = 0; I != N; ++I)
5949 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5950 CAT->getElementType()) ||
5951 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5952 CAT->getElementType(), 1))
5958 if (!Type->isRecordType())
5961 const CXXConstructorDecl *FD = E->getConstructor();
5963 bool ZeroInit = E->requiresZeroInitialization();
5964 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5968 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5969 ImplicitValueInitExpr VIE(Type);
5970 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5973 const FunctionDecl *Definition = nullptr;
5974 FD->getBody(Definition);
5976 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5979 if (ZeroInit && !HadZeroInit) {
5980 ImplicitValueInitExpr VIE(Type);
5981 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5985 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5986 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5987 cast<CXXConstructorDecl>(Definition),
5991 //===----------------------------------------------------------------------===//
5992 // Integer Evaluation
5994 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5995 // types and back in constant folding. Integer values are thus represented
5996 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5997 //===----------------------------------------------------------------------===//
6000 class IntExprEvaluator
6001 : public ExprEvaluatorBase<IntExprEvaluator> {
6004 IntExprEvaluator(EvalInfo &info, APValue &result)
6005 : ExprEvaluatorBaseTy(info), Result(result) {}
6007 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6008 assert(E->getType()->isIntegralOrEnumerationType() &&
6009 "Invalid evaluation result.");
6010 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6011 "Invalid evaluation result.");
6012 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6013 "Invalid evaluation result.");
6014 Result = APValue(SI);
6017 bool Success(const llvm::APSInt &SI, const Expr *E) {
6018 return Success(SI, E, Result);
6021 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6022 assert(E->getType()->isIntegralOrEnumerationType() &&
6023 "Invalid evaluation result.");
6024 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6025 "Invalid evaluation result.");
6026 Result = APValue(APSInt(I));
6027 Result.getInt().setIsUnsigned(
6028 E->getType()->isUnsignedIntegerOrEnumerationType());
6031 bool Success(const llvm::APInt &I, const Expr *E) {
6032 return Success(I, E, Result);
6035 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6036 assert(E->getType()->isIntegralOrEnumerationType() &&
6037 "Invalid evaluation result.");
6038 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6041 bool Success(uint64_t Value, const Expr *E) {
6042 return Success(Value, E, Result);
6045 bool Success(CharUnits Size, const Expr *E) {
6046 return Success(Size.getQuantity(), E);
6049 bool Success(const APValue &V, const Expr *E) {
6050 if (V.isLValue() || V.isAddrLabelDiff()) {
6054 return Success(V.getInt(), E);
6057 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6059 //===--------------------------------------------------------------------===//
6061 //===--------------------------------------------------------------------===//
6063 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6064 return Success(E->getValue(), E);
6066 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6067 return Success(E->getValue(), E);
6070 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6071 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6072 if (CheckReferencedDecl(E, E->getDecl()))
6075 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6077 bool VisitMemberExpr(const MemberExpr *E) {
6078 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6079 VisitIgnoredValue(E->getBase());
6083 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6086 bool VisitCallExpr(const CallExpr *E);
6087 bool VisitBinaryOperator(const BinaryOperator *E);
6088 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6089 bool VisitUnaryOperator(const UnaryOperator *E);
6091 bool VisitCastExpr(const CastExpr* E);
6092 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6094 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6095 return Success(E->getValue(), E);
6098 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6099 return Success(E->getValue(), E);
6102 // Note, GNU defines __null as an integer, not a pointer.
6103 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6104 return ZeroInitialization(E);
6107 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6108 return Success(E->getValue(), E);
6111 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6112 return Success(E->getValue(), E);
6115 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6116 return Success(E->getValue(), E);
6119 bool VisitUnaryReal(const UnaryOperator *E);
6120 bool VisitUnaryImag(const UnaryOperator *E);
6122 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6123 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6126 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
6127 // FIXME: Missing: array subscript of vector, member of vector
6129 } // end anonymous namespace
6131 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6132 /// produce either the integer value or a pointer.
6134 /// GCC has a heinous extension which folds casts between pointer types and
6135 /// pointer-sized integral types. We support this by allowing the evaluation of
6136 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6137 /// Some simple arithmetic on such values is supported (they are treated much
6139 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6141 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6142 return IntExprEvaluator(Info, Result).Visit(E);
6145 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6147 if (!EvaluateIntegerOrLValue(E, Val, Info))
6150 // FIXME: It would be better to produce the diagnostic for casting
6151 // a pointer to an integer.
6152 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6155 Result = Val.getInt();
6159 /// Check whether the given declaration can be directly converted to an integral
6160 /// rvalue. If not, no diagnostic is produced; there are other things we can
6162 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6163 // Enums are integer constant exprs.
6164 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6165 // Check for signedness/width mismatches between E type and ECD value.
6166 bool SameSign = (ECD->getInitVal().isSigned()
6167 == E->getType()->isSignedIntegerOrEnumerationType());
6168 bool SameWidth = (ECD->getInitVal().getBitWidth()
6169 == Info.Ctx.getIntWidth(E->getType()));
6170 if (SameSign && SameWidth)
6171 return Success(ECD->getInitVal(), E);
6173 // Get rid of mismatch (otherwise Success assertions will fail)
6174 // by computing a new value matching the type of E.
6175 llvm::APSInt Val = ECD->getInitVal();
6177 Val.setIsSigned(!ECD->getInitVal().isSigned());
6179 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6180 return Success(Val, E);
6186 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6188 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6189 // The following enum mimics the values returned by GCC.
6190 // FIXME: Does GCC differ between lvalue and rvalue references here?
6191 enum gcc_type_class {
6193 void_type_class, integer_type_class, char_type_class,
6194 enumeral_type_class, boolean_type_class,
6195 pointer_type_class, reference_type_class, offset_type_class,
6196 real_type_class, complex_type_class,
6197 function_type_class, method_type_class,
6198 record_type_class, union_type_class,
6199 array_type_class, string_type_class,
6203 // If no argument was supplied, default to "no_type_class". This isn't
6204 // ideal, however it is what gcc does.
6205 if (E->getNumArgs() == 0)
6206 return no_type_class;
6208 QualType ArgTy = E->getArg(0)->getType();
6209 if (ArgTy->isVoidType())
6210 return void_type_class;
6211 else if (ArgTy->isEnumeralType())
6212 return enumeral_type_class;
6213 else if (ArgTy->isBooleanType())
6214 return boolean_type_class;
6215 else if (ArgTy->isCharType())
6216 return string_type_class; // gcc doesn't appear to use char_type_class
6217 else if (ArgTy->isIntegerType())
6218 return integer_type_class;
6219 else if (ArgTy->isPointerType())
6220 return pointer_type_class;
6221 else if (ArgTy->isReferenceType())
6222 return reference_type_class;
6223 else if (ArgTy->isRealType())
6224 return real_type_class;
6225 else if (ArgTy->isComplexType())
6226 return complex_type_class;
6227 else if (ArgTy->isFunctionType())
6228 return function_type_class;
6229 else if (ArgTy->isStructureOrClassType())
6230 return record_type_class;
6231 else if (ArgTy->isUnionType())
6232 return union_type_class;
6233 else if (ArgTy->isArrayType())
6234 return array_type_class;
6235 else if (ArgTy->isUnionType())
6236 return union_type_class;
6237 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
6238 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6241 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6242 /// __builtin_constant_p when applied to the given lvalue.
6244 /// An lvalue is only "constant" if it is a pointer or reference to the first
6245 /// character of a string literal.
6246 template<typename LValue>
6247 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6248 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6249 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6252 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6253 /// GCC as we can manage.
6254 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6255 QualType ArgType = Arg->getType();
6257 // __builtin_constant_p always has one operand. The rules which gcc follows
6258 // are not precisely documented, but are as follows:
6260 // - If the operand is of integral, floating, complex or enumeration type,
6261 // and can be folded to a known value of that type, it returns 1.
6262 // - If the operand and can be folded to a pointer to the first character
6263 // of a string literal (or such a pointer cast to an integral type), it
6266 // Otherwise, it returns 0.
6268 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6269 // its support for this does not currently work.
6270 if (ArgType->isIntegralOrEnumerationType()) {
6271 Expr::EvalResult Result;
6272 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6275 APValue &V = Result.Val;
6276 if (V.getKind() == APValue::Int)
6278 if (V.getKind() == APValue::LValue)
6279 return EvaluateBuiltinConstantPForLValue(V);
6280 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6281 return Arg->isEvaluatable(Ctx);
6282 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6284 Expr::EvalStatus Status;
6285 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6286 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6287 : EvaluatePointer(Arg, LV, Info)) &&
6288 !Status.HasSideEffects)
6289 return EvaluateBuiltinConstantPForLValue(LV);
6292 // Anything else isn't considered to be sufficiently constant.
6296 /// Retrieves the "underlying object type" of the given expression,
6297 /// as used by __builtin_object_size.
6298 static QualType getObjectType(APValue::LValueBase B) {
6299 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6300 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6301 return VD->getType();
6302 } else if (const Expr *E = B.get<const Expr*>()) {
6303 if (isa<CompoundLiteralExpr>(E))
6304 return E->getType();
6310 /// A more selective version of E->IgnoreParenCasts for
6311 /// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6312 /// to change the type of E.
6313 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6315 /// Always returns an RValue with a pointer representation.
6316 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6317 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6319 auto *NoParens = E->IgnoreParens();
6320 auto *Cast = dyn_cast<CastExpr>(NoParens);
6321 if (Cast == nullptr)
6324 // We only conservatively allow a few kinds of casts, because this code is
6325 // inherently a simple solution that seeks to support the common case.
6326 auto CastKind = Cast->getCastKind();
6327 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6328 CastKind != CK_AddressSpaceConversion)
6331 auto *SubExpr = Cast->getSubExpr();
6332 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6334 return ignorePointerCastsAndParens(SubExpr);
6337 /// Checks to see if the given LValue's Designator is at the end of the LValue's
6338 /// record layout. e.g.
6339 /// struct { struct { int a, b; } fst, snd; } obj;
6345 /// obj.snd.b // yes
6347 /// Please note: this function is specialized for how __builtin_object_size
6348 /// views "objects".
6349 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6350 assert(!LVal.Designator.Invalid);
6352 auto IsLastFieldDecl = [&Ctx](const FieldDecl *FD) {
6353 if (FD->getParent()->isUnion())
6355 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
6356 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6359 auto &Base = LVal.getLValueBase();
6360 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6361 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6362 if (!IsLastFieldDecl(FD))
6364 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6365 for (auto *FD : IFD->chain())
6366 if (!IsLastFieldDecl(cast<FieldDecl>(FD)))
6371 QualType BaseType = getType(Base);
6372 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6373 if (BaseType->isArrayType()) {
6374 // Because __builtin_object_size treats arrays as objects, we can ignore
6375 // the index iff this is the last array in the Designator.
6378 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6379 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6380 if (Index + 1 != CAT->getSize())
6382 BaseType = CAT->getElementType();
6383 } else if (BaseType->isAnyComplexType()) {
6384 auto *CT = BaseType->castAs<ComplexType>();
6385 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6388 BaseType = CT->getElementType();
6389 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6390 if (!IsLastFieldDecl(FD))
6392 BaseType = FD->getType();
6394 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6395 "Expecting cast to a base class");
6402 /// Tests to see if the LValue has a designator (that isn't necessarily valid).
6403 static bool refersToCompleteObject(const LValue &LVal) {
6404 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6407 if (!LVal.InvalidBase)
6410 auto *E = LVal.Base.dyn_cast<const Expr *>();
6412 assert(E != nullptr && isa<MemberExpr>(E));
6416 /// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6417 /// true and stores the result in @p Size.
6419 /// If @p WasError is non-null, this will report whether the failure to evaluate
6420 /// is to be treated as an Error in IntExprEvaluator.
6421 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6422 EvalInfo &Info, uint64_t &Size,
6423 bool *WasError = nullptr) {
6424 if (WasError != nullptr)
6427 auto Error = [&](const Expr *E) {
6428 if (WasError != nullptr)
6433 auto Success = [&](uint64_t S, const Expr *E) {
6438 // Determine the denoted object.
6441 // The operand of __builtin_object_size is never evaluated for side-effects.
6442 // If there are any, but we can determine the pointed-to object anyway, then
6443 // ignore the side-effects.
6444 SpeculativeEvaluationRAII SpeculativeEval(Info);
6445 FoldOffsetRAII Fold(Info, Type & 1);
6447 if (E->isGLValue()) {
6448 // It's possible for us to be given GLValues if we're called via
6449 // Expr::tryEvaluateObjectSize.
6451 if (!EvaluateAsRValue(Info, E, RVal))
6453 Base.setFrom(Info.Ctx, RVal);
6454 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
6458 CharUnits BaseOffset = Base.getLValueOffset();
6459 // If we point to before the start of the object, there are no accessible
6461 if (BaseOffset.isNegative())
6462 return Success(0, E);
6464 // In the case where we're not dealing with a subobject, we discard the
6466 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
6468 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6469 // exist. If we can't verify the base, then we can't do that.
6471 // As a special case, we produce a valid object size for an unknown object
6472 // with a known designator if Type & 1 is 1. For instance:
6474 // extern struct X { char buff[32]; int a, b, c; } *p;
6475 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6476 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6478 // This matches GCC's behavior.
6479 if (Base.InvalidBase && !SubobjectOnly)
6482 // If we're not examining only the subobject, then we reset to a complete
6483 // object designator
6485 // If Type is 1 and we've lost track of the subobject, just find the complete
6486 // object instead. (If Type is 3, that's not correct behavior and we should
6487 // return 0 instead.)
6489 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
6490 QualType T = getObjectType(End.getLValueBase());
6492 End.Designator.setInvalid();
6494 End.Designator = SubobjectDesignator(T);
6495 End.Offset = CharUnits::Zero();
6499 // If it is not possible to determine which objects ptr points to at compile
6500 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6501 // and (size_t) 0 for type 2 or 3.
6502 if (End.Designator.Invalid)
6505 // According to the GCC documentation, we want the size of the subobject
6506 // denoted by the pointer. But that's not quite right -- what we actually
6507 // want is the size of the immediately-enclosing array, if there is one.
6508 int64_t AmountToAdd = 1;
6509 if (End.Designator.MostDerivedIsArrayElement &&
6510 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6511 // We got a pointer to an array. Step to its end.
6512 AmountToAdd = End.Designator.MostDerivedArraySize -
6513 End.Designator.Entries.back().ArrayIndex;
6514 } else if (End.Designator.isOnePastTheEnd()) {
6515 // We're already pointing at the end of the object.
6519 QualType PointeeType = End.Designator.MostDerivedType;
6520 assert(!PointeeType.isNull());
6521 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
6524 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6528 auto EndOffset = End.getLValueOffset();
6530 // The following is a moderately common idiom in C:
6532 // struct Foo { int a; char c[1]; };
6533 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6534 // strcpy(&F->c[0], Bar);
6536 // So, if we see that we're examining a 1-length (or 0-length) array at the
6537 // end of a struct with an unknown base, we give up instead of breaking code
6538 // that behaves this way. Note that we only do this when Type=1, because
6539 // Type=3 is a lower bound, so answering conservatively is fine.
6540 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6541 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6542 End.Designator.MostDerivedIsArrayElement &&
6543 End.Designator.MostDerivedArraySize < 2 &&
6544 isDesignatorAtObjectEnd(Info.Ctx, End))
6547 if (BaseOffset > EndOffset)
6548 return Success(0, E);
6550 return Success((EndOffset - BaseOffset).getQuantity(), E);
6553 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6557 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6558 return Success(Size, E);
6564 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6565 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6567 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6569 case Builtin::BI__builtin_object_size: {
6570 // The type was checked when we built the expression.
6572 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6573 assert(Type <= 3 && "unexpected type");
6575 if (TryEvaluateBuiltinObjectSize(E, Type))
6578 if (E->getArg(0)->HasSideEffects(Info.Ctx))
6579 return Success((Type & 2) ? 0 : -1, E);
6581 // Expression had no side effects, but we couldn't statically determine the
6582 // size of the referenced object.
6583 switch (Info.EvalMode) {
6584 case EvalInfo::EM_ConstantExpression:
6585 case EvalInfo::EM_PotentialConstantExpression:
6586 case EvalInfo::EM_ConstantFold:
6587 case EvalInfo::EM_EvaluateForOverflow:
6588 case EvalInfo::EM_IgnoreSideEffects:
6589 case EvalInfo::EM_DesignatorFold:
6590 // Leave it to IR generation.
6592 case EvalInfo::EM_ConstantExpressionUnevaluated:
6593 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6594 // Reduce it to a constant now.
6595 return Success((Type & 2) ? 0 : -1, E);
6599 case Builtin::BI__builtin_bswap16:
6600 case Builtin::BI__builtin_bswap32:
6601 case Builtin::BI__builtin_bswap64: {
6603 if (!EvaluateInteger(E->getArg(0), Val, Info))
6606 return Success(Val.byteSwap(), E);
6609 case Builtin::BI__builtin_classify_type:
6610 return Success(EvaluateBuiltinClassifyType(E), E);
6612 // FIXME: BI__builtin_clrsb
6613 // FIXME: BI__builtin_clrsbl
6614 // FIXME: BI__builtin_clrsbll
6616 case Builtin::BI__builtin_clz:
6617 case Builtin::BI__builtin_clzl:
6618 case Builtin::BI__builtin_clzll:
6619 case Builtin::BI__builtin_clzs: {
6621 if (!EvaluateInteger(E->getArg(0), Val, Info))
6626 return Success(Val.countLeadingZeros(), E);
6629 case Builtin::BI__builtin_constant_p:
6630 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6632 case Builtin::BI__builtin_ctz:
6633 case Builtin::BI__builtin_ctzl:
6634 case Builtin::BI__builtin_ctzll:
6635 case Builtin::BI__builtin_ctzs: {
6637 if (!EvaluateInteger(E->getArg(0), Val, Info))
6642 return Success(Val.countTrailingZeros(), E);
6645 case Builtin::BI__builtin_eh_return_data_regno: {
6646 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6647 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6648 return Success(Operand, E);
6651 case Builtin::BI__builtin_expect:
6652 return Visit(E->getArg(0));
6654 case Builtin::BI__builtin_ffs:
6655 case Builtin::BI__builtin_ffsl:
6656 case Builtin::BI__builtin_ffsll: {
6658 if (!EvaluateInteger(E->getArg(0), Val, Info))
6661 unsigned N = Val.countTrailingZeros();
6662 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6665 case Builtin::BI__builtin_fpclassify: {
6667 if (!EvaluateFloat(E->getArg(5), Val, Info))
6670 switch (Val.getCategory()) {
6671 case APFloat::fcNaN: Arg = 0; break;
6672 case APFloat::fcInfinity: Arg = 1; break;
6673 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6674 case APFloat::fcZero: Arg = 4; break;
6676 return Visit(E->getArg(Arg));
6679 case Builtin::BI__builtin_isinf_sign: {
6681 return EvaluateFloat(E->getArg(0), Val, Info) &&
6682 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6685 case Builtin::BI__builtin_isinf: {
6687 return EvaluateFloat(E->getArg(0), Val, Info) &&
6688 Success(Val.isInfinity() ? 1 : 0, E);
6691 case Builtin::BI__builtin_isfinite: {
6693 return EvaluateFloat(E->getArg(0), Val, Info) &&
6694 Success(Val.isFinite() ? 1 : 0, E);
6697 case Builtin::BI__builtin_isnan: {
6699 return EvaluateFloat(E->getArg(0), Val, Info) &&
6700 Success(Val.isNaN() ? 1 : 0, E);
6703 case Builtin::BI__builtin_isnormal: {
6705 return EvaluateFloat(E->getArg(0), Val, Info) &&
6706 Success(Val.isNormal() ? 1 : 0, E);
6709 case Builtin::BI__builtin_parity:
6710 case Builtin::BI__builtin_parityl:
6711 case Builtin::BI__builtin_parityll: {
6713 if (!EvaluateInteger(E->getArg(0), Val, Info))
6716 return Success(Val.countPopulation() % 2, E);
6719 case Builtin::BI__builtin_popcount:
6720 case Builtin::BI__builtin_popcountl:
6721 case Builtin::BI__builtin_popcountll: {
6723 if (!EvaluateInteger(E->getArg(0), Val, Info))
6726 return Success(Val.countPopulation(), E);
6729 case Builtin::BIstrlen:
6730 // A call to strlen is not a constant expression.
6731 if (Info.getLangOpts().CPlusPlus11)
6732 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6733 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6735 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6737 case Builtin::BI__builtin_strlen: {
6738 // As an extension, we support __builtin_strlen() as a constant expression,
6739 // and support folding strlen() to a constant.
6741 if (!EvaluatePointer(E->getArg(0), String, Info))
6744 // Fast path: if it's a string literal, search the string value.
6745 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6746 String.getLValueBase().dyn_cast<const Expr *>())) {
6747 // The string literal may have embedded null characters. Find the first
6748 // one and truncate there.
6749 StringRef Str = S->getBytes();
6750 int64_t Off = String.Offset.getQuantity();
6751 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6752 S->getCharByteWidth() == 1) {
6753 Str = Str.substr(Off);
6755 StringRef::size_type Pos = Str.find(0);
6756 if (Pos != StringRef::npos)
6757 Str = Str.substr(0, Pos);
6759 return Success(Str.size(), E);
6762 // Fall through to slow path to issue appropriate diagnostic.
6765 // Slow path: scan the bytes of the string looking for the terminating 0.
6766 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6767 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6769 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6773 return Success(Strlen, E);
6774 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6779 case Builtin::BI__atomic_always_lock_free:
6780 case Builtin::BI__atomic_is_lock_free:
6781 case Builtin::BI__c11_atomic_is_lock_free: {
6783 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6786 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6787 // of two less than the maximum inline atomic width, we know it is
6788 // lock-free. If the size isn't a power of two, or greater than the
6789 // maximum alignment where we promote atomics, we know it is not lock-free
6790 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6791 // the answer can only be determined at runtime; for example, 16-byte
6792 // atomics have lock-free implementations on some, but not all,
6793 // x86-64 processors.
6795 // Check power-of-two.
6796 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6797 if (Size.isPowerOfTwo()) {
6798 // Check against inlining width.
6799 unsigned InlineWidthBits =
6800 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6801 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6802 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6803 Size == CharUnits::One() ||
6804 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6805 Expr::NPC_NeverValueDependent))
6806 // OK, we will inline appropriately-aligned operations of this size,
6807 // and _Atomic(T) is appropriately-aligned.
6808 return Success(1, E);
6810 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6811 castAs<PointerType>()->getPointeeType();
6812 if (!PointeeType->isIncompleteType() &&
6813 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6814 // OK, we will inline operations on this object.
6815 return Success(1, E);
6820 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6821 Success(0, E) : Error(E);
6826 static bool HasSameBase(const LValue &A, const LValue &B) {
6827 if (!A.getLValueBase())
6828 return !B.getLValueBase();
6829 if (!B.getLValueBase())
6832 if (A.getLValueBase().getOpaqueValue() !=
6833 B.getLValueBase().getOpaqueValue()) {
6834 const Decl *ADecl = GetLValueBaseDecl(A);
6837 const Decl *BDecl = GetLValueBaseDecl(B);
6838 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6842 return IsGlobalLValue(A.getLValueBase()) ||
6843 A.getLValueCallIndex() == B.getLValueCallIndex();
6846 /// \brief Determine whether this is a pointer past the end of the complete
6847 /// object referred to by the lvalue.
6848 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6850 // A null pointer can be viewed as being "past the end" but we don't
6851 // choose to look at it that way here.
6852 if (!LV.getLValueBase())
6855 // If the designator is valid and refers to a subobject, we're not pointing
6857 if (!LV.getLValueDesignator().Invalid &&
6858 !LV.getLValueDesignator().isOnePastTheEnd())
6861 // A pointer to an incomplete type might be past-the-end if the type's size is
6862 // zero. We cannot tell because the type is incomplete.
6863 QualType Ty = getType(LV.getLValueBase());
6864 if (Ty->isIncompleteType())
6867 // We're a past-the-end pointer if we point to the byte after the object,
6868 // no matter what our type or path is.
6869 auto Size = Ctx.getTypeSizeInChars(Ty);
6870 return LV.getLValueOffset() == Size;
6875 /// \brief Data recursive integer evaluator of certain binary operators.
6877 /// We use a data recursive algorithm for binary operators so that we are able
6878 /// to handle extreme cases of chained binary operators without causing stack
6880 class DataRecursiveIntBinOpEvaluator {
6885 EvalResult() : Failed(false) { }
6887 void swap(EvalResult &RHS) {
6889 Failed = RHS.Failed;
6896 EvalResult LHSResult; // meaningful only for binary operator expression.
6897 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6901 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6902 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6903 J.StoredInfo = nullptr;
6906 void startSpeculativeEval(EvalInfo &Info) {
6907 OldEvalStatus = Info.EvalStatus;
6908 Info.EvalStatus.Diag = nullptr;
6913 StoredInfo->EvalStatus = OldEvalStatus;
6917 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
6918 Expr::EvalStatus OldEvalStatus;
6921 SmallVector<Job, 16> Queue;
6923 IntExprEvaluator &IntEval;
6925 APValue &FinalResult;
6928 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6929 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6931 /// \brief True if \param E is a binary operator that we are going to handle
6932 /// data recursively.
6933 /// We handle binary operators that are comma, logical, or that have operands
6934 /// with integral or enumeration type.
6935 static bool shouldEnqueue(const BinaryOperator *E) {
6936 return E->getOpcode() == BO_Comma ||
6938 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6939 E->getRHS()->getType()->isIntegralOrEnumerationType());
6942 bool Traverse(const BinaryOperator *E) {
6944 EvalResult PrevResult;
6945 while (!Queue.empty())
6946 process(PrevResult);
6948 if (PrevResult.Failed) return false;
6950 FinalResult.swap(PrevResult.Val);
6955 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6956 return IntEval.Success(Value, E, Result);
6958 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6959 return IntEval.Success(Value, E, Result);
6961 bool Error(const Expr *E) {
6962 return IntEval.Error(E);
6964 bool Error(const Expr *E, diag::kind D) {
6965 return IntEval.Error(E, D);
6968 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6969 return Info.CCEDiag(E, D);
6972 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6973 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6974 bool &SuppressRHSDiags);
6976 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6977 const BinaryOperator *E, APValue &Result);
6979 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6980 Result.Failed = !Evaluate(Result.Val, Info, E);
6982 Result.Val = APValue();
6985 void process(EvalResult &Result);
6987 void enqueue(const Expr *E) {
6988 E = E->IgnoreParens();
6989 Queue.resize(Queue.size()+1);
6991 Queue.back().Kind = Job::AnyExprKind;
6997 bool DataRecursiveIntBinOpEvaluator::
6998 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6999 bool &SuppressRHSDiags) {
7000 if (E->getOpcode() == BO_Comma) {
7001 // Ignore LHS but note if we could not evaluate it.
7002 if (LHSResult.Failed)
7003 return Info.noteSideEffect();
7007 if (E->isLogicalOp()) {
7009 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7010 // We were able to evaluate the LHS, see if we can get away with not
7011 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7012 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7013 Success(LHSAsBool, E, LHSResult.Val);
7014 return false; // Ignore RHS
7017 LHSResult.Failed = true;
7019 // Since we weren't able to evaluate the left hand side, it
7020 // must have had side effects.
7021 if (!Info.noteSideEffect())
7024 // We can't evaluate the LHS; however, sometimes the result
7025 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7026 // Don't ignore RHS and suppress diagnostics from this arm.
7027 SuppressRHSDiags = true;
7033 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7034 E->getRHS()->getType()->isIntegralOrEnumerationType());
7036 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
7037 return false; // Ignore RHS;
7042 bool DataRecursiveIntBinOpEvaluator::
7043 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7044 const BinaryOperator *E, APValue &Result) {
7045 if (E->getOpcode() == BO_Comma) {
7046 if (RHSResult.Failed)
7048 Result = RHSResult.Val;
7052 if (E->isLogicalOp()) {
7053 bool lhsResult, rhsResult;
7054 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7055 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7059 if (E->getOpcode() == BO_LOr)
7060 return Success(lhsResult || rhsResult, E, Result);
7062 return Success(lhsResult && rhsResult, E, Result);
7066 // We can't evaluate the LHS; however, sometimes the result
7067 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7068 if (rhsResult == (E->getOpcode() == BO_LOr))
7069 return Success(rhsResult, E, Result);
7076 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7077 E->getRHS()->getType()->isIntegralOrEnumerationType());
7079 if (LHSResult.Failed || RHSResult.Failed)
7082 const APValue &LHSVal = LHSResult.Val;
7083 const APValue &RHSVal = RHSResult.Val;
7085 // Handle cases like (unsigned long)&a + 4.
7086 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7088 CharUnits AdditionalOffset =
7089 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7090 if (E->getOpcode() == BO_Add)
7091 Result.getLValueOffset() += AdditionalOffset;
7093 Result.getLValueOffset() -= AdditionalOffset;
7097 // Handle cases like 4 + (unsigned long)&a
7098 if (E->getOpcode() == BO_Add &&
7099 RHSVal.isLValue() && LHSVal.isInt()) {
7101 Result.getLValueOffset() +=
7102 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
7106 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7107 // Handle (intptr_t)&&A - (intptr_t)&&B.
7108 if (!LHSVal.getLValueOffset().isZero() ||
7109 !RHSVal.getLValueOffset().isZero())
7111 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7112 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7113 if (!LHSExpr || !RHSExpr)
7115 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7116 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7117 if (!LHSAddrExpr || !RHSAddrExpr)
7119 // Make sure both labels come from the same function.
7120 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7121 RHSAddrExpr->getLabel()->getDeclContext())
7123 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7127 // All the remaining cases expect both operands to be an integer
7128 if (!LHSVal.isInt() || !RHSVal.isInt())
7131 // Set up the width and signedness manually, in case it can't be deduced
7132 // from the operation we're performing.
7133 // FIXME: Don't do this in the cases where we can deduce it.
7134 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7135 E->getType()->isUnsignedIntegerOrEnumerationType());
7136 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7137 RHSVal.getInt(), Value))
7139 return Success(Value, E, Result);
7142 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
7143 Job &job = Queue.back();
7146 case Job::AnyExprKind: {
7147 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7148 if (shouldEnqueue(Bop)) {
7149 job.Kind = Job::BinOpKind;
7150 enqueue(Bop->getLHS());
7155 EvaluateExpr(job.E, Result);
7160 case Job::BinOpKind: {
7161 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7162 bool SuppressRHSDiags = false;
7163 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
7167 if (SuppressRHSDiags)
7168 job.startSpeculativeEval(Info);
7169 job.LHSResult.swap(Result);
7170 job.Kind = Job::BinOpVisitedLHSKind;
7171 enqueue(Bop->getRHS());
7175 case Job::BinOpVisitedLHSKind: {
7176 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7179 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
7185 llvm_unreachable("Invalid Job::Kind!");
7188 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7189 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
7192 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7193 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
7195 QualType LHSTy = E->getLHS()->getType();
7196 QualType RHSTy = E->getRHS()->getType();
7198 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
7199 ComplexValue LHS, RHS;
7201 if (E->isAssignmentOp()) {
7203 EvaluateLValue(E->getLHS(), LV, Info);
7205 } else if (LHSTy->isRealFloatingType()) {
7206 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7208 LHS.makeComplexFloat();
7209 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7212 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7214 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7217 if (E->getRHS()->getType()->isRealFloatingType()) {
7218 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7220 RHS.makeComplexFloat();
7221 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7222 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7225 if (LHS.isComplexFloat()) {
7226 APFloat::cmpResult CR_r =
7227 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
7228 APFloat::cmpResult CR_i =
7229 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7231 if (E->getOpcode() == BO_EQ)
7232 return Success((CR_r == APFloat::cmpEqual &&
7233 CR_i == APFloat::cmpEqual), E);
7235 assert(E->getOpcode() == BO_NE &&
7236 "Invalid complex comparison.");
7237 return Success(((CR_r == APFloat::cmpGreaterThan ||
7238 CR_r == APFloat::cmpLessThan ||
7239 CR_r == APFloat::cmpUnordered) ||
7240 (CR_i == APFloat::cmpGreaterThan ||
7241 CR_i == APFloat::cmpLessThan ||
7242 CR_i == APFloat::cmpUnordered)), E);
7245 if (E->getOpcode() == BO_EQ)
7246 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7247 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7249 assert(E->getOpcode() == BO_NE &&
7250 "Invalid compex comparison.");
7251 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7252 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7257 if (LHSTy->isRealFloatingType() &&
7258 RHSTy->isRealFloatingType()) {
7259 APFloat RHS(0.0), LHS(0.0);
7261 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7262 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7265 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
7268 APFloat::cmpResult CR = LHS.compare(RHS);
7270 switch (E->getOpcode()) {
7272 llvm_unreachable("Invalid binary operator!");
7274 return Success(CR == APFloat::cmpLessThan, E);
7276 return Success(CR == APFloat::cmpGreaterThan, E);
7278 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
7280 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
7283 return Success(CR == APFloat::cmpEqual, E);
7285 return Success(CR == APFloat::cmpGreaterThan
7286 || CR == APFloat::cmpLessThan
7287 || CR == APFloat::cmpUnordered, E);
7291 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
7292 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
7293 LValue LHSValue, RHSValue;
7295 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7296 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7299 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7302 // Reject differing bases from the normal codepath; we special-case
7303 // comparisons to null.
7304 if (!HasSameBase(LHSValue, RHSValue)) {
7305 if (E->getOpcode() == BO_Sub) {
7306 // Handle &&A - &&B.
7307 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7309 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
7310 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
7311 if (!LHSExpr || !RHSExpr)
7313 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7314 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7315 if (!LHSAddrExpr || !RHSAddrExpr)
7317 // Make sure both labels come from the same function.
7318 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7319 RHSAddrExpr->getLabel()->getDeclContext())
7321 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
7323 // Inequalities and subtractions between unrelated pointers have
7324 // unspecified or undefined behavior.
7325 if (!E->isEqualityOp())
7327 // A constant address may compare equal to the address of a symbol.
7328 // The one exception is that address of an object cannot compare equal
7329 // to a null pointer constant.
7330 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7331 (!RHSValue.Base && !RHSValue.Offset.isZero()))
7333 // It's implementation-defined whether distinct literals will have
7334 // distinct addresses. In clang, the result of such a comparison is
7335 // unspecified, so it is not a constant expression. However, we do know
7336 // that the address of a literal will be non-null.
7337 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7338 LHSValue.Base && RHSValue.Base)
7340 // We can't tell whether weak symbols will end up pointing to the same
7342 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
7344 // We can't compare the address of the start of one object with the
7345 // past-the-end address of another object, per C++ DR1652.
7346 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7347 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7348 (RHSValue.Base && RHSValue.Offset.isZero() &&
7349 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7351 // We can't tell whether an object is at the same address as another
7352 // zero sized object.
7353 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7354 (LHSValue.Base && isZeroSized(RHSValue)))
7356 // Pointers with different bases cannot represent the same object.
7357 // (Note that clang defaults to -fmerge-all-constants, which can
7358 // lead to inconsistent results for comparisons involving the address
7359 // of a constant; this generally doesn't matter in practice.)
7360 return Success(E->getOpcode() == BO_NE, E);
7363 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7364 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7366 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7367 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7369 if (E->getOpcode() == BO_Sub) {
7370 // C++11 [expr.add]p6:
7371 // Unless both pointers point to elements of the same array object, or
7372 // one past the last element of the array object, the behavior is
7374 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7375 !AreElementsOfSameArray(getType(LHSValue.Base),
7376 LHSDesignator, RHSDesignator))
7377 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7379 QualType Type = E->getLHS()->getType();
7380 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7382 CharUnits ElementSize;
7383 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7386 // As an extension, a type may have zero size (empty struct or union in
7387 // C, array of zero length). Pointer subtraction in such cases has
7388 // undefined behavior, so is not constant.
7389 if (ElementSize.isZero()) {
7390 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7395 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7396 // and produce incorrect results when it overflows. Such behavior
7397 // appears to be non-conforming, but is common, so perhaps we should
7398 // assume the standard intended for such cases to be undefined behavior
7399 // and check for them.
7401 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7402 // overflow in the final conversion to ptrdiff_t.
7404 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7406 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7408 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7409 APSInt TrueResult = (LHS - RHS) / ElemSize;
7410 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7412 if (Result.extend(65) != TrueResult &&
7413 !HandleOverflow(Info, E, TrueResult, E->getType()))
7415 return Success(Result, E);
7418 // C++11 [expr.rel]p3:
7419 // Pointers to void (after pointer conversions) can be compared, with a
7420 // result defined as follows: If both pointers represent the same
7421 // address or are both the null pointer value, the result is true if the
7422 // operator is <= or >= and false otherwise; otherwise the result is
7424 // We interpret this as applying to pointers to *cv* void.
7425 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7426 E->isRelationalOp())
7427 CCEDiag(E, diag::note_constexpr_void_comparison);
7429 // C++11 [expr.rel]p2:
7430 // - If two pointers point to non-static data members of the same object,
7431 // or to subobjects or array elements fo such members, recursively, the
7432 // pointer to the later declared member compares greater provided the
7433 // two members have the same access control and provided their class is
7436 // - Otherwise pointer comparisons are unspecified.
7437 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7438 E->isRelationalOp()) {
7441 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7442 RHSDesignator, WasArrayIndex);
7443 // At the point where the designators diverge, the comparison has a
7444 // specified value if:
7445 // - we are comparing array indices
7446 // - we are comparing fields of a union, or fields with the same access
7447 // Otherwise, the result is unspecified and thus the comparison is not a
7448 // constant expression.
7449 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7450 Mismatch < RHSDesignator.Entries.size()) {
7451 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7452 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7454 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7456 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7457 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7458 << RF->getParent() << RF;
7460 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7461 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7462 << LF->getParent() << LF;
7463 else if (!LF->getParent()->isUnion() &&
7464 LF->getAccess() != RF->getAccess())
7465 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7466 << LF << LF->getAccess() << RF << RF->getAccess()
7471 // The comparison here must be unsigned, and performed with the same
7472 // width as the pointer.
7473 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7474 uint64_t CompareLHS = LHSOffset.getQuantity();
7475 uint64_t CompareRHS = RHSOffset.getQuantity();
7476 assert(PtrSize <= 64 && "Unexpected pointer width");
7477 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7481 // If there is a base and this is a relational operator, we can only
7482 // compare pointers within the object in question; otherwise, the result
7483 // depends on where the object is located in memory.
7484 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7485 QualType BaseTy = getType(LHSValue.Base);
7486 if (BaseTy->isIncompleteType())
7488 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7489 uint64_t OffsetLimit = Size.getQuantity();
7490 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7494 switch (E->getOpcode()) {
7495 default: llvm_unreachable("missing comparison operator");
7496 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7497 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7498 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7499 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7500 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7501 case BO_NE: return Success(CompareLHS != CompareRHS, E);
7506 if (LHSTy->isMemberPointerType()) {
7507 assert(E->isEqualityOp() && "unexpected member pointer operation");
7508 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7510 MemberPtr LHSValue, RHSValue;
7512 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7513 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7516 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7519 // C++11 [expr.eq]p2:
7520 // If both operands are null, they compare equal. Otherwise if only one is
7521 // null, they compare unequal.
7522 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7523 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7524 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7527 // Otherwise if either is a pointer to a virtual member function, the
7528 // result is unspecified.
7529 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7530 if (MD->isVirtual())
7531 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7532 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7533 if (MD->isVirtual())
7534 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7536 // Otherwise they compare equal if and only if they would refer to the
7537 // same member of the same most derived object or the same subobject if
7538 // they were dereferenced with a hypothetical object of the associated
7540 bool Equal = LHSValue == RHSValue;
7541 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7544 if (LHSTy->isNullPtrType()) {
7545 assert(E->isComparisonOp() && "unexpected nullptr operation");
7546 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7547 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7548 // are compared, the result is true of the operator is <=, >= or ==, and
7550 BinaryOperator::Opcode Opcode = E->getOpcode();
7551 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7554 assert((!LHSTy->isIntegralOrEnumerationType() ||
7555 !RHSTy->isIntegralOrEnumerationType()) &&
7556 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7557 // We can't continue from here for non-integral types.
7558 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7561 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7562 /// a result as the expression's type.
7563 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7564 const UnaryExprOrTypeTraitExpr *E) {
7565 switch(E->getKind()) {
7566 case UETT_AlignOf: {
7567 if (E->isArgumentType())
7568 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7570 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7573 case UETT_VecStep: {
7574 QualType Ty = E->getTypeOfArgument();
7576 if (Ty->isVectorType()) {
7577 unsigned n = Ty->castAs<VectorType>()->getNumElements();
7579 // The vec_step built-in functions that take a 3-component
7580 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7584 return Success(n, E);
7586 return Success(1, E);
7590 QualType SrcTy = E->getTypeOfArgument();
7591 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7592 // the result is the size of the referenced type."
7593 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7594 SrcTy = Ref->getPointeeType();
7597 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7599 return Success(Sizeof, E);
7601 case UETT_OpenMPRequiredSimdAlign:
7602 assert(E->isArgumentType());
7604 Info.Ctx.toCharUnitsFromBits(
7605 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7610 llvm_unreachable("unknown expr/type trait");
7613 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7615 unsigned n = OOE->getNumComponents();
7618 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7619 for (unsigned i = 0; i != n; ++i) {
7620 OffsetOfNode ON = OOE->getComponent(i);
7621 switch (ON.getKind()) {
7622 case OffsetOfNode::Array: {
7623 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7625 if (!EvaluateInteger(Idx, IdxResult, Info))
7627 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7630 CurrentType = AT->getElementType();
7631 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7632 Result += IdxResult.getSExtValue() * ElementSize;
7636 case OffsetOfNode::Field: {
7637 FieldDecl *MemberDecl = ON.getField();
7638 const RecordType *RT = CurrentType->getAs<RecordType>();
7641 RecordDecl *RD = RT->getDecl();
7642 if (RD->isInvalidDecl()) return false;
7643 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7644 unsigned i = MemberDecl->getFieldIndex();
7645 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7646 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7647 CurrentType = MemberDecl->getType().getNonReferenceType();
7651 case OffsetOfNode::Identifier:
7652 llvm_unreachable("dependent __builtin_offsetof");
7654 case OffsetOfNode::Base: {
7655 CXXBaseSpecifier *BaseSpec = ON.getBase();
7656 if (BaseSpec->isVirtual())
7659 // Find the layout of the class whose base we are looking into.
7660 const RecordType *RT = CurrentType->getAs<RecordType>();
7663 RecordDecl *RD = RT->getDecl();
7664 if (RD->isInvalidDecl()) return false;
7665 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7667 // Find the base class itself.
7668 CurrentType = BaseSpec->getType();
7669 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7673 // Add the offset to the base.
7674 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7679 return Success(Result, OOE);
7682 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7683 switch (E->getOpcode()) {
7685 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7689 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7690 // If so, we could clear the diagnostic ID.
7691 return Visit(E->getSubExpr());
7693 // The result is just the value.
7694 return Visit(E->getSubExpr());
7696 if (!Visit(E->getSubExpr()))
7698 if (!Result.isInt()) return Error(E);
7699 const APSInt &Value = Result.getInt();
7700 if (Value.isSigned() && Value.isMinSignedValue() &&
7701 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7704 return Success(-Value, E);
7707 if (!Visit(E->getSubExpr()))
7709 if (!Result.isInt()) return Error(E);
7710 return Success(~Result.getInt(), E);
7714 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7716 return Success(!bres, E);
7721 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7722 /// result type is integer.
7723 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7724 const Expr *SubExpr = E->getSubExpr();
7725 QualType DestType = E->getType();
7726 QualType SrcType = SubExpr->getType();
7728 switch (E->getCastKind()) {
7729 case CK_BaseToDerived:
7730 case CK_DerivedToBase:
7731 case CK_UncheckedDerivedToBase:
7734 case CK_ArrayToPointerDecay:
7735 case CK_FunctionToPointerDecay:
7736 case CK_NullToPointer:
7737 case CK_NullToMemberPointer:
7738 case CK_BaseToDerivedMemberPointer:
7739 case CK_DerivedToBaseMemberPointer:
7740 case CK_ReinterpretMemberPointer:
7741 case CK_ConstructorConversion:
7742 case CK_IntegralToPointer:
7744 case CK_VectorSplat:
7745 case CK_IntegralToFloating:
7746 case CK_FloatingCast:
7747 case CK_CPointerToObjCPointerCast:
7748 case CK_BlockPointerToObjCPointerCast:
7749 case CK_AnyPointerToBlockPointerCast:
7750 case CK_ObjCObjectLValueCast:
7751 case CK_FloatingRealToComplex:
7752 case CK_FloatingComplexToReal:
7753 case CK_FloatingComplexCast:
7754 case CK_FloatingComplexToIntegralComplex:
7755 case CK_IntegralRealToComplex:
7756 case CK_IntegralComplexCast:
7757 case CK_IntegralComplexToFloatingComplex:
7758 case CK_BuiltinFnToFnPtr:
7759 case CK_ZeroToOCLEvent:
7760 case CK_NonAtomicToAtomic:
7761 case CK_AddressSpaceConversion:
7762 llvm_unreachable("invalid cast kind for integral value");
7766 case CK_LValueBitCast:
7767 case CK_ARCProduceObject:
7768 case CK_ARCConsumeObject:
7769 case CK_ARCReclaimReturnedObject:
7770 case CK_ARCExtendBlockObject:
7771 case CK_CopyAndAutoreleaseBlockObject:
7774 case CK_UserDefinedConversion:
7775 case CK_LValueToRValue:
7776 case CK_AtomicToNonAtomic:
7778 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7780 case CK_MemberPointerToBoolean:
7781 case CK_PointerToBoolean:
7782 case CK_IntegralToBoolean:
7783 case CK_FloatingToBoolean:
7784 case CK_BooleanToSignedIntegral:
7785 case CK_FloatingComplexToBoolean:
7786 case CK_IntegralComplexToBoolean: {
7788 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7790 uint64_t IntResult = BoolResult;
7791 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
7792 IntResult = (uint64_t)-1;
7793 return Success(IntResult, E);
7796 case CK_IntegralCast: {
7797 if (!Visit(SubExpr))
7800 if (!Result.isInt()) {
7801 // Allow casts of address-of-label differences if they are no-ops
7802 // or narrowing. (The narrowing case isn't actually guaranteed to
7803 // be constant-evaluatable except in some narrow cases which are hard
7804 // to detect here. We let it through on the assumption the user knows
7805 // what they are doing.)
7806 if (Result.isAddrLabelDiff())
7807 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7808 // Only allow casts of lvalues if they are lossless.
7809 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7812 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7813 Result.getInt()), E);
7816 case CK_PointerToIntegral: {
7817 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7820 if (!EvaluatePointer(SubExpr, LV, Info))
7823 if (LV.getLValueBase()) {
7824 // Only allow based lvalue casts if they are lossless.
7825 // FIXME: Allow a larger integer size than the pointer size, and allow
7826 // narrowing back down to pointer width in subsequent integral casts.
7827 // FIXME: Check integer type's active bits, not its type size.
7828 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7831 LV.Designator.setInvalid();
7832 LV.moveInto(Result);
7836 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7838 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7841 case CK_IntegralComplexToReal: {
7843 if (!EvaluateComplex(SubExpr, C, Info))
7845 return Success(C.getComplexIntReal(), E);
7848 case CK_FloatingToIntegral: {
7850 if (!EvaluateFloat(SubExpr, F, Info))
7854 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7856 return Success(Value, E);
7860 llvm_unreachable("unknown cast resulting in integral value");
7863 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7864 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7866 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7868 if (!LV.isComplexInt())
7870 return Success(LV.getComplexIntReal(), E);
7873 return Visit(E->getSubExpr());
7876 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7877 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7879 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7881 if (!LV.isComplexInt())
7883 return Success(LV.getComplexIntImag(), E);
7886 VisitIgnoredValue(E->getSubExpr());
7887 return Success(0, E);
7890 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7891 return Success(E->getPackLength(), E);
7894 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7895 return Success(E->getValue(), E);
7898 //===----------------------------------------------------------------------===//
7900 //===----------------------------------------------------------------------===//
7903 class FloatExprEvaluator
7904 : public ExprEvaluatorBase<FloatExprEvaluator> {
7907 FloatExprEvaluator(EvalInfo &info, APFloat &result)
7908 : ExprEvaluatorBaseTy(info), Result(result) {}
7910 bool Success(const APValue &V, const Expr *e) {
7911 Result = V.getFloat();
7915 bool ZeroInitialization(const Expr *E) {
7916 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7920 bool VisitCallExpr(const CallExpr *E);
7922 bool VisitUnaryOperator(const UnaryOperator *E);
7923 bool VisitBinaryOperator(const BinaryOperator *E);
7924 bool VisitFloatingLiteral(const FloatingLiteral *E);
7925 bool VisitCastExpr(const CastExpr *E);
7927 bool VisitUnaryReal(const UnaryOperator *E);
7928 bool VisitUnaryImag(const UnaryOperator *E);
7930 // FIXME: Missing: array subscript of vector, member of vector
7932 } // end anonymous namespace
7934 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7935 assert(E->isRValue() && E->getType()->isRealFloatingType());
7936 return FloatExprEvaluator(Info, Result).Visit(E);
7939 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7943 llvm::APFloat &Result) {
7944 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7945 if (!S) return false;
7947 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7951 // Treat empty strings as if they were zero.
7952 if (S->getString().empty())
7953 fill = llvm::APInt(32, 0);
7954 else if (S->getString().getAsInteger(0, fill))
7957 if (Context.getTargetInfo().isNan2008()) {
7959 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7961 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7963 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7964 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7965 // a different encoding to what became a standard in 2008, and for pre-
7966 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7967 // sNaN. This is now known as "legacy NaN" encoding.
7969 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7971 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7977 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7978 switch (E->getBuiltinCallee()) {
7980 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7982 case Builtin::BI__builtin_huge_val:
7983 case Builtin::BI__builtin_huge_valf:
7984 case Builtin::BI__builtin_huge_vall:
7985 case Builtin::BI__builtin_inf:
7986 case Builtin::BI__builtin_inff:
7987 case Builtin::BI__builtin_infl: {
7988 const llvm::fltSemantics &Sem =
7989 Info.Ctx.getFloatTypeSemantics(E->getType());
7990 Result = llvm::APFloat::getInf(Sem);
7994 case Builtin::BI__builtin_nans:
7995 case Builtin::BI__builtin_nansf:
7996 case Builtin::BI__builtin_nansl:
7997 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8002 case Builtin::BI__builtin_nan:
8003 case Builtin::BI__builtin_nanf:
8004 case Builtin::BI__builtin_nanl:
8005 // If this is __builtin_nan() turn this into a nan, otherwise we
8006 // can't constant fold it.
8007 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8012 case Builtin::BI__builtin_fabs:
8013 case Builtin::BI__builtin_fabsf:
8014 case Builtin::BI__builtin_fabsl:
8015 if (!EvaluateFloat(E->getArg(0), Result, Info))
8018 if (Result.isNegative())
8019 Result.changeSign();
8022 // FIXME: Builtin::BI__builtin_powi
8023 // FIXME: Builtin::BI__builtin_powif
8024 // FIXME: Builtin::BI__builtin_powil
8026 case Builtin::BI__builtin_copysign:
8027 case Builtin::BI__builtin_copysignf:
8028 case Builtin::BI__builtin_copysignl: {
8030 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8031 !EvaluateFloat(E->getArg(1), RHS, Info))
8033 Result.copySign(RHS);
8039 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8040 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8042 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8044 Result = CV.FloatReal;
8048 return Visit(E->getSubExpr());
8051 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8052 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8054 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8056 Result = CV.FloatImag;
8060 VisitIgnoredValue(E->getSubExpr());
8061 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8062 Result = llvm::APFloat::getZero(Sem);
8066 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8067 switch (E->getOpcode()) {
8068 default: return Error(E);
8070 return EvaluateFloat(E->getSubExpr(), Result, Info);
8072 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8074 Result.changeSign();
8079 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8080 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8081 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8084 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8085 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
8087 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8088 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
8091 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8092 Result = E->getValue();
8096 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8097 const Expr* SubExpr = E->getSubExpr();
8099 switch (E->getCastKind()) {
8101 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8103 case CK_IntegralToFloating: {
8105 return EvaluateInteger(SubExpr, IntResult, Info) &&
8106 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8107 E->getType(), Result);
8110 case CK_FloatingCast: {
8111 if (!Visit(SubExpr))
8113 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8117 case CK_FloatingComplexToReal: {
8119 if (!EvaluateComplex(SubExpr, V, Info))
8121 Result = V.getComplexFloatReal();
8127 //===----------------------------------------------------------------------===//
8128 // Complex Evaluation (for float and integer)
8129 //===----------------------------------------------------------------------===//
8132 class ComplexExprEvaluator
8133 : public ExprEvaluatorBase<ComplexExprEvaluator> {
8134 ComplexValue &Result;
8137 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
8138 : ExprEvaluatorBaseTy(info), Result(Result) {}
8140 bool Success(const APValue &V, const Expr *e) {
8145 bool ZeroInitialization(const Expr *E);
8147 //===--------------------------------------------------------------------===//
8149 //===--------------------------------------------------------------------===//
8151 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
8152 bool VisitCastExpr(const CastExpr *E);
8153 bool VisitBinaryOperator(const BinaryOperator *E);
8154 bool VisitUnaryOperator(const UnaryOperator *E);
8155 bool VisitInitListExpr(const InitListExpr *E);
8157 } // end anonymous namespace
8159 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8161 assert(E->isRValue() && E->getType()->isAnyComplexType());
8162 return ComplexExprEvaluator(Info, Result).Visit(E);
8165 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
8166 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
8167 if (ElemTy->isRealFloatingType()) {
8168 Result.makeComplexFloat();
8169 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8170 Result.FloatReal = Zero;
8171 Result.FloatImag = Zero;
8173 Result.makeComplexInt();
8174 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8175 Result.IntReal = Zero;
8176 Result.IntImag = Zero;
8181 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8182 const Expr* SubExpr = E->getSubExpr();
8184 if (SubExpr->getType()->isRealFloatingType()) {
8185 Result.makeComplexFloat();
8186 APFloat &Imag = Result.FloatImag;
8187 if (!EvaluateFloat(SubExpr, Imag, Info))
8190 Result.FloatReal = APFloat(Imag.getSemantics());
8193 assert(SubExpr->getType()->isIntegerType() &&
8194 "Unexpected imaginary literal.");
8196 Result.makeComplexInt();
8197 APSInt &Imag = Result.IntImag;
8198 if (!EvaluateInteger(SubExpr, Imag, Info))
8201 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8206 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
8208 switch (E->getCastKind()) {
8210 case CK_BaseToDerived:
8211 case CK_DerivedToBase:
8212 case CK_UncheckedDerivedToBase:
8215 case CK_ArrayToPointerDecay:
8216 case CK_FunctionToPointerDecay:
8217 case CK_NullToPointer:
8218 case CK_NullToMemberPointer:
8219 case CK_BaseToDerivedMemberPointer:
8220 case CK_DerivedToBaseMemberPointer:
8221 case CK_MemberPointerToBoolean:
8222 case CK_ReinterpretMemberPointer:
8223 case CK_ConstructorConversion:
8224 case CK_IntegralToPointer:
8225 case CK_PointerToIntegral:
8226 case CK_PointerToBoolean:
8228 case CK_VectorSplat:
8229 case CK_IntegralCast:
8230 case CK_BooleanToSignedIntegral:
8231 case CK_IntegralToBoolean:
8232 case CK_IntegralToFloating:
8233 case CK_FloatingToIntegral:
8234 case CK_FloatingToBoolean:
8235 case CK_FloatingCast:
8236 case CK_CPointerToObjCPointerCast:
8237 case CK_BlockPointerToObjCPointerCast:
8238 case CK_AnyPointerToBlockPointerCast:
8239 case CK_ObjCObjectLValueCast:
8240 case CK_FloatingComplexToReal:
8241 case CK_FloatingComplexToBoolean:
8242 case CK_IntegralComplexToReal:
8243 case CK_IntegralComplexToBoolean:
8244 case CK_ARCProduceObject:
8245 case CK_ARCConsumeObject:
8246 case CK_ARCReclaimReturnedObject:
8247 case CK_ARCExtendBlockObject:
8248 case CK_CopyAndAutoreleaseBlockObject:
8249 case CK_BuiltinFnToFnPtr:
8250 case CK_ZeroToOCLEvent:
8251 case CK_NonAtomicToAtomic:
8252 case CK_AddressSpaceConversion:
8253 llvm_unreachable("invalid cast kind for complex value");
8255 case CK_LValueToRValue:
8256 case CK_AtomicToNonAtomic:
8258 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8261 case CK_LValueBitCast:
8262 case CK_UserDefinedConversion:
8265 case CK_FloatingRealToComplex: {
8266 APFloat &Real = Result.FloatReal;
8267 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
8270 Result.makeComplexFloat();
8271 Result.FloatImag = APFloat(Real.getSemantics());
8275 case CK_FloatingComplexCast: {
8276 if (!Visit(E->getSubExpr()))
8279 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8281 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8283 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8284 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
8287 case CK_FloatingComplexToIntegralComplex: {
8288 if (!Visit(E->getSubExpr()))
8291 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8293 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8294 Result.makeComplexInt();
8295 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8296 To, Result.IntReal) &&
8297 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8298 To, Result.IntImag);
8301 case CK_IntegralRealToComplex: {
8302 APSInt &Real = Result.IntReal;
8303 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8306 Result.makeComplexInt();
8307 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8311 case CK_IntegralComplexCast: {
8312 if (!Visit(E->getSubExpr()))
8315 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8317 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8319 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8320 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
8324 case CK_IntegralComplexToFloatingComplex: {
8325 if (!Visit(E->getSubExpr()))
8328 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
8330 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
8331 Result.makeComplexFloat();
8332 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8333 To, Result.FloatReal) &&
8334 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8335 To, Result.FloatImag);
8339 llvm_unreachable("unknown cast resulting in complex value");
8342 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8343 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8344 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8346 // Track whether the LHS or RHS is real at the type system level. When this is
8347 // the case we can simplify our evaluation strategy.
8348 bool LHSReal = false, RHSReal = false;
8351 if (E->getLHS()->getType()->isRealFloatingType()) {
8353 APFloat &Real = Result.FloatReal;
8354 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8356 Result.makeComplexFloat();
8357 Result.FloatImag = APFloat(Real.getSemantics());
8360 LHSOK = Visit(E->getLHS());
8362 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
8366 if (E->getRHS()->getType()->isRealFloatingType()) {
8368 APFloat &Real = RHS.FloatReal;
8369 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8371 RHS.makeComplexFloat();
8372 RHS.FloatImag = APFloat(Real.getSemantics());
8373 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8376 assert(!(LHSReal && RHSReal) &&
8377 "Cannot have both operands of a complex operation be real.");
8378 switch (E->getOpcode()) {
8379 default: return Error(E);
8381 if (Result.isComplexFloat()) {
8382 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8383 APFloat::rmNearestTiesToEven);
8385 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8387 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8388 APFloat::rmNearestTiesToEven);
8390 Result.getComplexIntReal() += RHS.getComplexIntReal();
8391 Result.getComplexIntImag() += RHS.getComplexIntImag();
8395 if (Result.isComplexFloat()) {
8396 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8397 APFloat::rmNearestTiesToEven);
8399 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8400 Result.getComplexFloatImag().changeSign();
8401 } else if (!RHSReal) {
8402 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8403 APFloat::rmNearestTiesToEven);
8406 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8407 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8411 if (Result.isComplexFloat()) {
8412 // This is an implementation of complex multiplication according to the
8413 // constraints laid out in C11 Annex G. The implemantion uses the
8414 // following naming scheme:
8415 // (a + ib) * (c + id)
8416 ComplexValue LHS = Result;
8417 APFloat &A = LHS.getComplexFloatReal();
8418 APFloat &B = LHS.getComplexFloatImag();
8419 APFloat &C = RHS.getComplexFloatReal();
8420 APFloat &D = RHS.getComplexFloatImag();
8421 APFloat &ResR = Result.getComplexFloatReal();
8422 APFloat &ResI = Result.getComplexFloatImag();
8424 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8427 } else if (RHSReal) {
8431 // In the fully general case, we need to handle NaNs and infinities
8439 if (ResR.isNaN() && ResI.isNaN()) {
8440 bool Recalc = false;
8441 if (A.isInfinity() || B.isInfinity()) {
8442 A = APFloat::copySign(
8443 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8444 B = APFloat::copySign(
8445 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8447 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8449 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8452 if (C.isInfinity() || D.isInfinity()) {
8453 C = APFloat::copySign(
8454 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8455 D = APFloat::copySign(
8456 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8458 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8460 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8463 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8464 AD.isInfinity() || BC.isInfinity())) {
8466 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8468 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8470 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8472 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8476 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8477 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8482 ComplexValue LHS = Result;
8483 Result.getComplexIntReal() =
8484 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8485 LHS.getComplexIntImag() * RHS.getComplexIntImag());
8486 Result.getComplexIntImag() =
8487 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8488 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8492 if (Result.isComplexFloat()) {
8493 // This is an implementation of complex division according to the
8494 // constraints laid out in C11 Annex G. The implemantion uses the
8495 // following naming scheme:
8496 // (a + ib) / (c + id)
8497 ComplexValue LHS = Result;
8498 APFloat &A = LHS.getComplexFloatReal();
8499 APFloat &B = LHS.getComplexFloatImag();
8500 APFloat &C = RHS.getComplexFloatReal();
8501 APFloat &D = RHS.getComplexFloatImag();
8502 APFloat &ResR = Result.getComplexFloatReal();
8503 APFloat &ResI = Result.getComplexFloatImag();
8509 // No real optimizations we can do here, stub out with zero.
8510 B = APFloat::getZero(A.getSemantics());
8513 APFloat MaxCD = maxnum(abs(C), abs(D));
8514 if (MaxCD.isFinite()) {
8515 DenomLogB = ilogb(MaxCD);
8516 C = scalbn(C, -DenomLogB);
8517 D = scalbn(D, -DenomLogB);
8519 APFloat Denom = C * C + D * D;
8520 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8521 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8522 if (ResR.isNaN() && ResI.isNaN()) {
8523 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8524 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8525 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8526 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8528 A = APFloat::copySign(
8529 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8530 B = APFloat::copySign(
8531 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8532 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8533 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8534 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8535 C = APFloat::copySign(
8536 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8537 D = APFloat::copySign(
8538 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8539 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8540 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8545 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8546 return Error(E, diag::note_expr_divide_by_zero);
8548 ComplexValue LHS = Result;
8549 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8550 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8551 Result.getComplexIntReal() =
8552 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8553 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8554 Result.getComplexIntImag() =
8555 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8556 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8564 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8565 // Get the operand value into 'Result'.
8566 if (!Visit(E->getSubExpr()))
8569 switch (E->getOpcode()) {
8575 // The result is always just the subexpr.
8578 if (Result.isComplexFloat()) {
8579 Result.getComplexFloatReal().changeSign();
8580 Result.getComplexFloatImag().changeSign();
8583 Result.getComplexIntReal() = -Result.getComplexIntReal();
8584 Result.getComplexIntImag() = -Result.getComplexIntImag();
8588 if (Result.isComplexFloat())
8589 Result.getComplexFloatImag().changeSign();
8591 Result.getComplexIntImag() = -Result.getComplexIntImag();
8596 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8597 if (E->getNumInits() == 2) {
8598 if (E->getType()->isComplexType()) {
8599 Result.makeComplexFloat();
8600 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8602 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8605 Result.makeComplexInt();
8606 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8608 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8613 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8616 //===----------------------------------------------------------------------===//
8617 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8618 // implicit conversion.
8619 //===----------------------------------------------------------------------===//
8622 class AtomicExprEvaluator :
8623 public ExprEvaluatorBase<AtomicExprEvaluator> {
8626 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8627 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8629 bool Success(const APValue &V, const Expr *E) {
8634 bool ZeroInitialization(const Expr *E) {
8635 ImplicitValueInitExpr VIE(
8636 E->getType()->castAs<AtomicType>()->getValueType());
8637 return Evaluate(Result, Info, &VIE);
8640 bool VisitCastExpr(const CastExpr *E) {
8641 switch (E->getCastKind()) {
8643 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8644 case CK_NonAtomicToAtomic:
8645 return Evaluate(Result, Info, E->getSubExpr());
8649 } // end anonymous namespace
8651 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8652 assert(E->isRValue() && E->getType()->isAtomicType());
8653 return AtomicExprEvaluator(Info, Result).Visit(E);
8656 //===----------------------------------------------------------------------===//
8657 // Void expression evaluation, primarily for a cast to void on the LHS of a
8659 //===----------------------------------------------------------------------===//
8662 class VoidExprEvaluator
8663 : public ExprEvaluatorBase<VoidExprEvaluator> {
8665 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8667 bool Success(const APValue &V, const Expr *e) { return true; }
8669 bool VisitCastExpr(const CastExpr *E) {
8670 switch (E->getCastKind()) {
8672 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8674 VisitIgnoredValue(E->getSubExpr());
8679 bool VisitCallExpr(const CallExpr *E) {
8680 switch (E->getBuiltinCallee()) {
8682 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8683 case Builtin::BI__assume:
8684 case Builtin::BI__builtin_assume:
8685 // The argument is not evaluated!
8690 } // end anonymous namespace
8692 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8693 assert(E->isRValue() && E->getType()->isVoidType());
8694 return VoidExprEvaluator(Info).Visit(E);
8697 //===----------------------------------------------------------------------===//
8698 // Top level Expr::EvaluateAsRValue method.
8699 //===----------------------------------------------------------------------===//
8701 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
8702 // In C, function designators are not lvalues, but we evaluate them as if they
8704 QualType T = E->getType();
8705 if (E->isGLValue() || T->isFunctionType()) {
8707 if (!EvaluateLValue(E, LV, Info))
8709 LV.moveInto(Result);
8710 } else if (T->isVectorType()) {
8711 if (!EvaluateVector(E, Result, Info))
8713 } else if (T->isIntegralOrEnumerationType()) {
8714 if (!IntExprEvaluator(Info, Result).Visit(E))
8716 } else if (T->hasPointerRepresentation()) {
8718 if (!EvaluatePointer(E, LV, Info))
8720 LV.moveInto(Result);
8721 } else if (T->isRealFloatingType()) {
8722 llvm::APFloat F(0.0);
8723 if (!EvaluateFloat(E, F, Info))
8725 Result = APValue(F);
8726 } else if (T->isAnyComplexType()) {
8728 if (!EvaluateComplex(E, C, Info))
8731 } else if (T->isMemberPointerType()) {
8733 if (!EvaluateMemberPointer(E, P, Info))
8737 } else if (T->isArrayType()) {
8739 LV.set(E, Info.CurrentCall->Index);
8740 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8741 if (!EvaluateArray(E, LV, Value, Info))
8744 } else if (T->isRecordType()) {
8746 LV.set(E, Info.CurrentCall->Index);
8747 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8748 if (!EvaluateRecord(E, LV, Value, Info))
8751 } else if (T->isVoidType()) {
8752 if (!Info.getLangOpts().CPlusPlus11)
8753 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8755 if (!EvaluateVoid(E, Info))
8757 } else if (T->isAtomicType()) {
8758 if (!EvaluateAtomic(E, Result, Info))
8760 } else if (Info.getLangOpts().CPlusPlus11) {
8761 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8764 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8771 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8772 /// cases, the in-place evaluation is essential, since later initializers for
8773 /// an object can indirectly refer to subobjects which were initialized earlier.
8774 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8775 const Expr *E, bool AllowNonLiteralTypes) {
8776 assert(!E->isValueDependent());
8778 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8781 if (E->isRValue()) {
8782 // Evaluate arrays and record types in-place, so that later initializers can
8783 // refer to earlier-initialized members of the object.
8784 if (E->getType()->isArrayType())
8785 return EvaluateArray(E, This, Result, Info);
8786 else if (E->getType()->isRecordType())
8787 return EvaluateRecord(E, This, Result, Info);
8790 // For any other type, in-place evaluation is unimportant.
8791 return Evaluate(Result, Info, E);
8794 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8795 /// lvalue-to-rvalue cast if it is an lvalue.
8796 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8797 if (E->getType().isNull())
8800 if (!CheckLiteralType(Info, E))
8803 if (!::Evaluate(Result, Info, E))
8806 if (E->isGLValue()) {
8808 LV.setFrom(Info.Ctx, Result);
8809 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8813 // Check this core constant expression is a constant expression.
8814 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8817 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8818 const ASTContext &Ctx, bool &IsConst) {
8819 // Fast-path evaluations of integer literals, since we sometimes see files
8820 // containing vast quantities of these.
8821 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8822 Result.Val = APValue(APSInt(L->getValue(),
8823 L->getType()->isUnsignedIntegerType()));
8828 // This case should be rare, but we need to check it before we check on
8830 if (Exp->getType().isNull()) {
8835 // FIXME: Evaluating values of large array and record types can cause
8836 // performance problems. Only do so in C++11 for now.
8837 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8838 Exp->getType()->isRecordType()) &&
8839 !Ctx.getLangOpts().CPlusPlus11) {
8847 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8848 /// any crazy technique (that has nothing to do with language standards) that
8849 /// we want to. If this function returns true, it returns the folded constant
8850 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8851 /// will be applied to the result.
8852 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8854 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8857 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8858 return ::EvaluateAsRValue(Info, this, Result.Val);
8861 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8862 const ASTContext &Ctx) const {
8864 return EvaluateAsRValue(Scratch, Ctx) &&
8865 HandleConversionToBool(Scratch.Val, Result);
8868 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
8869 Expr::SideEffectsKind SEK) {
8870 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
8871 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
8874 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8875 SideEffectsKind AllowSideEffects) const {
8876 if (!getType()->isIntegralOrEnumerationType())
8879 EvalResult ExprResult;
8880 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8881 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
8884 Result = ExprResult.Val.getInt();
8888 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8889 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8892 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8893 !CheckLValueConstantExpression(Info, getExprLoc(),
8894 Ctx.getLValueReferenceType(getType()), LV))
8897 LV.moveInto(Result.Val);
8901 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8903 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8904 // FIXME: Evaluating initializers for large array and record types can cause
8905 // performance problems. Only do so in C++11 for now.
8906 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8907 !Ctx.getLangOpts().CPlusPlus11)
8910 Expr::EvalStatus EStatus;
8911 EStatus.Diag = &Notes;
8913 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
8914 ? EvalInfo::EM_ConstantExpression
8915 : EvalInfo::EM_ConstantFold);
8916 InitInfo.setEvaluatingDecl(VD, Value);
8921 // C++11 [basic.start.init]p2:
8922 // Variables with static storage duration or thread storage duration shall be
8923 // zero-initialized before any other initialization takes place.
8924 // This behavior is not present in C.
8925 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8926 !VD->getType()->isReferenceType()) {
8927 ImplicitValueInitExpr VIE(VD->getType());
8928 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8929 /*AllowNonLiteralTypes=*/true))
8933 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8934 /*AllowNonLiteralTypes=*/true) ||
8935 EStatus.HasSideEffects)
8938 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8942 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8943 /// constant folded, but discard the result.
8944 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
8946 return EvaluateAsRValue(Result, Ctx) &&
8947 !hasUnacceptableSideEffect(Result, SEK);
8950 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8951 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8952 EvalResult EvalResult;
8953 EvalResult.Diag = Diag;
8954 bool Result = EvaluateAsRValue(EvalResult, Ctx);
8956 assert(Result && "Could not evaluate expression");
8957 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8959 return EvalResult.Val.getInt();
8962 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8964 EvalResult EvalResult;
8965 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8966 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8967 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8971 bool Expr::EvalResult::isGlobalLValue() const {
8972 assert(Val.isLValue());
8973 return IsGlobalLValue(Val.getLValueBase());
8977 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8978 /// an integer constant expression.
8980 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8983 // CheckICE - This function does the fundamental ICE checking: the returned
8984 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8985 // and a (possibly null) SourceLocation indicating the location of the problem.
8987 // Note that to reduce code duplication, this helper does no evaluation
8988 // itself; the caller checks whether the expression is evaluatable, and
8989 // in the rare cases where CheckICE actually cares about the evaluated
8990 // value, it calls into Evalute.
8995 /// This expression is an ICE.
8997 /// This expression is not an ICE, but if it isn't evaluated, it's
8998 /// a legal subexpression for an ICE. This return value is used to handle
8999 /// the comma operator in C99 mode, and non-constant subexpressions.
9000 IK_ICEIfUnevaluated,
9001 /// This expression is not an ICE, and is not a legal subexpression for one.
9009 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9014 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9016 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9018 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9019 Expr::EvalResult EVResult;
9020 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9021 !EVResult.Val.isInt())
9022 return ICEDiag(IK_NotICE, E->getLocStart());
9027 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9028 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9029 if (!E->getType()->isIntegralOrEnumerationType())
9030 return ICEDiag(IK_NotICE, E->getLocStart());
9032 switch (E->getStmtClass()) {
9033 #define ABSTRACT_STMT(Node)
9034 #define STMT(Node, Base) case Expr::Node##Class:
9035 #define EXPR(Node, Base)
9036 #include "clang/AST/StmtNodes.inc"
9037 case Expr::PredefinedExprClass:
9038 case Expr::FloatingLiteralClass:
9039 case Expr::ImaginaryLiteralClass:
9040 case Expr::StringLiteralClass:
9041 case Expr::ArraySubscriptExprClass:
9042 case Expr::OMPArraySectionExprClass:
9043 case Expr::MemberExprClass:
9044 case Expr::CompoundAssignOperatorClass:
9045 case Expr::CompoundLiteralExprClass:
9046 case Expr::ExtVectorElementExprClass:
9047 case Expr::DesignatedInitExprClass:
9048 case Expr::NoInitExprClass:
9049 case Expr::DesignatedInitUpdateExprClass:
9050 case Expr::ImplicitValueInitExprClass:
9051 case Expr::ParenListExprClass:
9052 case Expr::VAArgExprClass:
9053 case Expr::AddrLabelExprClass:
9054 case Expr::StmtExprClass:
9055 case Expr::CXXMemberCallExprClass:
9056 case Expr::CUDAKernelCallExprClass:
9057 case Expr::CXXDynamicCastExprClass:
9058 case Expr::CXXTypeidExprClass:
9059 case Expr::CXXUuidofExprClass:
9060 case Expr::MSPropertyRefExprClass:
9061 case Expr::MSPropertySubscriptExprClass:
9062 case Expr::CXXNullPtrLiteralExprClass:
9063 case Expr::UserDefinedLiteralClass:
9064 case Expr::CXXThisExprClass:
9065 case Expr::CXXThrowExprClass:
9066 case Expr::CXXNewExprClass:
9067 case Expr::CXXDeleteExprClass:
9068 case Expr::CXXPseudoDestructorExprClass:
9069 case Expr::UnresolvedLookupExprClass:
9070 case Expr::TypoExprClass:
9071 case Expr::DependentScopeDeclRefExprClass:
9072 case Expr::CXXConstructExprClass:
9073 case Expr::CXXStdInitializerListExprClass:
9074 case Expr::CXXBindTemporaryExprClass:
9075 case Expr::ExprWithCleanupsClass:
9076 case Expr::CXXTemporaryObjectExprClass:
9077 case Expr::CXXUnresolvedConstructExprClass:
9078 case Expr::CXXDependentScopeMemberExprClass:
9079 case Expr::UnresolvedMemberExprClass:
9080 case Expr::ObjCStringLiteralClass:
9081 case Expr::ObjCBoxedExprClass:
9082 case Expr::ObjCArrayLiteralClass:
9083 case Expr::ObjCDictionaryLiteralClass:
9084 case Expr::ObjCEncodeExprClass:
9085 case Expr::ObjCMessageExprClass:
9086 case Expr::ObjCSelectorExprClass:
9087 case Expr::ObjCProtocolExprClass:
9088 case Expr::ObjCIvarRefExprClass:
9089 case Expr::ObjCPropertyRefExprClass:
9090 case Expr::ObjCSubscriptRefExprClass:
9091 case Expr::ObjCIsaExprClass:
9092 case Expr::ShuffleVectorExprClass:
9093 case Expr::ConvertVectorExprClass:
9094 case Expr::BlockExprClass:
9095 case Expr::NoStmtClass:
9096 case Expr::OpaqueValueExprClass:
9097 case Expr::PackExpansionExprClass:
9098 case Expr::SubstNonTypeTemplateParmPackExprClass:
9099 case Expr::FunctionParmPackExprClass:
9100 case Expr::AsTypeExprClass:
9101 case Expr::ObjCIndirectCopyRestoreExprClass:
9102 case Expr::MaterializeTemporaryExprClass:
9103 case Expr::PseudoObjectExprClass:
9104 case Expr::AtomicExprClass:
9105 case Expr::LambdaExprClass:
9106 case Expr::CXXFoldExprClass:
9107 case Expr::CoawaitExprClass:
9108 case Expr::CoyieldExprClass:
9109 return ICEDiag(IK_NotICE, E->getLocStart());
9111 case Expr::InitListExprClass: {
9112 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9113 // form "T x = { a };" is equivalent to "T x = a;".
9114 // Unless we're initializing a reference, T is a scalar as it is known to be
9115 // of integral or enumeration type.
9117 if (cast<InitListExpr>(E)->getNumInits() == 1)
9118 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9119 return ICEDiag(IK_NotICE, E->getLocStart());
9122 case Expr::SizeOfPackExprClass:
9123 case Expr::GNUNullExprClass:
9124 // GCC considers the GNU __null value to be an integral constant expression.
9127 case Expr::SubstNonTypeTemplateParmExprClass:
9129 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9131 case Expr::ParenExprClass:
9132 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
9133 case Expr::GenericSelectionExprClass:
9134 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
9135 case Expr::IntegerLiteralClass:
9136 case Expr::CharacterLiteralClass:
9137 case Expr::ObjCBoolLiteralExprClass:
9138 case Expr::CXXBoolLiteralExprClass:
9139 case Expr::CXXScalarValueInitExprClass:
9140 case Expr::TypeTraitExprClass:
9141 case Expr::ArrayTypeTraitExprClass:
9142 case Expr::ExpressionTraitExprClass:
9143 case Expr::CXXNoexceptExprClass:
9145 case Expr::CallExprClass:
9146 case Expr::CXXOperatorCallExprClass: {
9147 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9148 // constant expressions, but they can never be ICEs because an ICE cannot
9149 // contain an operand of (pointer to) function type.
9150 const CallExpr *CE = cast<CallExpr>(E);
9151 if (CE->getBuiltinCallee())
9152 return CheckEvalInICE(E, Ctx);
9153 return ICEDiag(IK_NotICE, E->getLocStart());
9155 case Expr::DeclRefExprClass: {
9156 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9158 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
9159 if (Ctx.getLangOpts().CPlusPlus &&
9160 D && IsConstNonVolatile(D->getType())) {
9161 // Parameter variables are never constants. Without this check,
9162 // getAnyInitializer() can find a default argument, which leads
9164 if (isa<ParmVarDecl>(D))
9165 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9168 // A variable of non-volatile const-qualified integral or enumeration
9169 // type initialized by an ICE can be used in ICEs.
9170 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
9171 if (!Dcl->getType()->isIntegralOrEnumerationType())
9172 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9175 // Look for a declaration of this variable that has an initializer, and
9176 // check whether it is an ICE.
9177 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9180 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9183 return ICEDiag(IK_NotICE, E->getLocStart());
9185 case Expr::UnaryOperatorClass: {
9186 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9187 switch (Exp->getOpcode()) {
9195 // C99 6.6/3 allows increment and decrement within unevaluated
9196 // subexpressions of constant expressions, but they can never be ICEs
9197 // because an ICE cannot contain an lvalue operand.
9198 return ICEDiag(IK_NotICE, E->getLocStart());
9206 return CheckICE(Exp->getSubExpr(), Ctx);
9209 // OffsetOf falls through here.
9211 case Expr::OffsetOfExprClass: {
9212 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9213 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9214 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9215 // compliance: we should warn earlier for offsetof expressions with
9216 // array subscripts that aren't ICEs, and if the array subscripts
9217 // are ICEs, the value of the offsetof must be an integer constant.
9218 return CheckEvalInICE(E, Ctx);
9220 case Expr::UnaryExprOrTypeTraitExprClass: {
9221 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9222 if ((Exp->getKind() == UETT_SizeOf) &&
9223 Exp->getTypeOfArgument()->isVariableArrayType())
9224 return ICEDiag(IK_NotICE, E->getLocStart());
9227 case Expr::BinaryOperatorClass: {
9228 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9229 switch (Exp->getOpcode()) {
9243 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9244 // constant expressions, but they can never be ICEs because an ICE cannot
9245 // contain an lvalue operand.
9246 return ICEDiag(IK_NotICE, E->getLocStart());
9265 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9266 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
9267 if (Exp->getOpcode() == BO_Div ||
9268 Exp->getOpcode() == BO_Rem) {
9269 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
9270 // we don't evaluate one.
9271 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
9272 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
9274 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9275 if (REval.isSigned() && REval.isAllOnesValue()) {
9276 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
9277 if (LEval.isMinSignedValue())
9278 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9282 if (Exp->getOpcode() == BO_Comma) {
9283 if (Ctx.getLangOpts().C99) {
9284 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9285 // if it isn't evaluated.
9286 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9287 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9289 // In both C89 and C++, commas in ICEs are illegal.
9290 return ICEDiag(IK_NotICE, E->getLocStart());
9293 return Worst(LHSResult, RHSResult);
9297 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9298 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
9299 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
9300 // Rare case where the RHS has a comma "side-effect"; we need
9301 // to actually check the condition to see whether the side
9302 // with the comma is evaluated.
9303 if ((Exp->getOpcode() == BO_LAnd) !=
9304 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
9309 return Worst(LHSResult, RHSResult);
9313 case Expr::ImplicitCastExprClass:
9314 case Expr::CStyleCastExprClass:
9315 case Expr::CXXFunctionalCastExprClass:
9316 case Expr::CXXStaticCastExprClass:
9317 case Expr::CXXReinterpretCastExprClass:
9318 case Expr::CXXConstCastExprClass:
9319 case Expr::ObjCBridgedCastExprClass: {
9320 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
9321 if (isa<ExplicitCastExpr>(E)) {
9322 if (const FloatingLiteral *FL
9323 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9324 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9325 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9326 APSInt IgnoredVal(DestWidth, !DestSigned);
9328 // If the value does not fit in the destination type, the behavior is
9329 // undefined, so we are not required to treat it as a constant
9331 if (FL->getValue().convertToInteger(IgnoredVal,
9332 llvm::APFloat::rmTowardZero,
9333 &Ignored) & APFloat::opInvalidOp)
9334 return ICEDiag(IK_NotICE, E->getLocStart());
9338 switch (cast<CastExpr>(E)->getCastKind()) {
9339 case CK_LValueToRValue:
9340 case CK_AtomicToNonAtomic:
9341 case CK_NonAtomicToAtomic:
9343 case CK_IntegralToBoolean:
9344 case CK_IntegralCast:
9345 return CheckICE(SubExpr, Ctx);
9347 return ICEDiag(IK_NotICE, E->getLocStart());
9350 case Expr::BinaryConditionalOperatorClass: {
9351 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9352 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
9353 if (CommonResult.Kind == IK_NotICE) return CommonResult;
9354 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9355 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9356 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9357 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
9358 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
9361 case Expr::ConditionalOperatorClass: {
9362 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9363 // If the condition (ignoring parens) is a __builtin_constant_p call,
9364 // then only the true side is actually considered in an integer constant
9365 // expression, and it is fully evaluated. This is an important GNU
9366 // extension. See GCC PR38377 for discussion.
9367 if (const CallExpr *CallCE
9368 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
9369 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
9370 return CheckEvalInICE(E, Ctx);
9371 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
9372 if (CondResult.Kind == IK_NotICE)
9375 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9376 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9378 if (TrueResult.Kind == IK_NotICE)
9380 if (FalseResult.Kind == IK_NotICE)
9382 if (CondResult.Kind == IK_ICEIfUnevaluated)
9384 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
9386 // Rare case where the diagnostics depend on which side is evaluated
9387 // Note that if we get here, CondResult is 0, and at least one of
9388 // TrueResult and FalseResult is non-zero.
9389 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
9393 case Expr::CXXDefaultArgExprClass:
9394 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
9395 case Expr::CXXDefaultInitExprClass:
9396 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
9397 case Expr::ChooseExprClass: {
9398 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9402 llvm_unreachable("Invalid StmtClass!");
9405 /// Evaluate an expression as a C++11 integral constant expression.
9406 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
9408 llvm::APSInt *Value,
9409 SourceLocation *Loc) {
9410 if (!E->getType()->isIntegralOrEnumerationType()) {
9411 if (Loc) *Loc = E->getExprLoc();
9416 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9419 if (!Result.isInt()) {
9420 if (Loc) *Loc = E->getExprLoc();
9424 if (Value) *Value = Result.getInt();
9428 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9429 SourceLocation *Loc) const {
9430 if (Ctx.getLangOpts().CPlusPlus11)
9431 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9433 ICEDiag D = CheckICE(this, Ctx);
9434 if (D.Kind != IK_ICE) {
9435 if (Loc) *Loc = D.Loc;
9441 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9442 SourceLocation *Loc, bool isEvaluated) const {
9443 if (Ctx.getLangOpts().CPlusPlus11)
9444 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9446 if (!isIntegerConstantExpr(Ctx, Loc))
9448 // The only possible side-effects here are due to UB discovered in the
9449 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9450 // required to treat the expression as an ICE, so we produce the folded
9452 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
9453 llvm_unreachable("ICE cannot be evaluated!");
9457 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
9458 return CheckICE(this, Ctx).Kind == IK_ICE;
9461 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
9462 SourceLocation *Loc) const {
9463 // We support this checking in C++98 mode in order to diagnose compatibility
9465 assert(Ctx.getLangOpts().CPlusPlus);
9467 // Build evaluation settings.
9468 Expr::EvalStatus Status;
9469 SmallVector<PartialDiagnosticAt, 8> Diags;
9470 Status.Diag = &Diags;
9471 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9474 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9476 if (!Diags.empty()) {
9477 IsConstExpr = false;
9478 if (Loc) *Loc = Diags[0].first;
9479 } else if (!IsConstExpr) {
9480 // FIXME: This shouldn't happen.
9481 if (Loc) *Loc = getExprLoc();
9487 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9488 const FunctionDecl *Callee,
9489 ArrayRef<const Expr*> Args) const {
9490 Expr::EvalStatus Status;
9491 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9493 ArgVector ArgValues(Args.size());
9494 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9496 if ((*I)->isValueDependent() ||
9497 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9498 // If evaluation fails, throw away the argument entirely.
9499 ArgValues[I - Args.begin()] = APValue();
9500 if (Info.EvalStatus.HasSideEffects)
9504 // Build fake call to Callee.
9505 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9507 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9510 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
9512 PartialDiagnosticAt> &Diags) {
9513 // FIXME: It would be useful to check constexpr function templates, but at the
9514 // moment the constant expression evaluator cannot cope with the non-rigorous
9515 // ASTs which we build for dependent expressions.
9516 if (FD->isDependentContext())
9519 Expr::EvalStatus Status;
9520 Status.Diag = &Diags;
9522 EvalInfo Info(FD->getASTContext(), Status,
9523 EvalInfo::EM_PotentialConstantExpression);
9525 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9526 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9528 // Fabricate an arbitrary expression on the stack and pretend that it
9529 // is a temporary being used as the 'this' pointer.
9531 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9532 This.set(&VIE, Info.CurrentCall->Index);
9534 ArrayRef<const Expr*> Args;
9536 SourceLocation Loc = FD->getLocation();
9539 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9540 // Evaluate the call as a constant initializer, to allow the construction
9541 // of objects of non-literal types.
9542 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9543 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
9545 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9546 Args, FD->getBody(), Info, Scratch, nullptr);
9548 return Diags.empty();
9551 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9552 const FunctionDecl *FD,
9554 PartialDiagnosticAt> &Diags) {
9555 Expr::EvalStatus Status;
9556 Status.Diag = &Diags;
9558 EvalInfo Info(FD->getASTContext(), Status,
9559 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9561 // Fabricate a call stack frame to give the arguments a plausible cover story.
9562 ArrayRef<const Expr*> Args;
9563 ArgVector ArgValues(0);
9564 bool Success = EvaluateArgs(Args, ArgValues, Info);
9567 "Failed to set up arguments for potential constant evaluation");
9568 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9570 APValue ResultScratch;
9571 Evaluate(ResultScratch, Info, E);
9572 return Diags.empty();
9575 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9576 unsigned Type) const {
9577 if (!getType()->isPointerType())
9580 Expr::EvalStatus Status;
9581 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9582 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);