1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr constant evaluator.
12 // Constant expression evaluation produces four main results:
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
19 // * An evaluated result, valid only if constant folding has not failed.
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
34 //===----------------------------------------------------------------------===//
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
55 static bool IsGlobalLValue(APValue::LValueBase B);
59 struct CallStackFrame;
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67 const Expr *Base = B.get<const Expr*>();
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 // Keep any cv-qualifiers from the reference if we generated a temporary
81 return Inner->getType();
84 return Base->getType();
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field or base class.
90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
106 /// Determine whether this LValue path entry for a base class names a virtual
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return getAsBaseOrMember(E).getInt();
112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
131 MostDerivedLength = I + 1;
132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
135 MostDerivedLength = I + 1;
137 // Path[I] describes a base class.
141 return MostDerivedLength;
144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
147 CSK_This, CSK_Real, CSK_Imag
150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
160 /// The length of the path to the most-derived object of which this is a
162 unsigned MostDerivedPathLength : 30;
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
171 typedef APValue::LValuePathEntry PathEntry;
173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
176 SubobjectDesignator() : Invalid(true) {}
178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
216 return !isOnePastTheEnd();
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
225 Entry.ArrayIndex = 0;
226 Entries.push_back(Entry);
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
233 /// Update this designator to refer to the given base or member of this
235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
239 Entries.push_back(Entry);
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
261 /// Add N to the address of this subobject.
262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
265 Entries.back().ArrayIndex += N;
266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
290 /// Parent - The caller of this stack frame.
291 CallStackFrame *Caller;
293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
299 /// Index - The call index of this call.
302 /// This - The binding for the this pointer in this call, if any.
305 /// Arguments - Parameter bindings for this function call, indexed by
306 /// parameters' function scope indices.
309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
311 typedef std::map<const void*, APValue> MapTy;
312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
321 APValue *getTemporary(const void *Key) {
322 MapTy::iterator I = Temporaries.find(Key);
323 return I == Temporaries.end() ? nullptr : &I->second;
325 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
328 /// Temporarily override 'this'.
329 class ThisOverrideRAII {
331 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332 : Frame(Frame), OldThis(Frame.This) {
334 Frame.This = NewThis;
336 ~ThisOverrideRAII() {
337 Frame.This = OldThis;
340 CallStackFrame &Frame;
341 const LValue *OldThis;
344 /// A partial diagnostic which we might know in advance that we are not going
346 class OptionalDiagnostic {
347 PartialDiagnostic *Diag;
350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
354 OptionalDiagnostic &operator<<(const T &v) {
360 OptionalDiagnostic &operator<<(const APSInt &I) {
362 SmallVector<char, 32> Buffer;
364 *Diag << StringRef(Buffer.data(), Buffer.size());
369 OptionalDiagnostic &operator<<(const APFloat &F) {
371 // FIXME: Force the precision of the source value down so we don't
372 // print digits which are usually useless (we don't really care here if
373 // we truncate a digit by accident in edge cases). Ideally,
374 // APFloat::toString would automatically print the shortest
375 // representation which rounds to the correct value, but it's a bit
376 // tricky to implement.
378 llvm::APFloat::semanticsPrecision(F.getSemantics());
379 precision = (precision * 59 + 195) / 196;
380 SmallVector<char, 32> Buffer;
381 F.toString(Buffer, precision);
382 *Diag << StringRef(Buffer.data(), Buffer.size());
388 /// A cleanup, and a flag indicating whether it is lifetime-extended.
390 llvm::PointerIntPair<APValue*, 1, bool> Value;
393 Cleanup(APValue *Val, bool IsLifetimeExtended)
394 : Value(Val, IsLifetimeExtended) {}
396 bool isLifetimeExtended() const { return Value.getInt(); }
398 *Value.getPointer() = APValue();
402 /// EvalInfo - This is a private struct used by the evaluator to capture
403 /// information about a subexpression as it is folded. It retains information
404 /// about the AST context, but also maintains information about the folded
407 /// If an expression could be evaluated, it is still possible it is not a C
408 /// "integer constant expression" or constant expression. If not, this struct
409 /// captures information about how and why not.
411 /// One bit of information passed *into* the request for constant folding
412 /// indicates whether the subexpression is "evaluated" or not according to C
413 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
414 /// evaluate the expression regardless of what the RHS is, but C only allows
415 /// certain things in certain situations.
419 /// EvalStatus - Contains information about the evaluation.
420 Expr::EvalStatus &EvalStatus;
422 /// CurrentCall - The top of the constexpr call stack.
423 CallStackFrame *CurrentCall;
425 /// CallStackDepth - The number of calls in the call stack right now.
426 unsigned CallStackDepth;
428 /// NextCallIndex - The next call index to assign.
429 unsigned NextCallIndex;
431 /// StepsLeft - The remaining number of evaluation steps we're permitted
432 /// to perform. This is essentially a limit for the number of statements
433 /// we will evaluate.
436 /// BottomFrame - The frame in which evaluation started. This must be
437 /// initialized after CurrentCall and CallStackDepth.
438 CallStackFrame BottomFrame;
440 /// A stack of values whose lifetimes end at the end of some surrounding
441 /// evaluation frame.
442 llvm::SmallVector<Cleanup, 16> CleanupStack;
444 /// EvaluatingDecl - This is the declaration whose initializer is being
445 /// evaluated, if any.
446 APValue::LValueBase EvaluatingDecl;
448 /// EvaluatingDeclValue - This is the value being constructed for the
449 /// declaration whose initializer is being evaluated, if any.
450 APValue *EvaluatingDeclValue;
452 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
453 /// notes attached to it will also be stored, otherwise they will not be.
454 bool HasActiveDiagnostic;
456 enum EvaluationMode {
457 /// Evaluate as a constant expression. Stop if we find that the expression
458 /// is not a constant expression.
459 EM_ConstantExpression,
461 /// Evaluate as a potential constant expression. Keep going if we hit a
462 /// construct that we can't evaluate yet (because we don't yet know the
463 /// value of something) but stop if we hit something that could never be
464 /// a constant expression.
465 EM_PotentialConstantExpression,
467 /// Fold the expression to a constant. Stop if we hit a side-effect that
471 /// Evaluate the expression looking for integer overflow and similar
472 /// issues. Don't worry about side-effects, and try to visit all
474 EM_EvaluateForOverflow,
476 /// Evaluate in any way we know how. Don't worry about side-effects that
477 /// can't be modeled.
478 EM_IgnoreSideEffects,
480 /// Evaluate as a constant expression. Stop if we find that the expression
481 /// is not a constant expression. Some expressions can be retried in the
482 /// optimizer if we don't constant fold them here, but in an unevaluated
483 /// context we try to fold them immediately since the optimizer never
484 /// gets a chance to look at it.
485 EM_ConstantExpressionUnevaluated,
487 /// Evaluate as a potential constant expression. Keep going if we hit a
488 /// construct that we can't evaluate yet (because we don't yet know the
489 /// value of something) but stop if we hit something that could never be
490 /// a constant expression. Some expressions can be retried in the
491 /// optimizer if we don't constant fold them here, but in an unevaluated
492 /// context we try to fold them immediately since the optimizer never
493 /// gets a chance to look at it.
494 EM_PotentialConstantExpressionUnevaluated
497 /// Are we checking whether the expression is a potential constant
499 bool checkingPotentialConstantExpression() const {
500 return EvalMode == EM_PotentialConstantExpression ||
501 EvalMode == EM_PotentialConstantExpressionUnevaluated;
504 /// Are we checking an expression for overflow?
505 // FIXME: We should check for any kind of undefined or suspicious behavior
506 // in such constructs, not just overflow.
507 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
510 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
511 CallStackDepth(0), NextCallIndex(1),
512 StepsLeft(getLangOpts().ConstexprStepLimit),
513 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
514 EvaluatingDecl((const ValueDecl *)nullptr),
515 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
518 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
519 EvaluatingDecl = Base;
520 EvaluatingDeclValue = &Value;
523 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
525 bool CheckCallLimit(SourceLocation Loc) {
526 // Don't perform any constexpr calls (other than the call we're checking)
527 // when checking a potential constant expression.
528 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
530 if (NextCallIndex == 0) {
531 // NextCallIndex has wrapped around.
532 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
535 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
538 << getLangOpts().ConstexprCallDepth;
542 CallStackFrame *getCallFrame(unsigned CallIndex) {
543 assert(CallIndex && "no call index in getCallFrame");
544 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
545 // be null in this loop.
546 CallStackFrame *Frame = CurrentCall;
547 while (Frame->Index > CallIndex)
548 Frame = Frame->Caller;
549 return (Frame->Index == CallIndex) ? Frame : nullptr;
552 bool nextStep(const Stmt *S) {
554 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
562 /// Add a diagnostic to the diagnostics list.
563 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
564 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
565 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
566 return EvalStatus.Diag->back().second;
569 /// Add notes containing a call stack to the current point of evaluation.
570 void addCallStack(unsigned Limit);
573 /// Diagnose that the evaluation cannot be folded.
574 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
575 = diag::note_invalid_subexpr_in_const_expr,
576 unsigned ExtraNotes = 0) {
577 if (EvalStatus.Diag) {
578 // If we have a prior diagnostic, it will be noting that the expression
579 // isn't a constant expression. This diagnostic is more important,
580 // unless we require this evaluation to produce a constant expression.
582 // FIXME: We might want to show both diagnostics to the user in
583 // EM_ConstantFold mode.
584 if (!EvalStatus.Diag->empty()) {
586 case EM_ConstantFold:
587 case EM_IgnoreSideEffects:
588 case EM_EvaluateForOverflow:
589 if (!EvalStatus.HasSideEffects)
591 // We've had side-effects; we want the diagnostic from them, not
592 // some later problem.
593 case EM_ConstantExpression:
594 case EM_PotentialConstantExpression:
595 case EM_ConstantExpressionUnevaluated:
596 case EM_PotentialConstantExpressionUnevaluated:
597 HasActiveDiagnostic = false;
598 return OptionalDiagnostic();
602 unsigned CallStackNotes = CallStackDepth - 1;
603 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605 CallStackNotes = std::min(CallStackNotes, Limit + 1);
606 if (checkingPotentialConstantExpression())
609 HasActiveDiagnostic = true;
610 EvalStatus.Diag->clear();
611 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
612 addDiag(Loc, DiagId);
613 if (!checkingPotentialConstantExpression())
615 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
617 HasActiveDiagnostic = false;
618 return OptionalDiagnostic();
621 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
622 = diag::note_invalid_subexpr_in_const_expr,
623 unsigned ExtraNotes = 0) {
625 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
626 HasActiveDiagnostic = false;
627 return OptionalDiagnostic();
630 /// Diagnose that the evaluation does not produce a C++11 core constant
633 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
634 /// EM_PotentialConstantExpression mode and we produce one of these.
635 template<typename LocArg>
636 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
637 = diag::note_invalid_subexpr_in_const_expr,
638 unsigned ExtraNotes = 0) {
639 // Don't override a previous diagnostic. Don't bother collecting
640 // diagnostics if we're evaluating for overflow.
641 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
642 HasActiveDiagnostic = false;
643 return OptionalDiagnostic();
645 return Diag(Loc, DiagId, ExtraNotes);
648 /// Add a note to a prior diagnostic.
649 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
650 if (!HasActiveDiagnostic)
651 return OptionalDiagnostic();
652 return OptionalDiagnostic(&addDiag(Loc, DiagId));
655 /// Add a stack of notes to a prior diagnostic.
656 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
657 if (HasActiveDiagnostic) {
658 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
659 Diags.begin(), Diags.end());
663 /// Should we continue evaluation after encountering a side-effect that we
665 bool keepEvaluatingAfterSideEffect() {
667 case EM_PotentialConstantExpression:
668 case EM_PotentialConstantExpressionUnevaluated:
669 case EM_EvaluateForOverflow:
670 case EM_IgnoreSideEffects:
673 case EM_ConstantExpression:
674 case EM_ConstantExpressionUnevaluated:
675 case EM_ConstantFold:
678 llvm_unreachable("Missed EvalMode case");
681 /// Note that we have had a side-effect, and determine whether we should
683 bool noteSideEffect() {
684 EvalStatus.HasSideEffects = true;
685 return keepEvaluatingAfterSideEffect();
688 /// Should we continue evaluation as much as possible after encountering a
689 /// construct which can't be reduced to a value?
690 bool keepEvaluatingAfterFailure() {
695 case EM_PotentialConstantExpression:
696 case EM_PotentialConstantExpressionUnevaluated:
697 case EM_EvaluateForOverflow:
700 case EM_ConstantExpression:
701 case EM_ConstantExpressionUnevaluated:
702 case EM_ConstantFold:
703 case EM_IgnoreSideEffects:
706 llvm_unreachable("Missed EvalMode case");
710 /// Object used to treat all foldable expressions as constant expressions.
711 struct FoldConstant {
714 bool HadNoPriorDiags;
715 EvalInfo::EvaluationMode OldMode;
717 explicit FoldConstant(EvalInfo &Info, bool Enabled)
720 HadNoPriorDiags(Info.EvalStatus.Diag &&
721 Info.EvalStatus.Diag->empty() &&
722 !Info.EvalStatus.HasSideEffects),
723 OldMode(Info.EvalMode) {
725 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
726 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
727 Info.EvalMode = EvalInfo::EM_ConstantFold;
729 void keepDiagnostics() { Enabled = false; }
731 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
732 !Info.EvalStatus.HasSideEffects)
733 Info.EvalStatus.Diag->clear();
734 Info.EvalMode = OldMode;
738 /// RAII object used to suppress diagnostics and side-effects from a
739 /// speculative evaluation.
740 class SpeculativeEvaluationRAII {
742 Expr::EvalStatus Old;
745 SpeculativeEvaluationRAII(EvalInfo &Info,
746 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
747 : Info(Info), Old(Info.EvalStatus) {
748 Info.EvalStatus.Diag = NewDiag;
749 // If we're speculatively evaluating, we may have skipped over some
750 // evaluations and missed out a side effect.
751 Info.EvalStatus.HasSideEffects = true;
753 ~SpeculativeEvaluationRAII() {
754 Info.EvalStatus = Old;
758 /// RAII object wrapping a full-expression or block scope, and handling
759 /// the ending of the lifetime of temporaries created within it.
760 template<bool IsFullExpression>
763 unsigned OldStackSize;
765 ScopeRAII(EvalInfo &Info)
766 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
768 // Body moved to a static method to encourage the compiler to inline away
769 // instances of this class.
770 cleanup(Info, OldStackSize);
773 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
774 unsigned NewEnd = OldStackSize;
775 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
778 // Full-expression cleanup of a lifetime-extended temporary: nothing
779 // to do, just move this cleanup to the right place in the stack.
780 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
783 // End the lifetime of the object.
784 Info.CleanupStack[I].endLifetime();
787 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
788 Info.CleanupStack.end());
791 typedef ScopeRAII<false> BlockScopeRAII;
792 typedef ScopeRAII<true> FullExpressionRAII;
795 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
796 CheckSubobjectKind CSK) {
799 if (isOnePastTheEnd()) {
800 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
808 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
809 const Expr *E, uint64_t N) {
810 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
811 Info.CCEDiag(E, diag::note_constexpr_array_index)
812 << static_cast<int>(N) << /*array*/ 0
813 << static_cast<unsigned>(MostDerivedArraySize);
815 Info.CCEDiag(E, diag::note_constexpr_array_index)
816 << static_cast<int>(N) << /*non-array*/ 1;
820 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
821 const FunctionDecl *Callee, const LValue *This,
823 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
824 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
825 Info.CurrentCall = this;
826 ++Info.CallStackDepth;
829 CallStackFrame::~CallStackFrame() {
830 assert(Info.CurrentCall == this && "calls retired out of order");
831 --Info.CallStackDepth;
832 Info.CurrentCall = Caller;
835 APValue &CallStackFrame::createTemporary(const void *Key,
836 bool IsLifetimeExtended) {
837 APValue &Result = Temporaries[Key];
838 assert(Result.isUninit() && "temporary created multiple times");
839 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
843 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
845 void EvalInfo::addCallStack(unsigned Limit) {
846 // Determine which calls to skip, if any.
847 unsigned ActiveCalls = CallStackDepth - 1;
848 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
849 if (Limit && Limit < ActiveCalls) {
850 SkipStart = Limit / 2 + Limit % 2;
851 SkipEnd = ActiveCalls - Limit / 2;
854 // Walk the call stack and add the diagnostics.
855 unsigned CallIdx = 0;
856 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
857 Frame = Frame->Caller, ++CallIdx) {
859 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
860 if (CallIdx == SkipStart) {
861 // Note that we're skipping calls.
862 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
863 << unsigned(ActiveCalls - Limit);
868 SmallVector<char, 128> Buffer;
869 llvm::raw_svector_ostream Out(Buffer);
870 describeCall(Frame, Out);
871 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
876 struct ComplexValue {
881 APSInt IntReal, IntImag;
882 APFloat FloatReal, FloatImag;
884 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886 void makeComplexFloat() { IsInt = false; }
887 bool isComplexFloat() const { return !IsInt; }
888 APFloat &getComplexFloatReal() { return FloatReal; }
889 APFloat &getComplexFloatImag() { return FloatImag; }
891 void makeComplexInt() { IsInt = true; }
892 bool isComplexInt() const { return IsInt; }
893 APSInt &getComplexIntReal() { return IntReal; }
894 APSInt &getComplexIntImag() { return IntImag; }
896 void moveInto(APValue &v) const {
897 if (isComplexFloat())
898 v = APValue(FloatReal, FloatImag);
900 v = APValue(IntReal, IntImag);
902 void setFrom(const APValue &v) {
903 assert(v.isComplexFloat() || v.isComplexInt());
904 if (v.isComplexFloat()) {
906 FloatReal = v.getComplexFloatReal();
907 FloatImag = v.getComplexFloatImag();
910 IntReal = v.getComplexIntReal();
911 IntImag = v.getComplexIntImag();
917 APValue::LValueBase Base;
920 SubobjectDesignator Designator;
922 const APValue::LValueBase getLValueBase() const { return Base; }
923 CharUnits &getLValueOffset() { return Offset; }
924 const CharUnits &getLValueOffset() const { return Offset; }
925 unsigned getLValueCallIndex() const { return CallIndex; }
926 SubobjectDesignator &getLValueDesignator() { return Designator; }
927 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
929 void moveInto(APValue &V) const {
930 if (Designator.Invalid)
931 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933 V = APValue(Base, Offset, Designator.Entries,
934 Designator.IsOnePastTheEnd, CallIndex);
936 void setFrom(ASTContext &Ctx, const APValue &V) {
937 assert(V.isLValue());
938 Base = V.getLValueBase();
939 Offset = V.getLValueOffset();
940 CallIndex = V.getLValueCallIndex();
941 Designator = SubobjectDesignator(Ctx, V);
944 void set(APValue::LValueBase B, unsigned I = 0) {
946 Offset = CharUnits::Zero();
948 Designator = SubobjectDesignator(getType(B));
951 // Check that this LValue is not based on a null pointer. If it is, produce
952 // a diagnostic and mark the designator as invalid.
953 bool checkNullPointer(EvalInfo &Info, const Expr *E,
954 CheckSubobjectKind CSK) {
955 if (Designator.Invalid)
958 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
960 Designator.setInvalid();
966 // Check this LValue refers to an object. If not, set the designator to be
967 // invalid and emit a diagnostic.
968 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
969 // Outside C++11, do not build a designator referring to a subobject of
970 // any object: we won't use such a designator for anything.
971 if (!Info.getLangOpts().CPlusPlus11)
972 Designator.setInvalid();
973 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
974 Designator.checkSubobject(Info, E, CSK);
977 void addDecl(EvalInfo &Info, const Expr *E,
978 const Decl *D, bool Virtual = false) {
979 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
980 Designator.addDeclUnchecked(D, Virtual);
982 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
983 if (checkSubobject(Info, E, CSK_ArrayToPointer))
984 Designator.addArrayUnchecked(CAT);
986 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
987 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
988 Designator.addComplexUnchecked(EltTy, Imag);
990 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
991 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
992 Designator.adjustIndex(Info, E, N);
998 explicit MemberPtr(const ValueDecl *Decl) :
999 DeclAndIsDerivedMember(Decl, false), Path() {}
1001 /// The member or (direct or indirect) field referred to by this member
1002 /// pointer, or 0 if this is a null member pointer.
1003 const ValueDecl *getDecl() const {
1004 return DeclAndIsDerivedMember.getPointer();
1006 /// Is this actually a member of some type derived from the relevant class?
1007 bool isDerivedMember() const {
1008 return DeclAndIsDerivedMember.getInt();
1010 /// Get the class which the declaration actually lives in.
1011 const CXXRecordDecl *getContainingRecord() const {
1012 return cast<CXXRecordDecl>(
1013 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1016 void moveInto(APValue &V) const {
1017 V = APValue(getDecl(), isDerivedMember(), Path);
1019 void setFrom(const APValue &V) {
1020 assert(V.isMemberPointer());
1021 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1022 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1024 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1025 Path.insert(Path.end(), P.begin(), P.end());
1028 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1029 /// whether the member is a member of some class derived from the class type
1030 /// of the member pointer.
1031 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1032 /// Path - The path of base/derived classes from the member declaration's
1033 /// class (exclusive) to the class type of the member pointer (inclusive).
1034 SmallVector<const CXXRecordDecl*, 4> Path;
1036 /// Perform a cast towards the class of the Decl (either up or down the
1038 bool castBack(const CXXRecordDecl *Class) {
1039 assert(!Path.empty());
1040 const CXXRecordDecl *Expected;
1041 if (Path.size() >= 2)
1042 Expected = Path[Path.size() - 2];
1044 Expected = getContainingRecord();
1045 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1046 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1047 // if B does not contain the original member and is not a base or
1048 // derived class of the class containing the original member, the result
1049 // of the cast is undefined.
1050 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1051 // (D::*). We consider that to be a language defect.
1057 /// Perform a base-to-derived member pointer cast.
1058 bool castToDerived(const CXXRecordDecl *Derived) {
1061 if (!isDerivedMember()) {
1062 Path.push_back(Derived);
1065 if (!castBack(Derived))
1068 DeclAndIsDerivedMember.setInt(false);
1071 /// Perform a derived-to-base member pointer cast.
1072 bool castToBase(const CXXRecordDecl *Base) {
1076 DeclAndIsDerivedMember.setInt(true);
1077 if (isDerivedMember()) {
1078 Path.push_back(Base);
1081 return castBack(Base);
1085 /// Compare two member pointers, which are assumed to be of the same type.
1086 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1087 if (!LHS.getDecl() || !RHS.getDecl())
1088 return !LHS.getDecl() && !RHS.getDecl();
1089 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1091 return LHS.Path == RHS.Path;
1095 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1096 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1097 const LValue &This, const Expr *E,
1098 bool AllowNonLiteralTypes = false);
1099 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1100 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1101 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1103 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1104 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1105 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1107 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1108 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1109 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1111 //===----------------------------------------------------------------------===//
1113 //===----------------------------------------------------------------------===//
1115 /// Produce a string describing the given constexpr call.
1116 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1117 unsigned ArgIndex = 0;
1118 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1119 !isa<CXXConstructorDecl>(Frame->Callee) &&
1120 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1123 Out << *Frame->Callee << '(';
1125 if (Frame->This && IsMemberCall) {
1127 Frame->This->moveInto(Val);
1128 Val.printPretty(Out, Frame->Info.Ctx,
1129 Frame->This->Designator.MostDerivedType);
1130 // FIXME: Add parens around Val if needed.
1131 Out << "->" << *Frame->Callee << '(';
1132 IsMemberCall = false;
1135 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1136 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1137 if (ArgIndex > (unsigned)IsMemberCall)
1140 const ParmVarDecl *Param = *I;
1141 const APValue &Arg = Frame->Arguments[ArgIndex];
1142 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1144 if (ArgIndex == 0 && IsMemberCall)
1145 Out << "->" << *Frame->Callee << '(';
1151 /// Evaluate an expression to see if it had side-effects, and discard its
1153 /// \return \c true if the caller should keep evaluating.
1154 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1156 if (!Evaluate(Scratch, Info, E))
1157 // We don't need the value, but we might have skipped a side effect here.
1158 return Info.noteSideEffect();
1162 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1163 /// return its existing value.
1164 static int64_t getExtValue(const APSInt &Value) {
1165 return Value.isSigned() ? Value.getSExtValue()
1166 : static_cast<int64_t>(Value.getZExtValue());
1169 /// Should this call expression be treated as a string literal?
1170 static bool IsStringLiteralCall(const CallExpr *E) {
1171 unsigned Builtin = E->getBuiltinCallee();
1172 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1173 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1176 static bool IsGlobalLValue(APValue::LValueBase B) {
1177 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1178 // constant expression of pointer type that evaluates to...
1180 // ... a null pointer value, or a prvalue core constant expression of type
1182 if (!B) return true;
1184 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1185 // ... the address of an object with static storage duration,
1186 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1187 return VD->hasGlobalStorage();
1188 // ... the address of a function,
1189 return isa<FunctionDecl>(D);
1192 const Expr *E = B.get<const Expr*>();
1193 switch (E->getStmtClass()) {
1196 case Expr::CompoundLiteralExprClass: {
1197 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1198 return CLE->isFileScope() && CLE->isLValue();
1200 case Expr::MaterializeTemporaryExprClass:
1201 // A materialized temporary might have been lifetime-extended to static
1202 // storage duration.
1203 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1204 // A string literal has static storage duration.
1205 case Expr::StringLiteralClass:
1206 case Expr::PredefinedExprClass:
1207 case Expr::ObjCStringLiteralClass:
1208 case Expr::ObjCEncodeExprClass:
1209 case Expr::CXXTypeidExprClass:
1210 case Expr::CXXUuidofExprClass:
1212 case Expr::CallExprClass:
1213 return IsStringLiteralCall(cast<CallExpr>(E));
1214 // For GCC compatibility, &&label has static storage duration.
1215 case Expr::AddrLabelExprClass:
1217 // A Block literal expression may be used as the initialization value for
1218 // Block variables at global or local static scope.
1219 case Expr::BlockExprClass:
1220 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1221 case Expr::ImplicitValueInitExprClass:
1223 // We can never form an lvalue with an implicit value initialization as its
1224 // base through expression evaluation, so these only appear in one case: the
1225 // implicit variable declaration we invent when checking whether a constexpr
1226 // constructor can produce a constant expression. We must assume that such
1227 // an expression might be a global lvalue.
1232 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1233 assert(Base && "no location for a null lvalue");
1234 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1236 Info.Note(VD->getLocation(), diag::note_declared_at);
1238 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1239 diag::note_constexpr_temporary_here);
1242 /// Check that this reference or pointer core constant expression is a valid
1243 /// value for an address or reference constant expression. Return true if we
1244 /// can fold this expression, whether or not it's a constant expression.
1245 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1246 QualType Type, const LValue &LVal) {
1247 bool IsReferenceType = Type->isReferenceType();
1249 APValue::LValueBase Base = LVal.getLValueBase();
1250 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1252 // Check that the object is a global. Note that the fake 'this' object we
1253 // manufacture when checking potential constant expressions is conservatively
1254 // assumed to be global here.
1255 if (!IsGlobalLValue(Base)) {
1256 if (Info.getLangOpts().CPlusPlus11) {
1257 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1258 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1259 << IsReferenceType << !Designator.Entries.empty()
1261 NoteLValueLocation(Info, Base);
1265 // Don't allow references to temporaries to escape.
1268 assert((Info.checkingPotentialConstantExpression() ||
1269 LVal.getLValueCallIndex() == 0) &&
1270 "have call index for global lvalue");
1272 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1273 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1274 // Check if this is a thread-local variable.
1275 if (Var->getTLSKind())
1278 // A dllimport variable never acts like a constant.
1279 if (Var->hasAttr<DLLImportAttr>())
1282 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1283 // __declspec(dllimport) must be handled very carefully:
1284 // We must never initialize an expression with the thunk in C++.
1285 // Doing otherwise would allow the same id-expression to yield
1286 // different addresses for the same function in different translation
1287 // units. However, this means that we must dynamically initialize the
1288 // expression with the contents of the import address table at runtime.
1290 // The C language has no notion of ODR; furthermore, it has no notion of
1291 // dynamic initialization. This means that we are permitted to
1292 // perform initialization with the address of the thunk.
1293 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1298 // Allow address constant expressions to be past-the-end pointers. This is
1299 // an extension: the standard requires them to point to an object.
1300 if (!IsReferenceType)
1303 // A reference constant expression must refer to an object.
1305 // FIXME: diagnostic
1310 // Does this refer one past the end of some object?
1311 if (Designator.isOnePastTheEnd()) {
1312 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1313 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1314 << !Designator.Entries.empty() << !!VD << VD;
1315 NoteLValueLocation(Info, Base);
1321 /// Check that this core constant expression is of literal type, and if not,
1322 /// produce an appropriate diagnostic.
1323 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1324 const LValue *This = nullptr) {
1325 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1328 // C++1y: A constant initializer for an object o [...] may also invoke
1329 // constexpr constructors for o and its subobjects even if those objects
1330 // are of non-literal class types.
1331 if (Info.getLangOpts().CPlusPlus1y && This &&
1332 Info.EvaluatingDecl == This->getLValueBase())
1335 // Prvalue constant expressions must be of literal types.
1336 if (Info.getLangOpts().CPlusPlus11)
1337 Info.Diag(E, diag::note_constexpr_nonliteral)
1340 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1344 /// Check that this core constant expression value is a valid value for a
1345 /// constant expression. If not, report an appropriate diagnostic. Does not
1346 /// check that the expression is of literal type.
1347 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1348 QualType Type, const APValue &Value) {
1349 if (Value.isUninit()) {
1350 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1355 // We allow _Atomic(T) to be initialized from anything that T can be
1356 // initialized from.
1357 if (const AtomicType *AT = Type->getAs<AtomicType>())
1358 Type = AT->getValueType();
1360 // Core issue 1454: For a literal constant expression of array or class type,
1361 // each subobject of its value shall have been initialized by a constant
1363 if (Value.isArray()) {
1364 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1365 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1366 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1367 Value.getArrayInitializedElt(I)))
1370 if (!Value.hasArrayFiller())
1372 return CheckConstantExpression(Info, DiagLoc, EltTy,
1373 Value.getArrayFiller());
1375 if (Value.isUnion() && Value.getUnionField()) {
1376 return CheckConstantExpression(Info, DiagLoc,
1377 Value.getUnionField()->getType(),
1378 Value.getUnionValue());
1380 if (Value.isStruct()) {
1381 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1382 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1383 unsigned BaseIndex = 0;
1384 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1385 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1386 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1387 Value.getStructBase(BaseIndex)))
1391 for (const auto *I : RD->fields()) {
1392 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1393 Value.getStructField(I->getFieldIndex())))
1398 if (Value.isLValue()) {
1400 LVal.setFrom(Info.Ctx, Value);
1401 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1404 // Everything else is fine.
1408 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1409 return LVal.Base.dyn_cast<const ValueDecl*>();
1412 static bool IsLiteralLValue(const LValue &Value) {
1413 if (Value.CallIndex)
1415 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1416 return E && !isa<MaterializeTemporaryExpr>(E);
1419 static bool IsWeakLValue(const LValue &Value) {
1420 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1421 return Decl && Decl->isWeak();
1424 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1425 // A null base expression indicates a null pointer. These are always
1426 // evaluatable, and they are false unless the offset is zero.
1427 if (!Value.getLValueBase()) {
1428 Result = !Value.getLValueOffset().isZero();
1432 // We have a non-null base. These are generally known to be true, but if it's
1433 // a weak declaration it can be null at runtime.
1435 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1436 return !Decl || !Decl->isWeak();
1439 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1440 switch (Val.getKind()) {
1441 case APValue::Uninitialized:
1444 Result = Val.getInt().getBoolValue();
1446 case APValue::Float:
1447 Result = !Val.getFloat().isZero();
1449 case APValue::ComplexInt:
1450 Result = Val.getComplexIntReal().getBoolValue() ||
1451 Val.getComplexIntImag().getBoolValue();
1453 case APValue::ComplexFloat:
1454 Result = !Val.getComplexFloatReal().isZero() ||
1455 !Val.getComplexFloatImag().isZero();
1457 case APValue::LValue:
1458 return EvalPointerValueAsBool(Val, Result);
1459 case APValue::MemberPointer:
1460 Result = Val.getMemberPointerDecl();
1462 case APValue::Vector:
1463 case APValue::Array:
1464 case APValue::Struct:
1465 case APValue::Union:
1466 case APValue::AddrLabelDiff:
1470 llvm_unreachable("unknown APValue kind");
1473 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1475 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1477 if (!Evaluate(Val, Info, E))
1479 return HandleConversionToBool(Val, Result);
1482 template<typename T>
1483 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1484 const T &SrcValue, QualType DestType) {
1485 Info.CCEDiag(E, diag::note_constexpr_overflow)
1486 << SrcValue << DestType;
1489 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1490 QualType SrcType, const APFloat &Value,
1491 QualType DestType, APSInt &Result) {
1492 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1493 // Determine whether we are converting to unsigned or signed.
1494 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1496 Result = APSInt(DestWidth, !DestSigned);
1498 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1499 & APFloat::opInvalidOp)
1500 HandleOverflow(Info, E, Value, DestType);
1504 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1505 QualType SrcType, QualType DestType,
1507 APFloat Value = Result;
1509 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1510 APFloat::rmNearestTiesToEven, &ignored)
1511 & APFloat::opOverflow)
1512 HandleOverflow(Info, E, Value, DestType);
1516 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1517 QualType DestType, QualType SrcType,
1519 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1520 APSInt Result = Value;
1521 // Figure out if this is a truncate, extend or noop cast.
1522 // If the input is signed, do a sign extend, noop, or truncate.
1523 Result = Result.extOrTrunc(DestWidth);
1524 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1528 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1529 QualType SrcType, const APSInt &Value,
1530 QualType DestType, APFloat &Result) {
1531 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1532 if (Result.convertFromAPInt(Value, Value.isSigned(),
1533 APFloat::rmNearestTiesToEven)
1534 & APFloat::opOverflow)
1535 HandleOverflow(Info, E, Value, DestType);
1539 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1540 APValue &Value, const FieldDecl *FD) {
1541 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1543 if (!Value.isInt()) {
1544 // Trying to store a pointer-cast-to-integer into a bitfield.
1545 // FIXME: In this case, we should provide the diagnostic for casting
1546 // a pointer to an integer.
1547 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1552 APSInt &Int = Value.getInt();
1553 unsigned OldBitWidth = Int.getBitWidth();
1554 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1555 if (NewBitWidth < OldBitWidth)
1556 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1560 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1563 if (!Evaluate(SVal, Info, E))
1566 Res = SVal.getInt();
1569 if (SVal.isFloat()) {
1570 Res = SVal.getFloat().bitcastToAPInt();
1573 if (SVal.isVector()) {
1574 QualType VecTy = E->getType();
1575 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1576 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1577 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1578 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1579 Res = llvm::APInt::getNullValue(VecSize);
1580 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1581 APValue &Elt = SVal.getVectorElt(i);
1582 llvm::APInt EltAsInt;
1584 EltAsInt = Elt.getInt();
1585 } else if (Elt.isFloat()) {
1586 EltAsInt = Elt.getFloat().bitcastToAPInt();
1588 // Don't try to handle vectors of anything other than int or float
1589 // (not sure if it's possible to hit this case).
1590 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1593 unsigned BaseEltSize = EltAsInt.getBitWidth();
1595 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1597 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1601 // Give up if the input isn't an int, float, or vector. For example, we
1602 // reject "(v4i16)(intptr_t)&a".
1603 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1607 /// Perform the given integer operation, which is known to need at most BitWidth
1608 /// bits, and check for overflow in the original type (if that type was not an
1610 template<typename Operation>
1611 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1612 const APSInt &LHS, const APSInt &RHS,
1613 unsigned BitWidth, Operation Op) {
1614 if (LHS.isUnsigned())
1615 return Op(LHS, RHS);
1617 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1618 APSInt Result = Value.trunc(LHS.getBitWidth());
1619 if (Result.extend(BitWidth) != Value) {
1620 if (Info.checkingForOverflow())
1621 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1622 diag::warn_integer_constant_overflow)
1623 << Result.toString(10) << E->getType();
1625 HandleOverflow(Info, E, Value, E->getType());
1630 /// Perform the given binary integer operation.
1631 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1632 BinaryOperatorKind Opcode, APSInt RHS,
1639 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1640 std::multiplies<APSInt>());
1643 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1644 std::plus<APSInt>());
1647 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1648 std::minus<APSInt>());
1650 case BO_And: Result = LHS & RHS; return true;
1651 case BO_Xor: Result = LHS ^ RHS; return true;
1652 case BO_Or: Result = LHS | RHS; return true;
1656 Info.Diag(E, diag::note_expr_divide_by_zero);
1659 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1660 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1661 LHS.isSigned() && LHS.isMinSignedValue())
1662 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1663 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1666 if (Info.getLangOpts().OpenCL)
1667 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1668 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1669 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1671 else if (RHS.isSigned() && RHS.isNegative()) {
1672 // During constant-folding, a negative shift is an opposite shift. Such
1673 // a shift is not a constant expression.
1674 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1679 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1680 // the shifted type.
1681 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1683 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1684 << RHS << E->getType() << LHS.getBitWidth();
1685 } else if (LHS.isSigned()) {
1686 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1687 // operand, and must not overflow the corresponding unsigned type.
1688 if (LHS.isNegative())
1689 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1690 else if (LHS.countLeadingZeros() < SA)
1691 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1697 if (Info.getLangOpts().OpenCL)
1698 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1699 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1700 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1702 else if (RHS.isSigned() && RHS.isNegative()) {
1703 // During constant-folding, a negative shift is an opposite shift. Such a
1704 // shift is not a constant expression.
1705 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1710 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1712 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1714 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1715 << RHS << E->getType() << LHS.getBitWidth();
1720 case BO_LT: Result = LHS < RHS; return true;
1721 case BO_GT: Result = LHS > RHS; return true;
1722 case BO_LE: Result = LHS <= RHS; return true;
1723 case BO_GE: Result = LHS >= RHS; return true;
1724 case BO_EQ: Result = LHS == RHS; return true;
1725 case BO_NE: Result = LHS != RHS; return true;
1729 /// Perform the given binary floating-point operation, in-place, on LHS.
1730 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1731 APFloat &LHS, BinaryOperatorKind Opcode,
1732 const APFloat &RHS) {
1738 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1741 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1744 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1747 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1751 if (LHS.isInfinity() || LHS.isNaN())
1752 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1756 /// Cast an lvalue referring to a base subobject to a derived class, by
1757 /// truncating the lvalue's path to the given length.
1758 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1759 const RecordDecl *TruncatedType,
1760 unsigned TruncatedElements) {
1761 SubobjectDesignator &D = Result.Designator;
1763 // Check we actually point to a derived class object.
1764 if (TruncatedElements == D.Entries.size())
1766 assert(TruncatedElements >= D.MostDerivedPathLength &&
1767 "not casting to a derived class");
1768 if (!Result.checkSubobject(Info, E, CSK_Derived))
1771 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1772 const RecordDecl *RD = TruncatedType;
1773 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1774 if (RD->isInvalidDecl()) return false;
1775 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1776 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1777 if (isVirtualBaseClass(D.Entries[I]))
1778 Result.Offset -= Layout.getVBaseClassOffset(Base);
1780 Result.Offset -= Layout.getBaseClassOffset(Base);
1783 D.Entries.resize(TruncatedElements);
1787 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1788 const CXXRecordDecl *Derived,
1789 const CXXRecordDecl *Base,
1790 const ASTRecordLayout *RL = nullptr) {
1792 if (Derived->isInvalidDecl()) return false;
1793 RL = &Info.Ctx.getASTRecordLayout(Derived);
1796 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1797 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1801 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1802 const CXXRecordDecl *DerivedDecl,
1803 const CXXBaseSpecifier *Base) {
1804 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1806 if (!Base->isVirtual())
1807 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1809 SubobjectDesignator &D = Obj.Designator;
1813 // Extract most-derived object and corresponding type.
1814 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1815 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1818 // Find the virtual base class.
1819 if (DerivedDecl->isInvalidDecl()) return false;
1820 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1821 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1822 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1826 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1827 QualType Type, LValue &Result) {
1828 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1829 PathE = E->path_end();
1830 PathI != PathE; ++PathI) {
1831 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1834 Type = (*PathI)->getType();
1839 /// Update LVal to refer to the given field, which must be a member of the type
1840 /// currently described by LVal.
1841 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1842 const FieldDecl *FD,
1843 const ASTRecordLayout *RL = nullptr) {
1845 if (FD->getParent()->isInvalidDecl()) return false;
1846 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1849 unsigned I = FD->getFieldIndex();
1850 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1851 LVal.addDecl(Info, E, FD);
1855 /// Update LVal to refer to the given indirect field.
1856 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1858 const IndirectFieldDecl *IFD) {
1859 for (const auto *C : IFD->chain())
1860 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
1865 /// Get the size of the given type in char units.
1866 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1867 QualType Type, CharUnits &Size) {
1868 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1870 if (Type->isVoidType() || Type->isFunctionType()) {
1871 Size = CharUnits::One();
1875 if (!Type->isConstantSizeType()) {
1876 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1877 // FIXME: Better diagnostic.
1882 Size = Info.Ctx.getTypeSizeInChars(Type);
1886 /// Update a pointer value to model pointer arithmetic.
1887 /// \param Info - Information about the ongoing evaluation.
1888 /// \param E - The expression being evaluated, for diagnostic purposes.
1889 /// \param LVal - The pointer value to be updated.
1890 /// \param EltTy - The pointee type represented by LVal.
1891 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1892 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1893 LValue &LVal, QualType EltTy,
1894 int64_t Adjustment) {
1895 CharUnits SizeOfPointee;
1896 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1899 // Compute the new offset in the appropriate width.
1900 LVal.Offset += Adjustment * SizeOfPointee;
1901 LVal.adjustIndex(Info, E, Adjustment);
1905 /// Update an lvalue to refer to a component of a complex number.
1906 /// \param Info - Information about the ongoing evaluation.
1907 /// \param LVal - The lvalue to be updated.
1908 /// \param EltTy - The complex number's component type.
1909 /// \param Imag - False for the real component, true for the imaginary.
1910 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1911 LValue &LVal, QualType EltTy,
1914 CharUnits SizeOfComponent;
1915 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1917 LVal.Offset += SizeOfComponent;
1919 LVal.addComplex(Info, E, EltTy, Imag);
1923 /// Try to evaluate the initializer for a variable declaration.
1925 /// \param Info Information about the ongoing evaluation.
1926 /// \param E An expression to be used when printing diagnostics.
1927 /// \param VD The variable whose initializer should be obtained.
1928 /// \param Frame The frame in which the variable was created. Must be null
1929 /// if this variable is not local to the evaluation.
1930 /// \param Result Filled in with a pointer to the value of the variable.
1931 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1932 const VarDecl *VD, CallStackFrame *Frame,
1934 // If this is a parameter to an active constexpr function call, perform
1935 // argument substitution.
1936 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1937 // Assume arguments of a potential constant expression are unknown
1938 // constant expressions.
1939 if (Info.checkingPotentialConstantExpression())
1941 if (!Frame || !Frame->Arguments) {
1942 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1945 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1949 // If this is a local variable, dig out its value.
1951 Result = Frame->getTemporary(VD);
1952 assert(Result && "missing value for local variable");
1956 // Dig out the initializer, and use the declaration which it's attached to.
1957 const Expr *Init = VD->getAnyInitializer(VD);
1958 if (!Init || Init->isValueDependent()) {
1959 // If we're checking a potential constant expression, the variable could be
1960 // initialized later.
1961 if (!Info.checkingPotentialConstantExpression())
1962 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1966 // If we're currently evaluating the initializer of this declaration, use that
1968 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1969 Result = Info.EvaluatingDeclValue;
1973 // Never evaluate the initializer of a weak variable. We can't be sure that
1974 // this is the definition which will be used.
1976 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1980 // Check that we can fold the initializer. In C++, we will have already done
1981 // this in the cases where it matters for conformance.
1982 SmallVector<PartialDiagnosticAt, 8> Notes;
1983 if (!VD->evaluateValue(Notes)) {
1984 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1985 Notes.size() + 1) << VD;
1986 Info.Note(VD->getLocation(), diag::note_declared_at);
1987 Info.addNotes(Notes);
1989 } else if (!VD->checkInitIsICE()) {
1990 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1991 Notes.size() + 1) << VD;
1992 Info.Note(VD->getLocation(), diag::note_declared_at);
1993 Info.addNotes(Notes);
1996 Result = VD->getEvaluatedValue();
2000 static bool IsConstNonVolatile(QualType T) {
2001 Qualifiers Quals = T.getQualifiers();
2002 return Quals.hasConst() && !Quals.hasVolatile();
2005 /// Get the base index of the given base class within an APValue representing
2006 /// the given derived class.
2007 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2008 const CXXRecordDecl *Base) {
2009 Base = Base->getCanonicalDecl();
2011 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2012 E = Derived->bases_end(); I != E; ++I, ++Index) {
2013 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2017 llvm_unreachable("base class missing from derived class's bases list");
2020 /// Extract the value of a character from a string literal.
2021 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2023 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2024 const StringLiteral *S = cast<StringLiteral>(Lit);
2025 const ConstantArrayType *CAT =
2026 Info.Ctx.getAsConstantArrayType(S->getType());
2027 assert(CAT && "string literal isn't an array");
2028 QualType CharType = CAT->getElementType();
2029 assert(CharType->isIntegerType() && "unexpected character type");
2031 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2032 CharType->isUnsignedIntegerType());
2033 if (Index < S->getLength())
2034 Value = S->getCodeUnit(Index);
2038 // Expand a string literal into an array of characters.
2039 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2041 const StringLiteral *S = cast<StringLiteral>(Lit);
2042 const ConstantArrayType *CAT =
2043 Info.Ctx.getAsConstantArrayType(S->getType());
2044 assert(CAT && "string literal isn't an array");
2045 QualType CharType = CAT->getElementType();
2046 assert(CharType->isIntegerType() && "unexpected character type");
2048 unsigned Elts = CAT->getSize().getZExtValue();
2049 Result = APValue(APValue::UninitArray(),
2050 std::min(S->getLength(), Elts), Elts);
2051 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2052 CharType->isUnsignedIntegerType());
2053 if (Result.hasArrayFiller())
2054 Result.getArrayFiller() = APValue(Value);
2055 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2056 Value = S->getCodeUnit(I);
2057 Result.getArrayInitializedElt(I) = APValue(Value);
2061 // Expand an array so that it has more than Index filled elements.
2062 static void expandArray(APValue &Array, unsigned Index) {
2063 unsigned Size = Array.getArraySize();
2064 assert(Index < Size);
2066 // Always at least double the number of elements for which we store a value.
2067 unsigned OldElts = Array.getArrayInitializedElts();
2068 unsigned NewElts = std::max(Index+1, OldElts * 2);
2069 NewElts = std::min(Size, std::max(NewElts, 8u));
2071 // Copy the data across.
2072 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2073 for (unsigned I = 0; I != OldElts; ++I)
2074 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2075 for (unsigned I = OldElts; I != NewElts; ++I)
2076 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2077 if (NewValue.hasArrayFiller())
2078 NewValue.getArrayFiller() = Array.getArrayFiller();
2079 Array.swap(NewValue);
2082 /// Kinds of access we can perform on an object, for diagnostics.
2090 /// A handle to a complete object (an object that is not a subobject of
2091 /// another object).
2092 struct CompleteObject {
2093 /// The value of the complete object.
2095 /// The type of the complete object.
2098 CompleteObject() : Value(nullptr) {}
2099 CompleteObject(APValue *Value, QualType Type)
2100 : Value(Value), Type(Type) {
2101 assert(Value && "missing value for complete object");
2104 LLVM_EXPLICIT operator bool() const { return Value; }
2107 /// Find the designated sub-object of an rvalue.
2108 template<typename SubobjectHandler>
2109 typename SubobjectHandler::result_type
2110 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2111 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2113 // A diagnostic will have already been produced.
2114 return handler.failed();
2115 if (Sub.isOnePastTheEnd()) {
2116 if (Info.getLangOpts().CPlusPlus11)
2117 Info.Diag(E, diag::note_constexpr_access_past_end)
2118 << handler.AccessKind;
2121 return handler.failed();
2124 APValue *O = Obj.Value;
2125 QualType ObjType = Obj.Type;
2126 const FieldDecl *LastField = nullptr;
2128 // Walk the designator's path to find the subobject.
2129 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2130 if (O->isUninit()) {
2131 if (!Info.checkingPotentialConstantExpression())
2132 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2133 return handler.failed();
2137 if (!handler.found(*O, ObjType))
2140 // If we modified a bit-field, truncate it to the right width.
2141 if (handler.AccessKind != AK_Read &&
2142 LastField && LastField->isBitField() &&
2143 !truncateBitfieldValue(Info, E, *O, LastField))
2149 LastField = nullptr;
2150 if (ObjType->isArrayType()) {
2151 // Next subobject is an array element.
2152 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2153 assert(CAT && "vla in literal type?");
2154 uint64_t Index = Sub.Entries[I].ArrayIndex;
2155 if (CAT->getSize().ule(Index)) {
2156 // Note, it should not be possible to form a pointer with a valid
2157 // designator which points more than one past the end of the array.
2158 if (Info.getLangOpts().CPlusPlus11)
2159 Info.Diag(E, diag::note_constexpr_access_past_end)
2160 << handler.AccessKind;
2163 return handler.failed();
2166 ObjType = CAT->getElementType();
2168 // An array object is represented as either an Array APValue or as an
2169 // LValue which refers to a string literal.
2170 if (O->isLValue()) {
2171 assert(I == N - 1 && "extracting subobject of character?");
2172 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2173 if (handler.AccessKind != AK_Read)
2174 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2177 return handler.foundString(*O, ObjType, Index);
2180 if (O->getArrayInitializedElts() > Index)
2181 O = &O->getArrayInitializedElt(Index);
2182 else if (handler.AccessKind != AK_Read) {
2183 expandArray(*O, Index);
2184 O = &O->getArrayInitializedElt(Index);
2186 O = &O->getArrayFiller();
2187 } else if (ObjType->isAnyComplexType()) {
2188 // Next subobject is a complex number.
2189 uint64_t Index = Sub.Entries[I].ArrayIndex;
2191 if (Info.getLangOpts().CPlusPlus11)
2192 Info.Diag(E, diag::note_constexpr_access_past_end)
2193 << handler.AccessKind;
2196 return handler.failed();
2199 bool WasConstQualified = ObjType.isConstQualified();
2200 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2201 if (WasConstQualified)
2204 assert(I == N - 1 && "extracting subobject of scalar?");
2205 if (O->isComplexInt()) {
2206 return handler.found(Index ? O->getComplexIntImag()
2207 : O->getComplexIntReal(), ObjType);
2209 assert(O->isComplexFloat());
2210 return handler.found(Index ? O->getComplexFloatImag()
2211 : O->getComplexFloatReal(), ObjType);
2213 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2214 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2215 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2217 Info.Note(Field->getLocation(), diag::note_declared_at);
2218 return handler.failed();
2221 // Next subobject is a class, struct or union field.
2222 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2223 if (RD->isUnion()) {
2224 const FieldDecl *UnionField = O->getUnionField();
2226 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2227 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2228 << handler.AccessKind << Field << !UnionField << UnionField;
2229 return handler.failed();
2231 O = &O->getUnionValue();
2233 O = &O->getStructField(Field->getFieldIndex());
2235 bool WasConstQualified = ObjType.isConstQualified();
2236 ObjType = Field->getType();
2237 if (WasConstQualified && !Field->isMutable())
2240 if (ObjType.isVolatileQualified()) {
2241 if (Info.getLangOpts().CPlusPlus) {
2242 // FIXME: Include a description of the path to the volatile subobject.
2243 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2244 << handler.AccessKind << 2 << Field;
2245 Info.Note(Field->getLocation(), diag::note_declared_at);
2247 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2249 return handler.failed();
2254 // Next subobject is a base class.
2255 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2256 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2257 O = &O->getStructBase(getBaseIndex(Derived, Base));
2259 bool WasConstQualified = ObjType.isConstQualified();
2260 ObjType = Info.Ctx.getRecordType(Base);
2261 if (WasConstQualified)
2268 struct ExtractSubobjectHandler {
2272 static const AccessKinds AccessKind = AK_Read;
2274 typedef bool result_type;
2275 bool failed() { return false; }
2276 bool found(APValue &Subobj, QualType SubobjType) {
2280 bool found(APSInt &Value, QualType SubobjType) {
2281 Result = APValue(Value);
2284 bool found(APFloat &Value, QualType SubobjType) {
2285 Result = APValue(Value);
2288 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2289 Result = APValue(extractStringLiteralCharacter(
2290 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2294 } // end anonymous namespace
2296 const AccessKinds ExtractSubobjectHandler::AccessKind;
2298 /// Extract the designated sub-object of an rvalue.
2299 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2300 const CompleteObject &Obj,
2301 const SubobjectDesignator &Sub,
2303 ExtractSubobjectHandler Handler = { Info, Result };
2304 return findSubobject(Info, E, Obj, Sub, Handler);
2308 struct ModifySubobjectHandler {
2313 typedef bool result_type;
2314 static const AccessKinds AccessKind = AK_Assign;
2316 bool checkConst(QualType QT) {
2317 // Assigning to a const object has undefined behavior.
2318 if (QT.isConstQualified()) {
2319 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2325 bool failed() { return false; }
2326 bool found(APValue &Subobj, QualType SubobjType) {
2327 if (!checkConst(SubobjType))
2329 // We've been given ownership of NewVal, so just swap it in.
2330 Subobj.swap(NewVal);
2333 bool found(APSInt &Value, QualType SubobjType) {
2334 if (!checkConst(SubobjType))
2336 if (!NewVal.isInt()) {
2337 // Maybe trying to write a cast pointer value into a complex?
2341 Value = NewVal.getInt();
2344 bool found(APFloat &Value, QualType SubobjType) {
2345 if (!checkConst(SubobjType))
2347 Value = NewVal.getFloat();
2350 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2351 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2354 } // end anonymous namespace
2356 const AccessKinds ModifySubobjectHandler::AccessKind;
2358 /// Update the designated sub-object of an rvalue to the given value.
2359 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2360 const CompleteObject &Obj,
2361 const SubobjectDesignator &Sub,
2363 ModifySubobjectHandler Handler = { Info, NewVal, E };
2364 return findSubobject(Info, E, Obj, Sub, Handler);
2367 /// Find the position where two subobject designators diverge, or equivalently
2368 /// the length of the common initial subsequence.
2369 static unsigned FindDesignatorMismatch(QualType ObjType,
2370 const SubobjectDesignator &A,
2371 const SubobjectDesignator &B,
2372 bool &WasArrayIndex) {
2373 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2374 for (/**/; I != N; ++I) {
2375 if (!ObjType.isNull() &&
2376 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2377 // Next subobject is an array element.
2378 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2379 WasArrayIndex = true;
2382 if (ObjType->isAnyComplexType())
2383 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2385 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2387 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2388 WasArrayIndex = false;
2391 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2392 // Next subobject is a field.
2393 ObjType = FD->getType();
2395 // Next subobject is a base class.
2396 ObjType = QualType();
2399 WasArrayIndex = false;
2403 /// Determine whether the given subobject designators refer to elements of the
2404 /// same array object.
2405 static bool AreElementsOfSameArray(QualType ObjType,
2406 const SubobjectDesignator &A,
2407 const SubobjectDesignator &B) {
2408 if (A.Entries.size() != B.Entries.size())
2411 bool IsArray = A.MostDerivedArraySize != 0;
2412 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2413 // A is a subobject of the array element.
2416 // If A (and B) designates an array element, the last entry will be the array
2417 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2418 // of length 1' case, and the entire path must match.
2420 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2421 return CommonLength >= A.Entries.size() - IsArray;
2424 /// Find the complete object to which an LValue refers.
2425 CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2426 const LValue &LVal, QualType LValType) {
2428 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2429 return CompleteObject();
2432 CallStackFrame *Frame = nullptr;
2433 if (LVal.CallIndex) {
2434 Frame = Info.getCallFrame(LVal.CallIndex);
2436 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2437 << AK << LVal.Base.is<const ValueDecl*>();
2438 NoteLValueLocation(Info, LVal.Base);
2439 return CompleteObject();
2443 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2444 // is not a constant expression (even if the object is non-volatile). We also
2445 // apply this rule to C++98, in order to conform to the expected 'volatile'
2447 if (LValType.isVolatileQualified()) {
2448 if (Info.getLangOpts().CPlusPlus)
2449 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2453 return CompleteObject();
2456 // Compute value storage location and type of base object.
2457 APValue *BaseVal = nullptr;
2458 QualType BaseType = getType(LVal.Base);
2460 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2461 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2462 // In C++11, constexpr, non-volatile variables initialized with constant
2463 // expressions are constant expressions too. Inside constexpr functions,
2464 // parameters are constant expressions even if they're non-const.
2465 // In C++1y, objects local to a constant expression (those with a Frame) are
2466 // both readable and writable inside constant expressions.
2467 // In C, such things can also be folded, although they are not ICEs.
2468 const VarDecl *VD = dyn_cast<VarDecl>(D);
2470 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2473 if (!VD || VD->isInvalidDecl()) {
2475 return CompleteObject();
2478 // Accesses of volatile-qualified objects are not allowed.
2479 if (BaseType.isVolatileQualified()) {
2480 if (Info.getLangOpts().CPlusPlus) {
2481 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2483 Info.Note(VD->getLocation(), diag::note_declared_at);
2487 return CompleteObject();
2490 // Unless we're looking at a local variable or argument in a constexpr call,
2491 // the variable we're reading must be const.
2493 if (Info.getLangOpts().CPlusPlus1y &&
2494 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2495 // OK, we can read and modify an object if we're in the process of
2496 // evaluating its initializer, because its lifetime began in this
2498 } else if (AK != AK_Read) {
2499 // All the remaining cases only permit reading.
2500 Info.Diag(E, diag::note_constexpr_modify_global);
2501 return CompleteObject();
2502 } else if (VD->isConstexpr()) {
2503 // OK, we can read this variable.
2504 } else if (BaseType->isIntegralOrEnumerationType()) {
2505 if (!BaseType.isConstQualified()) {
2506 if (Info.getLangOpts().CPlusPlus) {
2507 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2508 Info.Note(VD->getLocation(), diag::note_declared_at);
2512 return CompleteObject();
2514 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2515 // We support folding of const floating-point types, in order to make
2516 // static const data members of such types (supported as an extension)
2518 if (Info.getLangOpts().CPlusPlus11) {
2519 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2520 Info.Note(VD->getLocation(), diag::note_declared_at);
2525 // FIXME: Allow folding of values of any literal type in all languages.
2526 if (Info.getLangOpts().CPlusPlus11) {
2527 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2528 Info.Note(VD->getLocation(), diag::note_declared_at);
2532 return CompleteObject();
2536 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2537 return CompleteObject();
2539 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2542 if (const MaterializeTemporaryExpr *MTE =
2543 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2544 assert(MTE->getStorageDuration() == SD_Static &&
2545 "should have a frame for a non-global materialized temporary");
2547 // Per C++1y [expr.const]p2:
2548 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2549 // - a [...] glvalue of integral or enumeration type that refers to
2550 // a non-volatile const object [...]
2552 // - a [...] glvalue of literal type that refers to a non-volatile
2553 // object whose lifetime began within the evaluation of e.
2555 // C++11 misses the 'began within the evaluation of e' check and
2556 // instead allows all temporaries, including things like:
2559 // constexpr int k = r;
2560 // Therefore we use the C++1y rules in C++11 too.
2561 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2562 const ValueDecl *ED = MTE->getExtendingDecl();
2563 if (!(BaseType.isConstQualified() &&
2564 BaseType->isIntegralOrEnumerationType()) &&
2565 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2566 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2567 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2568 return CompleteObject();
2571 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2572 assert(BaseVal && "got reference to unevaluated temporary");
2575 return CompleteObject();
2578 BaseVal = Frame->getTemporary(Base);
2579 assert(BaseVal && "missing value for temporary");
2582 // Volatile temporary objects cannot be accessed in constant expressions.
2583 if (BaseType.isVolatileQualified()) {
2584 if (Info.getLangOpts().CPlusPlus) {
2585 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2587 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2591 return CompleteObject();
2595 // During the construction of an object, it is not yet 'const'.
2596 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2597 // and this doesn't do quite the right thing for const subobjects of the
2598 // object under construction.
2599 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2600 BaseType = Info.Ctx.getCanonicalType(BaseType);
2601 BaseType.removeLocalConst();
2604 // In C++1y, we can't safely access any mutable state when we might be
2605 // evaluating after an unmodeled side effect or an evaluation failure.
2607 // FIXME: Not all local state is mutable. Allow local constant subobjects
2608 // to be read here (but take care with 'mutable' fields).
2609 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2610 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2611 return CompleteObject();
2613 return CompleteObject(BaseVal, BaseType);
2616 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2617 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2618 /// glvalue referred to by an entity of reference type.
2620 /// \param Info - Information about the ongoing evaluation.
2621 /// \param Conv - The expression for which we are performing the conversion.
2622 /// Used for diagnostics.
2623 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2624 /// case of a non-class type).
2625 /// \param LVal - The glvalue on which we are attempting to perform this action.
2626 /// \param RVal - The produced value will be placed here.
2627 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2629 const LValue &LVal, APValue &RVal) {
2630 if (LVal.Designator.Invalid)
2633 // Check for special cases where there is no existing APValue to look at.
2634 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2635 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2636 !Type.isVolatileQualified()) {
2637 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2638 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2639 // initializer until now for such expressions. Such an expression can't be
2640 // an ICE in C, so this only matters for fold.
2641 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2642 if (Type.isVolatileQualified()) {
2647 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2649 CompleteObject LitObj(&Lit, Base->getType());
2650 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2651 } else if (isa<StringLiteral>(Base)) {
2652 // We represent a string literal array as an lvalue pointing at the
2653 // corresponding expression, rather than building an array of chars.
2654 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2655 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2656 CompleteObject StrObj(&Str, Base->getType());
2657 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2661 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2662 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2665 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2666 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2667 QualType LValType, APValue &Val) {
2668 if (LVal.Designator.Invalid)
2671 if (!Info.getLangOpts().CPlusPlus1y) {
2676 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2677 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2680 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2681 return T->isSignedIntegerType() &&
2682 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2686 struct CompoundAssignSubobjectHandler {
2689 QualType PromotedLHSType;
2690 BinaryOperatorKind Opcode;
2693 static const AccessKinds AccessKind = AK_Assign;
2695 typedef bool result_type;
2697 bool checkConst(QualType QT) {
2698 // Assigning to a const object has undefined behavior.
2699 if (QT.isConstQualified()) {
2700 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2706 bool failed() { return false; }
2707 bool found(APValue &Subobj, QualType SubobjType) {
2708 switch (Subobj.getKind()) {
2710 return found(Subobj.getInt(), SubobjType);
2711 case APValue::Float:
2712 return found(Subobj.getFloat(), SubobjType);
2713 case APValue::ComplexInt:
2714 case APValue::ComplexFloat:
2715 // FIXME: Implement complex compound assignment.
2718 case APValue::LValue:
2719 return foundPointer(Subobj, SubobjType);
2721 // FIXME: can this happen?
2726 bool found(APSInt &Value, QualType SubobjType) {
2727 if (!checkConst(SubobjType))
2730 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2731 // We don't support compound assignment on integer-cast-to-pointer
2737 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2739 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2741 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2744 bool found(APFloat &Value, QualType SubobjType) {
2745 return checkConst(SubobjType) &&
2746 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2748 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2749 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2751 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2752 if (!checkConst(SubobjType))
2755 QualType PointeeType;
2756 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2757 PointeeType = PT->getPointeeType();
2759 if (PointeeType.isNull() || !RHS.isInt() ||
2760 (Opcode != BO_Add && Opcode != BO_Sub)) {
2765 int64_t Offset = getExtValue(RHS.getInt());
2766 if (Opcode == BO_Sub)
2770 LVal.setFrom(Info.Ctx, Subobj);
2771 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2773 LVal.moveInto(Subobj);
2776 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2777 llvm_unreachable("shouldn't encounter string elements here");
2780 } // end anonymous namespace
2782 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2784 /// Perform a compound assignment of LVal <op>= RVal.
2785 static bool handleCompoundAssignment(
2786 EvalInfo &Info, const Expr *E,
2787 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2788 BinaryOperatorKind Opcode, const APValue &RVal) {
2789 if (LVal.Designator.Invalid)
2792 if (!Info.getLangOpts().CPlusPlus1y) {
2797 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2798 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2800 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2804 struct IncDecSubobjectHandler {
2807 AccessKinds AccessKind;
2810 typedef bool result_type;
2812 bool checkConst(QualType QT) {
2813 // Assigning to a const object has undefined behavior.
2814 if (QT.isConstQualified()) {
2815 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2821 bool failed() { return false; }
2822 bool found(APValue &Subobj, QualType SubobjType) {
2823 // Stash the old value. Also clear Old, so we don't clobber it later
2824 // if we're post-incrementing a complex.
2830 switch (Subobj.getKind()) {
2832 return found(Subobj.getInt(), SubobjType);
2833 case APValue::Float:
2834 return found(Subobj.getFloat(), SubobjType);
2835 case APValue::ComplexInt:
2836 return found(Subobj.getComplexIntReal(),
2837 SubobjType->castAs<ComplexType>()->getElementType()
2838 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2839 case APValue::ComplexFloat:
2840 return found(Subobj.getComplexFloatReal(),
2841 SubobjType->castAs<ComplexType>()->getElementType()
2842 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2843 case APValue::LValue:
2844 return foundPointer(Subobj, SubobjType);
2846 // FIXME: can this happen?
2851 bool found(APSInt &Value, QualType SubobjType) {
2852 if (!checkConst(SubobjType))
2855 if (!SubobjType->isIntegerType()) {
2856 // We don't support increment / decrement on integer-cast-to-pointer
2862 if (Old) *Old = APValue(Value);
2864 // bool arithmetic promotes to int, and the conversion back to bool
2865 // doesn't reduce mod 2^n, so special-case it.
2866 if (SubobjType->isBooleanType()) {
2867 if (AccessKind == AK_Increment)
2874 bool WasNegative = Value.isNegative();
2875 if (AccessKind == AK_Increment) {
2878 if (!WasNegative && Value.isNegative() &&
2879 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2880 APSInt ActualValue(Value, /*IsUnsigned*/true);
2881 HandleOverflow(Info, E, ActualValue, SubobjType);
2886 if (WasNegative && !Value.isNegative() &&
2887 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2888 unsigned BitWidth = Value.getBitWidth();
2889 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2890 ActualValue.setBit(BitWidth);
2891 HandleOverflow(Info, E, ActualValue, SubobjType);
2896 bool found(APFloat &Value, QualType SubobjType) {
2897 if (!checkConst(SubobjType))
2900 if (Old) *Old = APValue(Value);
2902 APFloat One(Value.getSemantics(), 1);
2903 if (AccessKind == AK_Increment)
2904 Value.add(One, APFloat::rmNearestTiesToEven);
2906 Value.subtract(One, APFloat::rmNearestTiesToEven);
2909 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2910 if (!checkConst(SubobjType))
2913 QualType PointeeType;
2914 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2915 PointeeType = PT->getPointeeType();
2922 LVal.setFrom(Info.Ctx, Subobj);
2923 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2924 AccessKind == AK_Increment ? 1 : -1))
2926 LVal.moveInto(Subobj);
2929 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2930 llvm_unreachable("shouldn't encounter string elements here");
2933 } // end anonymous namespace
2935 /// Perform an increment or decrement on LVal.
2936 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2937 QualType LValType, bool IsIncrement, APValue *Old) {
2938 if (LVal.Designator.Invalid)
2941 if (!Info.getLangOpts().CPlusPlus1y) {
2946 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2947 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2948 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2949 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2952 /// Build an lvalue for the object argument of a member function call.
2953 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2955 if (Object->getType()->isPointerType())
2956 return EvaluatePointer(Object, This, Info);
2958 if (Object->isGLValue())
2959 return EvaluateLValue(Object, This, Info);
2961 if (Object->getType()->isLiteralType(Info.Ctx))
2962 return EvaluateTemporary(Object, This, Info);
2964 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
2968 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
2969 /// lvalue referring to the result.
2971 /// \param Info - Information about the ongoing evaluation.
2972 /// \param LV - An lvalue referring to the base of the member pointer.
2973 /// \param RHS - The member pointer expression.
2974 /// \param IncludeMember - Specifies whether the member itself is included in
2975 /// the resulting LValue subobject designator. This is not possible when
2976 /// creating a bound member function.
2977 /// \return The field or method declaration to which the member pointer refers,
2978 /// or 0 if evaluation fails.
2979 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2983 bool IncludeMember = true) {
2985 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
2988 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2989 // member value, the behavior is undefined.
2990 if (!MemPtr.getDecl()) {
2991 // FIXME: Specific diagnostic.
2996 if (MemPtr.isDerivedMember()) {
2997 // This is a member of some derived class. Truncate LV appropriately.
2998 // The end of the derived-to-base path for the base object must match the
2999 // derived-to-base path for the member pointer.
3000 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3001 LV.Designator.Entries.size()) {
3005 unsigned PathLengthToMember =
3006 LV.Designator.Entries.size() - MemPtr.Path.size();
3007 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3008 const CXXRecordDecl *LVDecl = getAsBaseClass(
3009 LV.Designator.Entries[PathLengthToMember + I]);
3010 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3011 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3017 // Truncate the lvalue to the appropriate derived class.
3018 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3019 PathLengthToMember))
3021 } else if (!MemPtr.Path.empty()) {
3022 // Extend the LValue path with the member pointer's path.
3023 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3024 MemPtr.Path.size() + IncludeMember);
3026 // Walk down to the appropriate base class.
3027 if (const PointerType *PT = LVType->getAs<PointerType>())
3028 LVType = PT->getPointeeType();
3029 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3030 assert(RD && "member pointer access on non-class-type expression");
3031 // The first class in the path is that of the lvalue.
3032 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3033 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3034 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3038 // Finally cast to the class containing the member.
3039 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3040 MemPtr.getContainingRecord()))
3044 // Add the member. Note that we cannot build bound member functions here.
3045 if (IncludeMember) {
3046 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3047 if (!HandleLValueMember(Info, RHS, LV, FD))
3049 } else if (const IndirectFieldDecl *IFD =
3050 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3051 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3054 llvm_unreachable("can't construct reference to bound member function");
3058 return MemPtr.getDecl();
3061 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3062 const BinaryOperator *BO,
3064 bool IncludeMember = true) {
3065 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3067 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3068 if (Info.keepEvaluatingAfterFailure()) {
3070 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3075 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3076 BO->getRHS(), IncludeMember);
3079 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3080 /// the provided lvalue, which currently refers to the base object.
3081 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3083 SubobjectDesignator &D = Result.Designator;
3084 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3087 QualType TargetQT = E->getType();
3088 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3089 TargetQT = PT->getPointeeType();
3091 // Check this cast lands within the final derived-to-base subobject path.
3092 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3093 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3094 << D.MostDerivedType << TargetQT;
3098 // Check the type of the final cast. We don't need to check the path,
3099 // since a cast can only be formed if the path is unique.
3100 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3101 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3102 const CXXRecordDecl *FinalType;
3103 if (NewEntriesSize == D.MostDerivedPathLength)
3104 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3106 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3107 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3108 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3109 << D.MostDerivedType << TargetQT;
3113 // Truncate the lvalue to the appropriate derived class.
3114 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3118 enum EvalStmtResult {
3119 /// Evaluation failed.
3121 /// Hit a 'return' statement.
3123 /// Evaluation succeeded.
3125 /// Hit a 'continue' statement.
3127 /// Hit a 'break' statement.
3129 /// Still scanning for 'case' or 'default' statement.
3134 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3135 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3136 // We don't need to evaluate the initializer for a static local.
3137 if (!VD->hasLocalStorage())
3141 Result.set(VD, Info.CurrentCall->Index);
3142 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3144 const Expr *InitE = VD->getInit();
3146 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3147 << false << VD->getType();
3152 if (InitE->isValueDependent())
3155 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3156 // Wipe out any partially-computed value, to allow tracking that this
3157 // evaluation failed.
3166 /// Evaluate a condition (either a variable declaration or an expression).
3167 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3168 const Expr *Cond, bool &Result) {
3169 FullExpressionRAII Scope(Info);
3170 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3172 return EvaluateAsBooleanCondition(Cond, Result, Info);
3175 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3177 const SwitchCase *SC = nullptr);
3179 /// Evaluate the body of a loop, and translate the result as appropriate.
3180 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3182 const SwitchCase *Case = nullptr) {
3183 BlockScopeRAII Scope(Info);
3184 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3186 return ESR_Succeeded;
3189 return ESR_Continue;
3192 case ESR_CaseNotFound:
3195 llvm_unreachable("Invalid EvalStmtResult!");
3198 /// Evaluate a switch statement.
3199 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3200 const SwitchStmt *SS) {
3201 BlockScopeRAII Scope(Info);
3203 // Evaluate the switch condition.
3206 FullExpressionRAII Scope(Info);
3207 if (SS->getConditionVariable() &&
3208 !EvaluateDecl(Info, SS->getConditionVariable()))
3210 if (!EvaluateInteger(SS->getCond(), Value, Info))
3214 // Find the switch case corresponding to the value of the condition.
3215 // FIXME: Cache this lookup.
3216 const SwitchCase *Found = nullptr;
3217 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3218 SC = SC->getNextSwitchCase()) {
3219 if (isa<DefaultStmt>(SC)) {
3224 const CaseStmt *CS = cast<CaseStmt>(SC);
3225 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3226 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3228 if (LHS <= Value && Value <= RHS) {
3235 return ESR_Succeeded;
3237 // Search the switch body for the switch case and evaluate it from there.
3238 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3240 return ESR_Succeeded;
3246 case ESR_CaseNotFound:
3247 // This can only happen if the switch case is nested within a statement
3248 // expression. We have no intention of supporting that.
3249 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3252 llvm_unreachable("Invalid EvalStmtResult!");
3255 // Evaluate a statement.
3256 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3257 const Stmt *S, const SwitchCase *Case) {
3258 if (!Info.nextStep(S))
3261 // If we're hunting down a 'case' or 'default' label, recurse through
3262 // substatements until we hit the label.
3264 // FIXME: We don't start the lifetime of objects whose initialization we
3265 // jump over. However, such objects must be of class type with a trivial
3266 // default constructor that initialize all subobjects, so must be empty,
3267 // so this almost never matters.
3268 switch (S->getStmtClass()) {
3269 case Stmt::CompoundStmtClass:
3270 // FIXME: Precompute which substatement of a compound statement we
3271 // would jump to, and go straight there rather than performing a
3272 // linear scan each time.
3273 case Stmt::LabelStmtClass:
3274 case Stmt::AttributedStmtClass:
3275 case Stmt::DoStmtClass:
3278 case Stmt::CaseStmtClass:
3279 case Stmt::DefaultStmtClass:
3284 case Stmt::IfStmtClass: {
3285 // FIXME: Precompute which side of an 'if' we would jump to, and go
3286 // straight there rather than scanning both sides.
3287 const IfStmt *IS = cast<IfStmt>(S);
3289 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3290 // preceded by our switch label.
3291 BlockScopeRAII Scope(Info);
3293 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3294 if (ESR != ESR_CaseNotFound || !IS->getElse())
3296 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3299 case Stmt::WhileStmtClass: {
3300 EvalStmtResult ESR =
3301 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3302 if (ESR != ESR_Continue)
3307 case Stmt::ForStmtClass: {
3308 const ForStmt *FS = cast<ForStmt>(S);
3309 EvalStmtResult ESR =
3310 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3311 if (ESR != ESR_Continue)
3314 FullExpressionRAII IncScope(Info);
3315 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3321 case Stmt::DeclStmtClass:
3322 // FIXME: If the variable has initialization that can't be jumped over,
3323 // bail out of any immediately-surrounding compound-statement too.
3325 return ESR_CaseNotFound;
3329 switch (S->getStmtClass()) {
3331 if (const Expr *E = dyn_cast<Expr>(S)) {
3332 // Don't bother evaluating beyond an expression-statement which couldn't
3334 FullExpressionRAII Scope(Info);
3335 if (!EvaluateIgnoredValue(Info, E))
3337 return ESR_Succeeded;
3340 Info.Diag(S->getLocStart());
3343 case Stmt::NullStmtClass:
3344 return ESR_Succeeded;
3346 case Stmt::DeclStmtClass: {
3347 const DeclStmt *DS = cast<DeclStmt>(S);
3348 for (const auto *DclIt : DS->decls()) {
3349 // Each declaration initialization is its own full-expression.
3350 // FIXME: This isn't quite right; if we're performing aggregate
3351 // initialization, each braced subexpression is its own full-expression.
3352 FullExpressionRAII Scope(Info);
3353 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3356 return ESR_Succeeded;
3359 case Stmt::ReturnStmtClass: {
3360 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3361 FullExpressionRAII Scope(Info);
3362 if (RetExpr && !Evaluate(Result, Info, RetExpr))
3364 return ESR_Returned;
3367 case Stmt::CompoundStmtClass: {
3368 BlockScopeRAII Scope(Info);
3370 const CompoundStmt *CS = cast<CompoundStmt>(S);
3371 for (const auto *BI : CS->body()) {
3372 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3373 if (ESR == ESR_Succeeded)
3375 else if (ESR != ESR_CaseNotFound)
3378 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3381 case Stmt::IfStmtClass: {
3382 const IfStmt *IS = cast<IfStmt>(S);
3384 // Evaluate the condition, as either a var decl or as an expression.
3385 BlockScopeRAII Scope(Info);
3387 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3390 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3391 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3392 if (ESR != ESR_Succeeded)
3395 return ESR_Succeeded;
3398 case Stmt::WhileStmtClass: {
3399 const WhileStmt *WS = cast<WhileStmt>(S);
3401 BlockScopeRAII Scope(Info);
3403 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3409 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3410 if (ESR != ESR_Continue)
3413 return ESR_Succeeded;
3416 case Stmt::DoStmtClass: {
3417 const DoStmt *DS = cast<DoStmt>(S);
3420 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3421 if (ESR != ESR_Continue)
3425 FullExpressionRAII CondScope(Info);
3426 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3429 return ESR_Succeeded;
3432 case Stmt::ForStmtClass: {
3433 const ForStmt *FS = cast<ForStmt>(S);
3434 BlockScopeRAII Scope(Info);
3435 if (FS->getInit()) {
3436 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3437 if (ESR != ESR_Succeeded)
3441 BlockScopeRAII Scope(Info);
3442 bool Continue = true;
3443 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3444 FS->getCond(), Continue))
3449 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3450 if (ESR != ESR_Continue)
3454 FullExpressionRAII IncScope(Info);
3455 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3459 return ESR_Succeeded;
3462 case Stmt::CXXForRangeStmtClass: {
3463 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3464 BlockScopeRAII Scope(Info);
3466 // Initialize the __range variable.
3467 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3468 if (ESR != ESR_Succeeded)
3471 // Create the __begin and __end iterators.
3472 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3473 if (ESR != ESR_Succeeded)
3477 // Condition: __begin != __end.
3479 bool Continue = true;
3480 FullExpressionRAII CondExpr(Info);
3481 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3487 // User's variable declaration, initialized by *__begin.
3488 BlockScopeRAII InnerScope(Info);
3489 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3490 if (ESR != ESR_Succeeded)
3494 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3495 if (ESR != ESR_Continue)
3498 // Increment: ++__begin
3499 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3503 return ESR_Succeeded;
3506 case Stmt::SwitchStmtClass:
3507 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3509 case Stmt::ContinueStmtClass:
3510 return ESR_Continue;
3512 case Stmt::BreakStmtClass:
3515 case Stmt::LabelStmtClass:
3516 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3518 case Stmt::AttributedStmtClass:
3519 // As a general principle, C++11 attributes can be ignored without
3520 // any semantic impact.
3521 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3524 case Stmt::CaseStmtClass:
3525 case Stmt::DefaultStmtClass:
3526 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3530 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3531 /// default constructor. If so, we'll fold it whether or not it's marked as
3532 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3533 /// so we need special handling.
3534 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3535 const CXXConstructorDecl *CD,
3536 bool IsValueInitialization) {
3537 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3540 // Value-initialization does not call a trivial default constructor, so such a
3541 // call is a core constant expression whether or not the constructor is
3543 if (!CD->isConstexpr() && !IsValueInitialization) {
3544 if (Info.getLangOpts().CPlusPlus11) {
3545 // FIXME: If DiagDecl is an implicitly-declared special member function,
3546 // we should be much more explicit about why it's not constexpr.
3547 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3548 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3549 Info.Note(CD->getLocation(), diag::note_declared_at);
3551 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3557 /// CheckConstexprFunction - Check that a function can be called in a constant
3559 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3560 const FunctionDecl *Declaration,
3561 const FunctionDecl *Definition) {
3562 // Potential constant expressions can contain calls to declared, but not yet
3563 // defined, constexpr functions.
3564 if (Info.checkingPotentialConstantExpression() && !Definition &&
3565 Declaration->isConstexpr())
3568 // Bail out with no diagnostic if the function declaration itself is invalid.
3569 // We will have produced a relevant diagnostic while parsing it.
3570 if (Declaration->isInvalidDecl())
3573 // Can we evaluate this function call?
3574 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3577 if (Info.getLangOpts().CPlusPlus11) {
3578 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3579 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3580 // should be much more explicit about why it's not constexpr.
3581 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3582 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3584 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3586 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3592 typedef SmallVector<APValue, 8> ArgVector;
3595 /// EvaluateArgs - Evaluate the arguments to a function call.
3596 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3598 bool Success = true;
3599 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3601 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3602 // If we're checking for a potential constant expression, evaluate all
3603 // initializers even if some of them fail.
3604 if (!Info.keepEvaluatingAfterFailure())
3612 /// Evaluate a function call.
3613 static bool HandleFunctionCall(SourceLocation CallLoc,
3614 const FunctionDecl *Callee, const LValue *This,
3615 ArrayRef<const Expr*> Args, const Stmt *Body,
3616 EvalInfo &Info, APValue &Result) {
3617 ArgVector ArgValues(Args.size());
3618 if (!EvaluateArgs(Args, ArgValues, Info))
3621 if (!Info.CheckCallLimit(CallLoc))
3624 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3626 // For a trivial copy or move assignment, perform an APValue copy. This is
3627 // essential for unions, where the operations performed by the assignment
3628 // operator cannot be represented as statements.
3629 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3630 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3632 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3634 RHS.setFrom(Info.Ctx, ArgValues[0]);
3636 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3639 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3642 This->moveInto(Result);
3646 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3647 if (ESR == ESR_Succeeded) {
3648 if (Callee->getReturnType()->isVoidType())
3650 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3652 return ESR == ESR_Returned;
3655 /// Evaluate a constructor call.
3656 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3657 ArrayRef<const Expr*> Args,
3658 const CXXConstructorDecl *Definition,
3659 EvalInfo &Info, APValue &Result) {
3660 ArgVector ArgValues(Args.size());
3661 if (!EvaluateArgs(Args, ArgValues, Info))
3664 if (!Info.CheckCallLimit(CallLoc))
3667 const CXXRecordDecl *RD = Definition->getParent();
3668 if (RD->getNumVBases()) {
3669 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3673 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3675 // If it's a delegating constructor, just delegate.
3676 if (Definition->isDelegatingConstructor()) {
3677 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3679 FullExpressionRAII InitScope(Info);
3680 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3683 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3686 // For a trivial copy or move constructor, perform an APValue copy. This is
3687 // essential for unions, where the operations performed by the constructor
3688 // cannot be represented by ctor-initializers.
3689 if (Definition->isDefaulted() &&
3690 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3691 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
3693 RHS.setFrom(Info.Ctx, ArgValues[0]);
3694 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3698 // Reserve space for the struct members.
3699 if (!RD->isUnion() && Result.isUninit())
3700 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3701 std::distance(RD->field_begin(), RD->field_end()));
3703 if (RD->isInvalidDecl()) return false;
3704 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3706 // A scope for temporaries lifetime-extended by reference members.
3707 BlockScopeRAII LifetimeExtendedScope(Info);
3709 bool Success = true;
3710 unsigned BasesSeen = 0;
3712 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3714 for (const auto *I : Definition->inits()) {
3715 LValue Subobject = This;
3716 APValue *Value = &Result;
3718 // Determine the subobject to initialize.
3719 FieldDecl *FD = nullptr;
3720 if (I->isBaseInitializer()) {
3721 QualType BaseType(I->getBaseClass(), 0);
3723 // Non-virtual base classes are initialized in the order in the class
3724 // definition. We have already checked for virtual base classes.
3725 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3726 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3727 "base class initializers not in expected order");
3730 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
3731 BaseType->getAsCXXRecordDecl(), &Layout))
3733 Value = &Result.getStructBase(BasesSeen++);
3734 } else if ((FD = I->getMember())) {
3735 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
3737 if (RD->isUnion()) {
3738 Result = APValue(FD);
3739 Value = &Result.getUnionValue();
3741 Value = &Result.getStructField(FD->getFieldIndex());
3743 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
3744 // Walk the indirect field decl's chain to find the object to initialize,
3745 // and make sure we've initialized every step along it.
3746 for (auto *C : IFD->chain()) {
3747 FD = cast<FieldDecl>(C);
3748 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3749 // Switch the union field if it differs. This happens if we had
3750 // preceding zero-initialization, and we're now initializing a union
3751 // subobject other than the first.
3752 // FIXME: In this case, the values of the other subobjects are
3753 // specified, since zero-initialization sets all padding bits to zero.
3754 if (Value->isUninit() ||
3755 (Value->isUnion() && Value->getUnionField() != FD)) {
3757 *Value = APValue(FD);
3759 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3760 std::distance(CD->field_begin(), CD->field_end()));
3762 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
3765 Value = &Value->getUnionValue();
3767 Value = &Value->getStructField(FD->getFieldIndex());
3770 llvm_unreachable("unknown base initializer kind");
3773 FullExpressionRAII InitScope(Info);
3774 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3775 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
3777 // If we're checking for a potential constant expression, evaluate all
3778 // initializers even if some of them fail.
3779 if (!Info.keepEvaluatingAfterFailure())
3786 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3789 //===----------------------------------------------------------------------===//
3790 // Generic Evaluation
3791 //===----------------------------------------------------------------------===//
3794 template <class Derived>
3795 class ExprEvaluatorBase
3796 : public ConstStmtVisitor<Derived, bool> {
3798 bool DerivedSuccess(const APValue &V, const Expr *E) {
3799 return static_cast<Derived*>(this)->Success(V, E);
3801 bool DerivedZeroInitialization(const Expr *E) {
3802 return static_cast<Derived*>(this)->ZeroInitialization(E);
3805 // Check whether a conditional operator with a non-constant condition is a
3806 // potential constant expression. If neither arm is a potential constant
3807 // expression, then the conditional operator is not either.
3808 template<typename ConditionalOperator>
3809 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3810 assert(Info.checkingPotentialConstantExpression());
3812 // Speculatively evaluate both arms.
3814 SmallVector<PartialDiagnosticAt, 8> Diag;
3815 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3817 StmtVisitorTy::Visit(E->getFalseExpr());
3822 StmtVisitorTy::Visit(E->getTrueExpr());
3827 Error(E, diag::note_constexpr_conditional_never_const);
3831 template<typename ConditionalOperator>
3832 bool HandleConditionalOperator(const ConditionalOperator *E) {
3834 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3835 if (Info.checkingPotentialConstantExpression())
3836 CheckPotentialConstantConditional(E);
3840 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3841 return StmtVisitorTy::Visit(EvalExpr);
3846 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
3847 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3849 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3850 return Info.CCEDiag(E, D);
3853 bool ZeroInitialization(const Expr *E) { return Error(E); }
3856 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3858 EvalInfo &getEvalInfo() { return Info; }
3860 /// Report an evaluation error. This should only be called when an error is
3861 /// first discovered. When propagating an error, just return false.
3862 bool Error(const Expr *E, diag::kind D) {
3866 bool Error(const Expr *E) {
3867 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3870 bool VisitStmt(const Stmt *) {
3871 llvm_unreachable("Expression evaluator should not be called on stmts");
3873 bool VisitExpr(const Expr *E) {
3877 bool VisitParenExpr(const ParenExpr *E)
3878 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3879 bool VisitUnaryExtension(const UnaryOperator *E)
3880 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3881 bool VisitUnaryPlus(const UnaryOperator *E)
3882 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3883 bool VisitChooseExpr(const ChooseExpr *E)
3884 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
3885 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3886 { return StmtVisitorTy::Visit(E->getResultExpr()); }
3887 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3888 { return StmtVisitorTy::Visit(E->getReplacement()); }
3889 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3890 { return StmtVisitorTy::Visit(E->getExpr()); }
3891 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3892 // The initializer may not have been parsed yet, or might be erroneous.
3895 return StmtVisitorTy::Visit(E->getExpr());
3897 // We cannot create any objects for which cleanups are required, so there is
3898 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3899 bool VisitExprWithCleanups(const ExprWithCleanups *E)
3900 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3902 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3903 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3904 return static_cast<Derived*>(this)->VisitCastExpr(E);
3906 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3907 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3908 return static_cast<Derived*>(this)->VisitCastExpr(E);
3911 bool VisitBinaryOperator(const BinaryOperator *E) {
3912 switch (E->getOpcode()) {
3917 VisitIgnoredValue(E->getLHS());
3918 return StmtVisitorTy::Visit(E->getRHS());
3923 if (!HandleMemberPointerAccess(Info, E, Obj))
3926 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
3928 return DerivedSuccess(Result, E);
3933 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
3934 // Evaluate and cache the common expression. We treat it as a temporary,
3935 // even though it's not quite the same thing.
3936 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
3937 Info, E->getCommon()))
3940 return HandleConditionalOperator(E);
3943 bool VisitConditionalOperator(const ConditionalOperator *E) {
3944 bool IsBcpCall = false;
3945 // If the condition (ignoring parens) is a __builtin_constant_p call,
3946 // the result is a constant expression if it can be folded without
3947 // side-effects. This is an important GNU extension. See GCC PR38377
3949 if (const CallExpr *CallCE =
3950 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3951 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
3954 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3955 // constant expression; we can't check whether it's potentially foldable.
3956 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
3959 FoldConstant Fold(Info, IsBcpCall);
3960 if (!HandleConditionalOperator(E)) {
3961 Fold.keepDiagnostics();
3968 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
3969 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3970 return DerivedSuccess(*Value, E);
3972 const Expr *Source = E->getSourceExpr();
3975 if (Source == E) { // sanity checking.
3976 assert(0 && "OpaqueValueExpr recursively refers to itself");
3979 return StmtVisitorTy::Visit(Source);
3982 bool VisitCallExpr(const CallExpr *E) {
3983 const Expr *Callee = E->getCallee()->IgnoreParens();
3984 QualType CalleeType = Callee->getType();
3986 const FunctionDecl *FD = nullptr;
3987 LValue *This = nullptr, ThisVal;
3988 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
3989 bool HasQualifier = false;
3991 // Extract function decl and 'this' pointer from the callee.
3992 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
3993 const ValueDecl *Member = nullptr;
3994 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3995 // Explicit bound member calls, such as x.f() or p->g();
3996 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
3998 Member = ME->getMemberDecl();
4000 HasQualifier = ME->hasQualifier();
4001 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4002 // Indirect bound member calls ('.*' or '->*').
4003 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4004 if (!Member) return false;
4007 return Error(Callee);
4009 FD = dyn_cast<FunctionDecl>(Member);
4011 return Error(Callee);
4012 } else if (CalleeType->isFunctionPointerType()) {
4014 if (!EvaluatePointer(Callee, Call, Info))
4017 if (!Call.getLValueOffset().isZero())
4018 return Error(Callee);
4019 FD = dyn_cast_or_null<FunctionDecl>(
4020 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4022 return Error(Callee);
4024 // Overloaded operator calls to member functions are represented as normal
4025 // calls with '*this' as the first argument.
4026 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4027 if (MD && !MD->isStatic()) {
4028 // FIXME: When selecting an implicit conversion for an overloaded
4029 // operator delete, we sometimes try to evaluate calls to conversion
4030 // operators without a 'this' parameter!
4034 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4037 Args = Args.slice(1);
4040 // Don't call function pointers which have been cast to some other type.
4041 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4046 if (This && !This->checkSubobject(Info, E, CSK_This))
4049 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4050 // calls to such functions in constant expressions.
4051 if (This && !HasQualifier &&
4052 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4053 return Error(E, diag::note_constexpr_virtual_call);
4055 const FunctionDecl *Definition = nullptr;
4056 Stmt *Body = FD->getBody(Definition);
4059 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4060 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4064 return DerivedSuccess(Result, E);
4067 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4068 return StmtVisitorTy::Visit(E->getInitializer());
4070 bool VisitInitListExpr(const InitListExpr *E) {
4071 if (E->getNumInits() == 0)
4072 return DerivedZeroInitialization(E);
4073 if (E->getNumInits() == 1)
4074 return StmtVisitorTy::Visit(E->getInit(0));
4077 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4078 return DerivedZeroInitialization(E);
4080 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4081 return DerivedZeroInitialization(E);
4083 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4084 return DerivedZeroInitialization(E);
4087 /// A member expression where the object is a prvalue is itself a prvalue.
4088 bool VisitMemberExpr(const MemberExpr *E) {
4089 assert(!E->isArrow() && "missing call to bound member function?");
4092 if (!Evaluate(Val, Info, E->getBase()))
4095 QualType BaseTy = E->getBase()->getType();
4097 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4098 if (!FD) return Error(E);
4099 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4100 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4101 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4103 CompleteObject Obj(&Val, BaseTy);
4104 SubobjectDesignator Designator(BaseTy);
4105 Designator.addDeclUnchecked(FD);
4108 return extractSubobject(Info, E, Obj, Designator, Result) &&
4109 DerivedSuccess(Result, E);
4112 bool VisitCastExpr(const CastExpr *E) {
4113 switch (E->getCastKind()) {
4117 case CK_AtomicToNonAtomic: {
4119 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4121 return DerivedSuccess(AtomicVal, E);
4125 case CK_UserDefinedConversion:
4126 return StmtVisitorTy::Visit(E->getSubExpr());
4128 case CK_LValueToRValue: {
4130 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4133 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4134 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4137 return DerivedSuccess(RVal, E);
4144 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4145 return VisitUnaryPostIncDec(UO);
4147 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4148 return VisitUnaryPostIncDec(UO);
4150 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4151 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4155 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4158 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4159 UO->isIncrementOp(), &RVal))
4161 return DerivedSuccess(RVal, UO);
4164 bool VisitStmtExpr(const StmtExpr *E) {
4165 // We will have checked the full-expressions inside the statement expression
4166 // when they were completed, and don't need to check them again now.
4167 if (Info.checkingForOverflow())
4170 BlockScopeRAII Scope(Info);
4171 const CompoundStmt *CS = E->getSubStmt();
4172 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4173 BE = CS->body_end();
4176 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4178 Info.Diag((*BI)->getLocStart(),
4179 diag::note_constexpr_stmt_expr_unsupported);
4182 return this->Visit(FinalExpr);
4185 APValue ReturnValue;
4186 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4187 if (ESR != ESR_Succeeded) {
4188 // FIXME: If the statement-expression terminated due to 'return',
4189 // 'break', or 'continue', it would be nice to propagate that to
4190 // the outer statement evaluation rather than bailing out.
4191 if (ESR != ESR_Failed)
4192 Info.Diag((*BI)->getLocStart(),
4193 diag::note_constexpr_stmt_expr_unsupported);
4199 /// Visit a value which is evaluated, but whose value is ignored.
4200 void VisitIgnoredValue(const Expr *E) {
4201 EvaluateIgnoredValue(Info, E);
4207 //===----------------------------------------------------------------------===//
4208 // Common base class for lvalue and temporary evaluation.
4209 //===----------------------------------------------------------------------===//
4211 template<class Derived>
4212 class LValueExprEvaluatorBase
4213 : public ExprEvaluatorBase<Derived> {
4216 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4217 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4219 bool Success(APValue::LValueBase B) {
4225 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4226 ExprEvaluatorBaseTy(Info), Result(Result) {}
4228 bool Success(const APValue &V, const Expr *E) {
4229 Result.setFrom(this->Info.Ctx, V);
4233 bool VisitMemberExpr(const MemberExpr *E) {
4234 // Handle non-static data members.
4237 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4239 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4240 } else if (E->getBase()->isRValue()) {
4241 assert(E->getBase()->getType()->isRecordType());
4242 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4244 BaseTy = E->getBase()->getType();
4246 if (!this->Visit(E->getBase()))
4248 BaseTy = E->getBase()->getType();
4251 const ValueDecl *MD = E->getMemberDecl();
4252 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4253 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4254 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4256 if (!HandleLValueMember(this->Info, E, Result, FD))
4258 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4259 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4262 return this->Error(E);
4264 if (MD->getType()->isReferenceType()) {
4266 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4269 return Success(RefValue, E);
4274 bool VisitBinaryOperator(const BinaryOperator *E) {
4275 switch (E->getOpcode()) {
4277 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4281 return HandleMemberPointerAccess(this->Info, E, Result);
4285 bool VisitCastExpr(const CastExpr *E) {
4286 switch (E->getCastKind()) {
4288 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4290 case CK_DerivedToBase:
4291 case CK_UncheckedDerivedToBase:
4292 if (!this->Visit(E->getSubExpr()))
4295 // Now figure out the necessary offset to add to the base LV to get from
4296 // the derived class to the base class.
4297 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4304 //===----------------------------------------------------------------------===//
4305 // LValue Evaluation
4307 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4308 // function designators (in C), decl references to void objects (in C), and
4309 // temporaries (if building with -Wno-address-of-temporary).
4311 // LValue evaluation produces values comprising a base expression of one of the
4317 // * CompoundLiteralExpr in C
4321 // * ObjCStringLiteralExpr
4325 // * CallExpr for a MakeStringConstant builtin
4326 // - Locals and temporaries
4327 // * MaterializeTemporaryExpr
4328 // * Any Expr, with a CallIndex indicating the function in which the temporary
4329 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4330 // from the AST (FIXME).
4331 // * A MaterializeTemporaryExpr that has static storage duration, with no
4332 // CallIndex, for a lifetime-extended temporary.
4333 // plus an offset in bytes.
4334 //===----------------------------------------------------------------------===//
4336 class LValueExprEvaluator
4337 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4339 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4340 LValueExprEvaluatorBaseTy(Info, Result) {}
4342 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4343 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4345 bool VisitDeclRefExpr(const DeclRefExpr *E);
4346 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4347 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4348 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4349 bool VisitMemberExpr(const MemberExpr *E);
4350 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4351 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4352 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4353 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4354 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4355 bool VisitUnaryDeref(const UnaryOperator *E);
4356 bool VisitUnaryReal(const UnaryOperator *E);
4357 bool VisitUnaryImag(const UnaryOperator *E);
4358 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4359 return VisitUnaryPreIncDec(UO);
4361 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4362 return VisitUnaryPreIncDec(UO);
4364 bool VisitBinAssign(const BinaryOperator *BO);
4365 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4367 bool VisitCastExpr(const CastExpr *E) {
4368 switch (E->getCastKind()) {
4370 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4372 case CK_LValueBitCast:
4373 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4374 if (!Visit(E->getSubExpr()))
4376 Result.Designator.setInvalid();
4379 case CK_BaseToDerived:
4380 if (!Visit(E->getSubExpr()))
4382 return HandleBaseToDerivedCast(Info, E, Result);
4386 } // end anonymous namespace
4388 /// Evaluate an expression as an lvalue. This can be legitimately called on
4389 /// expressions which are not glvalues, in two cases:
4390 /// * function designators in C, and
4391 /// * "extern void" objects
4392 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4393 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4394 E->getType()->isVoidType());
4395 return LValueExprEvaluator(Info, Result).Visit(E);
4398 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4399 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4401 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4402 return VisitVarDecl(E, VD);
4406 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4407 CallStackFrame *Frame = nullptr;
4408 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4409 Frame = Info.CurrentCall;
4411 if (!VD->getType()->isReferenceType()) {
4413 Result.set(VD, Frame->Index);
4420 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4422 if (V->isUninit()) {
4423 if (!Info.checkingPotentialConstantExpression())
4424 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4427 return Success(*V, E);
4430 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4431 const MaterializeTemporaryExpr *E) {
4432 // Walk through the expression to find the materialized temporary itself.
4433 SmallVector<const Expr *, 2> CommaLHSs;
4434 SmallVector<SubobjectAdjustment, 2> Adjustments;
4435 const Expr *Inner = E->GetTemporaryExpr()->
4436 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4438 // If we passed any comma operators, evaluate their LHSs.
4439 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4440 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4443 // A materialized temporary with static storage duration can appear within the
4444 // result of a constant expression evaluation, so we need to preserve its
4445 // value for use outside this evaluation.
4447 if (E->getStorageDuration() == SD_Static) {
4448 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4452 Value = &Info.CurrentCall->
4453 createTemporary(E, E->getStorageDuration() == SD_Automatic);
4454 Result.set(E, Info.CurrentCall->Index);
4457 QualType Type = Inner->getType();
4459 // Materialize the temporary itself.
4460 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4461 (E->getStorageDuration() == SD_Static &&
4462 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4467 // Adjust our lvalue to refer to the desired subobject.
4468 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4470 switch (Adjustments[I].Kind) {
4471 case SubobjectAdjustment::DerivedToBaseAdjustment:
4472 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4475 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4478 case SubobjectAdjustment::FieldAdjustment:
4479 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4481 Type = Adjustments[I].Field->getType();
4484 case SubobjectAdjustment::MemberPointerAdjustment:
4485 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4486 Adjustments[I].Ptr.RHS))
4488 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4497 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4498 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4499 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4500 // only see this when folding in C, so there's no standard to follow here.
4504 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4505 if (!E->isPotentiallyEvaluated())
4508 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4509 << E->getExprOperand()->getType()
4510 << E->getExprOperand()->getSourceRange();
4514 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4518 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4519 // Handle static data members.
4520 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4521 VisitIgnoredValue(E->getBase());
4522 return VisitVarDecl(E, VD);
4525 // Handle static member functions.
4526 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4527 if (MD->isStatic()) {
4528 VisitIgnoredValue(E->getBase());
4533 // Handle non-static data members.
4534 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4537 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4538 // FIXME: Deal with vectors as array subscript bases.
4539 if (E->getBase()->getType()->isVectorType())
4542 if (!EvaluatePointer(E->getBase(), Result, Info))
4546 if (!EvaluateInteger(E->getIdx(), Index, Info))
4549 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4550 getExtValue(Index));
4553 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4554 return EvaluatePointer(E->getSubExpr(), Result, Info);
4557 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4558 if (!Visit(E->getSubExpr()))
4560 // __real is a no-op on scalar lvalues.
4561 if (E->getSubExpr()->getType()->isAnyComplexType())
4562 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4566 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4567 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4568 "lvalue __imag__ on scalar?");
4569 if (!Visit(E->getSubExpr()))
4571 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4575 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4576 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4579 if (!this->Visit(UO->getSubExpr()))
4582 return handleIncDec(
4583 this->Info, UO, Result, UO->getSubExpr()->getType(),
4584 UO->isIncrementOp(), nullptr);
4587 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4588 const CompoundAssignOperator *CAO) {
4589 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4594 // The overall lvalue result is the result of evaluating the LHS.
4595 if (!this->Visit(CAO->getLHS())) {
4596 if (Info.keepEvaluatingAfterFailure())
4597 Evaluate(RHS, this->Info, CAO->getRHS());
4601 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4604 return handleCompoundAssignment(
4606 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4607 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4610 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4611 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4616 if (!this->Visit(E->getLHS())) {
4617 if (Info.keepEvaluatingAfterFailure())
4618 Evaluate(NewVal, this->Info, E->getRHS());
4622 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4625 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4629 //===----------------------------------------------------------------------===//
4630 // Pointer Evaluation
4631 //===----------------------------------------------------------------------===//
4634 class PointerExprEvaluator
4635 : public ExprEvaluatorBase<PointerExprEvaluator> {
4638 bool Success(const Expr *E) {
4644 PointerExprEvaluator(EvalInfo &info, LValue &Result)
4645 : ExprEvaluatorBaseTy(info), Result(Result) {}
4647 bool Success(const APValue &V, const Expr *E) {
4648 Result.setFrom(Info.Ctx, V);
4651 bool ZeroInitialization(const Expr *E) {
4652 return Success((Expr*)nullptr);
4655 bool VisitBinaryOperator(const BinaryOperator *E);
4656 bool VisitCastExpr(const CastExpr* E);
4657 bool VisitUnaryAddrOf(const UnaryOperator *E);
4658 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4659 { return Success(E); }
4660 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4661 { return Success(E); }
4662 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4663 { return Success(E); }
4664 bool VisitCallExpr(const CallExpr *E);
4665 bool VisitBlockExpr(const BlockExpr *E) {
4666 if (!E->getBlockDecl()->hasCaptures())
4670 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4671 // Can't look at 'this' when checking a potential constant expression.
4672 if (Info.checkingPotentialConstantExpression())
4674 if (!Info.CurrentCall->This) {
4675 if (Info.getLangOpts().CPlusPlus11)
4676 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4681 Result = *Info.CurrentCall->This;
4685 // FIXME: Missing: @protocol, @selector
4687 } // end anonymous namespace
4689 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4690 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4691 return PointerExprEvaluator(Info, Result).Visit(E);
4694 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4695 if (E->getOpcode() != BO_Add &&
4696 E->getOpcode() != BO_Sub)
4697 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4699 const Expr *PExp = E->getLHS();
4700 const Expr *IExp = E->getRHS();
4701 if (IExp->getType()->isPointerType())
4702 std::swap(PExp, IExp);
4704 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4705 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4708 llvm::APSInt Offset;
4709 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4712 int64_t AdditionalOffset = getExtValue(Offset);
4713 if (E->getOpcode() == BO_Sub)
4714 AdditionalOffset = -AdditionalOffset;
4716 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4717 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4721 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4722 return EvaluateLValue(E->getSubExpr(), Result, Info);
4725 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4726 const Expr* SubExpr = E->getSubExpr();
4728 switch (E->getCastKind()) {
4733 case CK_CPointerToObjCPointerCast:
4734 case CK_BlockPointerToObjCPointerCast:
4735 case CK_AnyPointerToBlockPointerCast:
4736 if (!Visit(SubExpr))
4738 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4739 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4740 // also static_casts, but we disallow them as a resolution to DR1312.
4741 if (!E->getType()->isVoidPointerType()) {
4742 Result.Designator.setInvalid();
4743 if (SubExpr->getType()->isVoidPointerType())
4744 CCEDiag(E, diag::note_constexpr_invalid_cast)
4745 << 3 << SubExpr->getType();
4747 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4751 case CK_DerivedToBase:
4752 case CK_UncheckedDerivedToBase:
4753 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4755 if (!Result.Base && Result.Offset.isZero())
4758 // Now figure out the necessary offset to add to the base LV to get from
4759 // the derived class to the base class.
4760 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4761 castAs<PointerType>()->getPointeeType(),
4764 case CK_BaseToDerived:
4765 if (!Visit(E->getSubExpr()))
4767 if (!Result.Base && Result.Offset.isZero())
4769 return HandleBaseToDerivedCast(Info, E, Result);
4771 case CK_NullToPointer:
4772 VisitIgnoredValue(E->getSubExpr());
4773 return ZeroInitialization(E);
4775 case CK_IntegralToPointer: {
4776 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4779 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4782 if (Value.isInt()) {
4783 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4784 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4785 Result.Base = (Expr*)nullptr;
4786 Result.Offset = CharUnits::fromQuantity(N);
4787 Result.CallIndex = 0;
4788 Result.Designator.setInvalid();
4791 // Cast is of an lvalue, no need to change value.
4792 Result.setFrom(Info.Ctx, Value);
4796 case CK_ArrayToPointerDecay:
4797 if (SubExpr->isGLValue()) {
4798 if (!EvaluateLValue(SubExpr, Result, Info))
4801 Result.set(SubExpr, Info.CurrentCall->Index);
4802 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4803 Info, Result, SubExpr))
4806 // The result is a pointer to the first element of the array.
4807 if (const ConstantArrayType *CAT
4808 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4809 Result.addArray(Info, E, CAT);
4811 Result.Designator.setInvalid();
4814 case CK_FunctionToPointerDecay:
4815 return EvaluateLValue(SubExpr, Result, Info);
4818 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4821 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4822 if (IsStringLiteralCall(E))
4825 switch (E->getBuiltinCallee()) {
4826 case Builtin::BI__builtin_addressof:
4827 return EvaluateLValue(E->getArg(0), Result, Info);
4830 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4834 //===----------------------------------------------------------------------===//
4835 // Member Pointer Evaluation
4836 //===----------------------------------------------------------------------===//
4839 class MemberPointerExprEvaluator
4840 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
4843 bool Success(const ValueDecl *D) {
4844 Result = MemberPtr(D);
4849 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4850 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4852 bool Success(const APValue &V, const Expr *E) {
4856 bool ZeroInitialization(const Expr *E) {
4857 return Success((const ValueDecl*)nullptr);
4860 bool VisitCastExpr(const CastExpr *E);
4861 bool VisitUnaryAddrOf(const UnaryOperator *E);
4863 } // end anonymous namespace
4865 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4867 assert(E->isRValue() && E->getType()->isMemberPointerType());
4868 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4871 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4872 switch (E->getCastKind()) {
4874 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4876 case CK_NullToMemberPointer:
4877 VisitIgnoredValue(E->getSubExpr());
4878 return ZeroInitialization(E);
4880 case CK_BaseToDerivedMemberPointer: {
4881 if (!Visit(E->getSubExpr()))
4883 if (E->path_empty())
4885 // Base-to-derived member pointer casts store the path in derived-to-base
4886 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4887 // the wrong end of the derived->base arc, so stagger the path by one class.
4888 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4889 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4890 PathI != PathE; ++PathI) {
4891 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4892 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4893 if (!Result.castToDerived(Derived))
4896 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4897 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
4902 case CK_DerivedToBaseMemberPointer:
4903 if (!Visit(E->getSubExpr()))
4905 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4906 PathE = E->path_end(); PathI != PathE; ++PathI) {
4907 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4908 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4909 if (!Result.castToBase(Base))
4916 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4917 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4918 // member can be formed.
4919 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4922 //===----------------------------------------------------------------------===//
4923 // Record Evaluation
4924 //===----------------------------------------------------------------------===//
4927 class RecordExprEvaluator
4928 : public ExprEvaluatorBase<RecordExprEvaluator> {
4933 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4934 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4936 bool Success(const APValue &V, const Expr *E) {
4940 bool ZeroInitialization(const Expr *E);
4942 bool VisitCastExpr(const CastExpr *E);
4943 bool VisitInitListExpr(const InitListExpr *E);
4944 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4945 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
4949 /// Perform zero-initialization on an object of non-union class type.
4950 /// C++11 [dcl.init]p5:
4951 /// To zero-initialize an object or reference of type T means:
4953 /// -- if T is a (possibly cv-qualified) non-union class type,
4954 /// each non-static data member and each base-class subobject is
4955 /// zero-initialized
4956 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4957 const RecordDecl *RD,
4958 const LValue &This, APValue &Result) {
4959 assert(!RD->isUnion() && "Expected non-union class type");
4960 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4961 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4962 std::distance(RD->field_begin(), RD->field_end()));
4964 if (RD->isInvalidDecl()) return false;
4965 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4969 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
4970 End = CD->bases_end(); I != End; ++I, ++Index) {
4971 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4972 LValue Subobject = This;
4973 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4975 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
4976 Result.getStructBase(Index)))
4981 for (const auto *I : RD->fields()) {
4982 // -- if T is a reference type, no initialization is performed.
4983 if (I->getType()->isReferenceType())
4986 LValue Subobject = This;
4987 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
4990 ImplicitValueInitExpr VIE(I->getType());
4991 if (!EvaluateInPlace(
4992 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
4999 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5000 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5001 if (RD->isInvalidDecl()) return false;
5002 if (RD->isUnion()) {
5003 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5004 // object's first non-static named data member is zero-initialized
5005 RecordDecl::field_iterator I = RD->field_begin();
5006 if (I == RD->field_end()) {
5007 Result = APValue((const FieldDecl*)nullptr);
5011 LValue Subobject = This;
5012 if (!HandleLValueMember(Info, E, Subobject, *I))
5014 Result = APValue(*I);
5015 ImplicitValueInitExpr VIE(I->getType());
5016 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5019 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5020 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5024 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5027 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5028 switch (E->getCastKind()) {
5030 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5032 case CK_ConstructorConversion:
5033 return Visit(E->getSubExpr());
5035 case CK_DerivedToBase:
5036 case CK_UncheckedDerivedToBase: {
5037 APValue DerivedObject;
5038 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5040 if (!DerivedObject.isStruct())
5041 return Error(E->getSubExpr());
5043 // Derived-to-base rvalue conversion: just slice off the derived part.
5044 APValue *Value = &DerivedObject;
5045 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5046 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5047 PathE = E->path_end(); PathI != PathE; ++PathI) {
5048 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5049 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5050 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5059 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5060 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5061 if (RD->isInvalidDecl()) return false;
5062 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5064 if (RD->isUnion()) {
5065 const FieldDecl *Field = E->getInitializedFieldInUnion();
5066 Result = APValue(Field);
5070 // If the initializer list for a union does not contain any elements, the
5071 // first element of the union is value-initialized.
5072 // FIXME: The element should be initialized from an initializer list.
5073 // Is this difference ever observable for initializer lists which
5075 ImplicitValueInitExpr VIE(Field->getType());
5076 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5078 LValue Subobject = This;
5079 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5082 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5083 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5084 isa<CXXDefaultInitExpr>(InitExpr));
5086 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5089 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5090 "initializer list for class with base classes");
5091 Result = APValue(APValue::UninitStruct(), 0,
5092 std::distance(RD->field_begin(), RD->field_end()));
5093 unsigned ElementNo = 0;
5094 bool Success = true;
5095 for (const auto *Field : RD->fields()) {
5096 // Anonymous bit-fields are not considered members of the class for
5097 // purposes of aggregate initialization.
5098 if (Field->isUnnamedBitfield())
5101 LValue Subobject = This;
5103 bool HaveInit = ElementNo < E->getNumInits();
5105 // FIXME: Diagnostics here should point to the end of the initializer
5106 // list, not the start.
5107 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5108 Subobject, Field, &Layout))
5111 // Perform an implicit value-initialization for members beyond the end of
5112 // the initializer list.
5113 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5114 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5116 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5117 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5118 isa<CXXDefaultInitExpr>(Init));
5120 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5121 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5122 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5123 FieldVal, Field))) {
5124 if (!Info.keepEvaluatingAfterFailure())
5133 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5134 const CXXConstructorDecl *FD = E->getConstructor();
5135 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5137 bool ZeroInit = E->requiresZeroInitialization();
5138 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5139 // If we've already performed zero-initialization, we're already done.
5140 if (!Result.isUninit())
5143 // We can get here in two different ways:
5144 // 1) We're performing value-initialization, and should zero-initialize
5146 // 2) We're performing default-initialization of an object with a trivial
5147 // constexpr default constructor, in which case we should start the
5148 // lifetimes of all the base subobjects (there can be no data member
5149 // subobjects in this case) per [basic.life]p1.
5150 // Either way, ZeroInitialization is appropriate.
5151 return ZeroInitialization(E);
5154 const FunctionDecl *Definition = nullptr;
5155 FD->getBody(Definition);
5157 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5160 // Avoid materializing a temporary for an elidable copy/move constructor.
5161 if (E->isElidable() && !ZeroInit)
5162 if (const MaterializeTemporaryExpr *ME
5163 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5164 return Visit(ME->GetTemporaryExpr());
5166 if (ZeroInit && !ZeroInitialization(E))
5169 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5170 return HandleConstructorCall(E->getExprLoc(), This, Args,
5171 cast<CXXConstructorDecl>(Definition), Info,
5175 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5176 const CXXStdInitializerListExpr *E) {
5177 const ConstantArrayType *ArrayType =
5178 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5181 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5184 // Get a pointer to the first element of the array.
5185 Array.addArray(Info, E, ArrayType);
5187 // FIXME: Perform the checks on the field types in SemaInit.
5188 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5189 RecordDecl::field_iterator Field = Record->field_begin();
5190 if (Field == Record->field_end())
5194 if (!Field->getType()->isPointerType() ||
5195 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5196 ArrayType->getElementType()))
5199 // FIXME: What if the initializer_list type has base classes, etc?
5200 Result = APValue(APValue::UninitStruct(), 0, 2);
5201 Array.moveInto(Result.getStructField(0));
5203 if (++Field == Record->field_end())
5206 if (Field->getType()->isPointerType() &&
5207 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5208 ArrayType->getElementType())) {
5210 if (!HandleLValueArrayAdjustment(Info, E, Array,
5211 ArrayType->getElementType(),
5212 ArrayType->getSize().getZExtValue()))
5214 Array.moveInto(Result.getStructField(1));
5215 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5217 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5221 if (++Field != Record->field_end())
5227 static bool EvaluateRecord(const Expr *E, const LValue &This,
5228 APValue &Result, EvalInfo &Info) {
5229 assert(E->isRValue() && E->getType()->isRecordType() &&
5230 "can't evaluate expression as a record rvalue");
5231 return RecordExprEvaluator(Info, This, Result).Visit(E);
5234 //===----------------------------------------------------------------------===//
5235 // Temporary Evaluation
5237 // Temporaries are represented in the AST as rvalues, but generally behave like
5238 // lvalues. The full-object of which the temporary is a subobject is implicitly
5239 // materialized so that a reference can bind to it.
5240 //===----------------------------------------------------------------------===//
5242 class TemporaryExprEvaluator
5243 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5245 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5246 LValueExprEvaluatorBaseTy(Info, Result) {}
5248 /// Visit an expression which constructs the value of this temporary.
5249 bool VisitConstructExpr(const Expr *E) {
5250 Result.set(E, Info.CurrentCall->Index);
5251 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5255 bool VisitCastExpr(const CastExpr *E) {
5256 switch (E->getCastKind()) {
5258 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5260 case CK_ConstructorConversion:
5261 return VisitConstructExpr(E->getSubExpr());
5264 bool VisitInitListExpr(const InitListExpr *E) {
5265 return VisitConstructExpr(E);
5267 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5268 return VisitConstructExpr(E);
5270 bool VisitCallExpr(const CallExpr *E) {
5271 return VisitConstructExpr(E);
5274 } // end anonymous namespace
5276 /// Evaluate an expression of record type as a temporary.
5277 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5278 assert(E->isRValue() && E->getType()->isRecordType());
5279 return TemporaryExprEvaluator(Info, Result).Visit(E);
5282 //===----------------------------------------------------------------------===//
5283 // Vector Evaluation
5284 //===----------------------------------------------------------------------===//
5287 class VectorExprEvaluator
5288 : public ExprEvaluatorBase<VectorExprEvaluator> {
5292 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5293 : ExprEvaluatorBaseTy(info), Result(Result) {}
5295 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5296 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5297 // FIXME: remove this APValue copy.
5298 Result = APValue(V.data(), V.size());
5301 bool Success(const APValue &V, const Expr *E) {
5302 assert(V.isVector());
5306 bool ZeroInitialization(const Expr *E);
5308 bool VisitUnaryReal(const UnaryOperator *E)
5309 { return Visit(E->getSubExpr()); }
5310 bool VisitCastExpr(const CastExpr* E);
5311 bool VisitInitListExpr(const InitListExpr *E);
5312 bool VisitUnaryImag(const UnaryOperator *E);
5313 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5314 // binary comparisons, binary and/or/xor,
5315 // shufflevector, ExtVectorElementExpr
5317 } // end anonymous namespace
5319 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5320 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5321 return VectorExprEvaluator(Info, Result).Visit(E);
5324 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5325 const VectorType *VTy = E->getType()->castAs<VectorType>();
5326 unsigned NElts = VTy->getNumElements();
5328 const Expr *SE = E->getSubExpr();
5329 QualType SETy = SE->getType();
5331 switch (E->getCastKind()) {
5332 case CK_VectorSplat: {
5333 APValue Val = APValue();
5334 if (SETy->isIntegerType()) {
5336 if (!EvaluateInteger(SE, IntResult, Info))
5338 Val = APValue(IntResult);
5339 } else if (SETy->isRealFloatingType()) {
5341 if (!EvaluateFloat(SE, F, Info))
5348 // Splat and create vector APValue.
5349 SmallVector<APValue, 4> Elts(NElts, Val);
5350 return Success(Elts, E);
5353 // Evaluate the operand into an APInt we can extract from.
5354 llvm::APInt SValInt;
5355 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5357 // Extract the elements
5358 QualType EltTy = VTy->getElementType();
5359 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5360 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5361 SmallVector<APValue, 4> Elts;
5362 if (EltTy->isRealFloatingType()) {
5363 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5364 unsigned FloatEltSize = EltSize;
5365 if (&Sem == &APFloat::x87DoubleExtended)
5367 for (unsigned i = 0; i < NElts; i++) {
5370 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5372 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5373 Elts.push_back(APValue(APFloat(Sem, Elt)));
5375 } else if (EltTy->isIntegerType()) {
5376 for (unsigned i = 0; i < NElts; i++) {
5379 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5381 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5382 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5387 return Success(Elts, E);
5390 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5395 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5396 const VectorType *VT = E->getType()->castAs<VectorType>();
5397 unsigned NumInits = E->getNumInits();
5398 unsigned NumElements = VT->getNumElements();
5400 QualType EltTy = VT->getElementType();
5401 SmallVector<APValue, 4> Elements;
5403 // The number of initializers can be less than the number of
5404 // vector elements. For OpenCL, this can be due to nested vector
5405 // initialization. For GCC compatibility, missing trailing elements
5406 // should be initialized with zeroes.
5407 unsigned CountInits = 0, CountElts = 0;
5408 while (CountElts < NumElements) {
5409 // Handle nested vector initialization.
5410 if (CountInits < NumInits
5411 && E->getInit(CountInits)->getType()->isVectorType()) {
5413 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5415 unsigned vlen = v.getVectorLength();
5416 for (unsigned j = 0; j < vlen; j++)
5417 Elements.push_back(v.getVectorElt(j));
5419 } else if (EltTy->isIntegerType()) {
5420 llvm::APSInt sInt(32);
5421 if (CountInits < NumInits) {
5422 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5424 } else // trailing integer zero.
5425 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5426 Elements.push_back(APValue(sInt));
5429 llvm::APFloat f(0.0);
5430 if (CountInits < NumInits) {
5431 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5433 } else // trailing float zero.
5434 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5435 Elements.push_back(APValue(f));
5440 return Success(Elements, E);
5444 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5445 const VectorType *VT = E->getType()->getAs<VectorType>();
5446 QualType EltTy = VT->getElementType();
5447 APValue ZeroElement;
5448 if (EltTy->isIntegerType())
5449 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5452 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5454 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5455 return Success(Elements, E);
5458 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5459 VisitIgnoredValue(E->getSubExpr());
5460 return ZeroInitialization(E);
5463 //===----------------------------------------------------------------------===//
5465 //===----------------------------------------------------------------------===//
5468 class ArrayExprEvaluator
5469 : public ExprEvaluatorBase<ArrayExprEvaluator> {
5474 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5475 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5477 bool Success(const APValue &V, const Expr *E) {
5478 assert((V.isArray() || V.isLValue()) &&
5479 "expected array or string literal");
5484 bool ZeroInitialization(const Expr *E) {
5485 const ConstantArrayType *CAT =
5486 Info.Ctx.getAsConstantArrayType(E->getType());
5490 Result = APValue(APValue::UninitArray(), 0,
5491 CAT->getSize().getZExtValue());
5492 if (!Result.hasArrayFiller()) return true;
5494 // Zero-initialize all elements.
5495 LValue Subobject = This;
5496 Subobject.addArray(Info, E, CAT);
5497 ImplicitValueInitExpr VIE(CAT->getElementType());
5498 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5501 bool VisitInitListExpr(const InitListExpr *E);
5502 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5503 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5504 const LValue &Subobject,
5505 APValue *Value, QualType Type);
5507 } // end anonymous namespace
5509 static bool EvaluateArray(const Expr *E, const LValue &This,
5510 APValue &Result, EvalInfo &Info) {
5511 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5512 return ArrayExprEvaluator(Info, This, Result).Visit(E);
5515 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5516 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5520 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5521 // an appropriately-typed string literal enclosed in braces.
5522 if (E->isStringLiteralInit()) {
5524 if (!EvaluateLValue(E->getInit(0), LV, Info))
5528 return Success(Val, E);
5531 bool Success = true;
5533 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5534 "zero-initialized array shouldn't have any initialized elts");
5536 if (Result.isArray() && Result.hasArrayFiller())
5537 Filler = Result.getArrayFiller();
5539 unsigned NumEltsToInit = E->getNumInits();
5540 unsigned NumElts = CAT->getSize().getZExtValue();
5541 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5543 // If the initializer might depend on the array index, run it for each
5544 // array element. For now, just whitelist non-class value-initialization.
5545 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5546 NumEltsToInit = NumElts;
5548 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5550 // If the array was previously zero-initialized, preserve the
5551 // zero-initialized values.
5552 if (!Filler.isUninit()) {
5553 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5554 Result.getArrayInitializedElt(I) = Filler;
5555 if (Result.hasArrayFiller())
5556 Result.getArrayFiller() = Filler;
5559 LValue Subobject = This;
5560 Subobject.addArray(Info, E, CAT);
5561 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5563 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5564 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5565 Info, Subobject, Init) ||
5566 !HandleLValueArrayAdjustment(Info, Init, Subobject,
5567 CAT->getElementType(), 1)) {
5568 if (!Info.keepEvaluatingAfterFailure())
5574 if (!Result.hasArrayFiller())
5577 // If we get here, we have a trivial filler, which we can just evaluate
5578 // once and splat over the rest of the array elements.
5579 assert(FillerExpr && "no array filler for incomplete init list");
5580 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5581 FillerExpr) && Success;
5584 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5585 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5588 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5589 const LValue &Subobject,
5592 bool HadZeroInit = !Value->isUninit();
5594 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5595 unsigned N = CAT->getSize().getZExtValue();
5597 // Preserve the array filler if we had prior zero-initialization.
5599 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5602 *Value = APValue(APValue::UninitArray(), N, N);
5605 for (unsigned I = 0; I != N; ++I)
5606 Value->getArrayInitializedElt(I) = Filler;
5608 // Initialize the elements.
5609 LValue ArrayElt = Subobject;
5610 ArrayElt.addArray(Info, E, CAT);
5611 for (unsigned I = 0; I != N; ++I)
5612 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5613 CAT->getElementType()) ||
5614 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5615 CAT->getElementType(), 1))
5621 if (!Type->isRecordType())
5624 const CXXConstructorDecl *FD = E->getConstructor();
5626 bool ZeroInit = E->requiresZeroInitialization();
5627 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5631 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5632 ImplicitValueInitExpr VIE(Type);
5633 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5636 const FunctionDecl *Definition = nullptr;
5637 FD->getBody(Definition);
5639 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5642 if (ZeroInit && !HadZeroInit) {
5643 ImplicitValueInitExpr VIE(Type);
5644 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5648 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5649 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5650 cast<CXXConstructorDecl>(Definition),
5654 //===----------------------------------------------------------------------===//
5655 // Integer Evaluation
5657 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5658 // types and back in constant folding. Integer values are thus represented
5659 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5660 //===----------------------------------------------------------------------===//
5663 class IntExprEvaluator
5664 : public ExprEvaluatorBase<IntExprEvaluator> {
5667 IntExprEvaluator(EvalInfo &info, APValue &result)
5668 : ExprEvaluatorBaseTy(info), Result(result) {}
5670 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5671 assert(E->getType()->isIntegralOrEnumerationType() &&
5672 "Invalid evaluation result.");
5673 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5674 "Invalid evaluation result.");
5675 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5676 "Invalid evaluation result.");
5677 Result = APValue(SI);
5680 bool Success(const llvm::APSInt &SI, const Expr *E) {
5681 return Success(SI, E, Result);
5684 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5685 assert(E->getType()->isIntegralOrEnumerationType() &&
5686 "Invalid evaluation result.");
5687 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5688 "Invalid evaluation result.");
5689 Result = APValue(APSInt(I));
5690 Result.getInt().setIsUnsigned(
5691 E->getType()->isUnsignedIntegerOrEnumerationType());
5694 bool Success(const llvm::APInt &I, const Expr *E) {
5695 return Success(I, E, Result);
5698 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5699 assert(E->getType()->isIntegralOrEnumerationType() &&
5700 "Invalid evaluation result.");
5701 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5704 bool Success(uint64_t Value, const Expr *E) {
5705 return Success(Value, E, Result);
5708 bool Success(CharUnits Size, const Expr *E) {
5709 return Success(Size.getQuantity(), E);
5712 bool Success(const APValue &V, const Expr *E) {
5713 if (V.isLValue() || V.isAddrLabelDiff()) {
5717 return Success(V.getInt(), E);
5720 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5722 //===--------------------------------------------------------------------===//
5724 //===--------------------------------------------------------------------===//
5726 bool VisitIntegerLiteral(const IntegerLiteral *E) {
5727 return Success(E->getValue(), E);
5729 bool VisitCharacterLiteral(const CharacterLiteral *E) {
5730 return Success(E->getValue(), E);
5733 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5734 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5735 if (CheckReferencedDecl(E, E->getDecl()))
5738 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5740 bool VisitMemberExpr(const MemberExpr *E) {
5741 if (CheckReferencedDecl(E, E->getMemberDecl())) {
5742 VisitIgnoredValue(E->getBase());
5746 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5749 bool VisitCallExpr(const CallExpr *E);
5750 bool VisitBinaryOperator(const BinaryOperator *E);
5751 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5752 bool VisitUnaryOperator(const UnaryOperator *E);
5754 bool VisitCastExpr(const CastExpr* E);
5755 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5757 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5758 return Success(E->getValue(), E);
5761 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5762 return Success(E->getValue(), E);
5765 // Note, GNU defines __null as an integer, not a pointer.
5766 bool VisitGNUNullExpr(const GNUNullExpr *E) {
5767 return ZeroInitialization(E);
5770 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5771 return Success(E->getValue(), E);
5774 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5775 return Success(E->getValue(), E);
5778 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5779 return Success(E->getValue(), E);
5782 bool VisitUnaryReal(const UnaryOperator *E);
5783 bool VisitUnaryImag(const UnaryOperator *E);
5785 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5786 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
5789 CharUnits GetAlignOfExpr(const Expr *E);
5790 CharUnits GetAlignOfType(QualType T);
5791 static QualType GetObjectType(APValue::LValueBase B);
5792 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
5793 // FIXME: Missing: array subscript of vector, member of vector
5795 } // end anonymous namespace
5797 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5798 /// produce either the integer value or a pointer.
5800 /// GCC has a heinous extension which folds casts between pointer types and
5801 /// pointer-sized integral types. We support this by allowing the evaluation of
5802 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5803 /// Some simple arithmetic on such values is supported (they are treated much
5805 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
5807 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
5808 return IntExprEvaluator(Info, Result).Visit(E);
5811 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
5813 if (!EvaluateIntegerOrLValue(E, Val, Info))
5816 // FIXME: It would be better to produce the diagnostic for casting
5817 // a pointer to an integer.
5818 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
5821 Result = Val.getInt();
5825 /// Check whether the given declaration can be directly converted to an integral
5826 /// rvalue. If not, no diagnostic is produced; there are other things we can
5828 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
5829 // Enums are integer constant exprs.
5830 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
5831 // Check for signedness/width mismatches between E type and ECD value.
5832 bool SameSign = (ECD->getInitVal().isSigned()
5833 == E->getType()->isSignedIntegerOrEnumerationType());
5834 bool SameWidth = (ECD->getInitVal().getBitWidth()
5835 == Info.Ctx.getIntWidth(E->getType()));
5836 if (SameSign && SameWidth)
5837 return Success(ECD->getInitVal(), E);
5839 // Get rid of mismatch (otherwise Success assertions will fail)
5840 // by computing a new value matching the type of E.
5841 llvm::APSInt Val = ECD->getInitVal();
5843 Val.setIsSigned(!ECD->getInitVal().isSigned());
5845 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5846 return Success(Val, E);
5852 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5854 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5855 // The following enum mimics the values returned by GCC.
5856 // FIXME: Does GCC differ between lvalue and rvalue references here?
5857 enum gcc_type_class {
5859 void_type_class, integer_type_class, char_type_class,
5860 enumeral_type_class, boolean_type_class,
5861 pointer_type_class, reference_type_class, offset_type_class,
5862 real_type_class, complex_type_class,
5863 function_type_class, method_type_class,
5864 record_type_class, union_type_class,
5865 array_type_class, string_type_class,
5869 // If no argument was supplied, default to "no_type_class". This isn't
5870 // ideal, however it is what gcc does.
5871 if (E->getNumArgs() == 0)
5872 return no_type_class;
5874 QualType ArgTy = E->getArg(0)->getType();
5875 if (ArgTy->isVoidType())
5876 return void_type_class;
5877 else if (ArgTy->isEnumeralType())
5878 return enumeral_type_class;
5879 else if (ArgTy->isBooleanType())
5880 return boolean_type_class;
5881 else if (ArgTy->isCharType())
5882 return string_type_class; // gcc doesn't appear to use char_type_class
5883 else if (ArgTy->isIntegerType())
5884 return integer_type_class;
5885 else if (ArgTy->isPointerType())
5886 return pointer_type_class;
5887 else if (ArgTy->isReferenceType())
5888 return reference_type_class;
5889 else if (ArgTy->isRealType())
5890 return real_type_class;
5891 else if (ArgTy->isComplexType())
5892 return complex_type_class;
5893 else if (ArgTy->isFunctionType())
5894 return function_type_class;
5895 else if (ArgTy->isStructureOrClassType())
5896 return record_type_class;
5897 else if (ArgTy->isUnionType())
5898 return union_type_class;
5899 else if (ArgTy->isArrayType())
5900 return array_type_class;
5901 else if (ArgTy->isUnionType())
5902 return union_type_class;
5903 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
5904 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
5907 /// EvaluateBuiltinConstantPForLValue - Determine the result of
5908 /// __builtin_constant_p when applied to the given lvalue.
5910 /// An lvalue is only "constant" if it is a pointer or reference to the first
5911 /// character of a string literal.
5912 template<typename LValue>
5913 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
5914 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
5915 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5918 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5919 /// GCC as we can manage.
5920 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5921 QualType ArgType = Arg->getType();
5923 // __builtin_constant_p always has one operand. The rules which gcc follows
5924 // are not precisely documented, but are as follows:
5926 // - If the operand is of integral, floating, complex or enumeration type,
5927 // and can be folded to a known value of that type, it returns 1.
5928 // - If the operand and can be folded to a pointer to the first character
5929 // of a string literal (or such a pointer cast to an integral type), it
5932 // Otherwise, it returns 0.
5934 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5935 // its support for this does not currently work.
5936 if (ArgType->isIntegralOrEnumerationType()) {
5937 Expr::EvalResult Result;
5938 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5941 APValue &V = Result.Val;
5942 if (V.getKind() == APValue::Int)
5945 return EvaluateBuiltinConstantPForLValue(V);
5946 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5947 return Arg->isEvaluatable(Ctx);
5948 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5950 Expr::EvalStatus Status;
5951 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
5952 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5953 : EvaluatePointer(Arg, LV, Info)) &&
5954 !Status.HasSideEffects)
5955 return EvaluateBuiltinConstantPForLValue(LV);
5958 // Anything else isn't considered to be sufficiently constant.
5962 /// Retrieves the "underlying object type" of the given expression,
5963 /// as used by __builtin_object_size.
5964 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5965 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5966 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5967 return VD->getType();
5968 } else if (const Expr *E = B.get<const Expr*>()) {
5969 if (isa<CompoundLiteralExpr>(E))
5970 return E->getType();
5976 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
5980 // The operand of __builtin_object_size is never evaluated for side-effects.
5981 // If there are any, but we can determine the pointed-to object anyway, then
5982 // ignore the side-effects.
5983 SpeculativeEvaluationRAII SpeculativeEval(Info);
5984 if (!EvaluatePointer(E->getArg(0), Base, Info))
5988 // If we can prove the base is null, lower to zero now.
5989 if (!Base.getLValueBase()) return Success(0, E);
5991 QualType T = GetObjectType(Base.getLValueBase());
5993 T->isIncompleteType() ||
5994 T->isFunctionType() ||
5995 T->isVariablyModifiedType() ||
5996 T->isDependentType())
5999 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6000 CharUnits Offset = Base.getLValueOffset();
6002 if (!Offset.isNegative() && Offset <= Size)
6005 Size = CharUnits::Zero();
6006 return Success(Size, E);
6009 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6010 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6012 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6014 case Builtin::BI__builtin_object_size: {
6015 if (TryEvaluateBuiltinObjectSize(E))
6018 // If evaluating the argument has side-effects, we can't determine the size
6019 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6020 // handle all cases where the expression has side-effects.
6021 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
6022 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
6023 return Success(-1ULL, E);
6024 return Success(0, E);
6027 // Expression had no side effects, but we couldn't statically determine the
6028 // size of the referenced object.
6029 switch (Info.EvalMode) {
6030 case EvalInfo::EM_ConstantExpression:
6031 case EvalInfo::EM_PotentialConstantExpression:
6032 case EvalInfo::EM_ConstantFold:
6033 case EvalInfo::EM_EvaluateForOverflow:
6034 case EvalInfo::EM_IgnoreSideEffects:
6036 case EvalInfo::EM_ConstantExpressionUnevaluated:
6037 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6038 return Success(-1ULL, E);
6042 case Builtin::BI__builtin_bswap16:
6043 case Builtin::BI__builtin_bswap32:
6044 case Builtin::BI__builtin_bswap64: {
6046 if (!EvaluateInteger(E->getArg(0), Val, Info))
6049 return Success(Val.byteSwap(), E);
6052 case Builtin::BI__builtin_classify_type:
6053 return Success(EvaluateBuiltinClassifyType(E), E);
6055 // FIXME: BI__builtin_clrsb
6056 // FIXME: BI__builtin_clrsbl
6057 // FIXME: BI__builtin_clrsbll
6059 case Builtin::BI__builtin_clz:
6060 case Builtin::BI__builtin_clzl:
6061 case Builtin::BI__builtin_clzll:
6062 case Builtin::BI__builtin_clzs: {
6064 if (!EvaluateInteger(E->getArg(0), Val, Info))
6069 return Success(Val.countLeadingZeros(), E);
6072 case Builtin::BI__builtin_constant_p:
6073 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6075 case Builtin::BI__builtin_ctz:
6076 case Builtin::BI__builtin_ctzl:
6077 case Builtin::BI__builtin_ctzll:
6078 case Builtin::BI__builtin_ctzs: {
6080 if (!EvaluateInteger(E->getArg(0), Val, Info))
6085 return Success(Val.countTrailingZeros(), E);
6088 case Builtin::BI__builtin_eh_return_data_regno: {
6089 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6090 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6091 return Success(Operand, E);
6094 case Builtin::BI__builtin_expect:
6095 return Visit(E->getArg(0));
6097 case Builtin::BI__builtin_ffs:
6098 case Builtin::BI__builtin_ffsl:
6099 case Builtin::BI__builtin_ffsll: {
6101 if (!EvaluateInteger(E->getArg(0), Val, Info))
6104 unsigned N = Val.countTrailingZeros();
6105 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6108 case Builtin::BI__builtin_fpclassify: {
6110 if (!EvaluateFloat(E->getArg(5), Val, Info))
6113 switch (Val.getCategory()) {
6114 case APFloat::fcNaN: Arg = 0; break;
6115 case APFloat::fcInfinity: Arg = 1; break;
6116 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6117 case APFloat::fcZero: Arg = 4; break;
6119 return Visit(E->getArg(Arg));
6122 case Builtin::BI__builtin_isinf_sign: {
6124 return EvaluateFloat(E->getArg(0), Val, Info) &&
6125 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6128 case Builtin::BI__builtin_isinf: {
6130 return EvaluateFloat(E->getArg(0), Val, Info) &&
6131 Success(Val.isInfinity() ? 1 : 0, E);
6134 case Builtin::BI__builtin_isfinite: {
6136 return EvaluateFloat(E->getArg(0), Val, Info) &&
6137 Success(Val.isFinite() ? 1 : 0, E);
6140 case Builtin::BI__builtin_isnan: {
6142 return EvaluateFloat(E->getArg(0), Val, Info) &&
6143 Success(Val.isNaN() ? 1 : 0, E);
6146 case Builtin::BI__builtin_isnormal: {
6148 return EvaluateFloat(E->getArg(0), Val, Info) &&
6149 Success(Val.isNormal() ? 1 : 0, E);
6152 case Builtin::BI__builtin_parity:
6153 case Builtin::BI__builtin_parityl:
6154 case Builtin::BI__builtin_parityll: {
6156 if (!EvaluateInteger(E->getArg(0), Val, Info))
6159 return Success(Val.countPopulation() % 2, E);
6162 case Builtin::BI__builtin_popcount:
6163 case Builtin::BI__builtin_popcountl:
6164 case Builtin::BI__builtin_popcountll: {
6166 if (!EvaluateInteger(E->getArg(0), Val, Info))
6169 return Success(Val.countPopulation(), E);
6172 case Builtin::BIstrlen:
6173 // A call to strlen is not a constant expression.
6174 if (Info.getLangOpts().CPlusPlus11)
6175 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6176 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6178 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6180 case Builtin::BI__builtin_strlen: {
6181 // As an extension, we support __builtin_strlen() as a constant expression,
6182 // and support folding strlen() to a constant.
6184 if (!EvaluatePointer(E->getArg(0), String, Info))
6187 // Fast path: if it's a string literal, search the string value.
6188 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6189 String.getLValueBase().dyn_cast<const Expr *>())) {
6190 // The string literal may have embedded null characters. Find the first
6191 // one and truncate there.
6192 StringRef Str = S->getBytes();
6193 int64_t Off = String.Offset.getQuantity();
6194 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6195 S->getCharByteWidth() == 1) {
6196 Str = Str.substr(Off);
6198 StringRef::size_type Pos = Str.find(0);
6199 if (Pos != StringRef::npos)
6200 Str = Str.substr(0, Pos);
6202 return Success(Str.size(), E);
6205 // Fall through to slow path to issue appropriate diagnostic.
6208 // Slow path: scan the bytes of the string looking for the terminating 0.
6209 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6210 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6212 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6216 return Success(Strlen, E);
6217 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6222 case Builtin::BI__atomic_always_lock_free:
6223 case Builtin::BI__atomic_is_lock_free:
6224 case Builtin::BI__c11_atomic_is_lock_free: {
6226 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6229 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6230 // of two less than the maximum inline atomic width, we know it is
6231 // lock-free. If the size isn't a power of two, or greater than the
6232 // maximum alignment where we promote atomics, we know it is not lock-free
6233 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6234 // the answer can only be determined at runtime; for example, 16-byte
6235 // atomics have lock-free implementations on some, but not all,
6236 // x86-64 processors.
6238 // Check power-of-two.
6239 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6240 if (Size.isPowerOfTwo()) {
6241 // Check against inlining width.
6242 unsigned InlineWidthBits =
6243 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6244 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6245 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6246 Size == CharUnits::One() ||
6247 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6248 Expr::NPC_NeverValueDependent))
6249 // OK, we will inline appropriately-aligned operations of this size,
6250 // and _Atomic(T) is appropriately-aligned.
6251 return Success(1, E);
6253 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6254 castAs<PointerType>()->getPointeeType();
6255 if (!PointeeType->isIncompleteType() &&
6256 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6257 // OK, we will inline operations on this object.
6258 return Success(1, E);
6263 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6264 Success(0, E) : Error(E);
6269 static bool HasSameBase(const LValue &A, const LValue &B) {
6270 if (!A.getLValueBase())
6271 return !B.getLValueBase();
6272 if (!B.getLValueBase())
6275 if (A.getLValueBase().getOpaqueValue() !=
6276 B.getLValueBase().getOpaqueValue()) {
6277 const Decl *ADecl = GetLValueBaseDecl(A);
6280 const Decl *BDecl = GetLValueBaseDecl(B);
6281 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6285 return IsGlobalLValue(A.getLValueBase()) ||
6286 A.getLValueCallIndex() == B.getLValueCallIndex();
6291 /// \brief Data recursive integer evaluator of certain binary operators.
6293 /// We use a data recursive algorithm for binary operators so that we are able
6294 /// to handle extreme cases of chained binary operators without causing stack
6296 class DataRecursiveIntBinOpEvaluator {
6301 EvalResult() : Failed(false) { }
6303 void swap(EvalResult &RHS) {
6305 Failed = RHS.Failed;
6312 EvalResult LHSResult; // meaningful only for binary operator expression.
6313 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6315 Job() : StoredInfo(nullptr) {}
6316 void startSpeculativeEval(EvalInfo &Info) {
6317 OldEvalStatus = Info.EvalStatus;
6318 Info.EvalStatus.Diag = nullptr;
6323 StoredInfo->EvalStatus = OldEvalStatus;
6327 EvalInfo *StoredInfo; // non-null if status changed.
6328 Expr::EvalStatus OldEvalStatus;
6331 SmallVector<Job, 16> Queue;
6333 IntExprEvaluator &IntEval;
6335 APValue &FinalResult;
6338 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6339 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6341 /// \brief True if \param E is a binary operator that we are going to handle
6342 /// data recursively.
6343 /// We handle binary operators that are comma, logical, or that have operands
6344 /// with integral or enumeration type.
6345 static bool shouldEnqueue(const BinaryOperator *E) {
6346 return E->getOpcode() == BO_Comma ||
6348 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6349 E->getRHS()->getType()->isIntegralOrEnumerationType());
6352 bool Traverse(const BinaryOperator *E) {
6354 EvalResult PrevResult;
6355 while (!Queue.empty())
6356 process(PrevResult);
6358 if (PrevResult.Failed) return false;
6360 FinalResult.swap(PrevResult.Val);
6365 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6366 return IntEval.Success(Value, E, Result);
6368 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6369 return IntEval.Success(Value, E, Result);
6371 bool Error(const Expr *E) {
6372 return IntEval.Error(E);
6374 bool Error(const Expr *E, diag::kind D) {
6375 return IntEval.Error(E, D);
6378 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6379 return Info.CCEDiag(E, D);
6382 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6383 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6384 bool &SuppressRHSDiags);
6386 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6387 const BinaryOperator *E, APValue &Result);
6389 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6390 Result.Failed = !Evaluate(Result.Val, Info, E);
6392 Result.Val = APValue();
6395 void process(EvalResult &Result);
6397 void enqueue(const Expr *E) {
6398 E = E->IgnoreParens();
6399 Queue.resize(Queue.size()+1);
6401 Queue.back().Kind = Job::AnyExprKind;
6407 bool DataRecursiveIntBinOpEvaluator::
6408 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6409 bool &SuppressRHSDiags) {
6410 if (E->getOpcode() == BO_Comma) {
6411 // Ignore LHS but note if we could not evaluate it.
6412 if (LHSResult.Failed)
6413 return Info.noteSideEffect();
6417 if (E->isLogicalOp()) {
6419 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6420 // We were able to evaluate the LHS, see if we can get away with not
6421 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6422 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6423 Success(LHSAsBool, E, LHSResult.Val);
6424 return false; // Ignore RHS
6427 LHSResult.Failed = true;
6429 // Since we weren't able to evaluate the left hand side, it
6430 // must have had side effects.
6431 if (!Info.noteSideEffect())
6434 // We can't evaluate the LHS; however, sometimes the result
6435 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6436 // Don't ignore RHS and suppress diagnostics from this arm.
6437 SuppressRHSDiags = true;
6443 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6444 E->getRHS()->getType()->isIntegralOrEnumerationType());
6446 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6447 return false; // Ignore RHS;
6452 bool DataRecursiveIntBinOpEvaluator::
6453 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6454 const BinaryOperator *E, APValue &Result) {
6455 if (E->getOpcode() == BO_Comma) {
6456 if (RHSResult.Failed)
6458 Result = RHSResult.Val;
6462 if (E->isLogicalOp()) {
6463 bool lhsResult, rhsResult;
6464 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6465 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6469 if (E->getOpcode() == BO_LOr)
6470 return Success(lhsResult || rhsResult, E, Result);
6472 return Success(lhsResult && rhsResult, E, Result);
6476 // We can't evaluate the LHS; however, sometimes the result
6477 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6478 if (rhsResult == (E->getOpcode() == BO_LOr))
6479 return Success(rhsResult, E, Result);
6486 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6487 E->getRHS()->getType()->isIntegralOrEnumerationType());
6489 if (LHSResult.Failed || RHSResult.Failed)
6492 const APValue &LHSVal = LHSResult.Val;
6493 const APValue &RHSVal = RHSResult.Val;
6495 // Handle cases like (unsigned long)&a + 4.
6496 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6498 CharUnits AdditionalOffset =
6499 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6500 if (E->getOpcode() == BO_Add)
6501 Result.getLValueOffset() += AdditionalOffset;
6503 Result.getLValueOffset() -= AdditionalOffset;
6507 // Handle cases like 4 + (unsigned long)&a
6508 if (E->getOpcode() == BO_Add &&
6509 RHSVal.isLValue() && LHSVal.isInt()) {
6511 Result.getLValueOffset() +=
6512 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6516 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6517 // Handle (intptr_t)&&A - (intptr_t)&&B.
6518 if (!LHSVal.getLValueOffset().isZero() ||
6519 !RHSVal.getLValueOffset().isZero())
6521 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6522 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6523 if (!LHSExpr || !RHSExpr)
6525 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6526 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6527 if (!LHSAddrExpr || !RHSAddrExpr)
6529 // Make sure both labels come from the same function.
6530 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6531 RHSAddrExpr->getLabel()->getDeclContext())
6533 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6537 // All the remaining cases expect both operands to be an integer
6538 if (!LHSVal.isInt() || !RHSVal.isInt())
6541 // Set up the width and signedness manually, in case it can't be deduced
6542 // from the operation we're performing.
6543 // FIXME: Don't do this in the cases where we can deduce it.
6544 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6545 E->getType()->isUnsignedIntegerOrEnumerationType());
6546 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6547 RHSVal.getInt(), Value))
6549 return Success(Value, E, Result);
6552 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6553 Job &job = Queue.back();
6556 case Job::AnyExprKind: {
6557 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6558 if (shouldEnqueue(Bop)) {
6559 job.Kind = Job::BinOpKind;
6560 enqueue(Bop->getLHS());
6565 EvaluateExpr(job.E, Result);
6570 case Job::BinOpKind: {
6571 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6572 bool SuppressRHSDiags = false;
6573 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6577 if (SuppressRHSDiags)
6578 job.startSpeculativeEval(Info);
6579 job.LHSResult.swap(Result);
6580 job.Kind = Job::BinOpVisitedLHSKind;
6581 enqueue(Bop->getRHS());
6585 case Job::BinOpVisitedLHSKind: {
6586 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6589 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6595 llvm_unreachable("Invalid Job::Kind!");
6598 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6599 if (E->isAssignmentOp())
6602 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6603 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6605 QualType LHSTy = E->getLHS()->getType();
6606 QualType RHSTy = E->getRHS()->getType();
6608 if (LHSTy->isAnyComplexType()) {
6609 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
6610 ComplexValue LHS, RHS;
6612 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6613 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6616 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6619 if (LHS.isComplexFloat()) {
6620 APFloat::cmpResult CR_r =
6621 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6622 APFloat::cmpResult CR_i =
6623 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6625 if (E->getOpcode() == BO_EQ)
6626 return Success((CR_r == APFloat::cmpEqual &&
6627 CR_i == APFloat::cmpEqual), E);
6629 assert(E->getOpcode() == BO_NE &&
6630 "Invalid complex comparison.");
6631 return Success(((CR_r == APFloat::cmpGreaterThan ||
6632 CR_r == APFloat::cmpLessThan ||
6633 CR_r == APFloat::cmpUnordered) ||
6634 (CR_i == APFloat::cmpGreaterThan ||
6635 CR_i == APFloat::cmpLessThan ||
6636 CR_i == APFloat::cmpUnordered)), E);
6639 if (E->getOpcode() == BO_EQ)
6640 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6641 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6643 assert(E->getOpcode() == BO_NE &&
6644 "Invalid compex comparison.");
6645 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6646 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6651 if (LHSTy->isRealFloatingType() &&
6652 RHSTy->isRealFloatingType()) {
6653 APFloat RHS(0.0), LHS(0.0);
6655 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6656 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6659 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6662 APFloat::cmpResult CR = LHS.compare(RHS);
6664 switch (E->getOpcode()) {
6666 llvm_unreachable("Invalid binary operator!");
6668 return Success(CR == APFloat::cmpLessThan, E);
6670 return Success(CR == APFloat::cmpGreaterThan, E);
6672 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6674 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6677 return Success(CR == APFloat::cmpEqual, E);
6679 return Success(CR == APFloat::cmpGreaterThan
6680 || CR == APFloat::cmpLessThan
6681 || CR == APFloat::cmpUnordered, E);
6685 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6686 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6687 LValue LHSValue, RHSValue;
6689 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6690 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6693 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6696 // Reject differing bases from the normal codepath; we special-case
6697 // comparisons to null.
6698 if (!HasSameBase(LHSValue, RHSValue)) {
6699 if (E->getOpcode() == BO_Sub) {
6700 // Handle &&A - &&B.
6701 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6703 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6704 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6705 if (!LHSExpr || !RHSExpr)
6707 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6708 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6709 if (!LHSAddrExpr || !RHSAddrExpr)
6711 // Make sure both labels come from the same function.
6712 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6713 RHSAddrExpr->getLabel()->getDeclContext())
6715 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6718 // Inequalities and subtractions between unrelated pointers have
6719 // unspecified or undefined behavior.
6720 if (!E->isEqualityOp())
6722 // A constant address may compare equal to the address of a symbol.
6723 // The one exception is that address of an object cannot compare equal
6724 // to a null pointer constant.
6725 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6726 (!RHSValue.Base && !RHSValue.Offset.isZero()))
6728 // It's implementation-defined whether distinct literals will have
6729 // distinct addresses. In clang, the result of such a comparison is
6730 // unspecified, so it is not a constant expression. However, we do know
6731 // that the address of a literal will be non-null.
6732 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6733 LHSValue.Base && RHSValue.Base)
6735 // We can't tell whether weak symbols will end up pointing to the same
6737 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6739 // Pointers with different bases cannot represent the same object.
6740 // (Note that clang defaults to -fmerge-all-constants, which can
6741 // lead to inconsistent results for comparisons involving the address
6742 // of a constant; this generally doesn't matter in practice.)
6743 return Success(E->getOpcode() == BO_NE, E);
6746 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6747 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6749 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6750 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6752 if (E->getOpcode() == BO_Sub) {
6753 // C++11 [expr.add]p6:
6754 // Unless both pointers point to elements of the same array object, or
6755 // one past the last element of the array object, the behavior is
6757 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6758 !AreElementsOfSameArray(getType(LHSValue.Base),
6759 LHSDesignator, RHSDesignator))
6760 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6762 QualType Type = E->getLHS()->getType();
6763 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
6765 CharUnits ElementSize;
6766 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
6769 // As an extension, a type may have zero size (empty struct or union in
6770 // C, array of zero length). Pointer subtraction in such cases has
6771 // undefined behavior, so is not constant.
6772 if (ElementSize.isZero()) {
6773 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6778 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6779 // and produce incorrect results when it overflows. Such behavior
6780 // appears to be non-conforming, but is common, so perhaps we should
6781 // assume the standard intended for such cases to be undefined behavior
6782 // and check for them.
6784 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6785 // overflow in the final conversion to ptrdiff_t.
6787 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6789 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6791 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6792 APSInt TrueResult = (LHS - RHS) / ElemSize;
6793 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6795 if (Result.extend(65) != TrueResult)
6796 HandleOverflow(Info, E, TrueResult, E->getType());
6797 return Success(Result, E);
6800 // C++11 [expr.rel]p3:
6801 // Pointers to void (after pointer conversions) can be compared, with a
6802 // result defined as follows: If both pointers represent the same
6803 // address or are both the null pointer value, the result is true if the
6804 // operator is <= or >= and false otherwise; otherwise the result is
6806 // We interpret this as applying to pointers to *cv* void.
6807 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
6808 E->isRelationalOp())
6809 CCEDiag(E, diag::note_constexpr_void_comparison);
6811 // C++11 [expr.rel]p2:
6812 // - If two pointers point to non-static data members of the same object,
6813 // or to subobjects or array elements fo such members, recursively, the
6814 // pointer to the later declared member compares greater provided the
6815 // two members have the same access control and provided their class is
6818 // - Otherwise pointer comparisons are unspecified.
6819 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6820 E->isRelationalOp()) {
6823 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6824 RHSDesignator, WasArrayIndex);
6825 // At the point where the designators diverge, the comparison has a
6826 // specified value if:
6827 // - we are comparing array indices
6828 // - we are comparing fields of a union, or fields with the same access
6829 // Otherwise, the result is unspecified and thus the comparison is not a
6830 // constant expression.
6831 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6832 Mismatch < RHSDesignator.Entries.size()) {
6833 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6834 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6836 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6838 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6839 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6840 << RF->getParent() << RF;
6842 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6843 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6844 << LF->getParent() << LF;
6845 else if (!LF->getParent()->isUnion() &&
6846 LF->getAccess() != RF->getAccess())
6847 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6848 << LF << LF->getAccess() << RF << RF->getAccess()
6853 // The comparison here must be unsigned, and performed with the same
6854 // width as the pointer.
6855 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6856 uint64_t CompareLHS = LHSOffset.getQuantity();
6857 uint64_t CompareRHS = RHSOffset.getQuantity();
6858 assert(PtrSize <= 64 && "Unexpected pointer width");
6859 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6863 // If there is a base and this is a relational operator, we can only
6864 // compare pointers within the object in question; otherwise, the result
6865 // depends on where the object is located in memory.
6866 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6867 QualType BaseTy = getType(LHSValue.Base);
6868 if (BaseTy->isIncompleteType())
6870 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6871 uint64_t OffsetLimit = Size.getQuantity();
6872 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6876 switch (E->getOpcode()) {
6877 default: llvm_unreachable("missing comparison operator");
6878 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6879 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6880 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6881 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6882 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6883 case BO_NE: return Success(CompareLHS != CompareRHS, E);
6888 if (LHSTy->isMemberPointerType()) {
6889 assert(E->isEqualityOp() && "unexpected member pointer operation");
6890 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6892 MemberPtr LHSValue, RHSValue;
6894 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6895 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6898 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6901 // C++11 [expr.eq]p2:
6902 // If both operands are null, they compare equal. Otherwise if only one is
6903 // null, they compare unequal.
6904 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6905 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6906 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6909 // Otherwise if either is a pointer to a virtual member function, the
6910 // result is unspecified.
6911 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6912 if (MD->isVirtual())
6913 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6914 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6915 if (MD->isVirtual())
6916 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6918 // Otherwise they compare equal if and only if they would refer to the
6919 // same member of the same most derived object or the same subobject if
6920 // they were dereferenced with a hypothetical object of the associated
6922 bool Equal = LHSValue == RHSValue;
6923 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6926 if (LHSTy->isNullPtrType()) {
6927 assert(E->isComparisonOp() && "unexpected nullptr operation");
6928 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6929 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6930 // are compared, the result is true of the operator is <=, >= or ==, and
6932 BinaryOperator::Opcode Opcode = E->getOpcode();
6933 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6936 assert((!LHSTy->isIntegralOrEnumerationType() ||
6937 !RHSTy->isIntegralOrEnumerationType()) &&
6938 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6939 // We can't continue from here for non-integral types.
6940 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6943 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
6944 // C++ [expr.alignof]p3:
6945 // When alignof is applied to a reference type, the result is the
6946 // alignment of the referenced type.
6947 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6948 T = Ref->getPointeeType();
6950 // __alignof is defined to return the preferred alignment.
6951 return Info.Ctx.toCharUnitsFromBits(
6952 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6955 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
6956 E = E->IgnoreParens();
6958 // The kinds of expressions that we have special-case logic here for
6959 // should be kept up to date with the special checks for those
6960 // expressions in Sema.
6962 // alignof decl is always accepted, even if it doesn't make sense: we default
6963 // to 1 in those cases.
6964 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6965 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6966 /*RefAsPointee*/true);
6968 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6969 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6970 /*RefAsPointee*/true);
6972 return GetAlignOfType(E->getType());
6976 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6977 /// a result as the expression's type.
6978 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6979 const UnaryExprOrTypeTraitExpr *E) {
6980 switch(E->getKind()) {
6981 case UETT_AlignOf: {
6982 if (E->isArgumentType())
6983 return Success(GetAlignOfType(E->getArgumentType()), E);
6985 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
6988 case UETT_VecStep: {
6989 QualType Ty = E->getTypeOfArgument();
6991 if (Ty->isVectorType()) {
6992 unsigned n = Ty->castAs<VectorType>()->getNumElements();
6994 // The vec_step built-in functions that take a 3-component
6995 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6999 return Success(n, E);
7001 return Success(1, E);
7005 QualType SrcTy = E->getTypeOfArgument();
7006 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7007 // the result is the size of the referenced type."
7008 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7009 SrcTy = Ref->getPointeeType();
7012 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7014 return Success(Sizeof, E);
7018 llvm_unreachable("unknown expr/type trait");
7021 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7023 unsigned n = OOE->getNumComponents();
7026 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7027 for (unsigned i = 0; i != n; ++i) {
7028 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7029 switch (ON.getKind()) {
7030 case OffsetOfExpr::OffsetOfNode::Array: {
7031 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7033 if (!EvaluateInteger(Idx, IdxResult, Info))
7035 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7038 CurrentType = AT->getElementType();
7039 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7040 Result += IdxResult.getSExtValue() * ElementSize;
7044 case OffsetOfExpr::OffsetOfNode::Field: {
7045 FieldDecl *MemberDecl = ON.getField();
7046 const RecordType *RT = CurrentType->getAs<RecordType>();
7049 RecordDecl *RD = RT->getDecl();
7050 if (RD->isInvalidDecl()) return false;
7051 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7052 unsigned i = MemberDecl->getFieldIndex();
7053 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7054 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7055 CurrentType = MemberDecl->getType().getNonReferenceType();
7059 case OffsetOfExpr::OffsetOfNode::Identifier:
7060 llvm_unreachable("dependent __builtin_offsetof");
7062 case OffsetOfExpr::OffsetOfNode::Base: {
7063 CXXBaseSpecifier *BaseSpec = ON.getBase();
7064 if (BaseSpec->isVirtual())
7067 // Find the layout of the class whose base we are looking into.
7068 const RecordType *RT = CurrentType->getAs<RecordType>();
7071 RecordDecl *RD = RT->getDecl();
7072 if (RD->isInvalidDecl()) return false;
7073 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7075 // Find the base class itself.
7076 CurrentType = BaseSpec->getType();
7077 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7081 // Add the offset to the base.
7082 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7087 return Success(Result, OOE);
7090 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7091 switch (E->getOpcode()) {
7093 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7097 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7098 // If so, we could clear the diagnostic ID.
7099 return Visit(E->getSubExpr());
7101 // The result is just the value.
7102 return Visit(E->getSubExpr());
7104 if (!Visit(E->getSubExpr()))
7106 if (!Result.isInt()) return Error(E);
7107 const APSInt &Value = Result.getInt();
7108 if (Value.isSigned() && Value.isMinSignedValue())
7109 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7111 return Success(-Value, E);
7114 if (!Visit(E->getSubExpr()))
7116 if (!Result.isInt()) return Error(E);
7117 return Success(~Result.getInt(), E);
7121 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7123 return Success(!bres, E);
7128 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7129 /// result type is integer.
7130 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7131 const Expr *SubExpr = E->getSubExpr();
7132 QualType DestType = E->getType();
7133 QualType SrcType = SubExpr->getType();
7135 switch (E->getCastKind()) {
7136 case CK_BaseToDerived:
7137 case CK_DerivedToBase:
7138 case CK_UncheckedDerivedToBase:
7141 case CK_ArrayToPointerDecay:
7142 case CK_FunctionToPointerDecay:
7143 case CK_NullToPointer:
7144 case CK_NullToMemberPointer:
7145 case CK_BaseToDerivedMemberPointer:
7146 case CK_DerivedToBaseMemberPointer:
7147 case CK_ReinterpretMemberPointer:
7148 case CK_ConstructorConversion:
7149 case CK_IntegralToPointer:
7151 case CK_VectorSplat:
7152 case CK_IntegralToFloating:
7153 case CK_FloatingCast:
7154 case CK_CPointerToObjCPointerCast:
7155 case CK_BlockPointerToObjCPointerCast:
7156 case CK_AnyPointerToBlockPointerCast:
7157 case CK_ObjCObjectLValueCast:
7158 case CK_FloatingRealToComplex:
7159 case CK_FloatingComplexToReal:
7160 case CK_FloatingComplexCast:
7161 case CK_FloatingComplexToIntegralComplex:
7162 case CK_IntegralRealToComplex:
7163 case CK_IntegralComplexCast:
7164 case CK_IntegralComplexToFloatingComplex:
7165 case CK_BuiltinFnToFnPtr:
7166 case CK_ZeroToOCLEvent:
7167 case CK_NonAtomicToAtomic:
7168 case CK_AddressSpaceConversion:
7169 llvm_unreachable("invalid cast kind for integral value");
7173 case CK_LValueBitCast:
7174 case CK_ARCProduceObject:
7175 case CK_ARCConsumeObject:
7176 case CK_ARCReclaimReturnedObject:
7177 case CK_ARCExtendBlockObject:
7178 case CK_CopyAndAutoreleaseBlockObject:
7181 case CK_UserDefinedConversion:
7182 case CK_LValueToRValue:
7183 case CK_AtomicToNonAtomic:
7185 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7187 case CK_MemberPointerToBoolean:
7188 case CK_PointerToBoolean:
7189 case CK_IntegralToBoolean:
7190 case CK_FloatingToBoolean:
7191 case CK_FloatingComplexToBoolean:
7192 case CK_IntegralComplexToBoolean: {
7194 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7196 return Success(BoolResult, E);
7199 case CK_IntegralCast: {
7200 if (!Visit(SubExpr))
7203 if (!Result.isInt()) {
7204 // Allow casts of address-of-label differences if they are no-ops
7205 // or narrowing. (The narrowing case isn't actually guaranteed to
7206 // be constant-evaluatable except in some narrow cases which are hard
7207 // to detect here. We let it through on the assumption the user knows
7208 // what they are doing.)
7209 if (Result.isAddrLabelDiff())
7210 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7211 // Only allow casts of lvalues if they are lossless.
7212 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7215 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7216 Result.getInt()), E);
7219 case CK_PointerToIntegral: {
7220 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7223 if (!EvaluatePointer(SubExpr, LV, Info))
7226 if (LV.getLValueBase()) {
7227 // Only allow based lvalue casts if they are lossless.
7228 // FIXME: Allow a larger integer size than the pointer size, and allow
7229 // narrowing back down to pointer width in subsequent integral casts.
7230 // FIXME: Check integer type's active bits, not its type size.
7231 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7234 LV.Designator.setInvalid();
7235 LV.moveInto(Result);
7239 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7241 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7244 case CK_IntegralComplexToReal: {
7246 if (!EvaluateComplex(SubExpr, C, Info))
7248 return Success(C.getComplexIntReal(), E);
7251 case CK_FloatingToIntegral: {
7253 if (!EvaluateFloat(SubExpr, F, Info))
7257 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7259 return Success(Value, E);
7263 llvm_unreachable("unknown cast resulting in integral value");
7266 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7267 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7269 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7271 if (!LV.isComplexInt())
7273 return Success(LV.getComplexIntReal(), E);
7276 return Visit(E->getSubExpr());
7279 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7280 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7282 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7284 if (!LV.isComplexInt())
7286 return Success(LV.getComplexIntImag(), E);
7289 VisitIgnoredValue(E->getSubExpr());
7290 return Success(0, E);
7293 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7294 return Success(E->getPackLength(), E);
7297 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7298 return Success(E->getValue(), E);
7301 //===----------------------------------------------------------------------===//
7303 //===----------------------------------------------------------------------===//
7306 class FloatExprEvaluator
7307 : public ExprEvaluatorBase<FloatExprEvaluator> {
7310 FloatExprEvaluator(EvalInfo &info, APFloat &result)
7311 : ExprEvaluatorBaseTy(info), Result(result) {}
7313 bool Success(const APValue &V, const Expr *e) {
7314 Result = V.getFloat();
7318 bool ZeroInitialization(const Expr *E) {
7319 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7323 bool VisitCallExpr(const CallExpr *E);
7325 bool VisitUnaryOperator(const UnaryOperator *E);
7326 bool VisitBinaryOperator(const BinaryOperator *E);
7327 bool VisitFloatingLiteral(const FloatingLiteral *E);
7328 bool VisitCastExpr(const CastExpr *E);
7330 bool VisitUnaryReal(const UnaryOperator *E);
7331 bool VisitUnaryImag(const UnaryOperator *E);
7333 // FIXME: Missing: array subscript of vector, member of vector
7335 } // end anonymous namespace
7337 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7338 assert(E->isRValue() && E->getType()->isRealFloatingType());
7339 return FloatExprEvaluator(Info, Result).Visit(E);
7342 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7346 llvm::APFloat &Result) {
7347 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7348 if (!S) return false;
7350 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7354 // Treat empty strings as if they were zero.
7355 if (S->getString().empty())
7356 fill = llvm::APInt(32, 0);
7357 else if (S->getString().getAsInteger(0, fill))
7361 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7363 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7367 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7368 switch (E->getBuiltinCallee()) {
7370 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7372 case Builtin::BI__builtin_huge_val:
7373 case Builtin::BI__builtin_huge_valf:
7374 case Builtin::BI__builtin_huge_vall:
7375 case Builtin::BI__builtin_inf:
7376 case Builtin::BI__builtin_inff:
7377 case Builtin::BI__builtin_infl: {
7378 const llvm::fltSemantics &Sem =
7379 Info.Ctx.getFloatTypeSemantics(E->getType());
7380 Result = llvm::APFloat::getInf(Sem);
7384 case Builtin::BI__builtin_nans:
7385 case Builtin::BI__builtin_nansf:
7386 case Builtin::BI__builtin_nansl:
7387 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7392 case Builtin::BI__builtin_nan:
7393 case Builtin::BI__builtin_nanf:
7394 case Builtin::BI__builtin_nanl:
7395 // If this is __builtin_nan() turn this into a nan, otherwise we
7396 // can't constant fold it.
7397 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7402 case Builtin::BI__builtin_fabs:
7403 case Builtin::BI__builtin_fabsf:
7404 case Builtin::BI__builtin_fabsl:
7405 if (!EvaluateFloat(E->getArg(0), Result, Info))
7408 if (Result.isNegative())
7409 Result.changeSign();
7412 // FIXME: Builtin::BI__builtin_powi
7413 // FIXME: Builtin::BI__builtin_powif
7414 // FIXME: Builtin::BI__builtin_powil
7416 case Builtin::BI__builtin_copysign:
7417 case Builtin::BI__builtin_copysignf:
7418 case Builtin::BI__builtin_copysignl: {
7420 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7421 !EvaluateFloat(E->getArg(1), RHS, Info))
7423 Result.copySign(RHS);
7429 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7430 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7432 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7434 Result = CV.FloatReal;
7438 return Visit(E->getSubExpr());
7441 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7442 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7444 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7446 Result = CV.FloatImag;
7450 VisitIgnoredValue(E->getSubExpr());
7451 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7452 Result = llvm::APFloat::getZero(Sem);
7456 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7457 switch (E->getOpcode()) {
7458 default: return Error(E);
7460 return EvaluateFloat(E->getSubExpr(), Result, Info);
7462 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7464 Result.changeSign();
7469 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7470 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7471 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7474 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7475 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7477 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7478 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7481 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7482 Result = E->getValue();
7486 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7487 const Expr* SubExpr = E->getSubExpr();
7489 switch (E->getCastKind()) {
7491 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7493 case CK_IntegralToFloating: {
7495 return EvaluateInteger(SubExpr, IntResult, Info) &&
7496 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7497 E->getType(), Result);
7500 case CK_FloatingCast: {
7501 if (!Visit(SubExpr))
7503 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7507 case CK_FloatingComplexToReal: {
7509 if (!EvaluateComplex(SubExpr, V, Info))
7511 Result = V.getComplexFloatReal();
7517 //===----------------------------------------------------------------------===//
7518 // Complex Evaluation (for float and integer)
7519 //===----------------------------------------------------------------------===//
7522 class ComplexExprEvaluator
7523 : public ExprEvaluatorBase<ComplexExprEvaluator> {
7524 ComplexValue &Result;
7527 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7528 : ExprEvaluatorBaseTy(info), Result(Result) {}
7530 bool Success(const APValue &V, const Expr *e) {
7535 bool ZeroInitialization(const Expr *E);
7537 //===--------------------------------------------------------------------===//
7539 //===--------------------------------------------------------------------===//
7541 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7542 bool VisitCastExpr(const CastExpr *E);
7543 bool VisitBinaryOperator(const BinaryOperator *E);
7544 bool VisitUnaryOperator(const UnaryOperator *E);
7545 bool VisitInitListExpr(const InitListExpr *E);
7547 } // end anonymous namespace
7549 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7551 assert(E->isRValue() && E->getType()->isAnyComplexType());
7552 return ComplexExprEvaluator(Info, Result).Visit(E);
7555 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7556 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7557 if (ElemTy->isRealFloatingType()) {
7558 Result.makeComplexFloat();
7559 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7560 Result.FloatReal = Zero;
7561 Result.FloatImag = Zero;
7563 Result.makeComplexInt();
7564 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7565 Result.IntReal = Zero;
7566 Result.IntImag = Zero;
7571 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7572 const Expr* SubExpr = E->getSubExpr();
7574 if (SubExpr->getType()->isRealFloatingType()) {
7575 Result.makeComplexFloat();
7576 APFloat &Imag = Result.FloatImag;
7577 if (!EvaluateFloat(SubExpr, Imag, Info))
7580 Result.FloatReal = APFloat(Imag.getSemantics());
7583 assert(SubExpr->getType()->isIntegerType() &&
7584 "Unexpected imaginary literal.");
7586 Result.makeComplexInt();
7587 APSInt &Imag = Result.IntImag;
7588 if (!EvaluateInteger(SubExpr, Imag, Info))
7591 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7596 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7598 switch (E->getCastKind()) {
7600 case CK_BaseToDerived:
7601 case CK_DerivedToBase:
7602 case CK_UncheckedDerivedToBase:
7605 case CK_ArrayToPointerDecay:
7606 case CK_FunctionToPointerDecay:
7607 case CK_NullToPointer:
7608 case CK_NullToMemberPointer:
7609 case CK_BaseToDerivedMemberPointer:
7610 case CK_DerivedToBaseMemberPointer:
7611 case CK_MemberPointerToBoolean:
7612 case CK_ReinterpretMemberPointer:
7613 case CK_ConstructorConversion:
7614 case CK_IntegralToPointer:
7615 case CK_PointerToIntegral:
7616 case CK_PointerToBoolean:
7618 case CK_VectorSplat:
7619 case CK_IntegralCast:
7620 case CK_IntegralToBoolean:
7621 case CK_IntegralToFloating:
7622 case CK_FloatingToIntegral:
7623 case CK_FloatingToBoolean:
7624 case CK_FloatingCast:
7625 case CK_CPointerToObjCPointerCast:
7626 case CK_BlockPointerToObjCPointerCast:
7627 case CK_AnyPointerToBlockPointerCast:
7628 case CK_ObjCObjectLValueCast:
7629 case CK_FloatingComplexToReal:
7630 case CK_FloatingComplexToBoolean:
7631 case CK_IntegralComplexToReal:
7632 case CK_IntegralComplexToBoolean:
7633 case CK_ARCProduceObject:
7634 case CK_ARCConsumeObject:
7635 case CK_ARCReclaimReturnedObject:
7636 case CK_ARCExtendBlockObject:
7637 case CK_CopyAndAutoreleaseBlockObject:
7638 case CK_BuiltinFnToFnPtr:
7639 case CK_ZeroToOCLEvent:
7640 case CK_NonAtomicToAtomic:
7641 case CK_AddressSpaceConversion:
7642 llvm_unreachable("invalid cast kind for complex value");
7644 case CK_LValueToRValue:
7645 case CK_AtomicToNonAtomic:
7647 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7650 case CK_LValueBitCast:
7651 case CK_UserDefinedConversion:
7654 case CK_FloatingRealToComplex: {
7655 APFloat &Real = Result.FloatReal;
7656 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7659 Result.makeComplexFloat();
7660 Result.FloatImag = APFloat(Real.getSemantics());
7664 case CK_FloatingComplexCast: {
7665 if (!Visit(E->getSubExpr()))
7668 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7670 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7672 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7673 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7676 case CK_FloatingComplexToIntegralComplex: {
7677 if (!Visit(E->getSubExpr()))
7680 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7682 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7683 Result.makeComplexInt();
7684 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7685 To, Result.IntReal) &&
7686 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7687 To, Result.IntImag);
7690 case CK_IntegralRealToComplex: {
7691 APSInt &Real = Result.IntReal;
7692 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7695 Result.makeComplexInt();
7696 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7700 case CK_IntegralComplexCast: {
7701 if (!Visit(E->getSubExpr()))
7704 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7706 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7708 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7709 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7713 case CK_IntegralComplexToFloatingComplex: {
7714 if (!Visit(E->getSubExpr()))
7717 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
7719 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
7720 Result.makeComplexFloat();
7721 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7722 To, Result.FloatReal) &&
7723 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7724 To, Result.FloatImag);
7728 llvm_unreachable("unknown cast resulting in complex value");
7731 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7732 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7733 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7735 bool LHSOK = Visit(E->getLHS());
7736 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7740 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7743 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7744 "Invalid operands to binary operator.");
7745 switch (E->getOpcode()) {
7746 default: return Error(E);
7748 if (Result.isComplexFloat()) {
7749 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7750 APFloat::rmNearestTiesToEven);
7751 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7752 APFloat::rmNearestTiesToEven);
7754 Result.getComplexIntReal() += RHS.getComplexIntReal();
7755 Result.getComplexIntImag() += RHS.getComplexIntImag();
7759 if (Result.isComplexFloat()) {
7760 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7761 APFloat::rmNearestTiesToEven);
7762 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7763 APFloat::rmNearestTiesToEven);
7765 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7766 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7770 if (Result.isComplexFloat()) {
7771 ComplexValue LHS = Result;
7772 APFloat &LHS_r = LHS.getComplexFloatReal();
7773 APFloat &LHS_i = LHS.getComplexFloatImag();
7774 APFloat &RHS_r = RHS.getComplexFloatReal();
7775 APFloat &RHS_i = RHS.getComplexFloatImag();
7777 APFloat Tmp = LHS_r;
7778 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7779 Result.getComplexFloatReal() = Tmp;
7781 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7782 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7785 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7786 Result.getComplexFloatImag() = Tmp;
7788 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7789 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7791 ComplexValue LHS = Result;
7792 Result.getComplexIntReal() =
7793 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7794 LHS.getComplexIntImag() * RHS.getComplexIntImag());
7795 Result.getComplexIntImag() =
7796 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7797 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7801 if (Result.isComplexFloat()) {
7802 ComplexValue LHS = Result;
7803 APFloat &LHS_r = LHS.getComplexFloatReal();
7804 APFloat &LHS_i = LHS.getComplexFloatImag();
7805 APFloat &RHS_r = RHS.getComplexFloatReal();
7806 APFloat &RHS_i = RHS.getComplexFloatImag();
7807 APFloat &Res_r = Result.getComplexFloatReal();
7808 APFloat &Res_i = Result.getComplexFloatImag();
7810 APFloat Den = RHS_r;
7811 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7812 APFloat Tmp = RHS_i;
7813 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7814 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7817 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7819 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7820 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7821 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7824 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7826 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7827 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7828 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7830 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7831 return Error(E, diag::note_expr_divide_by_zero);
7833 ComplexValue LHS = Result;
7834 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7835 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7836 Result.getComplexIntReal() =
7837 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7838 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7839 Result.getComplexIntImag() =
7840 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7841 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7849 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7850 // Get the operand value into 'Result'.
7851 if (!Visit(E->getSubExpr()))
7854 switch (E->getOpcode()) {
7860 // The result is always just the subexpr.
7863 if (Result.isComplexFloat()) {
7864 Result.getComplexFloatReal().changeSign();
7865 Result.getComplexFloatImag().changeSign();
7868 Result.getComplexIntReal() = -Result.getComplexIntReal();
7869 Result.getComplexIntImag() = -Result.getComplexIntImag();
7873 if (Result.isComplexFloat())
7874 Result.getComplexFloatImag().changeSign();
7876 Result.getComplexIntImag() = -Result.getComplexIntImag();
7881 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7882 if (E->getNumInits() == 2) {
7883 if (E->getType()->isComplexType()) {
7884 Result.makeComplexFloat();
7885 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7887 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7890 Result.makeComplexInt();
7891 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7893 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7898 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7901 //===----------------------------------------------------------------------===//
7902 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7903 // implicit conversion.
7904 //===----------------------------------------------------------------------===//
7907 class AtomicExprEvaluator :
7908 public ExprEvaluatorBase<AtomicExprEvaluator> {
7911 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7912 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7914 bool Success(const APValue &V, const Expr *E) {
7919 bool ZeroInitialization(const Expr *E) {
7920 ImplicitValueInitExpr VIE(
7921 E->getType()->castAs<AtomicType>()->getValueType());
7922 return Evaluate(Result, Info, &VIE);
7925 bool VisitCastExpr(const CastExpr *E) {
7926 switch (E->getCastKind()) {
7928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7929 case CK_NonAtomicToAtomic:
7930 return Evaluate(Result, Info, E->getSubExpr());
7934 } // end anonymous namespace
7936 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7937 assert(E->isRValue() && E->getType()->isAtomicType());
7938 return AtomicExprEvaluator(Info, Result).Visit(E);
7941 //===----------------------------------------------------------------------===//
7942 // Void expression evaluation, primarily for a cast to void on the LHS of a
7944 //===----------------------------------------------------------------------===//
7947 class VoidExprEvaluator
7948 : public ExprEvaluatorBase<VoidExprEvaluator> {
7950 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7952 bool Success(const APValue &V, const Expr *e) { return true; }
7954 bool VisitCastExpr(const CastExpr *E) {
7955 switch (E->getCastKind()) {
7957 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7959 VisitIgnoredValue(E->getSubExpr());
7964 bool VisitCallExpr(const CallExpr *E) {
7965 switch (E->getBuiltinCallee()) {
7967 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7968 case Builtin::BI__assume:
7969 // The argument is not evaluated!
7974 } // end anonymous namespace
7976 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7977 assert(E->isRValue() && E->getType()->isVoidType());
7978 return VoidExprEvaluator(Info).Visit(E);
7981 //===----------------------------------------------------------------------===//
7982 // Top level Expr::EvaluateAsRValue method.
7983 //===----------------------------------------------------------------------===//
7985 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
7986 // In C, function designators are not lvalues, but we evaluate them as if they
7988 QualType T = E->getType();
7989 if (E->isGLValue() || T->isFunctionType()) {
7991 if (!EvaluateLValue(E, LV, Info))
7993 LV.moveInto(Result);
7994 } else if (T->isVectorType()) {
7995 if (!EvaluateVector(E, Result, Info))
7997 } else if (T->isIntegralOrEnumerationType()) {
7998 if (!IntExprEvaluator(Info, Result).Visit(E))
8000 } else if (T->hasPointerRepresentation()) {
8002 if (!EvaluatePointer(E, LV, Info))
8004 LV.moveInto(Result);
8005 } else if (T->isRealFloatingType()) {
8006 llvm::APFloat F(0.0);
8007 if (!EvaluateFloat(E, F, Info))
8009 Result = APValue(F);
8010 } else if (T->isAnyComplexType()) {
8012 if (!EvaluateComplex(E, C, Info))
8015 } else if (T->isMemberPointerType()) {
8017 if (!EvaluateMemberPointer(E, P, Info))
8021 } else if (T->isArrayType()) {
8023 LV.set(E, Info.CurrentCall->Index);
8024 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8025 if (!EvaluateArray(E, LV, Value, Info))
8028 } else if (T->isRecordType()) {
8030 LV.set(E, Info.CurrentCall->Index);
8031 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8032 if (!EvaluateRecord(E, LV, Value, Info))
8035 } else if (T->isVoidType()) {
8036 if (!Info.getLangOpts().CPlusPlus11)
8037 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8039 if (!EvaluateVoid(E, Info))
8041 } else if (T->isAtomicType()) {
8042 if (!EvaluateAtomic(E, Result, Info))
8044 } else if (Info.getLangOpts().CPlusPlus11) {
8045 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8048 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8055 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8056 /// cases, the in-place evaluation is essential, since later initializers for
8057 /// an object can indirectly refer to subobjects which were initialized earlier.
8058 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8059 const Expr *E, bool AllowNonLiteralTypes) {
8060 assert(!E->isValueDependent());
8062 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8065 if (E->isRValue()) {
8066 // Evaluate arrays and record types in-place, so that later initializers can
8067 // refer to earlier-initialized members of the object.
8068 if (E->getType()->isArrayType())
8069 return EvaluateArray(E, This, Result, Info);
8070 else if (E->getType()->isRecordType())
8071 return EvaluateRecord(E, This, Result, Info);
8074 // For any other type, in-place evaluation is unimportant.
8075 return Evaluate(Result, Info, E);
8078 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8079 /// lvalue-to-rvalue cast if it is an lvalue.
8080 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8081 if (E->getType().isNull())
8084 if (!CheckLiteralType(Info, E))
8087 if (!::Evaluate(Result, Info, E))
8090 if (E->isGLValue()) {
8092 LV.setFrom(Info.Ctx, Result);
8093 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8097 // Check this core constant expression is a constant expression.
8098 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8101 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8102 const ASTContext &Ctx, bool &IsConst) {
8103 // Fast-path evaluations of integer literals, since we sometimes see files
8104 // containing vast quantities of these.
8105 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8106 Result.Val = APValue(APSInt(L->getValue(),
8107 L->getType()->isUnsignedIntegerType()));
8112 // This case should be rare, but we need to check it before we check on
8114 if (Exp->getType().isNull()) {
8119 // FIXME: Evaluating values of large array and record types can cause
8120 // performance problems. Only do so in C++11 for now.
8121 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8122 Exp->getType()->isRecordType()) &&
8123 !Ctx.getLangOpts().CPlusPlus11) {
8131 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8132 /// any crazy technique (that has nothing to do with language standards) that
8133 /// we want to. If this function returns true, it returns the folded constant
8134 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8135 /// will be applied to the result.
8136 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8138 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8141 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8142 return ::EvaluateAsRValue(Info, this, Result.Val);
8145 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8146 const ASTContext &Ctx) const {
8148 return EvaluateAsRValue(Scratch, Ctx) &&
8149 HandleConversionToBool(Scratch.Val, Result);
8152 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8153 SideEffectsKind AllowSideEffects) const {
8154 if (!getType()->isIntegralOrEnumerationType())
8157 EvalResult ExprResult;
8158 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8159 (!AllowSideEffects && ExprResult.HasSideEffects))
8162 Result = ExprResult.Val.getInt();
8166 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8167 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8170 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8171 !CheckLValueConstantExpression(Info, getExprLoc(),
8172 Ctx.getLValueReferenceType(getType()), LV))
8175 LV.moveInto(Result.Val);
8179 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8181 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8182 // FIXME: Evaluating initializers for large array and record types can cause
8183 // performance problems. Only do so in C++11 for now.
8184 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8185 !Ctx.getLangOpts().CPlusPlus11)
8188 Expr::EvalStatus EStatus;
8189 EStatus.Diag = &Notes;
8191 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8192 InitInfo.setEvaluatingDecl(VD, Value);
8197 // C++11 [basic.start.init]p2:
8198 // Variables with static storage duration or thread storage duration shall be
8199 // zero-initialized before any other initialization takes place.
8200 // This behavior is not present in C.
8201 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8202 !VD->getType()->isReferenceType()) {
8203 ImplicitValueInitExpr VIE(VD->getType());
8204 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8205 /*AllowNonLiteralTypes=*/true))
8209 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8210 /*AllowNonLiteralTypes=*/true) ||
8211 EStatus.HasSideEffects)
8214 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8218 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8219 /// constant folded, but discard the result.
8220 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8222 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8225 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8226 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8227 EvalResult EvalResult;
8228 EvalResult.Diag = Diag;
8229 bool Result = EvaluateAsRValue(EvalResult, Ctx);
8231 assert(Result && "Could not evaluate expression");
8232 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8234 return EvalResult.Val.getInt();
8237 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8239 EvalResult EvalResult;
8240 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8241 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8242 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8246 bool Expr::EvalResult::isGlobalLValue() const {
8247 assert(Val.isLValue());
8248 return IsGlobalLValue(Val.getLValueBase());
8252 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8253 /// an integer constant expression.
8255 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8258 // CheckICE - This function does the fundamental ICE checking: the returned
8259 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8260 // and a (possibly null) SourceLocation indicating the location of the problem.
8262 // Note that to reduce code duplication, this helper does no evaluation
8263 // itself; the caller checks whether the expression is evaluatable, and
8264 // in the rare cases where CheckICE actually cares about the evaluated
8265 // value, it calls into Evalute.
8270 /// This expression is an ICE.
8272 /// This expression is not an ICE, but if it isn't evaluated, it's
8273 /// a legal subexpression for an ICE. This return value is used to handle
8274 /// the comma operator in C99 mode, and non-constant subexpressions.
8275 IK_ICEIfUnevaluated,
8276 /// This expression is not an ICE, and is not a legal subexpression for one.
8284 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8289 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8291 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8293 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8294 Expr::EvalResult EVResult;
8295 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8296 !EVResult.Val.isInt())
8297 return ICEDiag(IK_NotICE, E->getLocStart());
8302 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8303 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8304 if (!E->getType()->isIntegralOrEnumerationType())
8305 return ICEDiag(IK_NotICE, E->getLocStart());
8307 switch (E->getStmtClass()) {
8308 #define ABSTRACT_STMT(Node)
8309 #define STMT(Node, Base) case Expr::Node##Class:
8310 #define EXPR(Node, Base)
8311 #include "clang/AST/StmtNodes.inc"
8312 case Expr::PredefinedExprClass:
8313 case Expr::FloatingLiteralClass:
8314 case Expr::ImaginaryLiteralClass:
8315 case Expr::StringLiteralClass:
8316 case Expr::ArraySubscriptExprClass:
8317 case Expr::MemberExprClass:
8318 case Expr::CompoundAssignOperatorClass:
8319 case Expr::CompoundLiteralExprClass:
8320 case Expr::ExtVectorElementExprClass:
8321 case Expr::DesignatedInitExprClass:
8322 case Expr::ImplicitValueInitExprClass:
8323 case Expr::ParenListExprClass:
8324 case Expr::VAArgExprClass:
8325 case Expr::AddrLabelExprClass:
8326 case Expr::StmtExprClass:
8327 case Expr::CXXMemberCallExprClass:
8328 case Expr::CUDAKernelCallExprClass:
8329 case Expr::CXXDynamicCastExprClass:
8330 case Expr::CXXTypeidExprClass:
8331 case Expr::CXXUuidofExprClass:
8332 case Expr::MSPropertyRefExprClass:
8333 case Expr::CXXNullPtrLiteralExprClass:
8334 case Expr::UserDefinedLiteralClass:
8335 case Expr::CXXThisExprClass:
8336 case Expr::CXXThrowExprClass:
8337 case Expr::CXXNewExprClass:
8338 case Expr::CXXDeleteExprClass:
8339 case Expr::CXXPseudoDestructorExprClass:
8340 case Expr::UnresolvedLookupExprClass:
8341 case Expr::DependentScopeDeclRefExprClass:
8342 case Expr::CXXConstructExprClass:
8343 case Expr::CXXStdInitializerListExprClass:
8344 case Expr::CXXBindTemporaryExprClass:
8345 case Expr::ExprWithCleanupsClass:
8346 case Expr::CXXTemporaryObjectExprClass:
8347 case Expr::CXXUnresolvedConstructExprClass:
8348 case Expr::CXXDependentScopeMemberExprClass:
8349 case Expr::UnresolvedMemberExprClass:
8350 case Expr::ObjCStringLiteralClass:
8351 case Expr::ObjCBoxedExprClass:
8352 case Expr::ObjCArrayLiteralClass:
8353 case Expr::ObjCDictionaryLiteralClass:
8354 case Expr::ObjCEncodeExprClass:
8355 case Expr::ObjCMessageExprClass:
8356 case Expr::ObjCSelectorExprClass:
8357 case Expr::ObjCProtocolExprClass:
8358 case Expr::ObjCIvarRefExprClass:
8359 case Expr::ObjCPropertyRefExprClass:
8360 case Expr::ObjCSubscriptRefExprClass:
8361 case Expr::ObjCIsaExprClass:
8362 case Expr::ShuffleVectorExprClass:
8363 case Expr::ConvertVectorExprClass:
8364 case Expr::BlockExprClass:
8365 case Expr::NoStmtClass:
8366 case Expr::OpaqueValueExprClass:
8367 case Expr::PackExpansionExprClass:
8368 case Expr::SubstNonTypeTemplateParmPackExprClass:
8369 case Expr::FunctionParmPackExprClass:
8370 case Expr::AsTypeExprClass:
8371 case Expr::ObjCIndirectCopyRestoreExprClass:
8372 case Expr::MaterializeTemporaryExprClass:
8373 case Expr::PseudoObjectExprClass:
8374 case Expr::AtomicExprClass:
8375 case Expr::LambdaExprClass:
8376 return ICEDiag(IK_NotICE, E->getLocStart());
8378 case Expr::InitListExprClass: {
8379 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8380 // form "T x = { a };" is equivalent to "T x = a;".
8381 // Unless we're initializing a reference, T is a scalar as it is known to be
8382 // of integral or enumeration type.
8384 if (cast<InitListExpr>(E)->getNumInits() == 1)
8385 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8386 return ICEDiag(IK_NotICE, E->getLocStart());
8389 case Expr::SizeOfPackExprClass:
8390 case Expr::GNUNullExprClass:
8391 // GCC considers the GNU __null value to be an integral constant expression.
8394 case Expr::SubstNonTypeTemplateParmExprClass:
8396 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8398 case Expr::ParenExprClass:
8399 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8400 case Expr::GenericSelectionExprClass:
8401 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8402 case Expr::IntegerLiteralClass:
8403 case Expr::CharacterLiteralClass:
8404 case Expr::ObjCBoolLiteralExprClass:
8405 case Expr::CXXBoolLiteralExprClass:
8406 case Expr::CXXScalarValueInitExprClass:
8407 case Expr::TypeTraitExprClass:
8408 case Expr::ArrayTypeTraitExprClass:
8409 case Expr::ExpressionTraitExprClass:
8410 case Expr::CXXNoexceptExprClass:
8412 case Expr::CallExprClass:
8413 case Expr::CXXOperatorCallExprClass: {
8414 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8415 // constant expressions, but they can never be ICEs because an ICE cannot
8416 // contain an operand of (pointer to) function type.
8417 const CallExpr *CE = cast<CallExpr>(E);
8418 if (CE->getBuiltinCallee())
8419 return CheckEvalInICE(E, Ctx);
8420 return ICEDiag(IK_NotICE, E->getLocStart());
8422 case Expr::DeclRefExprClass: {
8423 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8425 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8426 if (Ctx.getLangOpts().CPlusPlus &&
8427 D && IsConstNonVolatile(D->getType())) {
8428 // Parameter variables are never constants. Without this check,
8429 // getAnyInitializer() can find a default argument, which leads
8431 if (isa<ParmVarDecl>(D))
8432 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8435 // A variable of non-volatile const-qualified integral or enumeration
8436 // type initialized by an ICE can be used in ICEs.
8437 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8438 if (!Dcl->getType()->isIntegralOrEnumerationType())
8439 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8442 // Look for a declaration of this variable that has an initializer, and
8443 // check whether it is an ICE.
8444 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8447 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8450 return ICEDiag(IK_NotICE, E->getLocStart());
8452 case Expr::UnaryOperatorClass: {
8453 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8454 switch (Exp->getOpcode()) {
8461 // C99 6.6/3 allows increment and decrement within unevaluated
8462 // subexpressions of constant expressions, but they can never be ICEs
8463 // because an ICE cannot contain an lvalue operand.
8464 return ICEDiag(IK_NotICE, E->getLocStart());
8472 return CheckICE(Exp->getSubExpr(), Ctx);
8475 // OffsetOf falls through here.
8477 case Expr::OffsetOfExprClass: {
8478 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8479 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8480 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8481 // compliance: we should warn earlier for offsetof expressions with
8482 // array subscripts that aren't ICEs, and if the array subscripts
8483 // are ICEs, the value of the offsetof must be an integer constant.
8484 return CheckEvalInICE(E, Ctx);
8486 case Expr::UnaryExprOrTypeTraitExprClass: {
8487 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8488 if ((Exp->getKind() == UETT_SizeOf) &&
8489 Exp->getTypeOfArgument()->isVariableArrayType())
8490 return ICEDiag(IK_NotICE, E->getLocStart());
8493 case Expr::BinaryOperatorClass: {
8494 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8495 switch (Exp->getOpcode()) {
8509 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8510 // constant expressions, but they can never be ICEs because an ICE cannot
8511 // contain an lvalue operand.
8512 return ICEDiag(IK_NotICE, E->getLocStart());
8531 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8532 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8533 if (Exp->getOpcode() == BO_Div ||
8534 Exp->getOpcode() == BO_Rem) {
8535 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8536 // we don't evaluate one.
8537 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8538 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8540 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8541 if (REval.isSigned() && REval.isAllOnesValue()) {
8542 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8543 if (LEval.isMinSignedValue())
8544 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8548 if (Exp->getOpcode() == BO_Comma) {
8549 if (Ctx.getLangOpts().C99) {
8550 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8551 // if it isn't evaluated.
8552 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8553 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8555 // In both C89 and C++, commas in ICEs are illegal.
8556 return ICEDiag(IK_NotICE, E->getLocStart());
8559 return Worst(LHSResult, RHSResult);
8563 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8564 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8565 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8566 // Rare case where the RHS has a comma "side-effect"; we need
8567 // to actually check the condition to see whether the side
8568 // with the comma is evaluated.
8569 if ((Exp->getOpcode() == BO_LAnd) !=
8570 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8575 return Worst(LHSResult, RHSResult);
8579 case Expr::ImplicitCastExprClass:
8580 case Expr::CStyleCastExprClass:
8581 case Expr::CXXFunctionalCastExprClass:
8582 case Expr::CXXStaticCastExprClass:
8583 case Expr::CXXReinterpretCastExprClass:
8584 case Expr::CXXConstCastExprClass:
8585 case Expr::ObjCBridgedCastExprClass: {
8586 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8587 if (isa<ExplicitCastExpr>(E)) {
8588 if (const FloatingLiteral *FL
8589 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8590 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8591 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8592 APSInt IgnoredVal(DestWidth, !DestSigned);
8594 // If the value does not fit in the destination type, the behavior is
8595 // undefined, so we are not required to treat it as a constant
8597 if (FL->getValue().convertToInteger(IgnoredVal,
8598 llvm::APFloat::rmTowardZero,
8599 &Ignored) & APFloat::opInvalidOp)
8600 return ICEDiag(IK_NotICE, E->getLocStart());
8604 switch (cast<CastExpr>(E)->getCastKind()) {
8605 case CK_LValueToRValue:
8606 case CK_AtomicToNonAtomic:
8607 case CK_NonAtomicToAtomic:
8609 case CK_IntegralToBoolean:
8610 case CK_IntegralCast:
8611 return CheckICE(SubExpr, Ctx);
8613 return ICEDiag(IK_NotICE, E->getLocStart());
8616 case Expr::BinaryConditionalOperatorClass: {
8617 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8618 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8619 if (CommonResult.Kind == IK_NotICE) return CommonResult;
8620 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8621 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8622 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8623 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8624 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8627 case Expr::ConditionalOperatorClass: {
8628 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8629 // If the condition (ignoring parens) is a __builtin_constant_p call,
8630 // then only the true side is actually considered in an integer constant
8631 // expression, and it is fully evaluated. This is an important GNU
8632 // extension. See GCC PR38377 for discussion.
8633 if (const CallExpr *CallCE
8634 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
8635 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8636 return CheckEvalInICE(E, Ctx);
8637 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
8638 if (CondResult.Kind == IK_NotICE)
8641 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8642 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8644 if (TrueResult.Kind == IK_NotICE)
8646 if (FalseResult.Kind == IK_NotICE)
8648 if (CondResult.Kind == IK_ICEIfUnevaluated)
8650 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
8652 // Rare case where the diagnostics depend on which side is evaluated
8653 // Note that if we get here, CondResult is 0, and at least one of
8654 // TrueResult and FalseResult is non-zero.
8655 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
8659 case Expr::CXXDefaultArgExprClass:
8660 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
8661 case Expr::CXXDefaultInitExprClass:
8662 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
8663 case Expr::ChooseExprClass: {
8664 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
8668 llvm_unreachable("Invalid StmtClass!");
8671 /// Evaluate an expression as a C++11 integral constant expression.
8672 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
8674 llvm::APSInt *Value,
8675 SourceLocation *Loc) {
8676 if (!E->getType()->isIntegralOrEnumerationType()) {
8677 if (Loc) *Loc = E->getExprLoc();
8682 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
8685 assert(Result.isInt() && "pointer cast to int is not an ICE");
8686 if (Value) *Value = Result.getInt();
8690 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8691 SourceLocation *Loc) const {
8692 if (Ctx.getLangOpts().CPlusPlus11)
8693 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
8695 ICEDiag D = CheckICE(this, Ctx);
8696 if (D.Kind != IK_ICE) {
8697 if (Loc) *Loc = D.Loc;
8703 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
8704 SourceLocation *Loc, bool isEvaluated) const {
8705 if (Ctx.getLangOpts().CPlusPlus11)
8706 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8708 if (!isIntegerConstantExpr(Ctx, Loc))
8710 if (!EvaluateAsInt(Value, Ctx))
8711 llvm_unreachable("ICE cannot be evaluated!");
8715 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
8716 return CheckICE(this, Ctx).Kind == IK_ICE;
8719 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
8720 SourceLocation *Loc) const {
8721 // We support this checking in C++98 mode in order to diagnose compatibility
8723 assert(Ctx.getLangOpts().CPlusPlus);
8725 // Build evaluation settings.
8726 Expr::EvalStatus Status;
8727 SmallVector<PartialDiagnosticAt, 8> Diags;
8728 Status.Diag = &Diags;
8729 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
8732 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8734 if (!Diags.empty()) {
8735 IsConstExpr = false;
8736 if (Loc) *Loc = Diags[0].first;
8737 } else if (!IsConstExpr) {
8738 // FIXME: This shouldn't happen.
8739 if (Loc) *Loc = getExprLoc();
8745 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8746 const FunctionDecl *Callee,
8747 ArrayRef<const Expr*> Args) const {
8748 Expr::EvalStatus Status;
8749 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8751 ArgVector ArgValues(Args.size());
8752 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8754 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8755 // If evaluation fails, throw away the argument entirely.
8756 ArgValues[I - Args.begin()] = APValue();
8757 if (Info.EvalStatus.HasSideEffects)
8761 // Build fake call to Callee.
8762 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
8764 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8767 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
8769 PartialDiagnosticAt> &Diags) {
8770 // FIXME: It would be useful to check constexpr function templates, but at the
8771 // moment the constant expression evaluator cannot cope with the non-rigorous
8772 // ASTs which we build for dependent expressions.
8773 if (FD->isDependentContext())
8776 Expr::EvalStatus Status;
8777 Status.Diag = &Diags;
8779 EvalInfo Info(FD->getASTContext(), Status,
8780 EvalInfo::EM_PotentialConstantExpression);
8782 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8783 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
8785 // Fabricate an arbitrary expression on the stack and pretend that it
8786 // is a temporary being used as the 'this' pointer.
8788 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
8789 This.set(&VIE, Info.CurrentCall->Index);
8791 ArrayRef<const Expr*> Args;
8793 SourceLocation Loc = FD->getLocation();
8796 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8797 // Evaluate the call as a constant initializer, to allow the construction
8798 // of objects of non-literal types.
8799 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
8800 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
8802 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
8803 Args, FD->getBody(), Info, Scratch);
8805 return Diags.empty();
8808 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8809 const FunctionDecl *FD,
8811 PartialDiagnosticAt> &Diags) {
8812 Expr::EvalStatus Status;
8813 Status.Diag = &Diags;
8815 EvalInfo Info(FD->getASTContext(), Status,
8816 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8818 // Fabricate a call stack frame to give the arguments a plausible cover story.
8819 ArrayRef<const Expr*> Args;
8820 ArgVector ArgValues(0);
8821 bool Success = EvaluateArgs(Args, ArgValues, Info);
8824 "Failed to set up arguments for potential constant evaluation");
8825 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
8827 APValue ResultScratch;
8828 Evaluate(ResultScratch, Info, E);
8829 return Diags.empty();