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 rules only, at the moment), or, if folding failed too,
27 // 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*>())
66 return B.get<const Expr*>()->getType();
69 /// Get an LValue path entry, which is known to not be an array index, as a
70 /// field or base class.
72 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
73 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
80 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
81 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
85 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
86 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
88 /// Determine whether this LValue path entry for a base class names a virtual
90 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
91 return getAsBaseOrMember(E).getInt();
94 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
113 MostDerivedLength = I + 1;
114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
117 MostDerivedLength = I + 1;
119 // Path[I] describes a base class.
123 return MostDerivedLength;
126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
129 CSK_This, CSK_Real, CSK_Imag
132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
142 /// The length of the path to the most-derived object of which this is a
144 unsigned MostDerivedPathLength : 30;
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
153 typedef APValue::LValuePathEntry PathEntry;
155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
158 SubobjectDesignator() : Invalid(true) {}
160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
198 return !isOnePastTheEnd();
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
207 Entry.ArrayIndex = 0;
208 Entries.push_back(Entry);
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
215 /// Update this designator to refer to the given base or member of this
217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
221 Entries.push_back(Entry);
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
243 /// Add N to the address of this subobject.
244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
247 Entries.back().ArrayIndex += N;
248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
272 /// Parent - The caller of this stack frame.
273 CallStackFrame *Caller;
275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
281 /// Index - The call index of this call.
284 /// This - The binding for the this pointer in this call, if any.
287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
293 typedef std::map<const void*, APValue> MapTy;
294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
310 Frame.This = NewThis;
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
316 CallStackFrame &Frame;
317 const LValue *OldThis;
320 /// A partial diagnostic which we might know in advance that we are not going
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
329 OptionalDiagnostic &operator<<(const T &v) {
335 OptionalDiagnostic &operator<<(const APSInt &I) {
337 SmallVector<char, 32> Buffer;
339 *Diag << StringRef(Buffer.data(), Buffer.size());
344 OptionalDiagnostic &operator<<(const APFloat &F) {
346 SmallVector<char, 32> Buffer;
348 *Diag << StringRef(Buffer.data(), Buffer.size());
354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
383 /// BottomFrame - The frame in which evaluation started. This must be
384 /// initialized after CurrentCall and CallStackDepth.
385 CallStackFrame BottomFrame;
387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
402 bool CheckingPotentialConstantExpression;
404 bool IntOverflowCheckMode;
406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
417 EvaluatingDeclValue = &Value;
420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
422 bool CheckCallLimit(SourceLocation Loc) {
423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
461 /// Diagnose that the evaluation cannot be folded.
462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
464 unsigned ExtraNotes = 0) {
465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
468 if (EvalStatus.Diag) {
469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
473 if (CheckingPotentialConstantExpression)
476 HasActiveDiagnostic = true;
477 EvalStatus.Diag->clear();
478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
480 if (!CheckingPotentialConstantExpression)
482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
484 HasActiveDiagnostic = false;
485 return OptionalDiagnostic();
488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
499 /// Diagnose that the evaluation does not produce a C++11 core constant
501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
503 = diag::note_invalid_subexpr_in_const_expr,
504 unsigned ExtraNotes = 0) {
505 // Don't override a previous diagnostic.
506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
508 return OptionalDiagnostic();
510 return Diag(Loc, DiagId, ExtraNotes);
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
559 Expr::EvalStatus Old;
562 SpeculativeEvaluationRAII(EvalInfo &Info,
563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
573 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
577 if (isOnePastTheEnd()) {
578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
586 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
589 Info.CCEDiag(E, diag::note_constexpr_array_index)
590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
593 Info.CCEDiag(E, diag::note_constexpr_array_index)
594 << static_cast<int>(N) << /*non-array*/ 1;
598 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
607 CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
613 /// Produce a string describing the given constexpr call.
614 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
621 Out << *Frame->Callee << '(';
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
625 if (ArgIndex > (unsigned)IsMemberCall)
628 const ParmVarDecl *Param = *I;
629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
639 void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
662 SmallVector<char, 128> Buffer;
663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
670 struct ComplexValue {
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
690 void moveInto(APValue &v) const {
691 if (isComplexFloat())
692 v = APValue(FloatReal, FloatImag);
694 v = APValue(IntReal, IntImag);
696 void setFrom(const APValue &v) {
697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
711 APValue::LValueBase Base;
714 SubobjectDesignator Designator;
716 const APValue::LValueBase getLValueBase() const { return Base; }
717 CharUnits &getLValueOffset() { return Offset; }
718 const CharUnits &getLValueOffset() const { return Offset; }
719 unsigned getLValueCallIndex() const { return CallIndex; }
720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
730 void setFrom(ASTContext &Ctx, const APValue &V) {
731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
734 CallIndex = V.getLValueCallIndex();
735 Designator = SubobjectDesignator(Ctx, V);
738 void set(APValue::LValueBase B, unsigned I = 0) {
740 Offset = CharUnits::Zero();
742 Designator = SubobjectDesignator(getType(B));
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
754 Designator.setInvalid();
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
765 if (!Info.getLangOpts().CPlusPlus11)
766 Designator.setInvalid();
767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
813 void setFrom(const APValue &V) {
814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
830 /// Perform a cast towards the class of the Decl (either up or down the
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
859 if (!castBack(Derived))
862 DeclAndIsDerivedMember.setInt(false);
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
875 return castBack(Base);
879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
885 return LHS.Path == RHS.Path;
888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
896 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
897 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
901 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
903 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
905 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
906 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
907 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
909 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
910 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
912 //===----------------------------------------------------------------------===//
914 //===----------------------------------------------------------------------===//
916 /// Evaluate an expression to see if it had side-effects, and discard its
918 /// \return \c true if the caller should keep evaluating.
919 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
921 if (!Evaluate(Scratch, Info, E)) {
922 Info.EvalStatus.HasSideEffects = true;
923 return Info.keepEvaluatingAfterFailure();
928 /// Should this call expression be treated as a string literal?
929 static bool IsStringLiteralCall(const CallExpr *E) {
930 unsigned Builtin = E->isBuiltinCall();
931 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
932 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
935 static bool IsGlobalLValue(APValue::LValueBase B) {
936 // C++11 [expr.const]p3 An address constant expression is a prvalue core
937 // constant expression of pointer type that evaluates to...
939 // ... a null pointer value, or a prvalue core constant expression of type
943 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
944 // ... the address of an object with static storage duration,
945 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
946 return VD->hasGlobalStorage();
947 // ... the address of a function,
948 return isa<FunctionDecl>(D);
951 const Expr *E = B.get<const Expr*>();
952 switch (E->getStmtClass()) {
955 case Expr::CompoundLiteralExprClass: {
956 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
957 return CLE->isFileScope() && CLE->isLValue();
959 // A string literal has static storage duration.
960 case Expr::StringLiteralClass:
961 case Expr::PredefinedExprClass:
962 case Expr::ObjCStringLiteralClass:
963 case Expr::ObjCEncodeExprClass:
964 case Expr::CXXTypeidExprClass:
965 case Expr::CXXUuidofExprClass:
967 case Expr::CallExprClass:
968 return IsStringLiteralCall(cast<CallExpr>(E));
969 // For GCC compatibility, &&label has static storage duration.
970 case Expr::AddrLabelExprClass:
972 // A Block literal expression may be used as the initialization value for
973 // Block variables at global or local static scope.
974 case Expr::BlockExprClass:
975 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
976 case Expr::ImplicitValueInitExprClass:
978 // We can never form an lvalue with an implicit value initialization as its
979 // base through expression evaluation, so these only appear in one case: the
980 // implicit variable declaration we invent when checking whether a constexpr
981 // constructor can produce a constant expression. We must assume that such
982 // an expression might be a global lvalue.
987 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
988 assert(Base && "no location for a null lvalue");
989 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
991 Info.Note(VD->getLocation(), diag::note_declared_at);
993 Info.Note(Base.get<const Expr*>()->getExprLoc(),
994 diag::note_constexpr_temporary_here);
997 /// Check that this reference or pointer core constant expression is a valid
998 /// value for an address or reference constant expression. Return true if we
999 /// can fold this expression, whether or not it's a constant expression.
1000 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1001 QualType Type, const LValue &LVal) {
1002 bool IsReferenceType = Type->isReferenceType();
1004 APValue::LValueBase Base = LVal.getLValueBase();
1005 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1007 // Check that the object is a global. Note that the fake 'this' object we
1008 // manufacture when checking potential constant expressions is conservatively
1009 // assumed to be global here.
1010 if (!IsGlobalLValue(Base)) {
1011 if (Info.getLangOpts().CPlusPlus11) {
1012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1013 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1014 << IsReferenceType << !Designator.Entries.empty()
1016 NoteLValueLocation(Info, Base);
1020 // Don't allow references to temporaries to escape.
1023 assert((Info.CheckingPotentialConstantExpression ||
1024 LVal.getLValueCallIndex() == 0) &&
1025 "have call index for global lvalue");
1027 // Check if this is a thread-local variable.
1028 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1029 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1030 if (Var->getTLSKind())
1035 // Allow address constant expressions to be past-the-end pointers. This is
1036 // an extension: the standard requires them to point to an object.
1037 if (!IsReferenceType)
1040 // A reference constant expression must refer to an object.
1042 // FIXME: diagnostic
1047 // Does this refer one past the end of some object?
1048 if (Designator.isOnePastTheEnd()) {
1049 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1050 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1051 << !Designator.Entries.empty() << !!VD << VD;
1052 NoteLValueLocation(Info, Base);
1058 /// Check that this core constant expression is of literal type, and if not,
1059 /// produce an appropriate diagnostic.
1060 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1061 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1064 // Prvalue constant expressions must be of literal types.
1065 if (Info.getLangOpts().CPlusPlus11)
1066 Info.Diag(E, diag::note_constexpr_nonliteral)
1069 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1073 /// Check that this core constant expression value is a valid value for a
1074 /// constant expression. If not, report an appropriate diagnostic. Does not
1075 /// check that the expression is of literal type.
1076 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1077 QualType Type, const APValue &Value) {
1078 // Core issue 1454: For a literal constant expression of array or class type,
1079 // each subobject of its value shall have been initialized by a constant
1081 if (Value.isArray()) {
1082 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1083 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1084 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1085 Value.getArrayInitializedElt(I)))
1088 if (!Value.hasArrayFiller())
1090 return CheckConstantExpression(Info, DiagLoc, EltTy,
1091 Value.getArrayFiller());
1093 if (Value.isUnion() && Value.getUnionField()) {
1094 return CheckConstantExpression(Info, DiagLoc,
1095 Value.getUnionField()->getType(),
1096 Value.getUnionValue());
1098 if (Value.isStruct()) {
1099 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1100 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1101 unsigned BaseIndex = 0;
1102 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1103 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1104 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1105 Value.getStructBase(BaseIndex)))
1109 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1111 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1112 Value.getStructField(I->getFieldIndex())))
1117 if (Value.isLValue()) {
1119 LVal.setFrom(Info.Ctx, Value);
1120 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1123 // Everything else is fine.
1127 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1128 return LVal.Base.dyn_cast<const ValueDecl*>();
1131 static bool IsLiteralLValue(const LValue &Value) {
1132 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
1135 static bool IsWeakLValue(const LValue &Value) {
1136 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1137 return Decl && Decl->isWeak();
1140 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1141 // A null base expression indicates a null pointer. These are always
1142 // evaluatable, and they are false unless the offset is zero.
1143 if (!Value.getLValueBase()) {
1144 Result = !Value.getLValueOffset().isZero();
1148 // We have a non-null base. These are generally known to be true, but if it's
1149 // a weak declaration it can be null at runtime.
1151 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1152 return !Decl || !Decl->isWeak();
1155 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1156 switch (Val.getKind()) {
1157 case APValue::Uninitialized:
1160 Result = Val.getInt().getBoolValue();
1162 case APValue::Float:
1163 Result = !Val.getFloat().isZero();
1165 case APValue::ComplexInt:
1166 Result = Val.getComplexIntReal().getBoolValue() ||
1167 Val.getComplexIntImag().getBoolValue();
1169 case APValue::ComplexFloat:
1170 Result = !Val.getComplexFloatReal().isZero() ||
1171 !Val.getComplexFloatImag().isZero();
1173 case APValue::LValue:
1174 return EvalPointerValueAsBool(Val, Result);
1175 case APValue::MemberPointer:
1176 Result = Val.getMemberPointerDecl();
1178 case APValue::Vector:
1179 case APValue::Array:
1180 case APValue::Struct:
1181 case APValue::Union:
1182 case APValue::AddrLabelDiff:
1186 llvm_unreachable("unknown APValue kind");
1189 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1191 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1193 if (!Evaluate(Val, Info, E))
1195 return HandleConversionToBool(Val, Result);
1198 template<typename T>
1199 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1200 const T &SrcValue, QualType DestType) {
1201 Info.CCEDiag(E, diag::note_constexpr_overflow)
1202 << SrcValue << DestType;
1205 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1206 QualType SrcType, const APFloat &Value,
1207 QualType DestType, APSInt &Result) {
1208 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1209 // Determine whether we are converting to unsigned or signed.
1210 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1212 Result = APSInt(DestWidth, !DestSigned);
1214 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1215 & APFloat::opInvalidOp)
1216 HandleOverflow(Info, E, Value, DestType);
1220 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1221 QualType SrcType, QualType DestType,
1223 APFloat Value = Result;
1225 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1226 APFloat::rmNearestTiesToEven, &ignored)
1227 & APFloat::opOverflow)
1228 HandleOverflow(Info, E, Value, DestType);
1232 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1233 QualType DestType, QualType SrcType,
1235 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1236 APSInt Result = Value;
1237 // Figure out if this is a truncate, extend or noop cast.
1238 // If the input is signed, do a sign extend, noop, or truncate.
1239 Result = Result.extOrTrunc(DestWidth);
1240 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1244 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1245 QualType SrcType, const APSInt &Value,
1246 QualType DestType, APFloat &Result) {
1247 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1248 if (Result.convertFromAPInt(Value, Value.isSigned(),
1249 APFloat::rmNearestTiesToEven)
1250 & APFloat::opOverflow)
1251 HandleOverflow(Info, E, Value, DestType);
1255 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1258 if (!Evaluate(SVal, Info, E))
1261 Res = SVal.getInt();
1264 if (SVal.isFloat()) {
1265 Res = SVal.getFloat().bitcastToAPInt();
1268 if (SVal.isVector()) {
1269 QualType VecTy = E->getType();
1270 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1271 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1272 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1273 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1274 Res = llvm::APInt::getNullValue(VecSize);
1275 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1276 APValue &Elt = SVal.getVectorElt(i);
1277 llvm::APInt EltAsInt;
1279 EltAsInt = Elt.getInt();
1280 } else if (Elt.isFloat()) {
1281 EltAsInt = Elt.getFloat().bitcastToAPInt();
1283 // Don't try to handle vectors of anything other than int or float
1284 // (not sure if it's possible to hit this case).
1285 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1288 unsigned BaseEltSize = EltAsInt.getBitWidth();
1290 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1292 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1296 // Give up if the input isn't an int, float, or vector. For example, we
1297 // reject "(v4i16)(intptr_t)&a".
1298 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1302 /// Cast an lvalue referring to a base subobject to a derived class, by
1303 /// truncating the lvalue's path to the given length.
1304 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1305 const RecordDecl *TruncatedType,
1306 unsigned TruncatedElements) {
1307 SubobjectDesignator &D = Result.Designator;
1309 // Check we actually point to a derived class object.
1310 if (TruncatedElements == D.Entries.size())
1312 assert(TruncatedElements >= D.MostDerivedPathLength &&
1313 "not casting to a derived class");
1314 if (!Result.checkSubobject(Info, E, CSK_Derived))
1317 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1318 const RecordDecl *RD = TruncatedType;
1319 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1320 if (RD->isInvalidDecl()) return false;
1321 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1322 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1323 if (isVirtualBaseClass(D.Entries[I]))
1324 Result.Offset -= Layout.getVBaseClassOffset(Base);
1326 Result.Offset -= Layout.getBaseClassOffset(Base);
1329 D.Entries.resize(TruncatedElements);
1333 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1334 const CXXRecordDecl *Derived,
1335 const CXXRecordDecl *Base,
1336 const ASTRecordLayout *RL = 0) {
1338 if (Derived->isInvalidDecl()) return false;
1339 RL = &Info.Ctx.getASTRecordLayout(Derived);
1342 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1343 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1347 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1348 const CXXRecordDecl *DerivedDecl,
1349 const CXXBaseSpecifier *Base) {
1350 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1352 if (!Base->isVirtual())
1353 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1355 SubobjectDesignator &D = Obj.Designator;
1359 // Extract most-derived object and corresponding type.
1360 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1361 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1364 // Find the virtual base class.
1365 if (DerivedDecl->isInvalidDecl()) return false;
1366 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1367 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1368 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1372 /// Update LVal to refer to the given field, which must be a member of the type
1373 /// currently described by LVal.
1374 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1375 const FieldDecl *FD,
1376 const ASTRecordLayout *RL = 0) {
1378 if (FD->getParent()->isInvalidDecl()) return false;
1379 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1382 unsigned I = FD->getFieldIndex();
1383 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1384 LVal.addDecl(Info, E, FD);
1388 /// Update LVal to refer to the given indirect field.
1389 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1391 const IndirectFieldDecl *IFD) {
1392 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1393 CE = IFD->chain_end(); C != CE; ++C)
1394 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1399 /// Get the size of the given type in char units.
1400 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, CharUnits &Size) {
1402 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1404 if (Type->isVoidType() || Type->isFunctionType()) {
1405 Size = CharUnits::One();
1409 if (!Type->isConstantSizeType()) {
1410 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1411 // FIXME: Better diagnostic.
1416 Size = Info.Ctx.getTypeSizeInChars(Type);
1420 /// Update a pointer value to model pointer arithmetic.
1421 /// \param Info - Information about the ongoing evaluation.
1422 /// \param E - The expression being evaluated, for diagnostic purposes.
1423 /// \param LVal - The pointer value to be updated.
1424 /// \param EltTy - The pointee type represented by LVal.
1425 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1426 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1427 LValue &LVal, QualType EltTy,
1428 int64_t Adjustment) {
1429 CharUnits SizeOfPointee;
1430 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1433 // Compute the new offset in the appropriate width.
1434 LVal.Offset += Adjustment * SizeOfPointee;
1435 LVal.adjustIndex(Info, E, Adjustment);
1439 /// Update an lvalue to refer to a component of a complex number.
1440 /// \param Info - Information about the ongoing evaluation.
1441 /// \param LVal - The lvalue to be updated.
1442 /// \param EltTy - The complex number's component type.
1443 /// \param Imag - False for the real component, true for the imaginary.
1444 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1445 LValue &LVal, QualType EltTy,
1448 CharUnits SizeOfComponent;
1449 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1451 LVal.Offset += SizeOfComponent;
1453 LVal.addComplex(Info, E, EltTy, Imag);
1457 /// Try to evaluate the initializer for a variable declaration.
1459 /// \param Info Information about the ongoing evaluation.
1460 /// \param E An expression to be used when printing diagnostics.
1461 /// \param VD The variable whose initializer should be obtained.
1462 /// \param Frame The frame in which the variable was created. Must be null
1463 /// if this variable is not local to the evaluation.
1464 /// \param Result Filled in with a pointer to the value of the variable.
1465 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1466 const VarDecl *VD, CallStackFrame *Frame,
1468 // If this is a parameter to an active constexpr function call, perform
1469 // argument substitution.
1470 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1471 // Assume arguments of a potential constant expression are unknown
1472 // constant expressions.
1473 if (Info.CheckingPotentialConstantExpression)
1475 if (!Frame || !Frame->Arguments) {
1476 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1479 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1483 // If this is a local variable, dig out its value.
1485 Result = &Frame->Temporaries[VD];
1486 // If we've carried on past an unevaluatable local variable initializer,
1487 // we can't go any further. This can happen during potential constant
1488 // expression checking.
1489 return !Result->isUninit();
1492 // Dig out the initializer, and use the declaration which it's attached to.
1493 const Expr *Init = VD->getAnyInitializer(VD);
1494 if (!Init || Init->isValueDependent()) {
1495 // If we're checking a potential constant expression, the variable could be
1496 // initialized later.
1497 if (!Info.CheckingPotentialConstantExpression)
1498 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1502 // If we're currently evaluating the initializer of this declaration, use that
1504 if (Info.EvaluatingDecl == VD) {
1505 Result = Info.EvaluatingDeclValue;
1506 return !Result->isUninit();
1509 // Never evaluate the initializer of a weak variable. We can't be sure that
1510 // this is the definition which will be used.
1512 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1516 // Check that we can fold the initializer. In C++, we will have already done
1517 // this in the cases where it matters for conformance.
1518 SmallVector<PartialDiagnosticAt, 8> Notes;
1519 if (!VD->evaluateValue(Notes)) {
1520 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1521 Notes.size() + 1) << VD;
1522 Info.Note(VD->getLocation(), diag::note_declared_at);
1523 Info.addNotes(Notes);
1525 } else if (!VD->checkInitIsICE()) {
1526 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1527 Notes.size() + 1) << VD;
1528 Info.Note(VD->getLocation(), diag::note_declared_at);
1529 Info.addNotes(Notes);
1532 Result = VD->getEvaluatedValue();
1536 static bool IsConstNonVolatile(QualType T) {
1537 Qualifiers Quals = T.getQualifiers();
1538 return Quals.hasConst() && !Quals.hasVolatile();
1541 /// Get the base index of the given base class within an APValue representing
1542 /// the given derived class.
1543 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1544 const CXXRecordDecl *Base) {
1545 Base = Base->getCanonicalDecl();
1547 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1548 E = Derived->bases_end(); I != E; ++I, ++Index) {
1549 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1553 llvm_unreachable("base class missing from derived class's bases list");
1556 /// Extract the value of a character from a string literal.
1557 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1559 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1560 const StringLiteral *S = cast<StringLiteral>(Lit);
1561 const ConstantArrayType *CAT =
1562 Info.Ctx.getAsConstantArrayType(S->getType());
1563 assert(CAT && "string literal isn't an array");
1564 QualType CharType = CAT->getElementType();
1565 assert(CharType->isIntegerType() && "unexpected character type");
1567 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1568 CharType->isUnsignedIntegerType());
1569 if (Index < S->getLength())
1570 Value = S->getCodeUnit(Index);
1574 // Expand a string literal into an array of characters.
1575 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1577 const StringLiteral *S = cast<StringLiteral>(Lit);
1578 const ConstantArrayType *CAT =
1579 Info.Ctx.getAsConstantArrayType(S->getType());
1580 assert(CAT && "string literal isn't an array");
1581 QualType CharType = CAT->getElementType();
1582 assert(CharType->isIntegerType() && "unexpected character type");
1584 unsigned Elts = CAT->getSize().getZExtValue();
1585 Result = APValue(APValue::UninitArray(),
1586 std::min(S->getLength(), Elts), Elts);
1587 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1588 CharType->isUnsignedIntegerType());
1589 if (Result.hasArrayFiller())
1590 Result.getArrayFiller() = APValue(Value);
1591 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
1592 Value = S->getCodeUnit(I);
1593 Result.getArrayInitializedElt(I) = APValue(Value);
1597 // Expand an array so that it has more than Index filled elements.
1598 static void expandArray(APValue &Array, unsigned Index) {
1599 unsigned Size = Array.getArraySize();
1600 assert(Index < Size);
1602 // Always at least double the number of elements for which we store a value.
1603 unsigned OldElts = Array.getArrayInitializedElts();
1604 unsigned NewElts = std::max(Index+1, OldElts * 2);
1605 NewElts = std::min(Size, std::max(NewElts, 8u));
1607 // Copy the data across.
1608 APValue NewValue(APValue::UninitArray(), NewElts, Size);
1609 for (unsigned I = 0; I != OldElts; ++I)
1610 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
1611 for (unsigned I = OldElts; I != NewElts; ++I)
1612 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
1613 if (NewValue.hasArrayFiller())
1614 NewValue.getArrayFiller() = Array.getArrayFiller();
1615 Array.swap(NewValue);
1618 /// Kinds of access we can perform on an object.
1626 /// A handle to a complete object (an object that is not a subobject of
1627 /// another object).
1628 struct CompleteObject {
1629 /// The value of the complete object.
1631 /// The type of the complete object.
1634 CompleteObject() : Value(0) {}
1635 CompleteObject(APValue *Value, QualType Type)
1636 : Value(Value), Type(Type) {
1637 assert(Value && "missing value for complete object");
1640 operator bool() const { return Value; }
1643 /// Find the designated sub-object of an rvalue.
1644 template<typename SubobjectHandler>
1645 typename SubobjectHandler::result_type
1646 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
1647 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
1649 // A diagnostic will have already been produced.
1650 return handler.failed();
1651 if (Sub.isOnePastTheEnd()) {
1652 if (Info.getLangOpts().CPlusPlus11)
1653 Info.Diag(E, diag::note_constexpr_access_past_end)
1654 << handler.AccessKind;
1657 return handler.failed();
1659 if (Sub.Entries.empty())
1660 return handler.found(*Obj.Value, Obj.Type);
1661 if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
1662 // This object might be initialized later.
1663 return handler.failed();
1665 APValue *O = Obj.Value;
1666 QualType ObjType = Obj.Type;
1667 // Walk the designator's path to find the subobject.
1668 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1669 if (ObjType->isArrayType()) {
1670 // Next subobject is an array element.
1671 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1672 assert(CAT && "vla in literal type?");
1673 uint64_t Index = Sub.Entries[I].ArrayIndex;
1674 if (CAT->getSize().ule(Index)) {
1675 // Note, it should not be possible to form a pointer with a valid
1676 // designator which points more than one past the end of the array.
1677 if (Info.getLangOpts().CPlusPlus11)
1678 Info.Diag(E, diag::note_constexpr_access_past_end)
1679 << handler.AccessKind;
1682 return handler.failed();
1685 ObjType = CAT->getElementType();
1687 // An array object is represented as either an Array APValue or as an
1688 // LValue which refers to a string literal.
1689 if (O->isLValue()) {
1690 assert(I == N - 1 && "extracting subobject of character?");
1691 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1692 if (handler.AccessKind != AK_Read)
1693 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
1696 return handler.foundString(*O, ObjType, Index);
1699 if (O->getArrayInitializedElts() > Index)
1700 O = &O->getArrayInitializedElt(Index);
1701 else if (handler.AccessKind != AK_Read) {
1702 expandArray(*O, Index);
1703 O = &O->getArrayInitializedElt(Index);
1705 O = &O->getArrayFiller();
1706 } else if (ObjType->isAnyComplexType()) {
1707 // Next subobject is a complex number.
1708 uint64_t Index = Sub.Entries[I].ArrayIndex;
1710 if (Info.getLangOpts().CPlusPlus11)
1711 Info.Diag(E, diag::note_constexpr_access_past_end)
1712 << handler.AccessKind;
1715 return handler.failed();
1718 bool WasConstQualified = ObjType.isConstQualified();
1719 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1720 if (WasConstQualified)
1723 assert(I == N - 1 && "extracting subobject of scalar?");
1724 if (O->isComplexInt()) {
1725 return handler.found(Index ? O->getComplexIntImag()
1726 : O->getComplexIntReal(), ObjType);
1728 assert(O->isComplexFloat());
1729 return handler.found(Index ? O->getComplexFloatImag()
1730 : O->getComplexFloatReal(), ObjType);
1732 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1733 if (Field->isMutable() && handler.AccessKind == AK_Read) {
1734 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
1736 Info.Note(Field->getLocation(), diag::note_declared_at);
1737 return handler.failed();
1740 // Next subobject is a class, struct or union field.
1741 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1742 if (RD->isUnion()) {
1743 const FieldDecl *UnionField = O->getUnionField();
1745 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1746 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
1747 << handler.AccessKind << Field << !UnionField << UnionField;
1748 return handler.failed();
1750 O = &O->getUnionValue();
1752 O = &O->getStructField(Field->getFieldIndex());
1754 bool WasConstQualified = ObjType.isConstQualified();
1755 ObjType = Field->getType();
1756 if (WasConstQualified && !Field->isMutable())
1759 if (ObjType.isVolatileQualified()) {
1760 if (Info.getLangOpts().CPlusPlus) {
1761 // FIXME: Include a description of the path to the volatile subobject.
1762 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
1763 << handler.AccessKind << 2 << Field;
1764 Info.Note(Field->getLocation(), diag::note_declared_at);
1766 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1768 return handler.failed();
1771 // Next subobject is a base class.
1772 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1773 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1774 O = &O->getStructBase(getBaseIndex(Derived, Base));
1776 bool WasConstQualified = ObjType.isConstQualified();
1777 ObjType = Info.Ctx.getRecordType(Base);
1778 if (WasConstQualified)
1782 if (O->isUninit()) {
1783 if (!Info.CheckingPotentialConstantExpression)
1784 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
1785 return handler.failed();
1789 return handler.found(*O, ObjType);
1793 struct ExtractSubobjectHandler {
1797 static const AccessKinds AccessKind = AK_Read;
1799 typedef bool result_type;
1800 bool failed() { return false; }
1801 bool found(APValue &Subobj, QualType SubobjType) {
1805 bool found(APSInt &Value, QualType SubobjType) {
1806 Result = APValue(Value);
1809 bool found(APFloat &Value, QualType SubobjType) {
1810 Result = APValue(Value);
1813 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1814 Result = APValue(extractStringLiteralCharacter(
1815 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
1819 } // end anonymous namespace
1821 const AccessKinds ExtractSubobjectHandler::AccessKind;
1823 /// Extract the designated sub-object of an rvalue.
1824 static bool extractSubobject(EvalInfo &Info, const Expr *E,
1825 const CompleteObject &Obj,
1826 const SubobjectDesignator &Sub,
1828 ExtractSubobjectHandler Handler = { Info, Result };
1829 return findSubobject(Info, E, Obj, Sub, Handler);
1833 struct ModifySubobjectHandler {
1838 typedef bool result_type;
1839 static const AccessKinds AccessKind = AK_Assign;
1841 bool checkConst(QualType QT) {
1842 // Assigning to a const object has undefined behavior.
1843 if (QT.isConstQualified()) {
1844 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
1850 bool failed() { return false; }
1851 bool found(APValue &Subobj, QualType SubobjType) {
1852 if (!checkConst(SubobjType))
1854 // We've been given ownership of NewVal, so just swap it in.
1855 Subobj.swap(NewVal);
1858 bool found(APSInt &Value, QualType SubobjType) {
1859 if (!checkConst(SubobjType))
1861 if (!NewVal.isInt()) {
1862 // Maybe trying to write a cast pointer value into a complex?
1866 Value = NewVal.getInt();
1869 bool found(APFloat &Value, QualType SubobjType) {
1870 if (!checkConst(SubobjType))
1872 Value = NewVal.getFloat();
1875 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
1876 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
1879 } // end anonymous namespace
1881 const AccessKinds ModifySubobjectHandler::AccessKind;
1883 /// Update the designated sub-object of an rvalue to the given value.
1884 static bool modifySubobject(EvalInfo &Info, const Expr *E,
1885 const CompleteObject &Obj,
1886 const SubobjectDesignator &Sub,
1888 ModifySubobjectHandler Handler = { Info, NewVal, E };
1889 return findSubobject(Info, E, Obj, Sub, Handler);
1892 /// Find the position where two subobject designators diverge, or equivalently
1893 /// the length of the common initial subsequence.
1894 static unsigned FindDesignatorMismatch(QualType ObjType,
1895 const SubobjectDesignator &A,
1896 const SubobjectDesignator &B,
1897 bool &WasArrayIndex) {
1898 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1899 for (/**/; I != N; ++I) {
1900 if (!ObjType.isNull() &&
1901 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
1902 // Next subobject is an array element.
1903 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1904 WasArrayIndex = true;
1907 if (ObjType->isAnyComplexType())
1908 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1910 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1912 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1913 WasArrayIndex = false;
1916 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1917 // Next subobject is a field.
1918 ObjType = FD->getType();
1920 // Next subobject is a base class.
1921 ObjType = QualType();
1924 WasArrayIndex = false;
1928 /// Determine whether the given subobject designators refer to elements of the
1929 /// same array object.
1930 static bool AreElementsOfSameArray(QualType ObjType,
1931 const SubobjectDesignator &A,
1932 const SubobjectDesignator &B) {
1933 if (A.Entries.size() != B.Entries.size())
1936 bool IsArray = A.MostDerivedArraySize != 0;
1937 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1938 // A is a subobject of the array element.
1941 // If A (and B) designates an array element, the last entry will be the array
1942 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1943 // of length 1' case, and the entire path must match.
1945 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1946 return CommonLength >= A.Entries.size() - IsArray;
1949 /// Find the complete object to which an LValue refers.
1950 CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
1951 const LValue &LVal, QualType LValType) {
1953 Info.Diag(E, diag::note_constexpr_access_null) << AK;
1954 return CompleteObject();
1957 CallStackFrame *Frame = 0;
1958 if (LVal.CallIndex) {
1959 Frame = Info.getCallFrame(LVal.CallIndex);
1961 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
1962 << AK << LVal.Base.is<const ValueDecl*>();
1963 NoteLValueLocation(Info, LVal.Base);
1964 return CompleteObject();
1966 } else if (AK != AK_Read) {
1967 Info.Diag(E, diag::note_constexpr_modify_global);
1968 return CompleteObject();
1971 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1972 // is not a constant expression (even if the object is non-volatile). We also
1973 // apply this rule to C++98, in order to conform to the expected 'volatile'
1975 if (LValType.isVolatileQualified()) {
1976 if (Info.getLangOpts().CPlusPlus)
1977 Info.Diag(E, diag::note_constexpr_access_volatile_type)
1981 return CompleteObject();
1984 // Compute value storage location and type of base object.
1985 APValue *BaseVal = 0;
1988 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1989 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1990 // In C++11, constexpr, non-volatile variables initialized with constant
1991 // expressions are constant expressions too. Inside constexpr functions,
1992 // parameters are constant expressions even if they're non-const.
1993 // In C++1y, objects local to a constant expression (those with a Frame) are
1994 // both readable and writable inside constant expressions.
1995 // In C, such things can also be folded, although they are not ICEs.
1996 const VarDecl *VD = dyn_cast<VarDecl>(D);
1998 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2001 if (!VD || VD->isInvalidDecl()) {
2003 return CompleteObject();
2006 // Accesses of volatile-qualified objects are not allowed.
2007 BaseType = VD->getType();
2008 if (BaseType.isVolatileQualified()) {
2009 if (Info.getLangOpts().CPlusPlus) {
2010 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2012 Info.Note(VD->getLocation(), diag::note_declared_at);
2016 return CompleteObject();
2019 // Unless we're looking at a local variable or argument in a constexpr call,
2020 // the variable we're reading must be const.
2022 assert(AK == AK_Read && "can't modify non-local");
2023 if (VD->isConstexpr()) {
2024 // OK, we can read this variable.
2025 } else if (BaseType->isIntegralOrEnumerationType()) {
2026 if (!BaseType.isConstQualified()) {
2027 if (Info.getLangOpts().CPlusPlus) {
2028 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2029 Info.Note(VD->getLocation(), diag::note_declared_at);
2033 return CompleteObject();
2035 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2036 // We support folding of const floating-point types, in order to make
2037 // static const data members of such types (supported as an extension)
2039 if (Info.getLangOpts().CPlusPlus11) {
2040 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2041 Info.Note(VD->getLocation(), diag::note_declared_at);
2046 // FIXME: Allow folding of values of any literal type in all languages.
2047 if (Info.getLangOpts().CPlusPlus11) {
2048 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2049 Info.Note(VD->getLocation(), diag::note_declared_at);
2053 return CompleteObject();
2057 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2058 return CompleteObject();
2060 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2064 return CompleteObject();
2067 BaseType = Base->getType();
2068 BaseVal = &Frame->Temporaries[Base];
2070 // Volatile temporary objects cannot be accessed in constant expressions.
2071 if (BaseType.isVolatileQualified()) {
2072 if (Info.getLangOpts().CPlusPlus) {
2073 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2075 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2079 return CompleteObject();
2083 // In C++1y, we can't safely access any mutable state when checking a
2084 // potential constant expression.
2085 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2086 Info.CheckingPotentialConstantExpression)
2087 return CompleteObject();
2089 return CompleteObject(BaseVal, BaseType);
2092 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2093 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2094 /// glvalue referred to by an entity of reference type.
2096 /// \param Info - Information about the ongoing evaluation.
2097 /// \param Conv - The expression for which we are performing the conversion.
2098 /// Used for diagnostics.
2099 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2100 /// case of a non-class type).
2101 /// \param LVal - The glvalue on which we are attempting to perform this action.
2102 /// \param RVal - The produced value will be placed here.
2103 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2105 const LValue &LVal, APValue &RVal) {
2106 if (LVal.Designator.Invalid)
2109 // Check for special cases where there is no existing APValue to look at.
2110 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2111 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2112 !Type.isVolatileQualified()) {
2113 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2114 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2115 // initializer until now for such expressions. Such an expression can't be
2116 // an ICE in C, so this only matters for fold.
2117 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2118 if (Type.isVolatileQualified()) {
2123 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2125 CompleteObject LitObj(&Lit, Base->getType());
2126 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2127 } else if (isa<StringLiteral>(Base)) {
2128 // We represent a string literal array as an lvalue pointing at the
2129 // corresponding expression, rather than building an array of chars.
2130 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2131 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2132 CompleteObject StrObj(&Str, Base->getType());
2133 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2137 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2138 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2141 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2142 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2143 QualType LValType, APValue &Val) {
2144 if (LVal.Designator.Invalid)
2147 if (!Info.getLangOpts().CPlusPlus1y) {
2152 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2153 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2156 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2157 return T->isSignedIntegerType() &&
2158 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2162 struct IncDecSubobjectHandler {
2165 AccessKinds AccessKind;
2168 typedef bool result_type;
2170 bool checkConst(QualType QT) {
2171 // Assigning to a const object has undefined behavior.
2172 if (QT.isConstQualified()) {
2173 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2179 bool failed() { return false; }
2180 bool found(APValue &Subobj, QualType SubobjType) {
2181 // Stash the old value. Also clear Old, so we don't clobber it later
2182 // if we're post-incrementing a complex.
2188 switch (Subobj.getKind()) {
2190 return found(Subobj.getInt(), SubobjType);
2191 case APValue::Float:
2192 return found(Subobj.getFloat(), SubobjType);
2193 case APValue::ComplexInt:
2194 return found(Subobj.getComplexIntReal(),
2195 SubobjType->castAs<ComplexType>()->getElementType()
2196 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2197 case APValue::ComplexFloat:
2198 return found(Subobj.getComplexFloatReal(),
2199 SubobjType->castAs<ComplexType>()->getElementType()
2200 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2201 case APValue::LValue:
2202 return foundPointer(Subobj, SubobjType);
2204 // FIXME: can this happen?
2209 bool found(APSInt &Value, QualType SubobjType) {
2210 if (!checkConst(SubobjType))
2213 if (!SubobjType->isIntegerType()) {
2214 // We don't support increment / decrement on integer-cast-to-pointer
2220 if (Old) *Old = APValue(Value);
2222 // bool arithmetic promotes to int, and the conversion back to bool
2223 // doesn't reduce mod 2^n, so special-case it.
2224 if (SubobjType->isBooleanType()) {
2225 if (AccessKind == AK_Increment)
2232 bool WasNegative = Value.isNegative();
2233 if (AccessKind == AK_Increment) {
2236 if (!WasNegative && Value.isNegative() &&
2237 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2238 APSInt ActualValue(Value, /*IsUnsigned*/true);
2239 HandleOverflow(Info, E, ActualValue, SubobjType);
2244 if (WasNegative && !Value.isNegative() &&
2245 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2246 unsigned BitWidth = Value.getBitWidth();
2247 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2248 ActualValue.setBit(BitWidth);
2249 HandleOverflow(Info, E, ActualValue, SubobjType);
2254 bool found(APFloat &Value, QualType SubobjType) {
2255 if (!checkConst(SubobjType))
2258 if (Old) *Old = APValue(Value);
2260 APFloat One(Value.getSemantics(), 1);
2261 if (AccessKind == AK_Increment)
2262 Value.add(One, APFloat::rmNearestTiesToEven);
2264 Value.subtract(One, APFloat::rmNearestTiesToEven);
2267 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2268 if (!checkConst(SubobjType))
2271 QualType PointeeType;
2272 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2273 PointeeType = PT->getPointeeType();
2280 LVal.setFrom(Info.Ctx, Subobj);
2281 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2282 AccessKind == AK_Increment ? 1 : -1))
2284 LVal.moveInto(Subobj);
2287 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2288 llvm_unreachable("shouldn't encounter string elements here");
2291 } // end anonymous namespace
2293 /// Perform an increment or decrement on LVal.
2294 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2295 QualType LValType, bool IsIncrement, APValue *Old) {
2296 if (LVal.Designator.Invalid)
2299 if (!Info.getLangOpts().CPlusPlus1y) {
2304 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2305 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2306 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2307 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2310 /// Build an lvalue for the object argument of a member function call.
2311 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2313 if (Object->getType()->isPointerType())
2314 return EvaluatePointer(Object, This, Info);
2316 if (Object->isGLValue())
2317 return EvaluateLValue(Object, This, Info);
2319 if (Object->getType()->isLiteralType(Info.Ctx))
2320 return EvaluateTemporary(Object, This, Info);
2325 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
2326 /// lvalue referring to the result.
2328 /// \param Info - Information about the ongoing evaluation.
2329 /// \param BO - The member pointer access operation.
2330 /// \param LV - Filled in with a reference to the resulting object.
2331 /// \param IncludeMember - Specifies whether the member itself is included in
2332 /// the resulting LValue subobject designator. This is not possible when
2333 /// creating a bound member function.
2334 /// \return The field or method declaration to which the member pointer refers,
2335 /// or 0 if evaluation fails.
2336 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2337 const BinaryOperator *BO,
2339 bool IncludeMember = true) {
2340 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
2342 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
2343 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
2347 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
2350 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2351 // member value, the behavior is undefined.
2352 if (!MemPtr.getDecl())
2358 if (MemPtr.isDerivedMember()) {
2359 // This is a member of some derived class. Truncate LV appropriately.
2360 // The end of the derived-to-base path for the base object must match the
2361 // derived-to-base path for the member pointer.
2362 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
2363 LV.Designator.Entries.size())
2365 unsigned PathLengthToMember =
2366 LV.Designator.Entries.size() - MemPtr.Path.size();
2367 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2368 const CXXRecordDecl *LVDecl = getAsBaseClass(
2369 LV.Designator.Entries[PathLengthToMember + I]);
2370 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2371 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
2375 // Truncate the lvalue to the appropriate derived class.
2376 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
2377 PathLengthToMember))
2379 } else if (!MemPtr.Path.empty()) {
2380 // Extend the LValue path with the member pointer's path.
2381 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2382 MemPtr.Path.size() + IncludeMember);
2384 // Walk down to the appropriate base class.
2385 QualType LVType = BO->getLHS()->getType();
2386 if (const PointerType *PT = LVType->getAs<PointerType>())
2387 LVType = PT->getPointeeType();
2388 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2389 assert(RD && "member pointer access on non-class-type expression");
2390 // The first class in the path is that of the lvalue.
2391 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2392 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
2393 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
2397 // Finally cast to the class containing the member.
2398 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
2402 // Add the member. Note that we cannot build bound member functions here.
2403 if (IncludeMember) {
2404 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2405 if (!HandleLValueMember(Info, BO, LV, FD))
2407 } else if (const IndirectFieldDecl *IFD =
2408 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2409 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2412 llvm_unreachable("can't construct reference to bound member function");
2416 return MemPtr.getDecl();
2419 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2420 /// the provided lvalue, which currently refers to the base object.
2421 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2423 SubobjectDesignator &D = Result.Designator;
2424 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
2427 QualType TargetQT = E->getType();
2428 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2429 TargetQT = PT->getPointeeType();
2431 // Check this cast lands within the final derived-to-base subobject path.
2432 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
2433 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2434 << D.MostDerivedType << TargetQT;
2438 // Check the type of the final cast. We don't need to check the path,
2439 // since a cast can only be formed if the path is unique.
2440 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
2441 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2442 const CXXRecordDecl *FinalType;
2443 if (NewEntriesSize == D.MostDerivedPathLength)
2444 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2446 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
2447 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2448 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2449 << D.MostDerivedType << TargetQT;
2453 // Truncate the lvalue to the appropriate derived class.
2454 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
2458 enum EvalStmtResult {
2459 /// Evaluation failed.
2461 /// Hit a 'return' statement.
2463 /// Evaluation succeeded.
2465 /// Hit a 'continue' statement.
2467 /// Hit a 'break' statement.
2472 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
2473 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2474 // We don't need to evaluate the initializer for a static local.
2475 if (!VD->hasLocalStorage())
2479 Result.set(VD, Info.CurrentCall->Index);
2480 APValue &Val = Info.CurrentCall->Temporaries[VD];
2482 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
2483 // Wipe out any partially-computed value, to allow tracking that this
2484 // evaluation failed.
2493 /// Evaluate a condition (either a variable declaration or an expression).
2494 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
2495 const Expr *Cond, bool &Result) {
2496 if (CondDecl && !EvaluateDecl(Info, CondDecl))
2498 return EvaluateAsBooleanCondition(Cond, Result, Info);
2501 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2504 /// Evaluate the body of a loop, and translate the result as appropriate.
2505 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
2507 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
2509 return ESR_Succeeded;
2512 return ESR_Continue;
2517 llvm_unreachable("Invalid EvalStmtResult!");
2520 // Evaluate a statement.
2521 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2523 // FIXME: Mark all temporaries in the current frame as destroyed at
2524 // the end of each full-expression.
2525 switch (S->getStmtClass()) {
2527 if (const Expr *E = dyn_cast<Expr>(S)) {
2528 // Don't bother evaluating beyond an expression-statement which couldn't
2530 if (!EvaluateIgnoredValue(Info, E))
2532 return ESR_Succeeded;
2535 Info.Diag(S->getLocStart());
2538 case Stmt::NullStmtClass:
2539 return ESR_Succeeded;
2541 case Stmt::DeclStmtClass: {
2542 const DeclStmt *DS = cast<DeclStmt>(S);
2543 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
2544 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
2545 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
2547 return ESR_Succeeded;
2550 case Stmt::ReturnStmtClass: {
2551 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
2552 if (RetExpr && !Evaluate(Result, Info, RetExpr))
2554 return ESR_Returned;
2557 case Stmt::CompoundStmtClass: {
2558 const CompoundStmt *CS = cast<CompoundStmt>(S);
2559 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2560 BE = CS->body_end(); BI != BE; ++BI) {
2561 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2562 if (ESR != ESR_Succeeded)
2565 return ESR_Succeeded;
2568 case Stmt::IfStmtClass: {
2569 const IfStmt *IS = cast<IfStmt>(S);
2571 // Evaluate the condition, as either a var decl or as an expression.
2573 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
2576 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
2577 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
2578 if (ESR != ESR_Succeeded)
2581 return ESR_Succeeded;
2584 case Stmt::WhileStmtClass: {
2585 const WhileStmt *WS = cast<WhileStmt>(S);
2588 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
2594 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
2595 if (ESR != ESR_Continue)
2598 return ESR_Succeeded;
2601 case Stmt::DoStmtClass: {
2602 const DoStmt *DS = cast<DoStmt>(S);
2605 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
2606 if (ESR != ESR_Continue)
2609 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
2612 return ESR_Succeeded;
2615 case Stmt::ForStmtClass: {
2616 const ForStmt *FS = cast<ForStmt>(S);
2617 if (FS->getInit()) {
2618 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
2619 if (ESR != ESR_Succeeded)
2623 bool Continue = true;
2624 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
2625 FS->getCond(), Continue))
2630 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2631 if (ESR != ESR_Continue)
2634 if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
2637 return ESR_Succeeded;
2640 case Stmt::CXXForRangeStmtClass: {
2641 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
2643 // Initialize the __range variable.
2644 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
2645 if (ESR != ESR_Succeeded)
2648 // Create the __begin and __end iterators.
2649 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
2650 if (ESR != ESR_Succeeded)
2654 // Condition: __begin != __end.
2655 bool Continue = true;
2656 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
2661 // User's variable declaration, initialized by *__begin.
2662 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
2663 if (ESR != ESR_Succeeded)
2667 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
2668 if (ESR != ESR_Continue)
2671 // Increment: ++__begin
2672 if (!EvaluateIgnoredValue(Info, FS->getInc()))
2676 return ESR_Succeeded;
2679 case Stmt::ContinueStmtClass:
2680 return ESR_Continue;
2682 case Stmt::BreakStmtClass:
2687 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2688 /// default constructor. If so, we'll fold it whether or not it's marked as
2689 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
2690 /// so we need special handling.
2691 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
2692 const CXXConstructorDecl *CD,
2693 bool IsValueInitialization) {
2694 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2697 // Value-initialization does not call a trivial default constructor, so such a
2698 // call is a core constant expression whether or not the constructor is
2700 if (!CD->isConstexpr() && !IsValueInitialization) {
2701 if (Info.getLangOpts().CPlusPlus11) {
2702 // FIXME: If DiagDecl is an implicitly-declared special member function,
2703 // we should be much more explicit about why it's not constexpr.
2704 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2705 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2706 Info.Note(CD->getLocation(), diag::note_declared_at);
2708 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2714 /// CheckConstexprFunction - Check that a function can be called in a constant
2716 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2717 const FunctionDecl *Declaration,
2718 const FunctionDecl *Definition) {
2719 // Potential constant expressions can contain calls to declared, but not yet
2720 // defined, constexpr functions.
2721 if (Info.CheckingPotentialConstantExpression && !Definition &&
2722 Declaration->isConstexpr())
2725 // Can we evaluate this function call?
2726 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2729 if (Info.getLangOpts().CPlusPlus11) {
2730 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
2731 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2732 // should be much more explicit about why it's not constexpr.
2733 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2734 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2736 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2738 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2744 typedef SmallVector<APValue, 8> ArgVector;
2747 /// EvaluateArgs - Evaluate the arguments to a function call.
2748 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2750 bool Success = true;
2751 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
2753 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2754 // If we're checking for a potential constant expression, evaluate all
2755 // initializers even if some of them fail.
2756 if (!Info.keepEvaluatingAfterFailure())
2764 /// Evaluate a function call.
2765 static bool HandleFunctionCall(SourceLocation CallLoc,
2766 const FunctionDecl *Callee, const LValue *This,
2767 ArrayRef<const Expr*> Args, const Stmt *Body,
2768 EvalInfo &Info, APValue &Result) {
2769 ArgVector ArgValues(Args.size());
2770 if (!EvaluateArgs(Args, ArgValues, Info))
2773 if (!Info.CheckCallLimit(CallLoc))
2776 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
2777 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
2778 if (ESR == ESR_Succeeded) {
2779 if (Callee->getResultType()->isVoidType())
2781 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
2783 return ESR == ESR_Returned;
2786 /// Evaluate a constructor call.
2787 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
2788 ArrayRef<const Expr*> Args,
2789 const CXXConstructorDecl *Definition,
2790 EvalInfo &Info, APValue &Result) {
2791 ArgVector ArgValues(Args.size());
2792 if (!EvaluateArgs(Args, ArgValues, Info))
2795 if (!Info.CheckCallLimit(CallLoc))
2798 const CXXRecordDecl *RD = Definition->getParent();
2799 if (RD->getNumVBases()) {
2800 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2804 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
2806 // If it's a delegating constructor, just delegate.
2807 if (Definition->isDelegatingConstructor()) {
2808 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2809 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
2811 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
2814 // For a trivial copy or move constructor, perform an APValue copy. This is
2815 // essential for unions, where the operations performed by the constructor
2816 // cannot be represented by ctor-initializers.
2817 if (Definition->isDefaulted() &&
2818 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2819 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
2821 RHS.setFrom(Info.Ctx, ArgValues[0]);
2822 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2826 // Reserve space for the struct members.
2827 if (!RD->isUnion() && Result.isUninit())
2828 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2829 std::distance(RD->field_begin(), RD->field_end()));
2831 if (RD->isInvalidDecl()) return false;
2832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2834 bool Success = true;
2835 unsigned BasesSeen = 0;
2837 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2839 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2840 E = Definition->init_end(); I != E; ++I) {
2841 LValue Subobject = This;
2842 APValue *Value = &Result;
2844 // Determine the subobject to initialize.
2845 if ((*I)->isBaseInitializer()) {
2846 QualType BaseType((*I)->getBaseClass(), 0);
2848 // Non-virtual base classes are initialized in the order in the class
2849 // definition. We have already checked for virtual base classes.
2850 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2851 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2852 "base class initializers not in expected order");
2855 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2856 BaseType->getAsCXXRecordDecl(), &Layout))
2858 Value = &Result.getStructBase(BasesSeen++);
2859 } else if (FieldDecl *FD = (*I)->getMember()) {
2860 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2862 if (RD->isUnion()) {
2863 Result = APValue(FD);
2864 Value = &Result.getUnionValue();
2866 Value = &Result.getStructField(FD->getFieldIndex());
2868 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
2869 // Walk the indirect field decl's chain to find the object to initialize,
2870 // and make sure we've initialized every step along it.
2871 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2872 CE = IFD->chain_end();
2874 FieldDecl *FD = cast<FieldDecl>(*C);
2875 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2876 // Switch the union field if it differs. This happens if we had
2877 // preceding zero-initialization, and we're now initializing a union
2878 // subobject other than the first.
2879 // FIXME: In this case, the values of the other subobjects are
2880 // specified, since zero-initialization sets all padding bits to zero.
2881 if (Value->isUninit() ||
2882 (Value->isUnion() && Value->getUnionField() != FD)) {
2884 *Value = APValue(FD);
2886 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2887 std::distance(CD->field_begin(), CD->field_end()));
2889 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2892 Value = &Value->getUnionValue();
2894 Value = &Value->getStructField(FD->getFieldIndex());
2897 llvm_unreachable("unknown base initializer kind");
2900 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2901 (*I)->isBaseInitializer()
2902 ? CCEK_Constant : CCEK_MemberInit)) {
2903 // If we're checking for a potential constant expression, evaluate all
2904 // initializers even if some of them fail.
2905 if (!Info.keepEvaluatingAfterFailure())
2912 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
2915 //===----------------------------------------------------------------------===//
2916 // Generic Evaluation
2917 //===----------------------------------------------------------------------===//
2920 // FIXME: RetTy is always bool. Remove it.
2921 template <class Derived, typename RetTy=bool>
2922 class ExprEvaluatorBase
2923 : public ConstStmtVisitor<Derived, RetTy> {
2925 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
2926 return static_cast<Derived*>(this)->Success(V, E);
2928 RetTy DerivedZeroInitialization(const Expr *E) {
2929 return static_cast<Derived*>(this)->ZeroInitialization(E);
2932 // Check whether a conditional operator with a non-constant condition is a
2933 // potential constant expression. If neither arm is a potential constant
2934 // expression, then the conditional operator is not either.
2935 template<typename ConditionalOperator>
2936 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2937 assert(Info.CheckingPotentialConstantExpression);
2939 // Speculatively evaluate both arms.
2941 SmallVector<PartialDiagnosticAt, 8> Diag;
2942 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2944 StmtVisitorTy::Visit(E->getFalseExpr());
2949 StmtVisitorTy::Visit(E->getTrueExpr());
2954 Error(E, diag::note_constexpr_conditional_never_const);
2958 template<typename ConditionalOperator>
2959 bool HandleConditionalOperator(const ConditionalOperator *E) {
2961 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2962 if (Info.CheckingPotentialConstantExpression)
2963 CheckPotentialConstantConditional(E);
2967 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2968 return StmtVisitorTy::Visit(EvalExpr);
2973 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2974 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2976 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2977 return Info.CCEDiag(E, D);
2980 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2983 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2985 EvalInfo &getEvalInfo() { return Info; }
2987 /// Report an evaluation error. This should only be called when an error is
2988 /// first discovered. When propagating an error, just return false.
2989 bool Error(const Expr *E, diag::kind D) {
2993 bool Error(const Expr *E) {
2994 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2997 RetTy VisitStmt(const Stmt *) {
2998 llvm_unreachable("Expression evaluator should not be called on stmts");
3000 RetTy VisitExpr(const Expr *E) {
3004 RetTy VisitParenExpr(const ParenExpr *E)
3005 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3006 RetTy VisitUnaryExtension(const UnaryOperator *E)
3007 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3008 RetTy VisitUnaryPlus(const UnaryOperator *E)
3009 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3010 RetTy VisitChooseExpr(const ChooseExpr *E)
3011 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
3012 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3013 { return StmtVisitorTy::Visit(E->getResultExpr()); }
3014 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3015 { return StmtVisitorTy::Visit(E->getReplacement()); }
3016 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3017 { return StmtVisitorTy::Visit(E->getExpr()); }
3018 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
3019 { return StmtVisitorTy::Visit(E->getExpr()); }
3020 // We cannot create any objects for which cleanups are required, so there is
3021 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3022 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3023 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3025 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3026 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3027 return static_cast<Derived*>(this)->VisitCastExpr(E);
3029 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3030 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3031 return static_cast<Derived*>(this)->VisitCastExpr(E);
3034 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3035 switch (E->getOpcode()) {
3040 VisitIgnoredValue(E->getLHS());
3041 return StmtVisitorTy::Visit(E->getRHS());
3046 if (!HandleMemberPointerAccess(Info, E, Obj))
3049 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
3051 return DerivedSuccess(Result, E);
3056 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
3057 // Evaluate and cache the common expression. We treat it as a temporary,
3058 // even though it's not quite the same thing.
3059 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
3060 Info, E->getCommon()))
3063 return HandleConditionalOperator(E);
3066 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
3067 bool IsBcpCall = false;
3068 // If the condition (ignoring parens) is a __builtin_constant_p call,
3069 // the result is a constant expression if it can be folded without
3070 // side-effects. This is an important GNU extension. See GCC PR38377
3072 if (const CallExpr *CallCE =
3073 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3074 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3077 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3078 // constant expression; we can't check whether it's potentially foldable.
3079 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
3082 FoldConstant Fold(Info);
3084 if (!HandleConditionalOperator(E))
3093 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
3094 APValue &Value = Info.CurrentCall->Temporaries[E];
3095 if (Value.isUninit()) {
3096 const Expr *Source = E->getSourceExpr();
3099 if (Source == E) { // sanity checking.
3100 assert(0 && "OpaqueValueExpr recursively refers to itself");
3103 return StmtVisitorTy::Visit(Source);
3105 return DerivedSuccess(Value, E);
3108 RetTy VisitCallExpr(const CallExpr *E) {
3109 const Expr *Callee = E->getCallee()->IgnoreParens();
3110 QualType CalleeType = Callee->getType();
3112 const FunctionDecl *FD = 0;
3113 LValue *This = 0, ThisVal;
3114 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
3115 bool HasQualifier = false;
3117 // Extract function decl and 'this' pointer from the callee.
3118 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
3119 const ValueDecl *Member = 0;
3120 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3121 // Explicit bound member calls, such as x.f() or p->g();
3122 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
3124 Member = ME->getMemberDecl();
3126 HasQualifier = ME->hasQualifier();
3127 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3128 // Indirect bound member calls ('.*' or '->*').
3129 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3130 if (!Member) return false;
3133 return Error(Callee);
3135 FD = dyn_cast<FunctionDecl>(Member);
3137 return Error(Callee);
3138 } else if (CalleeType->isFunctionPointerType()) {
3140 if (!EvaluatePointer(Callee, Call, Info))
3143 if (!Call.getLValueOffset().isZero())
3144 return Error(Callee);
3145 FD = dyn_cast_or_null<FunctionDecl>(
3146 Call.getLValueBase().dyn_cast<const ValueDecl*>());
3148 return Error(Callee);
3150 // Overloaded operator calls to member functions are represented as normal
3151 // calls with '*this' as the first argument.
3152 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3153 if (MD && !MD->isStatic()) {
3154 // FIXME: When selecting an implicit conversion for an overloaded
3155 // operator delete, we sometimes try to evaluate calls to conversion
3156 // operators without a 'this' parameter!
3160 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3163 Args = Args.slice(1);
3166 // Don't call function pointers which have been cast to some other type.
3167 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
3172 if (This && !This->checkSubobject(Info, E, CSK_This))
3175 // DR1358 allows virtual constexpr functions in some cases. Don't allow
3176 // calls to such functions in constant expressions.
3177 if (This && !HasQualifier &&
3178 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
3179 return Error(E, diag::note_constexpr_virtual_call);
3181 const FunctionDecl *Definition = 0;
3182 Stmt *Body = FD->getBody(Definition);
3185 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
3186 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
3190 return DerivedSuccess(Result, E);
3193 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3194 return StmtVisitorTy::Visit(E->getInitializer());
3196 RetTy VisitInitListExpr(const InitListExpr *E) {
3197 if (E->getNumInits() == 0)
3198 return DerivedZeroInitialization(E);
3199 if (E->getNumInits() == 1)
3200 return StmtVisitorTy::Visit(E->getInit(0));
3203 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
3204 return DerivedZeroInitialization(E);
3206 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
3207 return DerivedZeroInitialization(E);
3209 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
3210 return DerivedZeroInitialization(E);
3213 /// A member expression where the object is a prvalue is itself a prvalue.
3214 RetTy VisitMemberExpr(const MemberExpr *E) {
3215 assert(!E->isArrow() && "missing call to bound member function?");
3218 if (!Evaluate(Val, Info, E->getBase()))
3221 QualType BaseTy = E->getBase()->getType();
3223 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
3224 if (!FD) return Error(E);
3225 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
3226 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3227 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3229 CompleteObject Obj(&Val, BaseTy);
3230 SubobjectDesignator Designator(BaseTy);
3231 Designator.addDeclUnchecked(FD);
3234 return extractSubobject(Info, E, Obj, Designator, Result) &&
3235 DerivedSuccess(Result, E);
3238 RetTy VisitCastExpr(const CastExpr *E) {
3239 switch (E->getCastKind()) {
3243 case CK_AtomicToNonAtomic:
3244 case CK_NonAtomicToAtomic:
3246 case CK_UserDefinedConversion:
3247 return StmtVisitorTy::Visit(E->getSubExpr());
3249 case CK_LValueToRValue: {
3251 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
3254 // Note, we use the subexpression's type in order to retain cv-qualifiers.
3255 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
3258 return DerivedSuccess(RVal, E);
3265 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
3266 return VisitUnaryPostIncDec(UO);
3268 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
3269 return VisitUnaryPostIncDec(UO);
3271 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
3272 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3276 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
3279 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
3280 UO->isIncrementOp(), &RVal))
3282 return DerivedSuccess(RVal, UO);
3285 /// Visit a value which is evaluated, but whose value is ignored.
3286 void VisitIgnoredValue(const Expr *E) {
3287 EvaluateIgnoredValue(Info, E);
3293 //===----------------------------------------------------------------------===//
3294 // Common base class for lvalue and temporary evaluation.
3295 //===----------------------------------------------------------------------===//
3297 template<class Derived>
3298 class LValueExprEvaluatorBase
3299 : public ExprEvaluatorBase<Derived, bool> {
3302 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
3303 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
3305 bool Success(APValue::LValueBase B) {
3311 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
3312 ExprEvaluatorBaseTy(Info), Result(Result) {}
3314 bool Success(const APValue &V, const Expr *E) {
3315 Result.setFrom(this->Info.Ctx, V);
3319 bool VisitMemberExpr(const MemberExpr *E) {
3320 // Handle non-static data members.
3323 if (!EvaluatePointer(E->getBase(), Result, this->Info))
3325 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
3326 } else if (E->getBase()->isRValue()) {
3327 assert(E->getBase()->getType()->isRecordType());
3328 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
3330 BaseTy = E->getBase()->getType();
3332 if (!this->Visit(E->getBase()))
3334 BaseTy = E->getBase()->getType();
3337 const ValueDecl *MD = E->getMemberDecl();
3338 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
3339 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
3340 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
3342 if (!HandleLValueMember(this->Info, E, Result, FD))
3344 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
3345 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
3348 return this->Error(E);
3350 if (MD->getType()->isReferenceType()) {
3352 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
3355 return Success(RefValue, E);
3360 bool VisitBinaryOperator(const BinaryOperator *E) {
3361 switch (E->getOpcode()) {
3363 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3367 return HandleMemberPointerAccess(this->Info, E, Result);
3371 bool VisitCastExpr(const CastExpr *E) {
3372 switch (E->getCastKind()) {
3374 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3376 case CK_DerivedToBase:
3377 case CK_UncheckedDerivedToBase: {
3378 if (!this->Visit(E->getSubExpr()))
3381 // Now figure out the necessary offset to add to the base LV to get from
3382 // the derived class to the base class.
3383 QualType Type = E->getSubExpr()->getType();
3385 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3386 PathE = E->path_end(); PathI != PathE; ++PathI) {
3387 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
3390 Type = (*PathI)->getType();
3400 //===----------------------------------------------------------------------===//
3401 // LValue Evaluation
3403 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
3404 // function designators (in C), decl references to void objects (in C), and
3405 // temporaries (if building with -Wno-address-of-temporary).
3407 // LValue evaluation produces values comprising a base expression of one of the
3413 // * CompoundLiteralExpr in C
3417 // * ObjCStringLiteralExpr
3421 // * CallExpr for a MakeStringConstant builtin
3422 // - Locals and temporaries
3423 // * Any Expr, with a CallIndex indicating the function in which the temporary
3425 // plus an offset in bytes.
3426 //===----------------------------------------------------------------------===//
3428 class LValueExprEvaluator
3429 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
3431 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
3432 LValueExprEvaluatorBaseTy(Info, Result) {}
3434 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
3435 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
3437 bool VisitDeclRefExpr(const DeclRefExpr *E);
3438 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
3439 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
3440 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
3441 bool VisitMemberExpr(const MemberExpr *E);
3442 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
3443 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
3444 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
3445 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
3446 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
3447 bool VisitUnaryDeref(const UnaryOperator *E);
3448 bool VisitUnaryReal(const UnaryOperator *E);
3449 bool VisitUnaryImag(const UnaryOperator *E);
3450 bool VisitUnaryPreInc(const UnaryOperator *UO) {
3451 return VisitUnaryPreIncDec(UO);
3453 bool VisitUnaryPreDec(const UnaryOperator *UO) {
3454 return VisitUnaryPreIncDec(UO);
3456 bool VisitBinAssign(const BinaryOperator *BO);
3457 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
3459 bool VisitCastExpr(const CastExpr *E) {
3460 switch (E->getCastKind()) {
3462 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3464 case CK_LValueBitCast:
3465 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3466 if (!Visit(E->getSubExpr()))
3468 Result.Designator.setInvalid();
3471 case CK_BaseToDerived:
3472 if (!Visit(E->getSubExpr()))
3474 return HandleBaseToDerivedCast(Info, E, Result);
3478 } // end anonymous namespace
3480 /// Evaluate an expression as an lvalue. This can be legitimately called on
3481 /// expressions which are not glvalues, in two cases:
3482 /// * function designators in C, and
3483 /// * "extern void" objects
3484 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
3485 assert(E->isGLValue() || E->getType()->isFunctionType() ||
3486 E->getType()->isVoidType());
3487 return LValueExprEvaluator(Info, Result).Visit(E);
3490 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
3491 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
3493 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
3494 return VisitVarDecl(E, VD);
3498 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
3499 CallStackFrame *Frame = 0;
3500 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
3501 Frame = Info.CurrentCall;
3503 if (!VD->getType()->isReferenceType()) {
3505 Result.set(VD, Frame->Index);
3512 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
3514 return Success(*V, E);
3517 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
3518 const MaterializeTemporaryExpr *E) {
3519 if (E->getType()->isRecordType())
3520 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
3522 Result.set(E, Info.CurrentCall->Index);
3523 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3524 Result, E->GetTemporaryExpr());
3528 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
3529 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3530 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3531 // only see this when folding in C, so there's no standard to follow here.
3535 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
3536 if (!E->isPotentiallyEvaluated())
3539 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
3540 << E->getExprOperand()->getType()
3541 << E->getExprOperand()->getSourceRange();
3545 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3549 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
3550 // Handle static data members.
3551 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3552 VisitIgnoredValue(E->getBase());
3553 return VisitVarDecl(E, VD);
3556 // Handle static member functions.
3557 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3558 if (MD->isStatic()) {
3559 VisitIgnoredValue(E->getBase());
3564 // Handle non-static data members.
3565 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
3568 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
3569 // FIXME: Deal with vectors as array subscript bases.
3570 if (E->getBase()->getType()->isVectorType())
3573 if (!EvaluatePointer(E->getBase(), Result, Info))
3577 if (!EvaluateInteger(E->getIdx(), Index, Info))
3580 = Index.isSigned() ? Index.getSExtValue()
3581 : static_cast<int64_t>(Index.getZExtValue());
3583 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
3586 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
3587 return EvaluatePointer(E->getSubExpr(), Result, Info);
3590 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3591 if (!Visit(E->getSubExpr()))
3593 // __real is a no-op on scalar lvalues.
3594 if (E->getSubExpr()->getType()->isAnyComplexType())
3595 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3599 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3600 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3601 "lvalue __imag__ on scalar?");
3602 if (!Visit(E->getSubExpr()))
3604 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3608 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
3609 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3612 if (!this->Visit(UO->getSubExpr()))
3615 return handleIncDec(
3616 this->Info, UO, Result, UO->getSubExpr()->getType(),
3617 UO->isIncrementOp(), 0);
3620 bool LValueExprEvaluator::VisitCompoundAssignOperator(
3621 const CompoundAssignOperator *CAO) {
3622 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3627 // The overall lvalue result is the result of evaluating the LHS.
3628 if (!this->Visit(CAO->getLHS())) {
3629 if (Info.keepEvaluatingAfterFailure())
3630 Evaluate(RHS, this->Info, CAO->getRHS());
3634 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
3638 //return handleCompoundAssignment(
3640 // Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
3641 // RHS, CAO->getRHS()->getType(),
3642 // CAO->getOpForCompoundAssignment(CAO->getOpcode()),
3643 // CAO->getComputationResultType());
3647 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
3648 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
3653 if (!this->Visit(E->getLHS())) {
3654 if (Info.keepEvaluatingAfterFailure())
3655 Evaluate(NewVal, this->Info, E->getRHS());
3659 if (!Evaluate(NewVal, this->Info, E->getRHS()))
3662 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
3666 //===----------------------------------------------------------------------===//
3667 // Pointer Evaluation
3668 //===----------------------------------------------------------------------===//
3671 class PointerExprEvaluator
3672 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
3675 bool Success(const Expr *E) {
3681 PointerExprEvaluator(EvalInfo &info, LValue &Result)
3682 : ExprEvaluatorBaseTy(info), Result(Result) {}
3684 bool Success(const APValue &V, const Expr *E) {
3685 Result.setFrom(Info.Ctx, V);
3688 bool ZeroInitialization(const Expr *E) {
3689 return Success((Expr*)0);
3692 bool VisitBinaryOperator(const BinaryOperator *E);
3693 bool VisitCastExpr(const CastExpr* E);
3694 bool VisitUnaryAddrOf(const UnaryOperator *E);
3695 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
3696 { return Success(E); }
3697 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
3698 { return Success(E); }
3699 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
3700 { return Success(E); }
3701 bool VisitCallExpr(const CallExpr *E);
3702 bool VisitBlockExpr(const BlockExpr *E) {
3703 if (!E->getBlockDecl()->hasCaptures())
3707 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3708 if (!Info.CurrentCall->This)
3710 Result = *Info.CurrentCall->This;
3714 // FIXME: Missing: @protocol, @selector
3716 } // end anonymous namespace
3718 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
3719 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
3720 return PointerExprEvaluator(Info, Result).Visit(E);
3723 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3724 if (E->getOpcode() != BO_Add &&
3725 E->getOpcode() != BO_Sub)
3726 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3728 const Expr *PExp = E->getLHS();
3729 const Expr *IExp = E->getRHS();
3730 if (IExp->getType()->isPointerType())
3731 std::swap(PExp, IExp);
3733 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3734 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
3737 llvm::APSInt Offset;
3738 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
3740 int64_t AdditionalOffset
3741 = Offset.isSigned() ? Offset.getSExtValue()
3742 : static_cast<int64_t>(Offset.getZExtValue());
3743 if (E->getOpcode() == BO_Sub)
3744 AdditionalOffset = -AdditionalOffset;
3746 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
3747 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3751 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3752 return EvaluateLValue(E->getSubExpr(), Result, Info);
3755 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3756 const Expr* SubExpr = E->getSubExpr();
3758 switch (E->getCastKind()) {
3763 case CK_CPointerToObjCPointerCast:
3764 case CK_BlockPointerToObjCPointerCast:
3765 case CK_AnyPointerToBlockPointerCast:
3766 if (!Visit(SubExpr))
3768 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3769 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3770 // also static_casts, but we disallow them as a resolution to DR1312.
3771 if (!E->getType()->isVoidPointerType()) {
3772 Result.Designator.setInvalid();
3773 if (SubExpr->getType()->isVoidPointerType())
3774 CCEDiag(E, diag::note_constexpr_invalid_cast)
3775 << 3 << SubExpr->getType();
3777 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3781 case CK_DerivedToBase:
3782 case CK_UncheckedDerivedToBase: {
3783 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
3785 if (!Result.Base && Result.Offset.isZero())
3788 // Now figure out the necessary offset to add to the base LV to get from
3789 // the derived class to the base class.
3791 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3793 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3794 PathE = E->path_end(); PathI != PathE; ++PathI) {
3795 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3798 Type = (*PathI)->getType();
3804 case CK_BaseToDerived:
3805 if (!Visit(E->getSubExpr()))
3807 if (!Result.Base && Result.Offset.isZero())
3809 return HandleBaseToDerivedCast(Info, E, Result);
3811 case CK_NullToPointer:
3812 VisitIgnoredValue(E->getSubExpr());
3813 return ZeroInitialization(E);
3815 case CK_IntegralToPointer: {
3816 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3819 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
3822 if (Value.isInt()) {
3823 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3824 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
3825 Result.Base = (Expr*)0;
3826 Result.Offset = CharUnits::fromQuantity(N);
3827 Result.CallIndex = 0;
3828 Result.Designator.setInvalid();
3831 // Cast is of an lvalue, no need to change value.
3832 Result.setFrom(Info.Ctx, Value);
3836 case CK_ArrayToPointerDecay:
3837 if (SubExpr->isGLValue()) {
3838 if (!EvaluateLValue(SubExpr, Result, Info))
3841 Result.set(SubExpr, Info.CurrentCall->Index);
3842 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3843 Info, Result, SubExpr))
3846 // The result is a pointer to the first element of the array.
3847 if (const ConstantArrayType *CAT
3848 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3849 Result.addArray(Info, E, CAT);
3851 Result.Designator.setInvalid();
3854 case CK_FunctionToPointerDecay:
3855 return EvaluateLValue(SubExpr, Result, Info);
3858 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3861 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
3862 if (IsStringLiteralCall(E))
3865 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3868 //===----------------------------------------------------------------------===//
3869 // Member Pointer Evaluation
3870 //===----------------------------------------------------------------------===//
3873 class MemberPointerExprEvaluator
3874 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3877 bool Success(const ValueDecl *D) {
3878 Result = MemberPtr(D);
3883 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3884 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3886 bool Success(const APValue &V, const Expr *E) {
3890 bool ZeroInitialization(const Expr *E) {
3891 return Success((const ValueDecl*)0);
3894 bool VisitCastExpr(const CastExpr *E);
3895 bool VisitUnaryAddrOf(const UnaryOperator *E);
3897 } // end anonymous namespace
3899 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3901 assert(E->isRValue() && E->getType()->isMemberPointerType());
3902 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3905 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3906 switch (E->getCastKind()) {
3908 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3910 case CK_NullToMemberPointer:
3911 VisitIgnoredValue(E->getSubExpr());
3912 return ZeroInitialization(E);
3914 case CK_BaseToDerivedMemberPointer: {
3915 if (!Visit(E->getSubExpr()))
3917 if (E->path_empty())
3919 // Base-to-derived member pointer casts store the path in derived-to-base
3920 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3921 // the wrong end of the derived->base arc, so stagger the path by one class.
3922 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3923 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3924 PathI != PathE; ++PathI) {
3925 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3926 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3927 if (!Result.castToDerived(Derived))
3930 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3931 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
3936 case CK_DerivedToBaseMemberPointer:
3937 if (!Visit(E->getSubExpr()))
3939 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3940 PathE = E->path_end(); PathI != PathE; ++PathI) {
3941 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3942 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3943 if (!Result.castToBase(Base))
3950 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3951 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3952 // member can be formed.
3953 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3956 //===----------------------------------------------------------------------===//
3957 // Record Evaluation
3958 //===----------------------------------------------------------------------===//
3961 class RecordExprEvaluator
3962 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3967 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3968 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3970 bool Success(const APValue &V, const Expr *E) {
3974 bool ZeroInitialization(const Expr *E);
3976 bool VisitCastExpr(const CastExpr *E);
3977 bool VisitInitListExpr(const InitListExpr *E);
3978 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3982 /// Perform zero-initialization on an object of non-union class type.
3983 /// C++11 [dcl.init]p5:
3984 /// To zero-initialize an object or reference of type T means:
3986 /// -- if T is a (possibly cv-qualified) non-union class type,
3987 /// each non-static data member and each base-class subobject is
3988 /// zero-initialized
3989 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3990 const RecordDecl *RD,
3991 const LValue &This, APValue &Result) {
3992 assert(!RD->isUnion() && "Expected non-union class type");
3993 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3994 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3995 std::distance(RD->field_begin(), RD->field_end()));
3997 if (RD->isInvalidDecl()) return false;
3998 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4002 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
4003 End = CD->bases_end(); I != End; ++I, ++Index) {
4004 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4005 LValue Subobject = This;
4006 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4008 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
4009 Result.getStructBase(Index)))
4014 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4016 // -- if T is a reference type, no initialization is performed.
4017 if (I->getType()->isReferenceType())
4020 LValue Subobject = This;
4021 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
4024 ImplicitValueInitExpr VIE(I->getType());
4025 if (!EvaluateInPlace(
4026 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
4033 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4034 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
4035 if (RD->isInvalidDecl()) return false;
4036 if (RD->isUnion()) {
4037 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4038 // object's first non-static named data member is zero-initialized
4039 RecordDecl::field_iterator I = RD->field_begin();
4040 if (I == RD->field_end()) {
4041 Result = APValue((const FieldDecl*)0);
4045 LValue Subobject = This;
4046 if (!HandleLValueMember(Info, E, Subobject, *I))
4048 Result = APValue(*I);
4049 ImplicitValueInitExpr VIE(I->getType());
4050 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
4053 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
4054 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
4058 return HandleClassZeroInitialization(Info, E, RD, This, Result);
4061 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4062 switch (E->getCastKind()) {
4064 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4066 case CK_ConstructorConversion:
4067 return Visit(E->getSubExpr());
4069 case CK_DerivedToBase:
4070 case CK_UncheckedDerivedToBase: {
4071 APValue DerivedObject;
4072 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
4074 if (!DerivedObject.isStruct())
4075 return Error(E->getSubExpr());
4077 // Derived-to-base rvalue conversion: just slice off the derived part.
4078 APValue *Value = &DerivedObject;
4079 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4080 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4081 PathE = E->path_end(); PathI != PathE; ++PathI) {
4082 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4083 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4084 Value = &Value->getStructBase(getBaseIndex(RD, Base));
4093 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4094 // Cannot constant-evaluate std::initializer_list inits.
4095 if (E->initializesStdInitializerList())
4098 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
4099 if (RD->isInvalidDecl()) return false;
4100 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4102 if (RD->isUnion()) {
4103 const FieldDecl *Field = E->getInitializedFieldInUnion();
4104 Result = APValue(Field);
4108 // If the initializer list for a union does not contain any elements, the
4109 // first element of the union is value-initialized.
4110 // FIXME: The element should be initialized from an initializer list.
4111 // Is this difference ever observable for initializer lists which
4113 ImplicitValueInitExpr VIE(Field->getType());
4114 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
4116 LValue Subobject = This;
4117 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
4120 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4121 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4122 isa<CXXDefaultInitExpr>(InitExpr));
4124 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
4127 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
4128 "initializer list for class with base classes");
4129 Result = APValue(APValue::UninitStruct(), 0,
4130 std::distance(RD->field_begin(), RD->field_end()));
4131 unsigned ElementNo = 0;
4132 bool Success = true;
4133 for (RecordDecl::field_iterator Field = RD->field_begin(),
4134 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
4135 // Anonymous bit-fields are not considered members of the class for
4136 // purposes of aggregate initialization.
4137 if (Field->isUnnamedBitfield())
4140 LValue Subobject = This;
4142 bool HaveInit = ElementNo < E->getNumInits();
4144 // FIXME: Diagnostics here should point to the end of the initializer
4145 // list, not the start.
4146 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
4147 Subobject, *Field, &Layout))
4150 // Perform an implicit value-initialization for members beyond the end of
4151 // the initializer list.
4152 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
4153 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
4155 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
4156 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
4157 isa<CXXDefaultInitExpr>(Init));
4159 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
4161 if (!Info.keepEvaluatingAfterFailure())
4170 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4171 const CXXConstructorDecl *FD = E->getConstructor();
4172 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
4174 bool ZeroInit = E->requiresZeroInitialization();
4175 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
4176 // If we've already performed zero-initialization, we're already done.
4177 if (!Result.isUninit())
4181 return ZeroInitialization(E);
4183 const CXXRecordDecl *RD = FD->getParent();
4185 Result = APValue((FieldDecl*)0);
4187 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4188 std::distance(RD->field_begin(), RD->field_end()));
4192 const FunctionDecl *Definition = 0;
4193 FD->getBody(Definition);
4195 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4198 // Avoid materializing a temporary for an elidable copy/move constructor.
4199 if (E->isElidable() && !ZeroInit)
4200 if (const MaterializeTemporaryExpr *ME
4201 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
4202 return Visit(ME->GetTemporaryExpr());
4204 if (ZeroInit && !ZeroInitialization(E))
4207 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
4208 return HandleConstructorCall(E->getExprLoc(), This, Args,
4209 cast<CXXConstructorDecl>(Definition), Info,
4213 static bool EvaluateRecord(const Expr *E, const LValue &This,
4214 APValue &Result, EvalInfo &Info) {
4215 assert(E->isRValue() && E->getType()->isRecordType() &&
4216 "can't evaluate expression as a record rvalue");
4217 return RecordExprEvaluator(Info, This, Result).Visit(E);
4220 //===----------------------------------------------------------------------===//
4221 // Temporary Evaluation
4223 // Temporaries are represented in the AST as rvalues, but generally behave like
4224 // lvalues. The full-object of which the temporary is a subobject is implicitly
4225 // materialized so that a reference can bind to it.
4226 //===----------------------------------------------------------------------===//
4228 class TemporaryExprEvaluator
4229 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
4231 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
4232 LValueExprEvaluatorBaseTy(Info, Result) {}
4234 /// Visit an expression which constructs the value of this temporary.
4235 bool VisitConstructExpr(const Expr *E) {
4236 Result.set(E, Info.CurrentCall->Index);
4237 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
4240 bool VisitCastExpr(const CastExpr *E) {
4241 switch (E->getCastKind()) {
4243 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4245 case CK_ConstructorConversion:
4246 return VisitConstructExpr(E->getSubExpr());
4249 bool VisitInitListExpr(const InitListExpr *E) {
4250 return VisitConstructExpr(E);
4252 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
4253 return VisitConstructExpr(E);
4255 bool VisitCallExpr(const CallExpr *E) {
4256 return VisitConstructExpr(E);
4259 } // end anonymous namespace
4261 /// Evaluate an expression of record type as a temporary.
4262 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
4263 assert(E->isRValue() && E->getType()->isRecordType());
4264 return TemporaryExprEvaluator(Info, Result).Visit(E);
4267 //===----------------------------------------------------------------------===//
4268 // Vector Evaluation
4269 //===----------------------------------------------------------------------===//
4272 class VectorExprEvaluator
4273 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
4277 VectorExprEvaluator(EvalInfo &info, APValue &Result)
4278 : ExprEvaluatorBaseTy(info), Result(Result) {}
4280 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
4281 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
4282 // FIXME: remove this APValue copy.
4283 Result = APValue(V.data(), V.size());
4286 bool Success(const APValue &V, const Expr *E) {
4287 assert(V.isVector());
4291 bool ZeroInitialization(const Expr *E);
4293 bool VisitUnaryReal(const UnaryOperator *E)
4294 { return Visit(E->getSubExpr()); }
4295 bool VisitCastExpr(const CastExpr* E);
4296 bool VisitInitListExpr(const InitListExpr *E);
4297 bool VisitUnaryImag(const UnaryOperator *E);
4298 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
4299 // binary comparisons, binary and/or/xor,
4300 // shufflevector, ExtVectorElementExpr
4302 } // end anonymous namespace
4304 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
4305 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
4306 return VectorExprEvaluator(Info, Result).Visit(E);
4309 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
4310 const VectorType *VTy = E->getType()->castAs<VectorType>();
4311 unsigned NElts = VTy->getNumElements();
4313 const Expr *SE = E->getSubExpr();
4314 QualType SETy = SE->getType();
4316 switch (E->getCastKind()) {
4317 case CK_VectorSplat: {
4318 APValue Val = APValue();
4319 if (SETy->isIntegerType()) {
4321 if (!EvaluateInteger(SE, IntResult, Info))
4323 Val = APValue(IntResult);
4324 } else if (SETy->isRealFloatingType()) {
4326 if (!EvaluateFloat(SE, F, Info))
4333 // Splat and create vector APValue.
4334 SmallVector<APValue, 4> Elts(NElts, Val);
4335 return Success(Elts, E);
4338 // Evaluate the operand into an APInt we can extract from.
4339 llvm::APInt SValInt;
4340 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
4342 // Extract the elements
4343 QualType EltTy = VTy->getElementType();
4344 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
4345 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
4346 SmallVector<APValue, 4> Elts;
4347 if (EltTy->isRealFloatingType()) {
4348 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
4349 unsigned FloatEltSize = EltSize;
4350 if (&Sem == &APFloat::x87DoubleExtended)
4352 for (unsigned i = 0; i < NElts; i++) {
4355 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
4357 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
4358 Elts.push_back(APValue(APFloat(Sem, Elt)));
4360 } else if (EltTy->isIntegerType()) {
4361 for (unsigned i = 0; i < NElts; i++) {
4364 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
4366 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
4367 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
4372 return Success(Elts, E);
4375 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4380 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4381 const VectorType *VT = E->getType()->castAs<VectorType>();
4382 unsigned NumInits = E->getNumInits();
4383 unsigned NumElements = VT->getNumElements();
4385 QualType EltTy = VT->getElementType();
4386 SmallVector<APValue, 4> Elements;
4388 // The number of initializers can be less than the number of
4389 // vector elements. For OpenCL, this can be due to nested vector
4390 // initialization. For GCC compatibility, missing trailing elements
4391 // should be initialized with zeroes.
4392 unsigned CountInits = 0, CountElts = 0;
4393 while (CountElts < NumElements) {
4394 // Handle nested vector initialization.
4395 if (CountInits < NumInits
4396 && E->getInit(CountInits)->getType()->isExtVectorType()) {
4398 if (!EvaluateVector(E->getInit(CountInits), v, Info))
4400 unsigned vlen = v.getVectorLength();
4401 for (unsigned j = 0; j < vlen; j++)
4402 Elements.push_back(v.getVectorElt(j));
4404 } else if (EltTy->isIntegerType()) {
4405 llvm::APSInt sInt(32);
4406 if (CountInits < NumInits) {
4407 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
4409 } else // trailing integer zero.
4410 sInt = Info.Ctx.MakeIntValue(0, EltTy);
4411 Elements.push_back(APValue(sInt));
4414 llvm::APFloat f(0.0);
4415 if (CountInits < NumInits) {
4416 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
4418 } else // trailing float zero.
4419 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
4420 Elements.push_back(APValue(f));
4425 return Success(Elements, E);
4429 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
4430 const VectorType *VT = E->getType()->getAs<VectorType>();
4431 QualType EltTy = VT->getElementType();
4432 APValue ZeroElement;
4433 if (EltTy->isIntegerType())
4434 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
4437 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
4439 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
4440 return Success(Elements, E);
4443 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4444 VisitIgnoredValue(E->getSubExpr());
4445 return ZeroInitialization(E);
4448 //===----------------------------------------------------------------------===//
4450 //===----------------------------------------------------------------------===//
4453 class ArrayExprEvaluator
4454 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
4459 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
4460 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
4462 bool Success(const APValue &V, const Expr *E) {
4463 assert((V.isArray() || V.isLValue()) &&
4464 "expected array or string literal");
4469 bool ZeroInitialization(const Expr *E) {
4470 const ConstantArrayType *CAT =
4471 Info.Ctx.getAsConstantArrayType(E->getType());
4475 Result = APValue(APValue::UninitArray(), 0,
4476 CAT->getSize().getZExtValue());
4477 if (!Result.hasArrayFiller()) return true;
4479 // Zero-initialize all elements.
4480 LValue Subobject = This;
4481 Subobject.addArray(Info, E, CAT);
4482 ImplicitValueInitExpr VIE(CAT->getElementType());
4483 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
4486 bool VisitInitListExpr(const InitListExpr *E);
4487 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4488 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
4489 const LValue &Subobject,
4490 APValue *Value, QualType Type);
4492 } // end anonymous namespace
4494 static bool EvaluateArray(const Expr *E, const LValue &This,
4495 APValue &Result, EvalInfo &Info) {
4496 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
4497 return ArrayExprEvaluator(Info, This, Result).Visit(E);
4500 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
4501 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
4505 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
4506 // an appropriately-typed string literal enclosed in braces.
4507 if (E->isStringLiteralInit()) {
4509 if (!EvaluateLValue(E->getInit(0), LV, Info))
4513 return Success(Val, E);
4516 bool Success = true;
4518 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
4519 "zero-initialized array shouldn't have any initialized elts");
4521 if (Result.isArray() && Result.hasArrayFiller())
4522 Filler = Result.getArrayFiller();
4524 unsigned NumEltsToInit = E->getNumInits();
4525 unsigned NumElts = CAT->getSize().getZExtValue();
4526 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
4528 // If the initializer might depend on the array index, run it for each
4529 // array element. For now, just whitelist non-class value-initialization.
4530 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
4531 NumEltsToInit = NumElts;
4533 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
4535 // If the array was previously zero-initialized, preserve the
4536 // zero-initialized values.
4537 if (!Filler.isUninit()) {
4538 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
4539 Result.getArrayInitializedElt(I) = Filler;
4540 if (Result.hasArrayFiller())
4541 Result.getArrayFiller() = Filler;
4544 LValue Subobject = This;
4545 Subobject.addArray(Info, E, CAT);
4546 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
4548 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
4549 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
4550 Info, Subobject, Init) ||
4551 !HandleLValueArrayAdjustment(Info, Init, Subobject,
4552 CAT->getElementType(), 1)) {
4553 if (!Info.keepEvaluatingAfterFailure())
4559 if (!Result.hasArrayFiller())
4562 // If we get here, we have a trivial filler, which we can just evaluate
4563 // once and splat over the rest of the array elements.
4564 assert(FillerExpr && "no array filler for incomplete init list");
4565 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
4566 FillerExpr) && Success;
4569 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
4570 return VisitCXXConstructExpr(E, This, &Result, E->getType());
4573 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
4574 const LValue &Subobject,
4577 bool HadZeroInit = !Value->isUninit();
4579 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
4580 unsigned N = CAT->getSize().getZExtValue();
4582 // Preserve the array filler if we had prior zero-initialization.
4584 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
4587 *Value = APValue(APValue::UninitArray(), N, N);
4590 for (unsigned I = 0; I != N; ++I)
4591 Value->getArrayInitializedElt(I) = Filler;
4593 // Initialize the elements.
4594 LValue ArrayElt = Subobject;
4595 ArrayElt.addArray(Info, E, CAT);
4596 for (unsigned I = 0; I != N; ++I)
4597 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
4598 CAT->getElementType()) ||
4599 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
4600 CAT->getElementType(), 1))
4606 if (!Type->isRecordType())
4609 const CXXConstructorDecl *FD = E->getConstructor();
4611 bool ZeroInit = E->requiresZeroInitialization();
4612 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
4617 ImplicitValueInitExpr VIE(Type);
4618 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
4621 const CXXRecordDecl *RD = FD->getParent();
4623 *Value = APValue((FieldDecl*)0);
4626 APValue(APValue::UninitStruct(), RD->getNumBases(),
4627 std::distance(RD->field_begin(), RD->field_end()));
4631 const FunctionDecl *Definition = 0;
4632 FD->getBody(Definition);
4634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
4637 if (ZeroInit && !HadZeroInit) {
4638 ImplicitValueInitExpr VIE(Type);
4639 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
4643 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
4644 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
4645 cast<CXXConstructorDecl>(Definition),
4649 //===----------------------------------------------------------------------===//
4650 // Integer Evaluation
4652 // As a GNU extension, we support casting pointers to sufficiently-wide integer
4653 // types and back in constant folding. Integer values are thus represented
4654 // either as an integer-valued APValue, or as an lvalue-valued APValue.
4655 //===----------------------------------------------------------------------===//
4658 class IntExprEvaluator
4659 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
4662 IntExprEvaluator(EvalInfo &info, APValue &result)
4663 : ExprEvaluatorBaseTy(info), Result(result) {}
4665 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
4666 assert(E->getType()->isIntegralOrEnumerationType() &&
4667 "Invalid evaluation result.");
4668 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
4669 "Invalid evaluation result.");
4670 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
4671 "Invalid evaluation result.");
4672 Result = APValue(SI);
4675 bool Success(const llvm::APSInt &SI, const Expr *E) {
4676 return Success(SI, E, Result);
4679 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
4680 assert(E->getType()->isIntegralOrEnumerationType() &&
4681 "Invalid evaluation result.");
4682 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
4683 "Invalid evaluation result.");
4684 Result = APValue(APSInt(I));
4685 Result.getInt().setIsUnsigned(
4686 E->getType()->isUnsignedIntegerOrEnumerationType());
4689 bool Success(const llvm::APInt &I, const Expr *E) {
4690 return Success(I, E, Result);
4693 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4694 assert(E->getType()->isIntegralOrEnumerationType() &&
4695 "Invalid evaluation result.");
4696 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
4699 bool Success(uint64_t Value, const Expr *E) {
4700 return Success(Value, E, Result);
4703 bool Success(CharUnits Size, const Expr *E) {
4704 return Success(Size.getQuantity(), E);
4707 bool Success(const APValue &V, const Expr *E) {
4708 if (V.isLValue() || V.isAddrLabelDiff()) {
4712 return Success(V.getInt(), E);
4715 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
4717 //===--------------------------------------------------------------------===//
4719 //===--------------------------------------------------------------------===//
4721 bool VisitIntegerLiteral(const IntegerLiteral *E) {
4722 return Success(E->getValue(), E);
4724 bool VisitCharacterLiteral(const CharacterLiteral *E) {
4725 return Success(E->getValue(), E);
4728 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4729 bool VisitDeclRefExpr(const DeclRefExpr *E) {
4730 if (CheckReferencedDecl(E, E->getDecl()))
4733 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
4735 bool VisitMemberExpr(const MemberExpr *E) {
4736 if (CheckReferencedDecl(E, E->getMemberDecl())) {
4737 VisitIgnoredValue(E->getBase());
4741 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
4744 bool VisitCallExpr(const CallExpr *E);
4745 bool VisitBinaryOperator(const BinaryOperator *E);
4746 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
4747 bool VisitUnaryOperator(const UnaryOperator *E);
4749 bool VisitCastExpr(const CastExpr* E);
4750 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
4752 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4753 return Success(E->getValue(), E);
4756 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4757 return Success(E->getValue(), E);
4760 // Note, GNU defines __null as an integer, not a pointer.
4761 bool VisitGNUNullExpr(const GNUNullExpr *E) {
4762 return ZeroInitialization(E);
4765 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
4766 return Success(E->getValue(), E);
4769 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4770 return Success(E->getValue(), E);
4773 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4774 return Success(E->getValue(), E);
4777 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4778 return Success(E->getValue(), E);
4781 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4782 return Success(E->getValue(), E);
4785 bool VisitUnaryReal(const UnaryOperator *E);
4786 bool VisitUnaryImag(const UnaryOperator *E);
4788 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
4789 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
4792 CharUnits GetAlignOfExpr(const Expr *E);
4793 CharUnits GetAlignOfType(QualType T);
4794 static QualType GetObjectType(APValue::LValueBase B);
4795 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
4796 // FIXME: Missing: array subscript of vector, member of vector
4798 } // end anonymous namespace
4800 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4801 /// produce either the integer value or a pointer.
4803 /// GCC has a heinous extension which folds casts between pointer types and
4804 /// pointer-sized integral types. We support this by allowing the evaluation of
4805 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4806 /// Some simple arithmetic on such values is supported (they are treated much
4808 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
4810 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
4811 return IntExprEvaluator(Info, Result).Visit(E);
4814 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
4816 if (!EvaluateIntegerOrLValue(E, Val, Info))
4819 // FIXME: It would be better to produce the diagnostic for casting
4820 // a pointer to an integer.
4821 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
4824 Result = Val.getInt();
4828 /// Check whether the given declaration can be directly converted to an integral
4829 /// rvalue. If not, no diagnostic is produced; there are other things we can
4831 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
4832 // Enums are integer constant exprs.
4833 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
4834 // Check for signedness/width mismatches between E type and ECD value.
4835 bool SameSign = (ECD->getInitVal().isSigned()
4836 == E->getType()->isSignedIntegerOrEnumerationType());
4837 bool SameWidth = (ECD->getInitVal().getBitWidth()
4838 == Info.Ctx.getIntWidth(E->getType()));
4839 if (SameSign && SameWidth)
4840 return Success(ECD->getInitVal(), E);
4842 // Get rid of mismatch (otherwise Success assertions will fail)
4843 // by computing a new value matching the type of E.
4844 llvm::APSInt Val = ECD->getInitVal();
4846 Val.setIsSigned(!ECD->getInitVal().isSigned());
4848 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4849 return Success(Val, E);
4855 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4857 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4858 // The following enum mimics the values returned by GCC.
4859 // FIXME: Does GCC differ between lvalue and rvalue references here?
4860 enum gcc_type_class {
4862 void_type_class, integer_type_class, char_type_class,
4863 enumeral_type_class, boolean_type_class,
4864 pointer_type_class, reference_type_class, offset_type_class,
4865 real_type_class, complex_type_class,
4866 function_type_class, method_type_class,
4867 record_type_class, union_type_class,
4868 array_type_class, string_type_class,
4872 // If no argument was supplied, default to "no_type_class". This isn't
4873 // ideal, however it is what gcc does.
4874 if (E->getNumArgs() == 0)
4875 return no_type_class;
4877 QualType ArgTy = E->getArg(0)->getType();
4878 if (ArgTy->isVoidType())
4879 return void_type_class;
4880 else if (ArgTy->isEnumeralType())
4881 return enumeral_type_class;
4882 else if (ArgTy->isBooleanType())
4883 return boolean_type_class;
4884 else if (ArgTy->isCharType())
4885 return string_type_class; // gcc doesn't appear to use char_type_class
4886 else if (ArgTy->isIntegerType())
4887 return integer_type_class;
4888 else if (ArgTy->isPointerType())
4889 return pointer_type_class;
4890 else if (ArgTy->isReferenceType())
4891 return reference_type_class;
4892 else if (ArgTy->isRealType())
4893 return real_type_class;
4894 else if (ArgTy->isComplexType())
4895 return complex_type_class;
4896 else if (ArgTy->isFunctionType())
4897 return function_type_class;
4898 else if (ArgTy->isStructureOrClassType())
4899 return record_type_class;
4900 else if (ArgTy->isUnionType())
4901 return union_type_class;
4902 else if (ArgTy->isArrayType())
4903 return array_type_class;
4904 else if (ArgTy->isUnionType())
4905 return union_type_class;
4906 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
4907 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
4910 /// EvaluateBuiltinConstantPForLValue - Determine the result of
4911 /// __builtin_constant_p when applied to the given lvalue.
4913 /// An lvalue is only "constant" if it is a pointer or reference to the first
4914 /// character of a string literal.
4915 template<typename LValue>
4916 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4917 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
4918 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4921 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4922 /// GCC as we can manage.
4923 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4924 QualType ArgType = Arg->getType();
4926 // __builtin_constant_p always has one operand. The rules which gcc follows
4927 // are not precisely documented, but are as follows:
4929 // - If the operand is of integral, floating, complex or enumeration type,
4930 // and can be folded to a known value of that type, it returns 1.
4931 // - If the operand and can be folded to a pointer to the first character
4932 // of a string literal (or such a pointer cast to an integral type), it
4935 // Otherwise, it returns 0.
4937 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4938 // its support for this does not currently work.
4939 if (ArgType->isIntegralOrEnumerationType()) {
4940 Expr::EvalResult Result;
4941 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4944 APValue &V = Result.Val;
4945 if (V.getKind() == APValue::Int)
4948 return EvaluateBuiltinConstantPForLValue(V);
4949 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4950 return Arg->isEvaluatable(Ctx);
4951 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4953 Expr::EvalStatus Status;
4954 EvalInfo Info(Ctx, Status);
4955 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4956 : EvaluatePointer(Arg, LV, Info)) &&
4957 !Status.HasSideEffects)
4958 return EvaluateBuiltinConstantPForLValue(LV);
4961 // Anything else isn't considered to be sufficiently constant.
4965 /// Retrieves the "underlying object type" of the given expression,
4966 /// as used by __builtin_object_size.
4967 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4968 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4969 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4970 return VD->getType();
4971 } else if (const Expr *E = B.get<const Expr*>()) {
4972 if (isa<CompoundLiteralExpr>(E))
4973 return E->getType();
4979 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
4983 // The operand of __builtin_object_size is never evaluated for side-effects.
4984 // If there are any, but we can determine the pointed-to object anyway, then
4985 // ignore the side-effects.
4986 SpeculativeEvaluationRAII SpeculativeEval(Info);
4987 if (!EvaluatePointer(E->getArg(0), Base, Info))
4991 // If we can prove the base is null, lower to zero now.
4992 if (!Base.getLValueBase()) return Success(0, E);
4994 QualType T = GetObjectType(Base.getLValueBase());
4996 T->isIncompleteType() ||
4997 T->isFunctionType() ||
4998 T->isVariablyModifiedType() ||
4999 T->isDependentType())
5002 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5003 CharUnits Offset = Base.getLValueOffset();
5005 if (!Offset.isNegative() && Offset <= Size)
5008 Size = CharUnits::Zero();
5009 return Success(Size, E);
5012 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
5013 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
5015 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5017 case Builtin::BI__builtin_object_size: {
5018 if (TryEvaluateBuiltinObjectSize(E))
5021 // If evaluating the argument has side-effects, we can't determine the size
5022 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5023 // handle all cases where the expression has side-effects.
5024 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
5025 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
5026 return Success(-1ULL, E);
5027 return Success(0, E);
5030 // Expression had no side effects, but we couldn't statically determine the
5031 // size of the referenced object.
5035 case Builtin::BI__builtin_bswap16:
5036 case Builtin::BI__builtin_bswap32:
5037 case Builtin::BI__builtin_bswap64: {
5039 if (!EvaluateInteger(E->getArg(0), Val, Info))
5042 return Success(Val.byteSwap(), E);
5045 case Builtin::BI__builtin_classify_type:
5046 return Success(EvaluateBuiltinClassifyType(E), E);
5048 case Builtin::BI__builtin_constant_p:
5049 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
5051 case Builtin::BI__builtin_eh_return_data_regno: {
5052 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
5053 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
5054 return Success(Operand, E);
5057 case Builtin::BI__builtin_expect:
5058 return Visit(E->getArg(0));
5060 case Builtin::BIstrlen:
5061 // A call to strlen is not a constant expression.
5062 if (Info.getLangOpts().CPlusPlus11)
5063 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5064 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
5066 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5068 case Builtin::BI__builtin_strlen:
5069 // As an extension, we support strlen() and __builtin_strlen() as constant
5070 // expressions when the argument is a string literal.
5071 if (const StringLiteral *S
5072 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
5073 // The string literal may have embedded null characters. Find the first
5074 // one and truncate there.
5075 StringRef Str = S->getString();
5076 StringRef::size_type Pos = Str.find(0);
5077 if (Pos != StringRef::npos)
5078 Str = Str.substr(0, Pos);
5080 return Success(Str.size(), E);
5085 case Builtin::BI__atomic_always_lock_free:
5086 case Builtin::BI__atomic_is_lock_free:
5087 case Builtin::BI__c11_atomic_is_lock_free: {
5089 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
5092 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
5093 // of two less than the maximum inline atomic width, we know it is
5094 // lock-free. If the size isn't a power of two, or greater than the
5095 // maximum alignment where we promote atomics, we know it is not lock-free
5096 // (at least not in the sense of atomic_is_lock_free). Otherwise,
5097 // the answer can only be determined at runtime; for example, 16-byte
5098 // atomics have lock-free implementations on some, but not all,
5099 // x86-64 processors.
5101 // Check power-of-two.
5102 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
5103 if (Size.isPowerOfTwo()) {
5104 // Check against inlining width.
5105 unsigned InlineWidthBits =
5106 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
5107 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
5108 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
5109 Size == CharUnits::One() ||
5110 E->getArg(1)->isNullPointerConstant(Info.Ctx,
5111 Expr::NPC_NeverValueDependent))
5112 // OK, we will inline appropriately-aligned operations of this size,
5113 // and _Atomic(T) is appropriately-aligned.
5114 return Success(1, E);
5116 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
5117 castAs<PointerType>()->getPointeeType();
5118 if (!PointeeType->isIncompleteType() &&
5119 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
5120 // OK, we will inline operations on this object.
5121 return Success(1, E);
5126 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
5127 Success(0, E) : Error(E);
5132 static bool HasSameBase(const LValue &A, const LValue &B) {
5133 if (!A.getLValueBase())
5134 return !B.getLValueBase();
5135 if (!B.getLValueBase())
5138 if (A.getLValueBase().getOpaqueValue() !=
5139 B.getLValueBase().getOpaqueValue()) {
5140 const Decl *ADecl = GetLValueBaseDecl(A);
5143 const Decl *BDecl = GetLValueBaseDecl(B);
5144 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
5148 return IsGlobalLValue(A.getLValueBase()) ||
5149 A.getLValueCallIndex() == B.getLValueCallIndex();
5152 /// Perform the given integer operation, which is known to need at most BitWidth
5153 /// bits, and check for overflow in the original type (if that type was not an
5155 template<typename Operation>
5156 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
5157 const APSInt &LHS, const APSInt &RHS,
5158 unsigned BitWidth, Operation Op) {
5159 if (LHS.isUnsigned())
5160 return Op(LHS, RHS);
5162 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
5163 APSInt Result = Value.trunc(LHS.getBitWidth());
5164 if (Result.extend(BitWidth) != Value) {
5165 if (Info.getIntOverflowCheckMode())
5166 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
5167 diag::warn_integer_constant_overflow)
5168 << Result.toString(10) << E->getType();
5170 HandleOverflow(Info, E, Value, E->getType());
5177 /// \brief Data recursive integer evaluator of certain binary operators.
5179 /// We use a data recursive algorithm for binary operators so that we are able
5180 /// to handle extreme cases of chained binary operators without causing stack
5182 class DataRecursiveIntBinOpEvaluator {
5187 EvalResult() : Failed(false) { }
5189 void swap(EvalResult &RHS) {
5191 Failed = RHS.Failed;
5198 EvalResult LHSResult; // meaningful only for binary operator expression.
5199 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
5201 Job() : StoredInfo(0) { }
5202 void startSpeculativeEval(EvalInfo &Info) {
5203 OldEvalStatus = Info.EvalStatus;
5204 Info.EvalStatus.Diag = 0;
5209 StoredInfo->EvalStatus = OldEvalStatus;
5213 EvalInfo *StoredInfo; // non-null if status changed.
5214 Expr::EvalStatus OldEvalStatus;
5217 SmallVector<Job, 16> Queue;
5219 IntExprEvaluator &IntEval;
5221 APValue &FinalResult;
5224 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
5225 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
5227 /// \brief True if \param E is a binary operator that we are going to handle
5228 /// data recursively.
5229 /// We handle binary operators that are comma, logical, or that have operands
5230 /// with integral or enumeration type.
5231 static bool shouldEnqueue(const BinaryOperator *E) {
5232 return E->getOpcode() == BO_Comma ||
5234 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5235 E->getRHS()->getType()->isIntegralOrEnumerationType());
5238 bool Traverse(const BinaryOperator *E) {
5240 EvalResult PrevResult;
5241 while (!Queue.empty())
5242 process(PrevResult);
5244 if (PrevResult.Failed) return false;
5246 FinalResult.swap(PrevResult.Val);
5251 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5252 return IntEval.Success(Value, E, Result);
5254 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
5255 return IntEval.Success(Value, E, Result);
5257 bool Error(const Expr *E) {
5258 return IntEval.Error(E);
5260 bool Error(const Expr *E, diag::kind D) {
5261 return IntEval.Error(E, D);
5264 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5265 return Info.CCEDiag(E, D);
5268 // \brief Returns true if visiting the RHS is necessary, false otherwise.
5269 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
5270 bool &SuppressRHSDiags);
5272 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5273 const BinaryOperator *E, APValue &Result);
5275 void EvaluateExpr(const Expr *E, EvalResult &Result) {
5276 Result.Failed = !Evaluate(Result.Val, Info, E);
5278 Result.Val = APValue();
5281 void process(EvalResult &Result);
5283 void enqueue(const Expr *E) {
5284 E = E->IgnoreParens();
5285 Queue.resize(Queue.size()+1);
5287 Queue.back().Kind = Job::AnyExprKind;
5293 bool DataRecursiveIntBinOpEvaluator::
5294 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
5295 bool &SuppressRHSDiags) {
5296 if (E->getOpcode() == BO_Comma) {
5297 // Ignore LHS but note if we could not evaluate it.
5298 if (LHSResult.Failed)
5299 Info.EvalStatus.HasSideEffects = true;
5303 if (E->isLogicalOp()) {
5305 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
5306 // We were able to evaluate the LHS, see if we can get away with not
5307 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
5308 if (lhsResult == (E->getOpcode() == BO_LOr)) {
5309 Success(lhsResult, E, LHSResult.Val);
5310 return false; // Ignore RHS
5313 // Since we weren't able to evaluate the left hand side, it
5314 // must have had side effects.
5315 Info.EvalStatus.HasSideEffects = true;
5317 // We can't evaluate the LHS; however, sometimes the result
5318 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5319 // Don't ignore RHS and suppress diagnostics from this arm.
5320 SuppressRHSDiags = true;
5326 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5327 E->getRHS()->getType()->isIntegralOrEnumerationType());
5329 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
5330 return false; // Ignore RHS;
5335 bool DataRecursiveIntBinOpEvaluator::
5336 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
5337 const BinaryOperator *E, APValue &Result) {
5338 if (E->getOpcode() == BO_Comma) {
5339 if (RHSResult.Failed)
5341 Result = RHSResult.Val;
5345 if (E->isLogicalOp()) {
5346 bool lhsResult, rhsResult;
5347 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
5348 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
5352 if (E->getOpcode() == BO_LOr)
5353 return Success(lhsResult || rhsResult, E, Result);
5355 return Success(lhsResult && rhsResult, E, Result);
5359 // We can't evaluate the LHS; however, sometimes the result
5360 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
5361 if (rhsResult == (E->getOpcode() == BO_LOr))
5362 return Success(rhsResult, E, Result);
5369 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
5370 E->getRHS()->getType()->isIntegralOrEnumerationType());
5372 if (LHSResult.Failed || RHSResult.Failed)
5375 const APValue &LHSVal = LHSResult.Val;
5376 const APValue &RHSVal = RHSResult.Val;
5378 // Handle cases like (unsigned long)&a + 4.
5379 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
5381 CharUnits AdditionalOffset = CharUnits::fromQuantity(
5382 RHSVal.getInt().getZExtValue());
5383 if (E->getOpcode() == BO_Add)
5384 Result.getLValueOffset() += AdditionalOffset;
5386 Result.getLValueOffset() -= AdditionalOffset;
5390 // Handle cases like 4 + (unsigned long)&a
5391 if (E->getOpcode() == BO_Add &&
5392 RHSVal.isLValue() && LHSVal.isInt()) {
5394 Result.getLValueOffset() += CharUnits::fromQuantity(
5395 LHSVal.getInt().getZExtValue());
5399 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
5400 // Handle (intptr_t)&&A - (intptr_t)&&B.
5401 if (!LHSVal.getLValueOffset().isZero() ||
5402 !RHSVal.getLValueOffset().isZero())
5404 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
5405 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
5406 if (!LHSExpr || !RHSExpr)
5408 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5409 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5410 if (!LHSAddrExpr || !RHSAddrExpr)
5412 // Make sure both labels come from the same function.
5413 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5414 RHSAddrExpr->getLabel()->getDeclContext())
5416 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5420 // All the following cases expect both operands to be an integer
5421 if (!LHSVal.isInt() || !RHSVal.isInt())
5424 const APSInt &LHS = LHSVal.getInt();
5425 APSInt RHS = RHSVal.getInt();
5427 switch (E->getOpcode()) {
5431 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5432 LHS.getBitWidth() * 2,
5433 std::multiplies<APSInt>()), E,
5436 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5437 LHS.getBitWidth() + 1,
5438 std::plus<APSInt>()), E, Result);
5440 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
5441 LHS.getBitWidth() + 1,
5442 std::minus<APSInt>()), E, Result);
5443 case BO_And: return Success(LHS & RHS, E, Result);
5444 case BO_Xor: return Success(LHS ^ RHS, E, Result);
5445 case BO_Or: return Success(LHS | RHS, E, Result);
5449 return Error(E, diag::note_expr_divide_by_zero);
5450 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
5451 // not actually undefined behavior in C++11 due to a language defect.
5452 if (RHS.isNegative() && RHS.isAllOnesValue() &&
5453 LHS.isSigned() && LHS.isMinSignedValue())
5454 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
5455 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
5458 if (Info.getLangOpts().OpenCL)
5459 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5460 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
5461 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5463 else if (RHS.isSigned() && RHS.isNegative()) {
5464 // During constant-folding, a negative shift is an opposite shift. Such
5465 // a shift is not a constant expression.
5466 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5472 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
5473 // the shifted type.
5474 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5476 CCEDiag(E, diag::note_constexpr_large_shift)
5477 << RHS << E->getType() << LHS.getBitWidth();
5478 } else if (LHS.isSigned()) {
5479 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
5480 // operand, and must not overflow the corresponding unsigned type.
5481 if (LHS.isNegative())
5482 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
5483 else if (LHS.countLeadingZeros() < SA)
5484 CCEDiag(E, diag::note_constexpr_lshift_discards);
5487 return Success(LHS << SA, E, Result);
5490 if (Info.getLangOpts().OpenCL)
5491 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5492 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
5493 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
5495 else if (RHS.isSigned() && RHS.isNegative()) {
5496 // During constant-folding, a negative shift is an opposite shift. Such a
5497 // shift is not a constant expression.
5498 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
5504 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
5506 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
5508 CCEDiag(E, diag::note_constexpr_large_shift)
5509 << RHS << E->getType() << LHS.getBitWidth();
5511 return Success(LHS >> SA, E, Result);
5514 case BO_LT: return Success(LHS < RHS, E, Result);
5515 case BO_GT: return Success(LHS > RHS, E, Result);
5516 case BO_LE: return Success(LHS <= RHS, E, Result);
5517 case BO_GE: return Success(LHS >= RHS, E, Result);
5518 case BO_EQ: return Success(LHS == RHS, E, Result);
5519 case BO_NE: return Success(LHS != RHS, E, Result);
5523 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
5524 Job &job = Queue.back();
5527 case Job::AnyExprKind: {
5528 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
5529 if (shouldEnqueue(Bop)) {
5530 job.Kind = Job::BinOpKind;
5531 enqueue(Bop->getLHS());
5536 EvaluateExpr(job.E, Result);
5541 case Job::BinOpKind: {
5542 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5543 bool SuppressRHSDiags = false;
5544 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
5548 if (SuppressRHSDiags)
5549 job.startSpeculativeEval(Info);
5550 job.LHSResult.swap(Result);
5551 job.Kind = Job::BinOpVisitedLHSKind;
5552 enqueue(Bop->getRHS());
5556 case Job::BinOpVisitedLHSKind: {
5557 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
5560 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
5566 llvm_unreachable("Invalid Job::Kind!");
5569 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5570 if (E->isAssignmentOp())
5573 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
5574 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
5576 QualType LHSTy = E->getLHS()->getType();
5577 QualType RHSTy = E->getRHS()->getType();
5579 if (LHSTy->isAnyComplexType()) {
5580 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
5581 ComplexValue LHS, RHS;
5583 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
5584 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5587 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5590 if (LHS.isComplexFloat()) {
5591 APFloat::cmpResult CR_r =
5592 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
5593 APFloat::cmpResult CR_i =
5594 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
5596 if (E->getOpcode() == BO_EQ)
5597 return Success((CR_r == APFloat::cmpEqual &&
5598 CR_i == APFloat::cmpEqual), E);
5600 assert(E->getOpcode() == BO_NE &&
5601 "Invalid complex comparison.");
5602 return Success(((CR_r == APFloat::cmpGreaterThan ||
5603 CR_r == APFloat::cmpLessThan ||
5604 CR_r == APFloat::cmpUnordered) ||
5605 (CR_i == APFloat::cmpGreaterThan ||
5606 CR_i == APFloat::cmpLessThan ||
5607 CR_i == APFloat::cmpUnordered)), E);
5610 if (E->getOpcode() == BO_EQ)
5611 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
5612 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
5614 assert(E->getOpcode() == BO_NE &&
5615 "Invalid compex comparison.");
5616 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
5617 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
5622 if (LHSTy->isRealFloatingType() &&
5623 RHSTy->isRealFloatingType()) {
5624 APFloat RHS(0.0), LHS(0.0);
5626 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
5627 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5630 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
5633 APFloat::cmpResult CR = LHS.compare(RHS);
5635 switch (E->getOpcode()) {
5637 llvm_unreachable("Invalid binary operator!");
5639 return Success(CR == APFloat::cmpLessThan, E);
5641 return Success(CR == APFloat::cmpGreaterThan, E);
5643 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
5645 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
5648 return Success(CR == APFloat::cmpEqual, E);
5650 return Success(CR == APFloat::cmpGreaterThan
5651 || CR == APFloat::cmpLessThan
5652 || CR == APFloat::cmpUnordered, E);
5656 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5657 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
5658 LValue LHSValue, RHSValue;
5660 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
5661 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5664 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5667 // Reject differing bases from the normal codepath; we special-case
5668 // comparisons to null.
5669 if (!HasSameBase(LHSValue, RHSValue)) {
5670 if (E->getOpcode() == BO_Sub) {
5671 // Handle &&A - &&B.
5672 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
5674 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
5675 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
5676 if (!LHSExpr || !RHSExpr)
5678 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
5679 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
5680 if (!LHSAddrExpr || !RHSAddrExpr)
5682 // Make sure both labels come from the same function.
5683 if (LHSAddrExpr->getLabel()->getDeclContext() !=
5684 RHSAddrExpr->getLabel()->getDeclContext())
5686 Result = APValue(LHSAddrExpr, RHSAddrExpr);
5689 // Inequalities and subtractions between unrelated pointers have
5690 // unspecified or undefined behavior.
5691 if (!E->isEqualityOp())
5693 // A constant address may compare equal to the address of a symbol.
5694 // The one exception is that address of an object cannot compare equal
5695 // to a null pointer constant.
5696 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5697 (!RHSValue.Base && !RHSValue.Offset.isZero()))
5699 // It's implementation-defined whether distinct literals will have
5700 // distinct addresses. In clang, the result of such a comparison is
5701 // unspecified, so it is not a constant expression. However, we do know
5702 // that the address of a literal will be non-null.
5703 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5704 LHSValue.Base && RHSValue.Base)
5706 // We can't tell whether weak symbols will end up pointing to the same
5708 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
5710 // Pointers with different bases cannot represent the same object.
5711 // (Note that clang defaults to -fmerge-all-constants, which can
5712 // lead to inconsistent results for comparisons involving the address
5713 // of a constant; this generally doesn't matter in practice.)
5714 return Success(E->getOpcode() == BO_NE, E);
5717 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5718 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5720 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5721 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5723 if (E->getOpcode() == BO_Sub) {
5724 // C++11 [expr.add]p6:
5725 // Unless both pointers point to elements of the same array object, or
5726 // one past the last element of the array object, the behavior is
5728 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5729 !AreElementsOfSameArray(getType(LHSValue.Base),
5730 LHSDesignator, RHSDesignator))
5731 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5733 QualType Type = E->getLHS()->getType();
5734 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
5736 CharUnits ElementSize;
5737 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
5740 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5741 // and produce incorrect results when it overflows. Such behavior
5742 // appears to be non-conforming, but is common, so perhaps we should
5743 // assume the standard intended for such cases to be undefined behavior
5744 // and check for them.
5746 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5747 // overflow in the final conversion to ptrdiff_t.
5749 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5751 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5753 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5754 APSInt TrueResult = (LHS - RHS) / ElemSize;
5755 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5757 if (Result.extend(65) != TrueResult)
5758 HandleOverflow(Info, E, TrueResult, E->getType());
5759 return Success(Result, E);
5762 // C++11 [expr.rel]p3:
5763 // Pointers to void (after pointer conversions) can be compared, with a
5764 // result defined as follows: If both pointers represent the same
5765 // address or are both the null pointer value, the result is true if the
5766 // operator is <= or >= and false otherwise; otherwise the result is
5768 // We interpret this as applying to pointers to *cv* void.
5769 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
5770 E->isRelationalOp())
5771 CCEDiag(E, diag::note_constexpr_void_comparison);
5773 // C++11 [expr.rel]p2:
5774 // - If two pointers point to non-static data members of the same object,
5775 // or to subobjects or array elements fo such members, recursively, the
5776 // pointer to the later declared member compares greater provided the
5777 // two members have the same access control and provided their class is
5780 // - Otherwise pointer comparisons are unspecified.
5781 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5782 E->isRelationalOp()) {
5785 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5786 RHSDesignator, WasArrayIndex);
5787 // At the point where the designators diverge, the comparison has a
5788 // specified value if:
5789 // - we are comparing array indices
5790 // - we are comparing fields of a union, or fields with the same access
5791 // Otherwise, the result is unspecified and thus the comparison is not a
5792 // constant expression.
5793 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5794 Mismatch < RHSDesignator.Entries.size()) {
5795 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5796 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5798 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5800 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5801 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5802 << RF->getParent() << RF;
5804 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5805 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5806 << LF->getParent() << LF;
5807 else if (!LF->getParent()->isUnion() &&
5808 LF->getAccess() != RF->getAccess())
5809 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5810 << LF << LF->getAccess() << RF << RF->getAccess()
5815 // The comparison here must be unsigned, and performed with the same
5816 // width as the pointer.
5817 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5818 uint64_t CompareLHS = LHSOffset.getQuantity();
5819 uint64_t CompareRHS = RHSOffset.getQuantity();
5820 assert(PtrSize <= 64 && "Unexpected pointer width");
5821 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5825 // If there is a base and this is a relational operator, we can only
5826 // compare pointers within the object in question; otherwise, the result
5827 // depends on where the object is located in memory.
5828 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5829 QualType BaseTy = getType(LHSValue.Base);
5830 if (BaseTy->isIncompleteType())
5832 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5833 uint64_t OffsetLimit = Size.getQuantity();
5834 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5838 switch (E->getOpcode()) {
5839 default: llvm_unreachable("missing comparison operator");
5840 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5841 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5842 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5843 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5844 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5845 case BO_NE: return Success(CompareLHS != CompareRHS, E);
5850 if (LHSTy->isMemberPointerType()) {
5851 assert(E->isEqualityOp() && "unexpected member pointer operation");
5852 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5854 MemberPtr LHSValue, RHSValue;
5856 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5857 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5860 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5863 // C++11 [expr.eq]p2:
5864 // If both operands are null, they compare equal. Otherwise if only one is
5865 // null, they compare unequal.
5866 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5867 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5868 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5871 // Otherwise if either is a pointer to a virtual member function, the
5872 // result is unspecified.
5873 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5874 if (MD->isVirtual())
5875 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5876 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5877 if (MD->isVirtual())
5878 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5880 // Otherwise they compare equal if and only if they would refer to the
5881 // same member of the same most derived object or the same subobject if
5882 // they were dereferenced with a hypothetical object of the associated
5884 bool Equal = LHSValue == RHSValue;
5885 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5888 if (LHSTy->isNullPtrType()) {
5889 assert(E->isComparisonOp() && "unexpected nullptr operation");
5890 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5891 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5892 // are compared, the result is true of the operator is <=, >= or ==, and
5894 BinaryOperator::Opcode Opcode = E->getOpcode();
5895 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5898 assert((!LHSTy->isIntegralOrEnumerationType() ||
5899 !RHSTy->isIntegralOrEnumerationType()) &&
5900 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5901 // We can't continue from here for non-integral types.
5902 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5905 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
5906 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5907 // result shall be the alignment of the referenced type."
5908 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5909 T = Ref->getPointeeType();
5911 // __alignof is defined to return the preferred alignment.
5912 return Info.Ctx.toCharUnitsFromBits(
5913 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5916 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
5917 E = E->IgnoreParens();
5919 // The kinds of expressions that we have special-case logic here for
5920 // should be kept up to date with the special checks for those
5921 // expressions in Sema.
5923 // alignof decl is always accepted, even if it doesn't make sense: we default
5924 // to 1 in those cases.
5925 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5926 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5927 /*RefAsPointee*/true);
5929 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5930 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5931 /*RefAsPointee*/true);
5933 return GetAlignOfType(E->getType());
5937 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5938 /// a result as the expression's type.
5939 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5940 const UnaryExprOrTypeTraitExpr *E) {
5941 switch(E->getKind()) {
5942 case UETT_AlignOf: {
5943 if (E->isArgumentType())
5944 return Success(GetAlignOfType(E->getArgumentType()), E);
5946 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
5949 case UETT_VecStep: {
5950 QualType Ty = E->getTypeOfArgument();
5952 if (Ty->isVectorType()) {
5953 unsigned n = Ty->castAs<VectorType>()->getNumElements();
5955 // The vec_step built-in functions that take a 3-component
5956 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5960 return Success(n, E);
5962 return Success(1, E);
5966 QualType SrcTy = E->getTypeOfArgument();
5967 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5968 // the result is the size of the referenced type."
5969 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5970 SrcTy = Ref->getPointeeType();
5973 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
5975 return Success(Sizeof, E);
5979 llvm_unreachable("unknown expr/type trait");
5982 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
5984 unsigned n = OOE->getNumComponents();
5987 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
5988 for (unsigned i = 0; i != n; ++i) {
5989 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5990 switch (ON.getKind()) {
5991 case OffsetOfExpr::OffsetOfNode::Array: {
5992 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
5994 if (!EvaluateInteger(Idx, IdxResult, Info))
5996 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5999 CurrentType = AT->getElementType();
6000 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6001 Result += IdxResult.getSExtValue() * ElementSize;
6005 case OffsetOfExpr::OffsetOfNode::Field: {
6006 FieldDecl *MemberDecl = ON.getField();
6007 const RecordType *RT = CurrentType->getAs<RecordType>();
6010 RecordDecl *RD = RT->getDecl();
6011 if (RD->isInvalidDecl()) return false;
6012 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6013 unsigned i = MemberDecl->getFieldIndex();
6014 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
6015 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
6016 CurrentType = MemberDecl->getType().getNonReferenceType();
6020 case OffsetOfExpr::OffsetOfNode::Identifier:
6021 llvm_unreachable("dependent __builtin_offsetof");
6023 case OffsetOfExpr::OffsetOfNode::Base: {
6024 CXXBaseSpecifier *BaseSpec = ON.getBase();
6025 if (BaseSpec->isVirtual())
6028 // Find the layout of the class whose base we are looking into.
6029 const RecordType *RT = CurrentType->getAs<RecordType>();
6032 RecordDecl *RD = RT->getDecl();
6033 if (RD->isInvalidDecl()) return false;
6034 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6036 // Find the base class itself.
6037 CurrentType = BaseSpec->getType();
6038 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
6042 // Add the offset to the base.
6043 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
6048 return Success(Result, OOE);
6051 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6052 switch (E->getOpcode()) {
6054 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
6058 // FIXME: Should extension allow i-c-e extension expressions in its scope?
6059 // If so, we could clear the diagnostic ID.
6060 return Visit(E->getSubExpr());
6062 // The result is just the value.
6063 return Visit(E->getSubExpr());
6065 if (!Visit(E->getSubExpr()))
6067 if (!Result.isInt()) return Error(E);
6068 const APSInt &Value = Result.getInt();
6069 if (Value.isSigned() && Value.isMinSignedValue())
6070 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
6072 return Success(-Value, E);
6075 if (!Visit(E->getSubExpr()))
6077 if (!Result.isInt()) return Error(E);
6078 return Success(~Result.getInt(), E);
6082 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
6084 return Success(!bres, E);
6089 /// HandleCast - This is used to evaluate implicit or explicit casts where the
6090 /// result type is integer.
6091 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
6092 const Expr *SubExpr = E->getSubExpr();
6093 QualType DestType = E->getType();
6094 QualType SrcType = SubExpr->getType();
6096 switch (E->getCastKind()) {
6097 case CK_BaseToDerived:
6098 case CK_DerivedToBase:
6099 case CK_UncheckedDerivedToBase:
6102 case CK_ArrayToPointerDecay:
6103 case CK_FunctionToPointerDecay:
6104 case CK_NullToPointer:
6105 case CK_NullToMemberPointer:
6106 case CK_BaseToDerivedMemberPointer:
6107 case CK_DerivedToBaseMemberPointer:
6108 case CK_ReinterpretMemberPointer:
6109 case CK_ConstructorConversion:
6110 case CK_IntegralToPointer:
6112 case CK_VectorSplat:
6113 case CK_IntegralToFloating:
6114 case CK_FloatingCast:
6115 case CK_CPointerToObjCPointerCast:
6116 case CK_BlockPointerToObjCPointerCast:
6117 case CK_AnyPointerToBlockPointerCast:
6118 case CK_ObjCObjectLValueCast:
6119 case CK_FloatingRealToComplex:
6120 case CK_FloatingComplexToReal:
6121 case CK_FloatingComplexCast:
6122 case CK_FloatingComplexToIntegralComplex:
6123 case CK_IntegralRealToComplex:
6124 case CK_IntegralComplexCast:
6125 case CK_IntegralComplexToFloatingComplex:
6126 case CK_BuiltinFnToFnPtr:
6127 case CK_ZeroToOCLEvent:
6128 llvm_unreachable("invalid cast kind for integral value");
6132 case CK_LValueBitCast:
6133 case CK_ARCProduceObject:
6134 case CK_ARCConsumeObject:
6135 case CK_ARCReclaimReturnedObject:
6136 case CK_ARCExtendBlockObject:
6137 case CK_CopyAndAutoreleaseBlockObject:
6140 case CK_UserDefinedConversion:
6141 case CK_LValueToRValue:
6142 case CK_AtomicToNonAtomic:
6143 case CK_NonAtomicToAtomic:
6145 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6147 case CK_MemberPointerToBoolean:
6148 case CK_PointerToBoolean:
6149 case CK_IntegralToBoolean:
6150 case CK_FloatingToBoolean:
6151 case CK_FloatingComplexToBoolean:
6152 case CK_IntegralComplexToBoolean: {
6154 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
6156 return Success(BoolResult, E);
6159 case CK_IntegralCast: {
6160 if (!Visit(SubExpr))
6163 if (!Result.isInt()) {
6164 // Allow casts of address-of-label differences if they are no-ops
6165 // or narrowing. (The narrowing case isn't actually guaranteed to
6166 // be constant-evaluatable except in some narrow cases which are hard
6167 // to detect here. We let it through on the assumption the user knows
6168 // what they are doing.)
6169 if (Result.isAddrLabelDiff())
6170 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
6171 // Only allow casts of lvalues if they are lossless.
6172 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
6175 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
6176 Result.getInt()), E);
6179 case CK_PointerToIntegral: {
6180 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6183 if (!EvaluatePointer(SubExpr, LV, Info))
6186 if (LV.getLValueBase()) {
6187 // Only allow based lvalue casts if they are lossless.
6188 // FIXME: Allow a larger integer size than the pointer size, and allow
6189 // narrowing back down to pointer width in subsequent integral casts.
6190 // FIXME: Check integer type's active bits, not its type size.
6191 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
6194 LV.Designator.setInvalid();
6195 LV.moveInto(Result);
6199 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
6201 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
6204 case CK_IntegralComplexToReal: {
6206 if (!EvaluateComplex(SubExpr, C, Info))
6208 return Success(C.getComplexIntReal(), E);
6211 case CK_FloatingToIntegral: {
6213 if (!EvaluateFloat(SubExpr, F, Info))
6217 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
6219 return Success(Value, E);
6223 llvm_unreachable("unknown cast resulting in integral value");
6226 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6227 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6229 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6231 if (!LV.isComplexInt())
6233 return Success(LV.getComplexIntReal(), E);
6236 return Visit(E->getSubExpr());
6239 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6240 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
6242 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
6244 if (!LV.isComplexInt())
6246 return Success(LV.getComplexIntImag(), E);
6249 VisitIgnoredValue(E->getSubExpr());
6250 return Success(0, E);
6253 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
6254 return Success(E->getPackLength(), E);
6257 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
6258 return Success(E->getValue(), E);
6261 //===----------------------------------------------------------------------===//
6263 //===----------------------------------------------------------------------===//
6266 class FloatExprEvaluator
6267 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
6270 FloatExprEvaluator(EvalInfo &info, APFloat &result)
6271 : ExprEvaluatorBaseTy(info), Result(result) {}
6273 bool Success(const APValue &V, const Expr *e) {
6274 Result = V.getFloat();
6278 bool ZeroInitialization(const Expr *E) {
6279 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
6283 bool VisitCallExpr(const CallExpr *E);
6285 bool VisitUnaryOperator(const UnaryOperator *E);
6286 bool VisitBinaryOperator(const BinaryOperator *E);
6287 bool VisitFloatingLiteral(const FloatingLiteral *E);
6288 bool VisitCastExpr(const CastExpr *E);
6290 bool VisitUnaryReal(const UnaryOperator *E);
6291 bool VisitUnaryImag(const UnaryOperator *E);
6293 // FIXME: Missing: array subscript of vector, member of vector
6295 } // end anonymous namespace
6297 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
6298 assert(E->isRValue() && E->getType()->isRealFloatingType());
6299 return FloatExprEvaluator(Info, Result).Visit(E);
6302 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
6306 llvm::APFloat &Result) {
6307 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
6308 if (!S) return false;
6310 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
6314 // Treat empty strings as if they were zero.
6315 if (S->getString().empty())
6316 fill = llvm::APInt(32, 0);
6317 else if (S->getString().getAsInteger(0, fill))
6321 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
6323 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
6327 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
6328 switch (E->isBuiltinCall()) {
6330 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6332 case Builtin::BI__builtin_huge_val:
6333 case Builtin::BI__builtin_huge_valf:
6334 case Builtin::BI__builtin_huge_vall:
6335 case Builtin::BI__builtin_inf:
6336 case Builtin::BI__builtin_inff:
6337 case Builtin::BI__builtin_infl: {
6338 const llvm::fltSemantics &Sem =
6339 Info.Ctx.getFloatTypeSemantics(E->getType());
6340 Result = llvm::APFloat::getInf(Sem);
6344 case Builtin::BI__builtin_nans:
6345 case Builtin::BI__builtin_nansf:
6346 case Builtin::BI__builtin_nansl:
6347 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6352 case Builtin::BI__builtin_nan:
6353 case Builtin::BI__builtin_nanf:
6354 case Builtin::BI__builtin_nanl:
6355 // If this is __builtin_nan() turn this into a nan, otherwise we
6356 // can't constant fold it.
6357 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
6362 case Builtin::BI__builtin_fabs:
6363 case Builtin::BI__builtin_fabsf:
6364 case Builtin::BI__builtin_fabsl:
6365 if (!EvaluateFloat(E->getArg(0), Result, Info))
6368 if (Result.isNegative())
6369 Result.changeSign();
6372 case Builtin::BI__builtin_copysign:
6373 case Builtin::BI__builtin_copysignf:
6374 case Builtin::BI__builtin_copysignl: {
6376 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
6377 !EvaluateFloat(E->getArg(1), RHS, Info))
6379 Result.copySign(RHS);
6385 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6386 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6388 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6390 Result = CV.FloatReal;
6394 return Visit(E->getSubExpr());
6397 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6398 if (E->getSubExpr()->getType()->isAnyComplexType()) {
6400 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
6402 Result = CV.FloatImag;
6406 VisitIgnoredValue(E->getSubExpr());
6407 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
6408 Result = llvm::APFloat::getZero(Sem);
6412 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6413 switch (E->getOpcode()) {
6414 default: return Error(E);
6416 return EvaluateFloat(E->getSubExpr(), Result, Info);
6418 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
6420 Result.changeSign();
6425 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6426 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6427 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6430 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
6431 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6433 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
6436 switch (E->getOpcode()) {
6437 default: return Error(E);
6439 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
6442 Result.add(RHS, APFloat::rmNearestTiesToEven);
6445 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
6448 Result.divide(RHS, APFloat::rmNearestTiesToEven);
6452 if (Result.isInfinity() || Result.isNaN())
6453 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
6457 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
6458 Result = E->getValue();
6462 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
6463 const Expr* SubExpr = E->getSubExpr();
6465 switch (E->getCastKind()) {
6467 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6469 case CK_IntegralToFloating: {
6471 return EvaluateInteger(SubExpr, IntResult, Info) &&
6472 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
6473 E->getType(), Result);
6476 case CK_FloatingCast: {
6477 if (!Visit(SubExpr))
6479 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
6483 case CK_FloatingComplexToReal: {
6485 if (!EvaluateComplex(SubExpr, V, Info))
6487 Result = V.getComplexFloatReal();
6493 //===----------------------------------------------------------------------===//
6494 // Complex Evaluation (for float and integer)
6495 //===----------------------------------------------------------------------===//
6498 class ComplexExprEvaluator
6499 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
6500 ComplexValue &Result;
6503 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
6504 : ExprEvaluatorBaseTy(info), Result(Result) {}
6506 bool Success(const APValue &V, const Expr *e) {
6511 bool ZeroInitialization(const Expr *E);
6513 //===--------------------------------------------------------------------===//
6515 //===--------------------------------------------------------------------===//
6517 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
6518 bool VisitCastExpr(const CastExpr *E);
6519 bool VisitBinaryOperator(const BinaryOperator *E);
6520 bool VisitUnaryOperator(const UnaryOperator *E);
6521 bool VisitInitListExpr(const InitListExpr *E);
6523 } // end anonymous namespace
6525 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
6527 assert(E->isRValue() && E->getType()->isAnyComplexType());
6528 return ComplexExprEvaluator(Info, Result).Visit(E);
6531 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
6532 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
6533 if (ElemTy->isRealFloatingType()) {
6534 Result.makeComplexFloat();
6535 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
6536 Result.FloatReal = Zero;
6537 Result.FloatImag = Zero;
6539 Result.makeComplexInt();
6540 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
6541 Result.IntReal = Zero;
6542 Result.IntImag = Zero;
6547 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
6548 const Expr* SubExpr = E->getSubExpr();
6550 if (SubExpr->getType()->isRealFloatingType()) {
6551 Result.makeComplexFloat();
6552 APFloat &Imag = Result.FloatImag;
6553 if (!EvaluateFloat(SubExpr, Imag, Info))
6556 Result.FloatReal = APFloat(Imag.getSemantics());
6559 assert(SubExpr->getType()->isIntegerType() &&
6560 "Unexpected imaginary literal.");
6562 Result.makeComplexInt();
6563 APSInt &Imag = Result.IntImag;
6564 if (!EvaluateInteger(SubExpr, Imag, Info))
6567 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
6572 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
6574 switch (E->getCastKind()) {
6576 case CK_BaseToDerived:
6577 case CK_DerivedToBase:
6578 case CK_UncheckedDerivedToBase:
6581 case CK_ArrayToPointerDecay:
6582 case CK_FunctionToPointerDecay:
6583 case CK_NullToPointer:
6584 case CK_NullToMemberPointer:
6585 case CK_BaseToDerivedMemberPointer:
6586 case CK_DerivedToBaseMemberPointer:
6587 case CK_MemberPointerToBoolean:
6588 case CK_ReinterpretMemberPointer:
6589 case CK_ConstructorConversion:
6590 case CK_IntegralToPointer:
6591 case CK_PointerToIntegral:
6592 case CK_PointerToBoolean:
6594 case CK_VectorSplat:
6595 case CK_IntegralCast:
6596 case CK_IntegralToBoolean:
6597 case CK_IntegralToFloating:
6598 case CK_FloatingToIntegral:
6599 case CK_FloatingToBoolean:
6600 case CK_FloatingCast:
6601 case CK_CPointerToObjCPointerCast:
6602 case CK_BlockPointerToObjCPointerCast:
6603 case CK_AnyPointerToBlockPointerCast:
6604 case CK_ObjCObjectLValueCast:
6605 case CK_FloatingComplexToReal:
6606 case CK_FloatingComplexToBoolean:
6607 case CK_IntegralComplexToReal:
6608 case CK_IntegralComplexToBoolean:
6609 case CK_ARCProduceObject:
6610 case CK_ARCConsumeObject:
6611 case CK_ARCReclaimReturnedObject:
6612 case CK_ARCExtendBlockObject:
6613 case CK_CopyAndAutoreleaseBlockObject:
6614 case CK_BuiltinFnToFnPtr:
6615 case CK_ZeroToOCLEvent:
6616 llvm_unreachable("invalid cast kind for complex value");
6618 case CK_LValueToRValue:
6619 case CK_AtomicToNonAtomic:
6620 case CK_NonAtomicToAtomic:
6622 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6625 case CK_LValueBitCast:
6626 case CK_UserDefinedConversion:
6629 case CK_FloatingRealToComplex: {
6630 APFloat &Real = Result.FloatReal;
6631 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
6634 Result.makeComplexFloat();
6635 Result.FloatImag = APFloat(Real.getSemantics());
6639 case CK_FloatingComplexCast: {
6640 if (!Visit(E->getSubExpr()))
6643 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6645 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6647 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
6648 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
6651 case CK_FloatingComplexToIntegralComplex: {
6652 if (!Visit(E->getSubExpr()))
6655 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6657 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6658 Result.makeComplexInt();
6659 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
6660 To, Result.IntReal) &&
6661 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
6662 To, Result.IntImag);
6665 case CK_IntegralRealToComplex: {
6666 APSInt &Real = Result.IntReal;
6667 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
6670 Result.makeComplexInt();
6671 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
6675 case CK_IntegralComplexCast: {
6676 if (!Visit(E->getSubExpr()))
6679 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
6681 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
6683 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
6684 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
6688 case CK_IntegralComplexToFloatingComplex: {
6689 if (!Visit(E->getSubExpr()))
6692 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
6694 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
6695 Result.makeComplexFloat();
6696 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
6697 To, Result.FloatReal) &&
6698 HandleIntToFloatCast(Info, E, From, Result.IntImag,
6699 To, Result.FloatImag);
6703 llvm_unreachable("unknown cast resulting in complex value");
6706 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6707 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
6708 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6710 bool LHSOK = Visit(E->getLHS());
6711 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6715 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6718 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6719 "Invalid operands to binary operator.");
6720 switch (E->getOpcode()) {
6721 default: return Error(E);
6723 if (Result.isComplexFloat()) {
6724 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6725 APFloat::rmNearestTiesToEven);
6726 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6727 APFloat::rmNearestTiesToEven);
6729 Result.getComplexIntReal() += RHS.getComplexIntReal();
6730 Result.getComplexIntImag() += RHS.getComplexIntImag();
6734 if (Result.isComplexFloat()) {
6735 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6736 APFloat::rmNearestTiesToEven);
6737 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6738 APFloat::rmNearestTiesToEven);
6740 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6741 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6745 if (Result.isComplexFloat()) {
6746 ComplexValue LHS = Result;
6747 APFloat &LHS_r = LHS.getComplexFloatReal();
6748 APFloat &LHS_i = LHS.getComplexFloatImag();
6749 APFloat &RHS_r = RHS.getComplexFloatReal();
6750 APFloat &RHS_i = RHS.getComplexFloatImag();
6752 APFloat Tmp = LHS_r;
6753 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6754 Result.getComplexFloatReal() = Tmp;
6756 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6757 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6760 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6761 Result.getComplexFloatImag() = Tmp;
6763 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6764 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6766 ComplexValue LHS = Result;
6767 Result.getComplexIntReal() =
6768 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6769 LHS.getComplexIntImag() * RHS.getComplexIntImag());
6770 Result.getComplexIntImag() =
6771 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6772 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6776 if (Result.isComplexFloat()) {
6777 ComplexValue LHS = Result;
6778 APFloat &LHS_r = LHS.getComplexFloatReal();
6779 APFloat &LHS_i = LHS.getComplexFloatImag();
6780 APFloat &RHS_r = RHS.getComplexFloatReal();
6781 APFloat &RHS_i = RHS.getComplexFloatImag();
6782 APFloat &Res_r = Result.getComplexFloatReal();
6783 APFloat &Res_i = Result.getComplexFloatImag();
6785 APFloat Den = RHS_r;
6786 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6787 APFloat Tmp = RHS_i;
6788 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6789 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6792 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6794 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6795 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6796 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6799 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6801 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6802 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6803 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6805 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6806 return Error(E, diag::note_expr_divide_by_zero);
6808 ComplexValue LHS = Result;
6809 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6810 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6811 Result.getComplexIntReal() =
6812 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6813 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6814 Result.getComplexIntImag() =
6815 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6816 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6824 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6825 // Get the operand value into 'Result'.
6826 if (!Visit(E->getSubExpr()))
6829 switch (E->getOpcode()) {
6835 // The result is always just the subexpr.
6838 if (Result.isComplexFloat()) {
6839 Result.getComplexFloatReal().changeSign();
6840 Result.getComplexFloatImag().changeSign();
6843 Result.getComplexIntReal() = -Result.getComplexIntReal();
6844 Result.getComplexIntImag() = -Result.getComplexIntImag();
6848 if (Result.isComplexFloat())
6849 Result.getComplexFloatImag().changeSign();
6851 Result.getComplexIntImag() = -Result.getComplexIntImag();
6856 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6857 if (E->getNumInits() == 2) {
6858 if (E->getType()->isComplexType()) {
6859 Result.makeComplexFloat();
6860 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6862 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6865 Result.makeComplexInt();
6866 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6868 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6873 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6876 //===----------------------------------------------------------------------===//
6877 // Void expression evaluation, primarily for a cast to void on the LHS of a
6879 //===----------------------------------------------------------------------===//
6882 class VoidExprEvaluator
6883 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6885 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6887 bool Success(const APValue &V, const Expr *e) { return true; }
6889 bool VisitCastExpr(const CastExpr *E) {
6890 switch (E->getCastKind()) {
6892 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6894 VisitIgnoredValue(E->getSubExpr());
6899 } // end anonymous namespace
6901 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6902 assert(E->isRValue() && E->getType()->isVoidType());
6903 return VoidExprEvaluator(Info).Visit(E);
6906 //===----------------------------------------------------------------------===//
6907 // Top level Expr::EvaluateAsRValue method.
6908 //===----------------------------------------------------------------------===//
6910 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
6911 // In C, function designators are not lvalues, but we evaluate them as if they
6913 if (E->isGLValue() || E->getType()->isFunctionType()) {
6915 if (!EvaluateLValue(E, LV, Info))
6917 LV.moveInto(Result);
6918 } else if (E->getType()->isVectorType()) {
6919 if (!EvaluateVector(E, Result, Info))
6921 } else if (E->getType()->isIntegralOrEnumerationType()) {
6922 if (!IntExprEvaluator(Info, Result).Visit(E))
6924 } else if (E->getType()->hasPointerRepresentation()) {
6926 if (!EvaluatePointer(E, LV, Info))
6928 LV.moveInto(Result);
6929 } else if (E->getType()->isRealFloatingType()) {
6930 llvm::APFloat F(0.0);
6931 if (!EvaluateFloat(E, F, Info))
6933 Result = APValue(F);
6934 } else if (E->getType()->isAnyComplexType()) {
6936 if (!EvaluateComplex(E, C, Info))
6939 } else if (E->getType()->isMemberPointerType()) {
6941 if (!EvaluateMemberPointer(E, P, Info))
6945 } else if (E->getType()->isArrayType()) {
6947 LV.set(E, Info.CurrentCall->Index);
6948 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
6950 Result = Info.CurrentCall->Temporaries[E];
6951 } else if (E->getType()->isRecordType()) {
6953 LV.set(E, Info.CurrentCall->Index);
6954 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6956 Result = Info.CurrentCall->Temporaries[E];
6957 } else if (E->getType()->isVoidType()) {
6958 if (!Info.getLangOpts().CPlusPlus11)
6959 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
6961 if (!EvaluateVoid(E, Info))
6963 } else if (Info.getLangOpts().CPlusPlus11) {
6964 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
6967 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6974 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6975 /// cases, the in-place evaluation is essential, since later initializers for
6976 /// an object can indirectly refer to subobjects which were initialized earlier.
6977 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6978 const Expr *E, CheckConstantExpressionKind CCEK,
6979 bool AllowNonLiteralTypes) {
6980 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
6983 if (E->isRValue()) {
6984 // Evaluate arrays and record types in-place, so that later initializers can
6985 // refer to earlier-initialized members of the object.
6986 if (E->getType()->isArrayType())
6987 return EvaluateArray(E, This, Result, Info);
6988 else if (E->getType()->isRecordType())
6989 return EvaluateRecord(E, This, Result, Info);
6992 // For any other type, in-place evaluation is unimportant.
6993 return Evaluate(Result, Info, E);
6996 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6997 /// lvalue-to-rvalue cast if it is an lvalue.
6998 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
6999 if (!CheckLiteralType(Info, E))
7002 if (!::Evaluate(Result, Info, E))
7005 if (E->isGLValue()) {
7007 LV.setFrom(Info.Ctx, Result);
7008 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
7012 // Check this core constant expression is a constant expression.
7013 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
7016 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
7017 const ASTContext &Ctx, bool &IsConst) {
7018 // Fast-path evaluations of integer literals, since we sometimes see files
7019 // containing vast quantities of these.
7020 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
7021 Result.Val = APValue(APSInt(L->getValue(),
7022 L->getType()->isUnsignedIntegerType()));
7027 // FIXME: Evaluating values of large array and record types can cause
7028 // performance problems. Only do so in C++11 for now.
7029 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
7030 Exp->getType()->isRecordType()) &&
7031 !Ctx.getLangOpts().CPlusPlus11) {
7039 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
7040 /// any crazy technique (that has nothing to do with language standards) that
7041 /// we want to. If this function returns true, it returns the folded constant
7042 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
7043 /// will be applied to the result.
7044 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
7046 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
7049 EvalInfo Info(Ctx, Result);
7050 return ::EvaluateAsRValue(Info, this, Result.Val);
7053 bool Expr::EvaluateAsBooleanCondition(bool &Result,
7054 const ASTContext &Ctx) const {
7056 return EvaluateAsRValue(Scratch, Ctx) &&
7057 HandleConversionToBool(Scratch.Val, Result);
7060 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
7061 SideEffectsKind AllowSideEffects) const {
7062 if (!getType()->isIntegralOrEnumerationType())
7065 EvalResult ExprResult;
7066 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
7067 (!AllowSideEffects && ExprResult.HasSideEffects))
7070 Result = ExprResult.Val.getInt();
7074 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
7075 EvalInfo Info(Ctx, Result);
7078 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
7079 !CheckLValueConstantExpression(Info, getExprLoc(),
7080 Ctx.getLValueReferenceType(getType()), LV))
7083 LV.moveInto(Result.Val);
7087 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
7089 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
7090 // FIXME: Evaluating initializers for large array and record types can cause
7091 // performance problems. Only do so in C++11 for now.
7092 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
7093 !Ctx.getLangOpts().CPlusPlus11)
7096 Expr::EvalStatus EStatus;
7097 EStatus.Diag = &Notes;
7099 EvalInfo InitInfo(Ctx, EStatus);
7100 InitInfo.setEvaluatingDecl(VD, Value);
7105 // C++11 [basic.start.init]p2:
7106 // Variables with static storage duration or thread storage duration shall be
7107 // zero-initialized before any other initialization takes place.
7108 // This behavior is not present in C.
7109 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
7110 !VD->getType()->isReferenceType()) {
7111 ImplicitValueInitExpr VIE(VD->getType());
7112 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
7113 /*AllowNonLiteralTypes=*/true))
7117 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
7118 /*AllowNonLiteralTypes=*/true) ||
7119 EStatus.HasSideEffects)
7122 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
7126 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
7127 /// constant folded, but discard the result.
7128 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
7130 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
7133 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
7134 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
7135 EvalResult EvalResult;
7136 EvalResult.Diag = Diag;
7137 bool Result = EvaluateAsRValue(EvalResult, Ctx);
7139 assert(Result && "Could not evaluate expression");
7140 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
7142 return EvalResult.Val.getInt();
7145 void Expr::EvaluateForOverflow(const ASTContext &Ctx,
7146 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
7148 EvalResult EvalResult;
7149 EvalResult.Diag = Diags;
7150 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
7151 EvalInfo Info(Ctx, EvalResult, true);
7152 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
7156 bool Expr::EvalResult::isGlobalLValue() const {
7157 assert(Val.isLValue());
7158 return IsGlobalLValue(Val.getLValueBase());
7162 /// isIntegerConstantExpr - this recursive routine will test if an expression is
7163 /// an integer constant expression.
7165 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
7168 // CheckICE - This function does the fundamental ICE checking: the returned
7169 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
7170 // and a (possibly null) SourceLocation indicating the location of the problem.
7172 // Note that to reduce code duplication, this helper does no evaluation
7173 // itself; the caller checks whether the expression is evaluatable, and
7174 // in the rare cases where CheckICE actually cares about the evaluated
7175 // value, it calls into Evalute.
7180 /// This expression is an ICE.
7182 /// This expression is not an ICE, but if it isn't evaluated, it's
7183 /// a legal subexpression for an ICE. This return value is used to handle
7184 /// the comma operator in C99 mode, and non-constant subexpressions.
7185 IK_ICEIfUnevaluated,
7186 /// This expression is not an ICE, and is not a legal subexpression for one.
7194 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
7199 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
7201 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
7203 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
7204 Expr::EvalResult EVResult;
7205 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
7206 !EVResult.Val.isInt())
7207 return ICEDiag(IK_NotICE, E->getLocStart());
7212 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
7213 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
7214 if (!E->getType()->isIntegralOrEnumerationType())
7215 return ICEDiag(IK_NotICE, E->getLocStart());
7217 switch (E->getStmtClass()) {
7218 #define ABSTRACT_STMT(Node)
7219 #define STMT(Node, Base) case Expr::Node##Class:
7220 #define EXPR(Node, Base)
7221 #include "clang/AST/StmtNodes.inc"
7222 case Expr::PredefinedExprClass:
7223 case Expr::FloatingLiteralClass:
7224 case Expr::ImaginaryLiteralClass:
7225 case Expr::StringLiteralClass:
7226 case Expr::ArraySubscriptExprClass:
7227 case Expr::MemberExprClass:
7228 case Expr::CompoundAssignOperatorClass:
7229 case Expr::CompoundLiteralExprClass:
7230 case Expr::ExtVectorElementExprClass:
7231 case Expr::DesignatedInitExprClass:
7232 case Expr::ImplicitValueInitExprClass:
7233 case Expr::ParenListExprClass:
7234 case Expr::VAArgExprClass:
7235 case Expr::AddrLabelExprClass:
7236 case Expr::StmtExprClass:
7237 case Expr::CXXMemberCallExprClass:
7238 case Expr::CUDAKernelCallExprClass:
7239 case Expr::CXXDynamicCastExprClass:
7240 case Expr::CXXTypeidExprClass:
7241 case Expr::CXXUuidofExprClass:
7242 case Expr::MSPropertyRefExprClass:
7243 case Expr::CXXNullPtrLiteralExprClass:
7244 case Expr::UserDefinedLiteralClass:
7245 case Expr::CXXThisExprClass:
7246 case Expr::CXXThrowExprClass:
7247 case Expr::CXXNewExprClass:
7248 case Expr::CXXDeleteExprClass:
7249 case Expr::CXXPseudoDestructorExprClass:
7250 case Expr::UnresolvedLookupExprClass:
7251 case Expr::DependentScopeDeclRefExprClass:
7252 case Expr::CXXConstructExprClass:
7253 case Expr::CXXBindTemporaryExprClass:
7254 case Expr::ExprWithCleanupsClass:
7255 case Expr::CXXTemporaryObjectExprClass:
7256 case Expr::CXXUnresolvedConstructExprClass:
7257 case Expr::CXXDependentScopeMemberExprClass:
7258 case Expr::UnresolvedMemberExprClass:
7259 case Expr::ObjCStringLiteralClass:
7260 case Expr::ObjCBoxedExprClass:
7261 case Expr::ObjCArrayLiteralClass:
7262 case Expr::ObjCDictionaryLiteralClass:
7263 case Expr::ObjCEncodeExprClass:
7264 case Expr::ObjCMessageExprClass:
7265 case Expr::ObjCSelectorExprClass:
7266 case Expr::ObjCProtocolExprClass:
7267 case Expr::ObjCIvarRefExprClass:
7268 case Expr::ObjCPropertyRefExprClass:
7269 case Expr::ObjCSubscriptRefExprClass:
7270 case Expr::ObjCIsaExprClass:
7271 case Expr::ShuffleVectorExprClass:
7272 case Expr::BlockExprClass:
7273 case Expr::NoStmtClass:
7274 case Expr::OpaqueValueExprClass:
7275 case Expr::PackExpansionExprClass:
7276 case Expr::SubstNonTypeTemplateParmPackExprClass:
7277 case Expr::FunctionParmPackExprClass:
7278 case Expr::AsTypeExprClass:
7279 case Expr::ObjCIndirectCopyRestoreExprClass:
7280 case Expr::MaterializeTemporaryExprClass:
7281 case Expr::PseudoObjectExprClass:
7282 case Expr::AtomicExprClass:
7283 case Expr::InitListExprClass:
7284 case Expr::LambdaExprClass:
7285 return ICEDiag(IK_NotICE, E->getLocStart());
7287 case Expr::SizeOfPackExprClass:
7288 case Expr::GNUNullExprClass:
7289 // GCC considers the GNU __null value to be an integral constant expression.
7292 case Expr::SubstNonTypeTemplateParmExprClass:
7294 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
7296 case Expr::ParenExprClass:
7297 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
7298 case Expr::GenericSelectionExprClass:
7299 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
7300 case Expr::IntegerLiteralClass:
7301 case Expr::CharacterLiteralClass:
7302 case Expr::ObjCBoolLiteralExprClass:
7303 case Expr::CXXBoolLiteralExprClass:
7304 case Expr::CXXScalarValueInitExprClass:
7305 case Expr::UnaryTypeTraitExprClass:
7306 case Expr::BinaryTypeTraitExprClass:
7307 case Expr::TypeTraitExprClass:
7308 case Expr::ArrayTypeTraitExprClass:
7309 case Expr::ExpressionTraitExprClass:
7310 case Expr::CXXNoexceptExprClass:
7312 case Expr::CallExprClass:
7313 case Expr::CXXOperatorCallExprClass: {
7314 // C99 6.6/3 allows function calls within unevaluated subexpressions of
7315 // constant expressions, but they can never be ICEs because an ICE cannot
7316 // contain an operand of (pointer to) function type.
7317 const CallExpr *CE = cast<CallExpr>(E);
7318 if (CE->isBuiltinCall())
7319 return CheckEvalInICE(E, Ctx);
7320 return ICEDiag(IK_NotICE, E->getLocStart());
7322 case Expr::DeclRefExprClass: {
7323 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
7325 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
7326 if (Ctx.getLangOpts().CPlusPlus &&
7327 D && IsConstNonVolatile(D->getType())) {
7328 // Parameter variables are never constants. Without this check,
7329 // getAnyInitializer() can find a default argument, which leads
7331 if (isa<ParmVarDecl>(D))
7332 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
7335 // A variable of non-volatile const-qualified integral or enumeration
7336 // type initialized by an ICE can be used in ICEs.
7337 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
7338 if (!Dcl->getType()->isIntegralOrEnumerationType())
7339 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
7342 // Look for a declaration of this variable that has an initializer, and
7343 // check whether it is an ICE.
7344 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
7347 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
7350 return ICEDiag(IK_NotICE, E->getLocStart());
7352 case Expr::UnaryOperatorClass: {
7353 const UnaryOperator *Exp = cast<UnaryOperator>(E);
7354 switch (Exp->getOpcode()) {
7361 // C99 6.6/3 allows increment and decrement within unevaluated
7362 // subexpressions of constant expressions, but they can never be ICEs
7363 // because an ICE cannot contain an lvalue operand.
7364 return ICEDiag(IK_NotICE, E->getLocStart());
7372 return CheckICE(Exp->getSubExpr(), Ctx);
7375 // OffsetOf falls through here.
7377 case Expr::OffsetOfExprClass: {
7378 // Note that per C99, offsetof must be an ICE. And AFAIK, using
7379 // EvaluateAsRValue matches the proposed gcc behavior for cases like
7380 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
7381 // compliance: we should warn earlier for offsetof expressions with
7382 // array subscripts that aren't ICEs, and if the array subscripts
7383 // are ICEs, the value of the offsetof must be an integer constant.
7384 return CheckEvalInICE(E, Ctx);
7386 case Expr::UnaryExprOrTypeTraitExprClass: {
7387 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
7388 if ((Exp->getKind() == UETT_SizeOf) &&
7389 Exp->getTypeOfArgument()->isVariableArrayType())
7390 return ICEDiag(IK_NotICE, E->getLocStart());
7393 case Expr::BinaryOperatorClass: {
7394 const BinaryOperator *Exp = cast<BinaryOperator>(E);
7395 switch (Exp->getOpcode()) {
7409 // C99 6.6/3 allows assignments within unevaluated subexpressions of
7410 // constant expressions, but they can never be ICEs because an ICE cannot
7411 // contain an lvalue operand.
7412 return ICEDiag(IK_NotICE, E->getLocStart());
7431 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7432 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
7433 if (Exp->getOpcode() == BO_Div ||
7434 Exp->getOpcode() == BO_Rem) {
7435 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
7436 // we don't evaluate one.
7437 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
7438 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
7440 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
7441 if (REval.isSigned() && REval.isAllOnesValue()) {
7442 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
7443 if (LEval.isMinSignedValue())
7444 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
7448 if (Exp->getOpcode() == BO_Comma) {
7449 if (Ctx.getLangOpts().C99) {
7450 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
7451 // if it isn't evaluated.
7452 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
7453 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
7455 // In both C89 and C++, commas in ICEs are illegal.
7456 return ICEDiag(IK_NotICE, E->getLocStart());
7459 return Worst(LHSResult, RHSResult);
7463 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
7464 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
7465 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
7466 // Rare case where the RHS has a comma "side-effect"; we need
7467 // to actually check the condition to see whether the side
7468 // with the comma is evaluated.
7469 if ((Exp->getOpcode() == BO_LAnd) !=
7470 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
7475 return Worst(LHSResult, RHSResult);
7479 case Expr::ImplicitCastExprClass:
7480 case Expr::CStyleCastExprClass:
7481 case Expr::CXXFunctionalCastExprClass:
7482 case Expr::CXXStaticCastExprClass:
7483 case Expr::CXXReinterpretCastExprClass:
7484 case Expr::CXXConstCastExprClass:
7485 case Expr::ObjCBridgedCastExprClass: {
7486 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
7487 if (isa<ExplicitCastExpr>(E)) {
7488 if (const FloatingLiteral *FL
7489 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
7490 unsigned DestWidth = Ctx.getIntWidth(E->getType());
7491 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
7492 APSInt IgnoredVal(DestWidth, !DestSigned);
7494 // If the value does not fit in the destination type, the behavior is
7495 // undefined, so we are not required to treat it as a constant
7497 if (FL->getValue().convertToInteger(IgnoredVal,
7498 llvm::APFloat::rmTowardZero,
7499 &Ignored) & APFloat::opInvalidOp)
7500 return ICEDiag(IK_NotICE, E->getLocStart());
7504 switch (cast<CastExpr>(E)->getCastKind()) {
7505 case CK_LValueToRValue:
7506 case CK_AtomicToNonAtomic:
7507 case CK_NonAtomicToAtomic:
7509 case CK_IntegralToBoolean:
7510 case CK_IntegralCast:
7511 return CheckICE(SubExpr, Ctx);
7513 return ICEDiag(IK_NotICE, E->getLocStart());
7516 case Expr::BinaryConditionalOperatorClass: {
7517 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
7518 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
7519 if (CommonResult.Kind == IK_NotICE) return CommonResult;
7520 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
7521 if (FalseResult.Kind == IK_NotICE) return FalseResult;
7522 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
7523 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
7524 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
7527 case Expr::ConditionalOperatorClass: {
7528 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
7529 // If the condition (ignoring parens) is a __builtin_constant_p call,
7530 // then only the true side is actually considered in an integer constant
7531 // expression, and it is fully evaluated. This is an important GNU
7532 // extension. See GCC PR38377 for discussion.
7533 if (const CallExpr *CallCE
7534 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
7535 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
7536 return CheckEvalInICE(E, Ctx);
7537 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
7538 if (CondResult.Kind == IK_NotICE)
7541 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
7542 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
7544 if (TrueResult.Kind == IK_NotICE)
7546 if (FalseResult.Kind == IK_NotICE)
7548 if (CondResult.Kind == IK_ICEIfUnevaluated)
7550 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
7552 // Rare case where the diagnostics depend on which side is evaluated
7553 // Note that if we get here, CondResult is 0, and at least one of
7554 // TrueResult and FalseResult is non-zero.
7555 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
7559 case Expr::CXXDefaultArgExprClass:
7560 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
7561 case Expr::CXXDefaultInitExprClass:
7562 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
7563 case Expr::ChooseExprClass: {
7564 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
7568 llvm_unreachable("Invalid StmtClass!");
7571 /// Evaluate an expression as a C++11 integral constant expression.
7572 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
7574 llvm::APSInt *Value,
7575 SourceLocation *Loc) {
7576 if (!E->getType()->isIntegralOrEnumerationType()) {
7577 if (Loc) *Loc = E->getExprLoc();
7582 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
7585 assert(Result.isInt() && "pointer cast to int is not an ICE");
7586 if (Value) *Value = Result.getInt();
7590 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
7591 if (Ctx.getLangOpts().CPlusPlus11)
7592 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
7594 ICEDiag D = CheckICE(this, Ctx);
7595 if (D.Kind != IK_ICE) {
7596 if (Loc) *Loc = D.Loc;
7602 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
7603 SourceLocation *Loc, bool isEvaluated) const {
7604 if (Ctx.getLangOpts().CPlusPlus11)
7605 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
7607 if (!isIntegerConstantExpr(Ctx, Loc))
7609 if (!EvaluateAsInt(Value, Ctx))
7610 llvm_unreachable("ICE cannot be evaluated!");
7614 bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
7615 return CheckICE(this, Ctx).Kind == IK_ICE;
7618 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
7619 SourceLocation *Loc) const {
7620 // We support this checking in C++98 mode in order to diagnose compatibility
7622 assert(Ctx.getLangOpts().CPlusPlus);
7624 // Build evaluation settings.
7625 Expr::EvalStatus Status;
7626 SmallVector<PartialDiagnosticAt, 8> Diags;
7627 Status.Diag = &Diags;
7628 EvalInfo Info(Ctx, Status);
7631 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
7633 if (!Diags.empty()) {
7634 IsConstExpr = false;
7635 if (Loc) *Loc = Diags[0].first;
7636 } else if (!IsConstExpr) {
7637 // FIXME: This shouldn't happen.
7638 if (Loc) *Loc = getExprLoc();
7644 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
7646 PartialDiagnosticAt> &Diags) {
7647 // FIXME: It would be useful to check constexpr function templates, but at the
7648 // moment the constant expression evaluator cannot cope with the non-rigorous
7649 // ASTs which we build for dependent expressions.
7650 if (FD->isDependentContext())
7653 Expr::EvalStatus Status;
7654 Status.Diag = &Diags;
7656 EvalInfo Info(FD->getASTContext(), Status);
7657 Info.CheckingPotentialConstantExpression = true;
7659 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7660 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
7662 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
7663 // is a temporary being used as the 'this' pointer.
7665 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
7666 This.set(&VIE, Info.CurrentCall->Index);
7668 ArrayRef<const Expr*> Args;
7670 SourceLocation Loc = FD->getLocation();
7673 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
7674 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
7676 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
7677 Args, FD->getBody(), Info, Scratch);
7679 return Diags.empty();