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 {
207 if (MostDerivedArraySize &&
208 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
213 /// Check that this refers to a valid subobject.
214 bool isValidSubobject() const {
217 return !isOnePastTheEnd();
219 /// Check that this refers to a valid subobject, and if not, produce a
220 /// relevant diagnostic and set the designator as invalid.
221 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
223 /// Update this designator to refer to the first element within this array.
224 void addArrayUnchecked(const ConstantArrayType *CAT) {
226 Entry.ArrayIndex = 0;
227 Entries.push_back(Entry);
229 // This is a most-derived object.
230 MostDerivedType = CAT->getElementType();
231 MostDerivedArraySize = CAT->getSize().getZExtValue();
232 MostDerivedPathLength = Entries.size();
234 /// Update this designator to refer to the given base or member of this
236 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
238 APValue::BaseOrMemberType Value(D, Virtual);
239 Entry.BaseOrMember = Value.getOpaqueValue();
240 Entries.push_back(Entry);
242 // If this isn't a base class, it's a new most-derived object.
243 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244 MostDerivedType = FD->getType();
245 MostDerivedArraySize = 0;
246 MostDerivedPathLength = Entries.size();
249 /// Update this designator to refer to the given complex component.
250 void addComplexUnchecked(QualType EltTy, bool Imag) {
252 Entry.ArrayIndex = Imag;
253 Entries.push_back(Entry);
255 // This is technically a most-derived object, though in practice this
256 // is unlikely to matter.
257 MostDerivedType = EltTy;
258 MostDerivedArraySize = 2;
259 MostDerivedPathLength = Entries.size();
261 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
262 /// Add N to the address of this subobject.
263 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
265 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
266 Entries.back().ArrayIndex += N;
267 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
273 // [expr.add]p4: For the purposes of these operators, a pointer to a
274 // nonarray object behaves the same as a pointer to the first element of
275 // an array of length one with the type of the object as its element type.
276 if (IsOnePastTheEnd && N == (uint64_t)-1)
277 IsOnePastTheEnd = false;
278 else if (!IsOnePastTheEnd && N == 1)
279 IsOnePastTheEnd = true;
281 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
287 /// A stack frame in the constexpr call stack.
288 struct CallStackFrame {
291 /// Parent - The caller of this stack frame.
292 CallStackFrame *Caller;
294 /// CallLoc - The location of the call expression for this call.
295 SourceLocation CallLoc;
297 /// Callee - The function which was called.
298 const FunctionDecl *Callee;
300 /// Index - The call index of this call.
303 /// This - The binding for the this pointer in this call, if any.
306 /// Arguments - Parameter bindings for this function call, indexed by
307 /// parameters' function scope indices.
310 // Note that we intentionally use std::map here so that references to
311 // values are stable.
312 typedef std::map<const void*, APValue> MapTy;
313 typedef MapTy::const_iterator temp_iterator;
314 /// Temporaries - Temporary lvalues materialized within this stack frame.
317 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318 const FunctionDecl *Callee, const LValue *This,
322 APValue *getTemporary(const void *Key) {
323 MapTy::iterator I = Temporaries.find(Key);
324 return I == Temporaries.end() ? nullptr : &I->second;
326 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
329 /// Temporarily override 'this'.
330 class ThisOverrideRAII {
332 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333 : Frame(Frame), OldThis(Frame.This) {
335 Frame.This = NewThis;
337 ~ThisOverrideRAII() {
338 Frame.This = OldThis;
341 CallStackFrame &Frame;
342 const LValue *OldThis;
345 /// A partial diagnostic which we might know in advance that we are not going
347 class OptionalDiagnostic {
348 PartialDiagnostic *Diag;
351 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
355 OptionalDiagnostic &operator<<(const T &v) {
361 OptionalDiagnostic &operator<<(const APSInt &I) {
363 SmallVector<char, 32> Buffer;
365 *Diag << StringRef(Buffer.data(), Buffer.size());
370 OptionalDiagnostic &operator<<(const APFloat &F) {
372 // FIXME: Force the precision of the source value down so we don't
373 // print digits which are usually useless (we don't really care here if
374 // we truncate a digit by accident in edge cases). Ideally,
375 // APFloat::toString would automatically print the shortest
376 // representation which rounds to the correct value, but it's a bit
377 // tricky to implement.
379 llvm::APFloat::semanticsPrecision(F.getSemantics());
380 precision = (precision * 59 + 195) / 196;
381 SmallVector<char, 32> Buffer;
382 F.toString(Buffer, precision);
383 *Diag << StringRef(Buffer.data(), Buffer.size());
389 /// A cleanup, and a flag indicating whether it is lifetime-extended.
391 llvm::PointerIntPair<APValue*, 1, bool> Value;
394 Cleanup(APValue *Val, bool IsLifetimeExtended)
395 : Value(Val, IsLifetimeExtended) {}
397 bool isLifetimeExtended() const { return Value.getInt(); }
399 *Value.getPointer() = APValue();
403 /// EvalInfo - This is a private struct used by the evaluator to capture
404 /// information about a subexpression as it is folded. It retains information
405 /// about the AST context, but also maintains information about the folded
408 /// If an expression could be evaluated, it is still possible it is not a C
409 /// "integer constant expression" or constant expression. If not, this struct
410 /// captures information about how and why not.
412 /// One bit of information passed *into* the request for constant folding
413 /// indicates whether the subexpression is "evaluated" or not according to C
414 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
415 /// evaluate the expression regardless of what the RHS is, but C only allows
416 /// certain things in certain situations.
420 /// EvalStatus - Contains information about the evaluation.
421 Expr::EvalStatus &EvalStatus;
423 /// CurrentCall - The top of the constexpr call stack.
424 CallStackFrame *CurrentCall;
426 /// CallStackDepth - The number of calls in the call stack right now.
427 unsigned CallStackDepth;
429 /// NextCallIndex - The next call index to assign.
430 unsigned NextCallIndex;
432 /// StepsLeft - The remaining number of evaluation steps we're permitted
433 /// to perform. This is essentially a limit for the number of statements
434 /// we will evaluate.
437 /// BottomFrame - The frame in which evaluation started. This must be
438 /// initialized after CurrentCall and CallStackDepth.
439 CallStackFrame BottomFrame;
441 /// A stack of values whose lifetimes end at the end of some surrounding
442 /// evaluation frame.
443 llvm::SmallVector<Cleanup, 16> CleanupStack;
445 /// EvaluatingDecl - This is the declaration whose initializer is being
446 /// evaluated, if any.
447 APValue::LValueBase EvaluatingDecl;
449 /// EvaluatingDeclValue - This is the value being constructed for the
450 /// declaration whose initializer is being evaluated, if any.
451 APValue *EvaluatingDeclValue;
453 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454 /// notes attached to it will also be stored, otherwise they will not be.
455 bool HasActiveDiagnostic;
457 enum EvaluationMode {
458 /// Evaluate as a constant expression. Stop if we find that the expression
459 /// is not a constant expression.
460 EM_ConstantExpression,
462 /// Evaluate as a potential constant expression. Keep going if we hit a
463 /// construct that we can't evaluate yet (because we don't yet know the
464 /// value of something) but stop if we hit something that could never be
465 /// a constant expression.
466 EM_PotentialConstantExpression,
468 /// Fold the expression to a constant. Stop if we hit a side-effect that
472 /// Evaluate the expression looking for integer overflow and similar
473 /// issues. Don't worry about side-effects, and try to visit all
475 EM_EvaluateForOverflow,
477 /// Evaluate in any way we know how. Don't worry about side-effects that
478 /// can't be modeled.
479 EM_IgnoreSideEffects,
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression. Some expressions can be retried in the
483 /// optimizer if we don't constant fold them here, but in an unevaluated
484 /// context we try to fold them immediately since the optimizer never
485 /// gets a chance to look at it.
486 EM_ConstantExpressionUnevaluated,
488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression. Some expressions can be retried in the
492 /// optimizer if we don't constant fold them here, but in an unevaluated
493 /// context we try to fold them immediately since the optimizer never
494 /// gets a chance to look at it.
495 EM_PotentialConstantExpressionUnevaluated
498 /// Are we checking whether the expression is a potential constant
500 bool checkingPotentialConstantExpression() const {
501 return EvalMode == EM_PotentialConstantExpression ||
502 EvalMode == EM_PotentialConstantExpressionUnevaluated;
505 /// Are we checking an expression for overflow?
506 // FIXME: We should check for any kind of undefined or suspicious behavior
507 // in such constructs, not just overflow.
508 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
510 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
511 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
512 CallStackDepth(0), NextCallIndex(1),
513 StepsLeft(getLangOpts().ConstexprStepLimit),
514 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515 EvaluatingDecl((const ValueDecl *)nullptr),
516 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
519 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520 EvaluatingDecl = Base;
521 EvaluatingDeclValue = &Value;
524 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
526 bool CheckCallLimit(SourceLocation Loc) {
527 // Don't perform any constexpr calls (other than the call we're checking)
528 // when checking a potential constant expression.
529 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
531 if (NextCallIndex == 0) {
532 // NextCallIndex has wrapped around.
533 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
536 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
538 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539 << getLangOpts().ConstexprCallDepth;
543 CallStackFrame *getCallFrame(unsigned CallIndex) {
544 assert(CallIndex && "no call index in getCallFrame");
545 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546 // be null in this loop.
547 CallStackFrame *Frame = CurrentCall;
548 while (Frame->Index > CallIndex)
549 Frame = Frame->Caller;
550 return (Frame->Index == CallIndex) ? Frame : nullptr;
553 bool nextStep(const Stmt *S) {
555 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
563 /// Add a diagnostic to the diagnostics list.
564 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567 return EvalStatus.Diag->back().second;
570 /// Add notes containing a call stack to the current point of evaluation.
571 void addCallStack(unsigned Limit);
574 /// Diagnose that the evaluation cannot be folded.
575 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576 = diag::note_invalid_subexpr_in_const_expr,
577 unsigned ExtraNotes = 0) {
578 if (EvalStatus.Diag) {
579 // If we have a prior diagnostic, it will be noting that the expression
580 // isn't a constant expression. This diagnostic is more important,
581 // unless we require this evaluation to produce a constant expression.
583 // FIXME: We might want to show both diagnostics to the user in
584 // EM_ConstantFold mode.
585 if (!EvalStatus.Diag->empty()) {
587 case EM_ConstantFold:
588 case EM_IgnoreSideEffects:
589 case EM_EvaluateForOverflow:
590 if (!EvalStatus.HasSideEffects)
592 // We've had side-effects; we want the diagnostic from them, not
593 // some later problem.
594 case EM_ConstantExpression:
595 case EM_PotentialConstantExpression:
596 case EM_ConstantExpressionUnevaluated:
597 case EM_PotentialConstantExpressionUnevaluated:
598 HasActiveDiagnostic = false;
599 return OptionalDiagnostic();
603 unsigned CallStackNotes = CallStackDepth - 1;
604 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
606 CallStackNotes = std::min(CallStackNotes, Limit + 1);
607 if (checkingPotentialConstantExpression())
610 HasActiveDiagnostic = true;
611 EvalStatus.Diag->clear();
612 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613 addDiag(Loc, DiagId);
614 if (!checkingPotentialConstantExpression())
616 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
618 HasActiveDiagnostic = false;
619 return OptionalDiagnostic();
622 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623 = diag::note_invalid_subexpr_in_const_expr,
624 unsigned ExtraNotes = 0) {
626 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627 HasActiveDiagnostic = false;
628 return OptionalDiagnostic();
631 /// Diagnose that the evaluation does not produce a C++11 core constant
634 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635 /// EM_PotentialConstantExpression mode and we produce one of these.
636 template<typename LocArg>
637 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
638 = diag::note_invalid_subexpr_in_const_expr,
639 unsigned ExtraNotes = 0) {
640 // Don't override a previous diagnostic. Don't bother collecting
641 // diagnostics if we're evaluating for overflow.
642 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
643 HasActiveDiagnostic = false;
644 return OptionalDiagnostic();
646 return Diag(Loc, DiagId, ExtraNotes);
649 /// Add a note to a prior diagnostic.
650 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651 if (!HasActiveDiagnostic)
652 return OptionalDiagnostic();
653 return OptionalDiagnostic(&addDiag(Loc, DiagId));
656 /// Add a stack of notes to a prior diagnostic.
657 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658 if (HasActiveDiagnostic) {
659 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660 Diags.begin(), Diags.end());
664 /// Should we continue evaluation after encountering a side-effect that we
666 bool keepEvaluatingAfterSideEffect() {
668 case EM_PotentialConstantExpression:
669 case EM_PotentialConstantExpressionUnevaluated:
670 case EM_EvaluateForOverflow:
671 case EM_IgnoreSideEffects:
674 case EM_ConstantExpression:
675 case EM_ConstantExpressionUnevaluated:
676 case EM_ConstantFold:
679 llvm_unreachable("Missed EvalMode case");
682 /// Note that we have had a side-effect, and determine whether we should
684 bool noteSideEffect() {
685 EvalStatus.HasSideEffects = true;
686 return keepEvaluatingAfterSideEffect();
689 /// Should we continue evaluation as much as possible after encountering a
690 /// construct which can't be reduced to a value?
691 bool keepEvaluatingAfterFailure() {
696 case EM_PotentialConstantExpression:
697 case EM_PotentialConstantExpressionUnevaluated:
698 case EM_EvaluateForOverflow:
701 case EM_ConstantExpression:
702 case EM_ConstantExpressionUnevaluated:
703 case EM_ConstantFold:
704 case EM_IgnoreSideEffects:
707 llvm_unreachable("Missed EvalMode case");
711 /// Object used to treat all foldable expressions as constant expressions.
712 struct FoldConstant {
715 bool HadNoPriorDiags;
716 EvalInfo::EvaluationMode OldMode;
718 explicit FoldConstant(EvalInfo &Info, bool Enabled)
721 HadNoPriorDiags(Info.EvalStatus.Diag &&
722 Info.EvalStatus.Diag->empty() &&
723 !Info.EvalStatus.HasSideEffects),
724 OldMode(Info.EvalMode) {
726 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
728 Info.EvalMode = EvalInfo::EM_ConstantFold;
730 void keepDiagnostics() { Enabled = false; }
732 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
733 !Info.EvalStatus.HasSideEffects)
734 Info.EvalStatus.Diag->clear();
735 Info.EvalMode = OldMode;
739 /// RAII object used to suppress diagnostics and side-effects from a
740 /// speculative evaluation.
741 class SpeculativeEvaluationRAII {
743 Expr::EvalStatus Old;
746 SpeculativeEvaluationRAII(EvalInfo &Info,
747 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
748 : Info(Info), Old(Info.EvalStatus) {
749 Info.EvalStatus.Diag = NewDiag;
750 // If we're speculatively evaluating, we may have skipped over some
751 // evaluations and missed out a side effect.
752 Info.EvalStatus.HasSideEffects = true;
754 ~SpeculativeEvaluationRAII() {
755 Info.EvalStatus = Old;
759 /// RAII object wrapping a full-expression or block scope, and handling
760 /// the ending of the lifetime of temporaries created within it.
761 template<bool IsFullExpression>
764 unsigned OldStackSize;
766 ScopeRAII(EvalInfo &Info)
767 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
769 // Body moved to a static method to encourage the compiler to inline away
770 // instances of this class.
771 cleanup(Info, OldStackSize);
774 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775 unsigned NewEnd = OldStackSize;
776 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
778 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779 // Full-expression cleanup of a lifetime-extended temporary: nothing
780 // to do, just move this cleanup to the right place in the stack.
781 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
784 // End the lifetime of the object.
785 Info.CleanupStack[I].endLifetime();
788 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789 Info.CleanupStack.end());
792 typedef ScopeRAII<false> BlockScopeRAII;
793 typedef ScopeRAII<true> FullExpressionRAII;
796 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797 CheckSubobjectKind CSK) {
800 if (isOnePastTheEnd()) {
801 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
809 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810 const Expr *E, uint64_t N) {
811 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
812 Info.CCEDiag(E, diag::note_constexpr_array_index)
813 << static_cast<int>(N) << /*array*/ 0
814 << static_cast<unsigned>(MostDerivedArraySize);
816 Info.CCEDiag(E, diag::note_constexpr_array_index)
817 << static_cast<int>(N) << /*non-array*/ 1;
821 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822 const FunctionDecl *Callee, const LValue *This,
824 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
825 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
826 Info.CurrentCall = this;
827 ++Info.CallStackDepth;
830 CallStackFrame::~CallStackFrame() {
831 assert(Info.CurrentCall == this && "calls retired out of order");
832 --Info.CallStackDepth;
833 Info.CurrentCall = Caller;
836 APValue &CallStackFrame::createTemporary(const void *Key,
837 bool IsLifetimeExtended) {
838 APValue &Result = Temporaries[Key];
839 assert(Result.isUninit() && "temporary created multiple times");
840 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
844 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
846 void EvalInfo::addCallStack(unsigned Limit) {
847 // Determine which calls to skip, if any.
848 unsigned ActiveCalls = CallStackDepth - 1;
849 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850 if (Limit && Limit < ActiveCalls) {
851 SkipStart = Limit / 2 + Limit % 2;
852 SkipEnd = ActiveCalls - Limit / 2;
855 // Walk the call stack and add the diagnostics.
856 unsigned CallIdx = 0;
857 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858 Frame = Frame->Caller, ++CallIdx) {
860 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861 if (CallIdx == SkipStart) {
862 // Note that we're skipping calls.
863 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864 << unsigned(ActiveCalls - Limit);
869 SmallVector<char, 128> Buffer;
870 llvm::raw_svector_ostream Out(Buffer);
871 describeCall(Frame, Out);
872 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
877 struct ComplexValue {
882 APSInt IntReal, IntImag;
883 APFloat FloatReal, FloatImag;
885 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
887 void makeComplexFloat() { IsInt = false; }
888 bool isComplexFloat() const { return !IsInt; }
889 APFloat &getComplexFloatReal() { return FloatReal; }
890 APFloat &getComplexFloatImag() { return FloatImag; }
892 void makeComplexInt() { IsInt = true; }
893 bool isComplexInt() const { return IsInt; }
894 APSInt &getComplexIntReal() { return IntReal; }
895 APSInt &getComplexIntImag() { return IntImag; }
897 void moveInto(APValue &v) const {
898 if (isComplexFloat())
899 v = APValue(FloatReal, FloatImag);
901 v = APValue(IntReal, IntImag);
903 void setFrom(const APValue &v) {
904 assert(v.isComplexFloat() || v.isComplexInt());
905 if (v.isComplexFloat()) {
907 FloatReal = v.getComplexFloatReal();
908 FloatImag = v.getComplexFloatImag();
911 IntReal = v.getComplexIntReal();
912 IntImag = v.getComplexIntImag();
918 APValue::LValueBase Base;
921 SubobjectDesignator Designator;
923 const APValue::LValueBase getLValueBase() const { return Base; }
924 CharUnits &getLValueOffset() { return Offset; }
925 const CharUnits &getLValueOffset() const { return Offset; }
926 unsigned getLValueCallIndex() const { return CallIndex; }
927 SubobjectDesignator &getLValueDesignator() { return Designator; }
928 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
930 void moveInto(APValue &V) const {
931 if (Designator.Invalid)
932 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
934 V = APValue(Base, Offset, Designator.Entries,
935 Designator.IsOnePastTheEnd, CallIndex);
937 void setFrom(ASTContext &Ctx, const APValue &V) {
938 assert(V.isLValue());
939 Base = V.getLValueBase();
940 Offset = V.getLValueOffset();
941 CallIndex = V.getLValueCallIndex();
942 Designator = SubobjectDesignator(Ctx, V);
945 void set(APValue::LValueBase B, unsigned I = 0) {
947 Offset = CharUnits::Zero();
949 Designator = SubobjectDesignator(getType(B));
952 // Check that this LValue is not based on a null pointer. If it is, produce
953 // a diagnostic and mark the designator as invalid.
954 bool checkNullPointer(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Designator.Invalid)
959 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
961 Designator.setInvalid();
967 // Check this LValue refers to an object. If not, set the designator to be
968 // invalid and emit a diagnostic.
969 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
970 // Outside C++11, do not build a designator referring to a subobject of
971 // any object: we won't use such a designator for anything.
972 if (!Info.getLangOpts().CPlusPlus11)
973 Designator.setInvalid();
974 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
975 Designator.checkSubobject(Info, E, CSK);
978 void addDecl(EvalInfo &Info, const Expr *E,
979 const Decl *D, bool Virtual = false) {
980 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
981 Designator.addDeclUnchecked(D, Virtual);
983 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
984 if (checkSubobject(Info, E, CSK_ArrayToPointer))
985 Designator.addArrayUnchecked(CAT);
987 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
988 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
989 Designator.addComplexUnchecked(EltTy, Imag);
991 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
992 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
993 Designator.adjustIndex(Info, E, N);
999 explicit MemberPtr(const ValueDecl *Decl) :
1000 DeclAndIsDerivedMember(Decl, false), Path() {}
1002 /// The member or (direct or indirect) field referred to by this member
1003 /// pointer, or 0 if this is a null member pointer.
1004 const ValueDecl *getDecl() const {
1005 return DeclAndIsDerivedMember.getPointer();
1007 /// Is this actually a member of some type derived from the relevant class?
1008 bool isDerivedMember() const {
1009 return DeclAndIsDerivedMember.getInt();
1011 /// Get the class which the declaration actually lives in.
1012 const CXXRecordDecl *getContainingRecord() const {
1013 return cast<CXXRecordDecl>(
1014 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1017 void moveInto(APValue &V) const {
1018 V = APValue(getDecl(), isDerivedMember(), Path);
1020 void setFrom(const APValue &V) {
1021 assert(V.isMemberPointer());
1022 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1023 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1025 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1026 Path.insert(Path.end(), P.begin(), P.end());
1029 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1030 /// whether the member is a member of some class derived from the class type
1031 /// of the member pointer.
1032 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1033 /// Path - The path of base/derived classes from the member declaration's
1034 /// class (exclusive) to the class type of the member pointer (inclusive).
1035 SmallVector<const CXXRecordDecl*, 4> Path;
1037 /// Perform a cast towards the class of the Decl (either up or down the
1039 bool castBack(const CXXRecordDecl *Class) {
1040 assert(!Path.empty());
1041 const CXXRecordDecl *Expected;
1042 if (Path.size() >= 2)
1043 Expected = Path[Path.size() - 2];
1045 Expected = getContainingRecord();
1046 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1047 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1048 // if B does not contain the original member and is not a base or
1049 // derived class of the class containing the original member, the result
1050 // of the cast is undefined.
1051 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1052 // (D::*). We consider that to be a language defect.
1058 /// Perform a base-to-derived member pointer cast.
1059 bool castToDerived(const CXXRecordDecl *Derived) {
1062 if (!isDerivedMember()) {
1063 Path.push_back(Derived);
1066 if (!castBack(Derived))
1069 DeclAndIsDerivedMember.setInt(false);
1072 /// Perform a derived-to-base member pointer cast.
1073 bool castToBase(const CXXRecordDecl *Base) {
1077 DeclAndIsDerivedMember.setInt(true);
1078 if (isDerivedMember()) {
1079 Path.push_back(Base);
1082 return castBack(Base);
1086 /// Compare two member pointers, which are assumed to be of the same type.
1087 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1088 if (!LHS.getDecl() || !RHS.getDecl())
1089 return !LHS.getDecl() && !RHS.getDecl();
1090 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1092 return LHS.Path == RHS.Path;
1096 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1097 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1098 const LValue &This, const Expr *E,
1099 bool AllowNonLiteralTypes = false);
1100 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1101 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1102 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1104 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1105 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1106 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1108 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1109 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1110 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1112 //===----------------------------------------------------------------------===//
1114 //===----------------------------------------------------------------------===//
1116 /// Produce a string describing the given constexpr call.
1117 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1118 unsigned ArgIndex = 0;
1119 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1120 !isa<CXXConstructorDecl>(Frame->Callee) &&
1121 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1124 Out << *Frame->Callee << '(';
1126 if (Frame->This && IsMemberCall) {
1128 Frame->This->moveInto(Val);
1129 Val.printPretty(Out, Frame->Info.Ctx,
1130 Frame->This->Designator.MostDerivedType);
1131 // FIXME: Add parens around Val if needed.
1132 Out << "->" << *Frame->Callee << '(';
1133 IsMemberCall = false;
1136 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1137 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1138 if (ArgIndex > (unsigned)IsMemberCall)
1141 const ParmVarDecl *Param = *I;
1142 const APValue &Arg = Frame->Arguments[ArgIndex];
1143 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1145 if (ArgIndex == 0 && IsMemberCall)
1146 Out << "->" << *Frame->Callee << '(';
1152 /// Evaluate an expression to see if it had side-effects, and discard its
1154 /// \return \c true if the caller should keep evaluating.
1155 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1157 if (!Evaluate(Scratch, Info, E))
1158 // We don't need the value, but we might have skipped a side effect here.
1159 return Info.noteSideEffect();
1163 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1164 /// return its existing value.
1165 static int64_t getExtValue(const APSInt &Value) {
1166 return Value.isSigned() ? Value.getSExtValue()
1167 : static_cast<int64_t>(Value.getZExtValue());
1170 /// Should this call expression be treated as a string literal?
1171 static bool IsStringLiteralCall(const CallExpr *E) {
1172 unsigned Builtin = E->getBuiltinCallee();
1173 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1174 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1177 static bool IsGlobalLValue(APValue::LValueBase B) {
1178 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1179 // constant expression of pointer type that evaluates to...
1181 // ... a null pointer value, or a prvalue core constant expression of type
1183 if (!B) return true;
1185 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1186 // ... the address of an object with static storage duration,
1187 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1188 return VD->hasGlobalStorage();
1189 // ... the address of a function,
1190 return isa<FunctionDecl>(D);
1193 const Expr *E = B.get<const Expr*>();
1194 switch (E->getStmtClass()) {
1197 case Expr::CompoundLiteralExprClass: {
1198 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1199 return CLE->isFileScope() && CLE->isLValue();
1201 case Expr::MaterializeTemporaryExprClass:
1202 // A materialized temporary might have been lifetime-extended to static
1203 // storage duration.
1204 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1205 // A string literal has static storage duration.
1206 case Expr::StringLiteralClass:
1207 case Expr::PredefinedExprClass:
1208 case Expr::ObjCStringLiteralClass:
1209 case Expr::ObjCEncodeExprClass:
1210 case Expr::CXXTypeidExprClass:
1211 case Expr::CXXUuidofExprClass:
1213 case Expr::CallExprClass:
1214 return IsStringLiteralCall(cast<CallExpr>(E));
1215 // For GCC compatibility, &&label has static storage duration.
1216 case Expr::AddrLabelExprClass:
1218 // A Block literal expression may be used as the initialization value for
1219 // Block variables at global or local static scope.
1220 case Expr::BlockExprClass:
1221 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1222 case Expr::ImplicitValueInitExprClass:
1224 // We can never form an lvalue with an implicit value initialization as its
1225 // base through expression evaluation, so these only appear in one case: the
1226 // implicit variable declaration we invent when checking whether a constexpr
1227 // constructor can produce a constant expression. We must assume that such
1228 // an expression might be a global lvalue.
1233 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1234 assert(Base && "no location for a null lvalue");
1235 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1237 Info.Note(VD->getLocation(), diag::note_declared_at);
1239 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1240 diag::note_constexpr_temporary_here);
1243 /// Check that this reference or pointer core constant expression is a valid
1244 /// value for an address or reference constant expression. Return true if we
1245 /// can fold this expression, whether or not it's a constant expression.
1246 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1247 QualType Type, const LValue &LVal) {
1248 bool IsReferenceType = Type->isReferenceType();
1250 APValue::LValueBase Base = LVal.getLValueBase();
1251 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1253 // Check that the object is a global. Note that the fake 'this' object we
1254 // manufacture when checking potential constant expressions is conservatively
1255 // assumed to be global here.
1256 if (!IsGlobalLValue(Base)) {
1257 if (Info.getLangOpts().CPlusPlus11) {
1258 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1259 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1260 << IsReferenceType << !Designator.Entries.empty()
1262 NoteLValueLocation(Info, Base);
1266 // Don't allow references to temporaries to escape.
1269 assert((Info.checkingPotentialConstantExpression() ||
1270 LVal.getLValueCallIndex() == 0) &&
1271 "have call index for global lvalue");
1273 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1275 // Check if this is a thread-local variable.
1276 if (Var->getTLSKind())
1279 // A dllimport variable never acts like a constant.
1280 if (Var->hasAttr<DLLImportAttr>())
1283 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1284 // __declspec(dllimport) must be handled very carefully:
1285 // We must never initialize an expression with the thunk in C++.
1286 // Doing otherwise would allow the same id-expression to yield
1287 // different addresses for the same function in different translation
1288 // units. However, this means that we must dynamically initialize the
1289 // expression with the contents of the import address table at runtime.
1291 // The C language has no notion of ODR; furthermore, it has no notion of
1292 // dynamic initialization. This means that we are permitted to
1293 // perform initialization with the address of the thunk.
1294 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1299 // Allow address constant expressions to be past-the-end pointers. This is
1300 // an extension: the standard requires them to point to an object.
1301 if (!IsReferenceType)
1304 // A reference constant expression must refer to an object.
1306 // FIXME: diagnostic
1311 // Does this refer one past the end of some object?
1312 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1313 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1314 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1315 << !Designator.Entries.empty() << !!VD << VD;
1316 NoteLValueLocation(Info, Base);
1322 /// Check that this core constant expression is of literal type, and if not,
1323 /// produce an appropriate diagnostic.
1324 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1325 const LValue *This = nullptr) {
1326 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1329 // C++1y: A constant initializer for an object o [...] may also invoke
1330 // constexpr constructors for o and its subobjects even if those objects
1331 // are of non-literal class types.
1332 if (Info.getLangOpts().CPlusPlus14 && This &&
1333 Info.EvaluatingDecl == This->getLValueBase())
1336 // Prvalue constant expressions must be of literal types.
1337 if (Info.getLangOpts().CPlusPlus11)
1338 Info.Diag(E, diag::note_constexpr_nonliteral)
1341 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1345 /// Check that this core constant expression value is a valid value for a
1346 /// constant expression. If not, report an appropriate diagnostic. Does not
1347 /// check that the expression is of literal type.
1348 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1349 QualType Type, const APValue &Value) {
1350 if (Value.isUninit()) {
1351 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1356 // We allow _Atomic(T) to be initialized from anything that T can be
1357 // initialized from.
1358 if (const AtomicType *AT = Type->getAs<AtomicType>())
1359 Type = AT->getValueType();
1361 // Core issue 1454: For a literal constant expression of array or class type,
1362 // each subobject of its value shall have been initialized by a constant
1364 if (Value.isArray()) {
1365 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1366 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1367 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1368 Value.getArrayInitializedElt(I)))
1371 if (!Value.hasArrayFiller())
1373 return CheckConstantExpression(Info, DiagLoc, EltTy,
1374 Value.getArrayFiller());
1376 if (Value.isUnion() && Value.getUnionField()) {
1377 return CheckConstantExpression(Info, DiagLoc,
1378 Value.getUnionField()->getType(),
1379 Value.getUnionValue());
1381 if (Value.isStruct()) {
1382 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1383 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1384 unsigned BaseIndex = 0;
1385 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1386 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1387 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388 Value.getStructBase(BaseIndex)))
1392 for (const auto *I : RD->fields()) {
1393 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1394 Value.getStructField(I->getFieldIndex())))
1399 if (Value.isLValue()) {
1401 LVal.setFrom(Info.Ctx, Value);
1402 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1405 // Everything else is fine.
1409 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1410 return LVal.Base.dyn_cast<const ValueDecl*>();
1413 static bool IsLiteralLValue(const LValue &Value) {
1414 if (Value.CallIndex)
1416 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1417 return E && !isa<MaterializeTemporaryExpr>(E);
1420 static bool IsWeakLValue(const LValue &Value) {
1421 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1422 return Decl && Decl->isWeak();
1425 static bool isZeroSized(const LValue &Value) {
1426 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1427 if (Decl && isa<VarDecl>(Decl)) {
1428 QualType Ty = Decl->getType();
1429 if (Ty->isArrayType())
1430 return Ty->isIncompleteType() ||
1431 Decl->getASTContext().getTypeSize(Ty) == 0;
1436 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1437 // A null base expression indicates a null pointer. These are always
1438 // evaluatable, and they are false unless the offset is zero.
1439 if (!Value.getLValueBase()) {
1440 Result = !Value.getLValueOffset().isZero();
1444 // We have a non-null base. These are generally known to be true, but if it's
1445 // a weak declaration it can be null at runtime.
1447 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1448 return !Decl || !Decl->isWeak();
1451 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1452 switch (Val.getKind()) {
1453 case APValue::Uninitialized:
1456 Result = Val.getInt().getBoolValue();
1458 case APValue::Float:
1459 Result = !Val.getFloat().isZero();
1461 case APValue::ComplexInt:
1462 Result = Val.getComplexIntReal().getBoolValue() ||
1463 Val.getComplexIntImag().getBoolValue();
1465 case APValue::ComplexFloat:
1466 Result = !Val.getComplexFloatReal().isZero() ||
1467 !Val.getComplexFloatImag().isZero();
1469 case APValue::LValue:
1470 return EvalPointerValueAsBool(Val, Result);
1471 case APValue::MemberPointer:
1472 Result = Val.getMemberPointerDecl();
1474 case APValue::Vector:
1475 case APValue::Array:
1476 case APValue::Struct:
1477 case APValue::Union:
1478 case APValue::AddrLabelDiff:
1482 llvm_unreachable("unknown APValue kind");
1485 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1487 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1489 if (!Evaluate(Val, Info, E))
1491 return HandleConversionToBool(Val, Result);
1494 template<typename T>
1495 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1496 const T &SrcValue, QualType DestType) {
1497 Info.CCEDiag(E, diag::note_constexpr_overflow)
1498 << SrcValue << DestType;
1501 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1502 QualType SrcType, const APFloat &Value,
1503 QualType DestType, APSInt &Result) {
1504 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1505 // Determine whether we are converting to unsigned or signed.
1506 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1508 Result = APSInt(DestWidth, !DestSigned);
1510 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1511 & APFloat::opInvalidOp)
1512 HandleOverflow(Info, E, Value, DestType);
1516 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1517 QualType SrcType, QualType DestType,
1519 APFloat Value = Result;
1521 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1522 APFloat::rmNearestTiesToEven, &ignored)
1523 & APFloat::opOverflow)
1524 HandleOverflow(Info, E, Value, DestType);
1528 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1529 QualType DestType, QualType SrcType,
1531 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1532 APSInt Result = Value;
1533 // Figure out if this is a truncate, extend or noop cast.
1534 // If the input is signed, do a sign extend, noop, or truncate.
1535 Result = Result.extOrTrunc(DestWidth);
1536 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1540 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1541 QualType SrcType, const APSInt &Value,
1542 QualType DestType, APFloat &Result) {
1543 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1544 if (Result.convertFromAPInt(Value, Value.isSigned(),
1545 APFloat::rmNearestTiesToEven)
1546 & APFloat::opOverflow)
1547 HandleOverflow(Info, E, Value, DestType);
1551 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1552 APValue &Value, const FieldDecl *FD) {
1553 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1555 if (!Value.isInt()) {
1556 // Trying to store a pointer-cast-to-integer into a bitfield.
1557 // FIXME: In this case, we should provide the diagnostic for casting
1558 // a pointer to an integer.
1559 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1564 APSInt &Int = Value.getInt();
1565 unsigned OldBitWidth = Int.getBitWidth();
1566 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1567 if (NewBitWidth < OldBitWidth)
1568 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1572 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1575 if (!Evaluate(SVal, Info, E))
1578 Res = SVal.getInt();
1581 if (SVal.isFloat()) {
1582 Res = SVal.getFloat().bitcastToAPInt();
1585 if (SVal.isVector()) {
1586 QualType VecTy = E->getType();
1587 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1588 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1589 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1590 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1591 Res = llvm::APInt::getNullValue(VecSize);
1592 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1593 APValue &Elt = SVal.getVectorElt(i);
1594 llvm::APInt EltAsInt;
1596 EltAsInt = Elt.getInt();
1597 } else if (Elt.isFloat()) {
1598 EltAsInt = Elt.getFloat().bitcastToAPInt();
1600 // Don't try to handle vectors of anything other than int or float
1601 // (not sure if it's possible to hit this case).
1602 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1605 unsigned BaseEltSize = EltAsInt.getBitWidth();
1607 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1609 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1613 // Give up if the input isn't an int, float, or vector. For example, we
1614 // reject "(v4i16)(intptr_t)&a".
1615 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1619 /// Perform the given integer operation, which is known to need at most BitWidth
1620 /// bits, and check for overflow in the original type (if that type was not an
1622 template<typename Operation>
1623 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1624 const APSInt &LHS, const APSInt &RHS,
1625 unsigned BitWidth, Operation Op) {
1626 if (LHS.isUnsigned())
1627 return Op(LHS, RHS);
1629 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1630 APSInt Result = Value.trunc(LHS.getBitWidth());
1631 if (Result.extend(BitWidth) != Value) {
1632 if (Info.checkingForOverflow())
1633 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1634 diag::warn_integer_constant_overflow)
1635 << Result.toString(10) << E->getType();
1637 HandleOverflow(Info, E, Value, E->getType());
1642 /// Perform the given binary integer operation.
1643 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1644 BinaryOperatorKind Opcode, APSInt RHS,
1651 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1652 std::multiplies<APSInt>());
1655 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1656 std::plus<APSInt>());
1659 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1660 std::minus<APSInt>());
1662 case BO_And: Result = LHS & RHS; return true;
1663 case BO_Xor: Result = LHS ^ RHS; return true;
1664 case BO_Or: Result = LHS | RHS; return true;
1668 Info.Diag(E, diag::note_expr_divide_by_zero);
1671 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1672 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1673 LHS.isSigned() && LHS.isMinSignedValue())
1674 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1675 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1678 if (Info.getLangOpts().OpenCL)
1679 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1680 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1681 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1683 else if (RHS.isSigned() && RHS.isNegative()) {
1684 // During constant-folding, a negative shift is an opposite shift. Such
1685 // a shift is not a constant expression.
1686 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1691 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1692 // the shifted type.
1693 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1695 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1696 << RHS << E->getType() << LHS.getBitWidth();
1697 } else if (LHS.isSigned()) {
1698 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1699 // operand, and must not overflow the corresponding unsigned type.
1700 if (LHS.isNegative())
1701 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1702 else if (LHS.countLeadingZeros() < SA)
1703 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1709 if (Info.getLangOpts().OpenCL)
1710 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1711 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1712 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1714 else if (RHS.isSigned() && RHS.isNegative()) {
1715 // During constant-folding, a negative shift is an opposite shift. Such a
1716 // shift is not a constant expression.
1717 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1722 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1724 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1726 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1727 << RHS << E->getType() << LHS.getBitWidth();
1732 case BO_LT: Result = LHS < RHS; return true;
1733 case BO_GT: Result = LHS > RHS; return true;
1734 case BO_LE: Result = LHS <= RHS; return true;
1735 case BO_GE: Result = LHS >= RHS; return true;
1736 case BO_EQ: Result = LHS == RHS; return true;
1737 case BO_NE: Result = LHS != RHS; return true;
1741 /// Perform the given binary floating-point operation, in-place, on LHS.
1742 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1743 APFloat &LHS, BinaryOperatorKind Opcode,
1744 const APFloat &RHS) {
1750 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1753 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1756 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1759 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1763 if (LHS.isInfinity() || LHS.isNaN())
1764 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1768 /// Cast an lvalue referring to a base subobject to a derived class, by
1769 /// truncating the lvalue's path to the given length.
1770 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1771 const RecordDecl *TruncatedType,
1772 unsigned TruncatedElements) {
1773 SubobjectDesignator &D = Result.Designator;
1775 // Check we actually point to a derived class object.
1776 if (TruncatedElements == D.Entries.size())
1778 assert(TruncatedElements >= D.MostDerivedPathLength &&
1779 "not casting to a derived class");
1780 if (!Result.checkSubobject(Info, E, CSK_Derived))
1783 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1784 const RecordDecl *RD = TruncatedType;
1785 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1786 if (RD->isInvalidDecl()) return false;
1787 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1788 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1789 if (isVirtualBaseClass(D.Entries[I]))
1790 Result.Offset -= Layout.getVBaseClassOffset(Base);
1792 Result.Offset -= Layout.getBaseClassOffset(Base);
1795 D.Entries.resize(TruncatedElements);
1799 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1800 const CXXRecordDecl *Derived,
1801 const CXXRecordDecl *Base,
1802 const ASTRecordLayout *RL = nullptr) {
1804 if (Derived->isInvalidDecl()) return false;
1805 RL = &Info.Ctx.getASTRecordLayout(Derived);
1808 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1809 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1813 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1814 const CXXRecordDecl *DerivedDecl,
1815 const CXXBaseSpecifier *Base) {
1816 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1818 if (!Base->isVirtual())
1819 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1821 SubobjectDesignator &D = Obj.Designator;
1825 // Extract most-derived object and corresponding type.
1826 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1827 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1830 // Find the virtual base class.
1831 if (DerivedDecl->isInvalidDecl()) return false;
1832 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1833 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1834 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1838 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1839 QualType Type, LValue &Result) {
1840 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1841 PathE = E->path_end();
1842 PathI != PathE; ++PathI) {
1843 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1846 Type = (*PathI)->getType();
1851 /// Update LVal to refer to the given field, which must be a member of the type
1852 /// currently described by LVal.
1853 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1854 const FieldDecl *FD,
1855 const ASTRecordLayout *RL = nullptr) {
1857 if (FD->getParent()->isInvalidDecl()) return false;
1858 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1861 unsigned I = FD->getFieldIndex();
1862 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1863 LVal.addDecl(Info, E, FD);
1867 /// Update LVal to refer to the given indirect field.
1868 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1870 const IndirectFieldDecl *IFD) {
1871 for (const auto *C : IFD->chain())
1872 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
1877 /// Get the size of the given type in char units.
1878 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1879 QualType Type, CharUnits &Size) {
1880 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1882 if (Type->isVoidType() || Type->isFunctionType()) {
1883 Size = CharUnits::One();
1887 if (!Type->isConstantSizeType()) {
1888 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1889 // FIXME: Better diagnostic.
1894 Size = Info.Ctx.getTypeSizeInChars(Type);
1898 /// Update a pointer value to model pointer arithmetic.
1899 /// \param Info - Information about the ongoing evaluation.
1900 /// \param E - The expression being evaluated, for diagnostic purposes.
1901 /// \param LVal - The pointer value to be updated.
1902 /// \param EltTy - The pointee type represented by LVal.
1903 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1904 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1905 LValue &LVal, QualType EltTy,
1906 int64_t Adjustment) {
1907 CharUnits SizeOfPointee;
1908 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1911 // Compute the new offset in the appropriate width.
1912 LVal.Offset += Adjustment * SizeOfPointee;
1913 LVal.adjustIndex(Info, E, Adjustment);
1917 /// Update an lvalue to refer to a component of a complex number.
1918 /// \param Info - Information about the ongoing evaluation.
1919 /// \param LVal - The lvalue to be updated.
1920 /// \param EltTy - The complex number's component type.
1921 /// \param Imag - False for the real component, true for the imaginary.
1922 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1923 LValue &LVal, QualType EltTy,
1926 CharUnits SizeOfComponent;
1927 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1929 LVal.Offset += SizeOfComponent;
1931 LVal.addComplex(Info, E, EltTy, Imag);
1935 /// Try to evaluate the initializer for a variable declaration.
1937 /// \param Info Information about the ongoing evaluation.
1938 /// \param E An expression to be used when printing diagnostics.
1939 /// \param VD The variable whose initializer should be obtained.
1940 /// \param Frame The frame in which the variable was created. Must be null
1941 /// if this variable is not local to the evaluation.
1942 /// \param Result Filled in with a pointer to the value of the variable.
1943 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1944 const VarDecl *VD, CallStackFrame *Frame,
1946 // If this is a parameter to an active constexpr function call, perform
1947 // argument substitution.
1948 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1949 // Assume arguments of a potential constant expression are unknown
1950 // constant expressions.
1951 if (Info.checkingPotentialConstantExpression())
1953 if (!Frame || !Frame->Arguments) {
1954 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1957 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1961 // If this is a local variable, dig out its value.
1963 Result = Frame->getTemporary(VD);
1964 assert(Result && "missing value for local variable");
1968 // Dig out the initializer, and use the declaration which it's attached to.
1969 const Expr *Init = VD->getAnyInitializer(VD);
1970 if (!Init || Init->isValueDependent()) {
1971 // If we're checking a potential constant expression, the variable could be
1972 // initialized later.
1973 if (!Info.checkingPotentialConstantExpression())
1974 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1978 // If we're currently evaluating the initializer of this declaration, use that
1980 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1981 Result = Info.EvaluatingDeclValue;
1985 // Never evaluate the initializer of a weak variable. We can't be sure that
1986 // this is the definition which will be used.
1988 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1992 // Check that we can fold the initializer. In C++, we will have already done
1993 // this in the cases where it matters for conformance.
1994 SmallVector<PartialDiagnosticAt, 8> Notes;
1995 if (!VD->evaluateValue(Notes)) {
1996 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1997 Notes.size() + 1) << VD;
1998 Info.Note(VD->getLocation(), diag::note_declared_at);
1999 Info.addNotes(Notes);
2001 } else if (!VD->checkInitIsICE()) {
2002 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2003 Notes.size() + 1) << VD;
2004 Info.Note(VD->getLocation(), diag::note_declared_at);
2005 Info.addNotes(Notes);
2008 Result = VD->getEvaluatedValue();
2012 static bool IsConstNonVolatile(QualType T) {
2013 Qualifiers Quals = T.getQualifiers();
2014 return Quals.hasConst() && !Quals.hasVolatile();
2017 /// Get the base index of the given base class within an APValue representing
2018 /// the given derived class.
2019 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2020 const CXXRecordDecl *Base) {
2021 Base = Base->getCanonicalDecl();
2023 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2024 E = Derived->bases_end(); I != E; ++I, ++Index) {
2025 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2029 llvm_unreachable("base class missing from derived class's bases list");
2032 /// Extract the value of a character from a string literal.
2033 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2035 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2036 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2037 Lit = PE->getFunctionName();
2038 const StringLiteral *S = cast<StringLiteral>(Lit);
2039 const ConstantArrayType *CAT =
2040 Info.Ctx.getAsConstantArrayType(S->getType());
2041 assert(CAT && "string literal isn't an array");
2042 QualType CharType = CAT->getElementType();
2043 assert(CharType->isIntegerType() && "unexpected character type");
2045 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2046 CharType->isUnsignedIntegerType());
2047 if (Index < S->getLength())
2048 Value = S->getCodeUnit(Index);
2052 // Expand a string literal into an array of characters.
2053 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2055 const StringLiteral *S = cast<StringLiteral>(Lit);
2056 const ConstantArrayType *CAT =
2057 Info.Ctx.getAsConstantArrayType(S->getType());
2058 assert(CAT && "string literal isn't an array");
2059 QualType CharType = CAT->getElementType();
2060 assert(CharType->isIntegerType() && "unexpected character type");
2062 unsigned Elts = CAT->getSize().getZExtValue();
2063 Result = APValue(APValue::UninitArray(),
2064 std::min(S->getLength(), Elts), Elts);
2065 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2066 CharType->isUnsignedIntegerType());
2067 if (Result.hasArrayFiller())
2068 Result.getArrayFiller() = APValue(Value);
2069 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2070 Value = S->getCodeUnit(I);
2071 Result.getArrayInitializedElt(I) = APValue(Value);
2075 // Expand an array so that it has more than Index filled elements.
2076 static void expandArray(APValue &Array, unsigned Index) {
2077 unsigned Size = Array.getArraySize();
2078 assert(Index < Size);
2080 // Always at least double the number of elements for which we store a value.
2081 unsigned OldElts = Array.getArrayInitializedElts();
2082 unsigned NewElts = std::max(Index+1, OldElts * 2);
2083 NewElts = std::min(Size, std::max(NewElts, 8u));
2085 // Copy the data across.
2086 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2087 for (unsigned I = 0; I != OldElts; ++I)
2088 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2089 for (unsigned I = OldElts; I != NewElts; ++I)
2090 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2091 if (NewValue.hasArrayFiller())
2092 NewValue.getArrayFiller() = Array.getArrayFiller();
2093 Array.swap(NewValue);
2096 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2097 /// conversion. If it's of class type, we may assume that the copy operation
2098 /// is trivial. Note that this is never true for a union type with fields
2099 /// (because the copy always "reads" the active member) and always true for
2100 /// a non-class type.
2101 static bool isReadByLvalueToRvalueConversion(QualType T) {
2102 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2103 if (!RD || (RD->isUnion() && !RD->field_empty()))
2108 for (auto *Field : RD->fields())
2109 if (isReadByLvalueToRvalueConversion(Field->getType()))
2112 for (auto &BaseSpec : RD->bases())
2113 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2119 /// Diagnose an attempt to read from any unreadable field within the specified
2120 /// type, which might be a class type.
2121 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2123 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2127 if (!RD->hasMutableFields())
2130 for (auto *Field : RD->fields()) {
2131 // If we're actually going to read this field in some way, then it can't
2132 // be mutable. If we're in a union, then assigning to a mutable field
2133 // (even an empty one) can change the active member, so that's not OK.
2134 // FIXME: Add core issue number for the union case.
2135 if (Field->isMutable() &&
2136 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2137 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2138 Info.Note(Field->getLocation(), diag::note_declared_at);
2142 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2146 for (auto &BaseSpec : RD->bases())
2147 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2150 // All mutable fields were empty, and thus not actually read.
2154 /// Kinds of access we can perform on an object, for diagnostics.
2162 /// A handle to a complete object (an object that is not a subobject of
2163 /// another object).
2164 struct CompleteObject {
2165 /// The value of the complete object.
2167 /// The type of the complete object.
2170 CompleteObject() : Value(nullptr) {}
2171 CompleteObject(APValue *Value, QualType Type)
2172 : Value(Value), Type(Type) {
2173 assert(Value && "missing value for complete object");
2176 LLVM_EXPLICIT operator bool() const { return Value; }
2179 /// Find the designated sub-object of an rvalue.
2180 template<typename SubobjectHandler>
2181 typename SubobjectHandler::result_type
2182 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2183 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2185 // A diagnostic will have already been produced.
2186 return handler.failed();
2187 if (Sub.isOnePastTheEnd()) {
2188 if (Info.getLangOpts().CPlusPlus11)
2189 Info.Diag(E, diag::note_constexpr_access_past_end)
2190 << handler.AccessKind;
2193 return handler.failed();
2196 APValue *O = Obj.Value;
2197 QualType ObjType = Obj.Type;
2198 const FieldDecl *LastField = nullptr;
2200 // Walk the designator's path to find the subobject.
2201 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2202 if (O->isUninit()) {
2203 if (!Info.checkingPotentialConstantExpression())
2204 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2205 return handler.failed();
2209 // If we are reading an object of class type, there may still be more
2210 // things we need to check: if there are any mutable subobjects, we
2211 // cannot perform this read. (This only happens when performing a trivial
2212 // copy or assignment.)
2213 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2214 diagnoseUnreadableFields(Info, E, ObjType))
2215 return handler.failed();
2217 if (!handler.found(*O, ObjType))
2220 // If we modified a bit-field, truncate it to the right width.
2221 if (handler.AccessKind != AK_Read &&
2222 LastField && LastField->isBitField() &&
2223 !truncateBitfieldValue(Info, E, *O, LastField))
2229 LastField = nullptr;
2230 if (ObjType->isArrayType()) {
2231 // Next subobject is an array element.
2232 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2233 assert(CAT && "vla in literal type?");
2234 uint64_t Index = Sub.Entries[I].ArrayIndex;
2235 if (CAT->getSize().ule(Index)) {
2236 // Note, it should not be possible to form a pointer with a valid
2237 // designator which points more than one past the end of the array.
2238 if (Info.getLangOpts().CPlusPlus11)
2239 Info.Diag(E, diag::note_constexpr_access_past_end)
2240 << handler.AccessKind;
2243 return handler.failed();
2246 ObjType = CAT->getElementType();
2248 // An array object is represented as either an Array APValue or as an
2249 // LValue which refers to a string literal.
2250 if (O->isLValue()) {
2251 assert(I == N - 1 && "extracting subobject of character?");
2252 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2253 if (handler.AccessKind != AK_Read)
2254 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2257 return handler.foundString(*O, ObjType, Index);
2260 if (O->getArrayInitializedElts() > Index)
2261 O = &O->getArrayInitializedElt(Index);
2262 else if (handler.AccessKind != AK_Read) {
2263 expandArray(*O, Index);
2264 O = &O->getArrayInitializedElt(Index);
2266 O = &O->getArrayFiller();
2267 } else if (ObjType->isAnyComplexType()) {
2268 // Next subobject is a complex number.
2269 uint64_t Index = Sub.Entries[I].ArrayIndex;
2271 if (Info.getLangOpts().CPlusPlus11)
2272 Info.Diag(E, diag::note_constexpr_access_past_end)
2273 << handler.AccessKind;
2276 return handler.failed();
2279 bool WasConstQualified = ObjType.isConstQualified();
2280 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2281 if (WasConstQualified)
2284 assert(I == N - 1 && "extracting subobject of scalar?");
2285 if (O->isComplexInt()) {
2286 return handler.found(Index ? O->getComplexIntImag()
2287 : O->getComplexIntReal(), ObjType);
2289 assert(O->isComplexFloat());
2290 return handler.found(Index ? O->getComplexFloatImag()
2291 : O->getComplexFloatReal(), ObjType);
2293 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2294 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2295 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2297 Info.Note(Field->getLocation(), diag::note_declared_at);
2298 return handler.failed();
2301 // Next subobject is a class, struct or union field.
2302 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2303 if (RD->isUnion()) {
2304 const FieldDecl *UnionField = O->getUnionField();
2306 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2307 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2308 << handler.AccessKind << Field << !UnionField << UnionField;
2309 return handler.failed();
2311 O = &O->getUnionValue();
2313 O = &O->getStructField(Field->getFieldIndex());
2315 bool WasConstQualified = ObjType.isConstQualified();
2316 ObjType = Field->getType();
2317 if (WasConstQualified && !Field->isMutable())
2320 if (ObjType.isVolatileQualified()) {
2321 if (Info.getLangOpts().CPlusPlus) {
2322 // FIXME: Include a description of the path to the volatile subobject.
2323 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2324 << handler.AccessKind << 2 << Field;
2325 Info.Note(Field->getLocation(), diag::note_declared_at);
2327 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2329 return handler.failed();
2334 // Next subobject is a base class.
2335 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2336 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2337 O = &O->getStructBase(getBaseIndex(Derived, Base));
2339 bool WasConstQualified = ObjType.isConstQualified();
2340 ObjType = Info.Ctx.getRecordType(Base);
2341 if (WasConstQualified)
2348 struct ExtractSubobjectHandler {
2352 static const AccessKinds AccessKind = AK_Read;
2354 typedef bool result_type;
2355 bool failed() { return false; }
2356 bool found(APValue &Subobj, QualType SubobjType) {
2360 bool found(APSInt &Value, QualType SubobjType) {
2361 Result = APValue(Value);
2364 bool found(APFloat &Value, QualType SubobjType) {
2365 Result = APValue(Value);
2368 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2369 Result = APValue(extractStringLiteralCharacter(
2370 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2374 } // end anonymous namespace
2376 const AccessKinds ExtractSubobjectHandler::AccessKind;
2378 /// Extract the designated sub-object of an rvalue.
2379 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2380 const CompleteObject &Obj,
2381 const SubobjectDesignator &Sub,
2383 ExtractSubobjectHandler Handler = { Info, Result };
2384 return findSubobject(Info, E, Obj, Sub, Handler);
2388 struct ModifySubobjectHandler {
2393 typedef bool result_type;
2394 static const AccessKinds AccessKind = AK_Assign;
2396 bool checkConst(QualType QT) {
2397 // Assigning to a const object has undefined behavior.
2398 if (QT.isConstQualified()) {
2399 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2405 bool failed() { return false; }
2406 bool found(APValue &Subobj, QualType SubobjType) {
2407 if (!checkConst(SubobjType))
2409 // We've been given ownership of NewVal, so just swap it in.
2410 Subobj.swap(NewVal);
2413 bool found(APSInt &Value, QualType SubobjType) {
2414 if (!checkConst(SubobjType))
2416 if (!NewVal.isInt()) {
2417 // Maybe trying to write a cast pointer value into a complex?
2421 Value = NewVal.getInt();
2424 bool found(APFloat &Value, QualType SubobjType) {
2425 if (!checkConst(SubobjType))
2427 Value = NewVal.getFloat();
2430 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2431 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2434 } // end anonymous namespace
2436 const AccessKinds ModifySubobjectHandler::AccessKind;
2438 /// Update the designated sub-object of an rvalue to the given value.
2439 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2440 const CompleteObject &Obj,
2441 const SubobjectDesignator &Sub,
2443 ModifySubobjectHandler Handler = { Info, NewVal, E };
2444 return findSubobject(Info, E, Obj, Sub, Handler);
2447 /// Find the position where two subobject designators diverge, or equivalently
2448 /// the length of the common initial subsequence.
2449 static unsigned FindDesignatorMismatch(QualType ObjType,
2450 const SubobjectDesignator &A,
2451 const SubobjectDesignator &B,
2452 bool &WasArrayIndex) {
2453 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2454 for (/**/; I != N; ++I) {
2455 if (!ObjType.isNull() &&
2456 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2457 // Next subobject is an array element.
2458 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2459 WasArrayIndex = true;
2462 if (ObjType->isAnyComplexType())
2463 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2465 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2467 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2468 WasArrayIndex = false;
2471 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2472 // Next subobject is a field.
2473 ObjType = FD->getType();
2475 // Next subobject is a base class.
2476 ObjType = QualType();
2479 WasArrayIndex = false;
2483 /// Determine whether the given subobject designators refer to elements of the
2484 /// same array object.
2485 static bool AreElementsOfSameArray(QualType ObjType,
2486 const SubobjectDesignator &A,
2487 const SubobjectDesignator &B) {
2488 if (A.Entries.size() != B.Entries.size())
2491 bool IsArray = A.MostDerivedArraySize != 0;
2492 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2493 // A is a subobject of the array element.
2496 // If A (and B) designates an array element, the last entry will be the array
2497 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2498 // of length 1' case, and the entire path must match.
2500 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2501 return CommonLength >= A.Entries.size() - IsArray;
2504 /// Find the complete object to which an LValue refers.
2505 CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2506 const LValue &LVal, QualType LValType) {
2508 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2509 return CompleteObject();
2512 CallStackFrame *Frame = nullptr;
2513 if (LVal.CallIndex) {
2514 Frame = Info.getCallFrame(LVal.CallIndex);
2516 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2517 << AK << LVal.Base.is<const ValueDecl*>();
2518 NoteLValueLocation(Info, LVal.Base);
2519 return CompleteObject();
2523 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2524 // is not a constant expression (even if the object is non-volatile). We also
2525 // apply this rule to C++98, in order to conform to the expected 'volatile'
2527 if (LValType.isVolatileQualified()) {
2528 if (Info.getLangOpts().CPlusPlus)
2529 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2533 return CompleteObject();
2536 // Compute value storage location and type of base object.
2537 APValue *BaseVal = nullptr;
2538 QualType BaseType = getType(LVal.Base);
2540 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2541 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2542 // In C++11, constexpr, non-volatile variables initialized with constant
2543 // expressions are constant expressions too. Inside constexpr functions,
2544 // parameters are constant expressions even if they're non-const.
2545 // In C++1y, objects local to a constant expression (those with a Frame) are
2546 // both readable and writable inside constant expressions.
2547 // In C, such things can also be folded, although they are not ICEs.
2548 const VarDecl *VD = dyn_cast<VarDecl>(D);
2550 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2553 if (!VD || VD->isInvalidDecl()) {
2555 return CompleteObject();
2558 // Accesses of volatile-qualified objects are not allowed.
2559 if (BaseType.isVolatileQualified()) {
2560 if (Info.getLangOpts().CPlusPlus) {
2561 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2563 Info.Note(VD->getLocation(), diag::note_declared_at);
2567 return CompleteObject();
2570 // Unless we're looking at a local variable or argument in a constexpr call,
2571 // the variable we're reading must be const.
2573 if (Info.getLangOpts().CPlusPlus14 &&
2574 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2575 // OK, we can read and modify an object if we're in the process of
2576 // evaluating its initializer, because its lifetime began in this
2578 } else if (AK != AK_Read) {
2579 // All the remaining cases only permit reading.
2580 Info.Diag(E, diag::note_constexpr_modify_global);
2581 return CompleteObject();
2582 } else if (VD->isConstexpr()) {
2583 // OK, we can read this variable.
2584 } else if (BaseType->isIntegralOrEnumerationType()) {
2585 if (!BaseType.isConstQualified()) {
2586 if (Info.getLangOpts().CPlusPlus) {
2587 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2588 Info.Note(VD->getLocation(), diag::note_declared_at);
2592 return CompleteObject();
2594 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2595 // We support folding of const floating-point types, in order to make
2596 // static const data members of such types (supported as an extension)
2598 if (Info.getLangOpts().CPlusPlus11) {
2599 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2600 Info.Note(VD->getLocation(), diag::note_declared_at);
2605 // FIXME: Allow folding of values of any literal type in all languages.
2606 if (Info.getLangOpts().CPlusPlus11) {
2607 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2608 Info.Note(VD->getLocation(), diag::note_declared_at);
2612 return CompleteObject();
2616 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2617 return CompleteObject();
2619 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2622 if (const MaterializeTemporaryExpr *MTE =
2623 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2624 assert(MTE->getStorageDuration() == SD_Static &&
2625 "should have a frame for a non-global materialized temporary");
2627 // Per C++1y [expr.const]p2:
2628 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2629 // - a [...] glvalue of integral or enumeration type that refers to
2630 // a non-volatile const object [...]
2632 // - a [...] glvalue of literal type that refers to a non-volatile
2633 // object whose lifetime began within the evaluation of e.
2635 // C++11 misses the 'began within the evaluation of e' check and
2636 // instead allows all temporaries, including things like:
2639 // constexpr int k = r;
2640 // Therefore we use the C++1y rules in C++11 too.
2641 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2642 const ValueDecl *ED = MTE->getExtendingDecl();
2643 if (!(BaseType.isConstQualified() &&
2644 BaseType->isIntegralOrEnumerationType()) &&
2645 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2646 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2647 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2648 return CompleteObject();
2651 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2652 assert(BaseVal && "got reference to unevaluated temporary");
2655 return CompleteObject();
2658 BaseVal = Frame->getTemporary(Base);
2659 assert(BaseVal && "missing value for temporary");
2662 // Volatile temporary objects cannot be accessed in constant expressions.
2663 if (BaseType.isVolatileQualified()) {
2664 if (Info.getLangOpts().CPlusPlus) {
2665 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2667 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2671 return CompleteObject();
2675 // During the construction of an object, it is not yet 'const'.
2676 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2677 // and this doesn't do quite the right thing for const subobjects of the
2678 // object under construction.
2679 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2680 BaseType = Info.Ctx.getCanonicalType(BaseType);
2681 BaseType.removeLocalConst();
2684 // In C++1y, we can't safely access any mutable state when we might be
2685 // evaluating after an unmodeled side effect or an evaluation failure.
2687 // FIXME: Not all local state is mutable. Allow local constant subobjects
2688 // to be read here (but take care with 'mutable' fields).
2689 if (Frame && Info.getLangOpts().CPlusPlus14 &&
2690 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2691 return CompleteObject();
2693 return CompleteObject(BaseVal, BaseType);
2696 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2697 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2698 /// glvalue referred to by an entity of reference type.
2700 /// \param Info - Information about the ongoing evaluation.
2701 /// \param Conv - The expression for which we are performing the conversion.
2702 /// Used for diagnostics.
2703 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2704 /// case of a non-class type).
2705 /// \param LVal - The glvalue on which we are attempting to perform this action.
2706 /// \param RVal - The produced value will be placed here.
2707 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2709 const LValue &LVal, APValue &RVal) {
2710 if (LVal.Designator.Invalid)
2713 // Check for special cases where there is no existing APValue to look at.
2714 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2715 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2716 !Type.isVolatileQualified()) {
2717 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2718 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2719 // initializer until now for such expressions. Such an expression can't be
2720 // an ICE in C, so this only matters for fold.
2721 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2722 if (Type.isVolatileQualified()) {
2727 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2729 CompleteObject LitObj(&Lit, Base->getType());
2730 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2731 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
2732 // We represent a string literal array as an lvalue pointing at the
2733 // corresponding expression, rather than building an array of chars.
2734 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2735 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2736 CompleteObject StrObj(&Str, Base->getType());
2737 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2741 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2742 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2745 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2746 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2747 QualType LValType, APValue &Val) {
2748 if (LVal.Designator.Invalid)
2751 if (!Info.getLangOpts().CPlusPlus14) {
2756 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2757 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2760 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2761 return T->isSignedIntegerType() &&
2762 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2766 struct CompoundAssignSubobjectHandler {
2769 QualType PromotedLHSType;
2770 BinaryOperatorKind Opcode;
2773 static const AccessKinds AccessKind = AK_Assign;
2775 typedef bool result_type;
2777 bool checkConst(QualType QT) {
2778 // Assigning to a const object has undefined behavior.
2779 if (QT.isConstQualified()) {
2780 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2786 bool failed() { return false; }
2787 bool found(APValue &Subobj, QualType SubobjType) {
2788 switch (Subobj.getKind()) {
2790 return found(Subobj.getInt(), SubobjType);
2791 case APValue::Float:
2792 return found(Subobj.getFloat(), SubobjType);
2793 case APValue::ComplexInt:
2794 case APValue::ComplexFloat:
2795 // FIXME: Implement complex compound assignment.
2798 case APValue::LValue:
2799 return foundPointer(Subobj, SubobjType);
2801 // FIXME: can this happen?
2806 bool found(APSInt &Value, QualType SubobjType) {
2807 if (!checkConst(SubobjType))
2810 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2811 // We don't support compound assignment on integer-cast-to-pointer
2817 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2819 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2821 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2824 bool found(APFloat &Value, QualType SubobjType) {
2825 return checkConst(SubobjType) &&
2826 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2828 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2829 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2831 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2832 if (!checkConst(SubobjType))
2835 QualType PointeeType;
2836 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2837 PointeeType = PT->getPointeeType();
2839 if (PointeeType.isNull() || !RHS.isInt() ||
2840 (Opcode != BO_Add && Opcode != BO_Sub)) {
2845 int64_t Offset = getExtValue(RHS.getInt());
2846 if (Opcode == BO_Sub)
2850 LVal.setFrom(Info.Ctx, Subobj);
2851 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2853 LVal.moveInto(Subobj);
2856 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2857 llvm_unreachable("shouldn't encounter string elements here");
2860 } // end anonymous namespace
2862 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2864 /// Perform a compound assignment of LVal <op>= RVal.
2865 static bool handleCompoundAssignment(
2866 EvalInfo &Info, const Expr *E,
2867 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2868 BinaryOperatorKind Opcode, const APValue &RVal) {
2869 if (LVal.Designator.Invalid)
2872 if (!Info.getLangOpts().CPlusPlus14) {
2877 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2878 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2880 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2884 struct IncDecSubobjectHandler {
2887 AccessKinds AccessKind;
2890 typedef bool result_type;
2892 bool checkConst(QualType QT) {
2893 // Assigning to a const object has undefined behavior.
2894 if (QT.isConstQualified()) {
2895 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2901 bool failed() { return false; }
2902 bool found(APValue &Subobj, QualType SubobjType) {
2903 // Stash the old value. Also clear Old, so we don't clobber it later
2904 // if we're post-incrementing a complex.
2910 switch (Subobj.getKind()) {
2912 return found(Subobj.getInt(), SubobjType);
2913 case APValue::Float:
2914 return found(Subobj.getFloat(), SubobjType);
2915 case APValue::ComplexInt:
2916 return found(Subobj.getComplexIntReal(),
2917 SubobjType->castAs<ComplexType>()->getElementType()
2918 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2919 case APValue::ComplexFloat:
2920 return found(Subobj.getComplexFloatReal(),
2921 SubobjType->castAs<ComplexType>()->getElementType()
2922 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2923 case APValue::LValue:
2924 return foundPointer(Subobj, SubobjType);
2926 // FIXME: can this happen?
2931 bool found(APSInt &Value, QualType SubobjType) {
2932 if (!checkConst(SubobjType))
2935 if (!SubobjType->isIntegerType()) {
2936 // We don't support increment / decrement on integer-cast-to-pointer
2942 if (Old) *Old = APValue(Value);
2944 // bool arithmetic promotes to int, and the conversion back to bool
2945 // doesn't reduce mod 2^n, so special-case it.
2946 if (SubobjType->isBooleanType()) {
2947 if (AccessKind == AK_Increment)
2954 bool WasNegative = Value.isNegative();
2955 if (AccessKind == AK_Increment) {
2958 if (!WasNegative && Value.isNegative() &&
2959 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2960 APSInt ActualValue(Value, /*IsUnsigned*/true);
2961 HandleOverflow(Info, E, ActualValue, SubobjType);
2966 if (WasNegative && !Value.isNegative() &&
2967 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2968 unsigned BitWidth = Value.getBitWidth();
2969 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2970 ActualValue.setBit(BitWidth);
2971 HandleOverflow(Info, E, ActualValue, SubobjType);
2976 bool found(APFloat &Value, QualType SubobjType) {
2977 if (!checkConst(SubobjType))
2980 if (Old) *Old = APValue(Value);
2982 APFloat One(Value.getSemantics(), 1);
2983 if (AccessKind == AK_Increment)
2984 Value.add(One, APFloat::rmNearestTiesToEven);
2986 Value.subtract(One, APFloat::rmNearestTiesToEven);
2989 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2990 if (!checkConst(SubobjType))
2993 QualType PointeeType;
2994 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2995 PointeeType = PT->getPointeeType();
3002 LVal.setFrom(Info.Ctx, Subobj);
3003 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3004 AccessKind == AK_Increment ? 1 : -1))
3006 LVal.moveInto(Subobj);
3009 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3010 llvm_unreachable("shouldn't encounter string elements here");
3013 } // end anonymous namespace
3015 /// Perform an increment or decrement on LVal.
3016 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3017 QualType LValType, bool IsIncrement, APValue *Old) {
3018 if (LVal.Designator.Invalid)
3021 if (!Info.getLangOpts().CPlusPlus14) {
3026 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3027 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3028 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3029 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3032 /// Build an lvalue for the object argument of a member function call.
3033 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3035 if (Object->getType()->isPointerType())
3036 return EvaluatePointer(Object, This, Info);
3038 if (Object->isGLValue())
3039 return EvaluateLValue(Object, This, Info);
3041 if (Object->getType()->isLiteralType(Info.Ctx))
3042 return EvaluateTemporary(Object, This, Info);
3044 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3048 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3049 /// lvalue referring to the result.
3051 /// \param Info - Information about the ongoing evaluation.
3052 /// \param LV - An lvalue referring to the base of the member pointer.
3053 /// \param RHS - The member pointer expression.
3054 /// \param IncludeMember - Specifies whether the member itself is included in
3055 /// the resulting LValue subobject designator. This is not possible when
3056 /// creating a bound member function.
3057 /// \return The field or method declaration to which the member pointer refers,
3058 /// or 0 if evaluation fails.
3059 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3063 bool IncludeMember = true) {
3065 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3068 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3069 // member value, the behavior is undefined.
3070 if (!MemPtr.getDecl()) {
3071 // FIXME: Specific diagnostic.
3076 if (MemPtr.isDerivedMember()) {
3077 // This is a member of some derived class. Truncate LV appropriately.
3078 // The end of the derived-to-base path for the base object must match the
3079 // derived-to-base path for the member pointer.
3080 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3081 LV.Designator.Entries.size()) {
3085 unsigned PathLengthToMember =
3086 LV.Designator.Entries.size() - MemPtr.Path.size();
3087 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3088 const CXXRecordDecl *LVDecl = getAsBaseClass(
3089 LV.Designator.Entries[PathLengthToMember + I]);
3090 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3091 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3097 // Truncate the lvalue to the appropriate derived class.
3098 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3099 PathLengthToMember))
3101 } else if (!MemPtr.Path.empty()) {
3102 // Extend the LValue path with the member pointer's path.
3103 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3104 MemPtr.Path.size() + IncludeMember);
3106 // Walk down to the appropriate base class.
3107 if (const PointerType *PT = LVType->getAs<PointerType>())
3108 LVType = PT->getPointeeType();
3109 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3110 assert(RD && "member pointer access on non-class-type expression");
3111 // The first class in the path is that of the lvalue.
3112 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3113 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3114 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3118 // Finally cast to the class containing the member.
3119 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3120 MemPtr.getContainingRecord()))
3124 // Add the member. Note that we cannot build bound member functions here.
3125 if (IncludeMember) {
3126 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3127 if (!HandleLValueMember(Info, RHS, LV, FD))
3129 } else if (const IndirectFieldDecl *IFD =
3130 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3131 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3134 llvm_unreachable("can't construct reference to bound member function");
3138 return MemPtr.getDecl();
3141 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3142 const BinaryOperator *BO,
3144 bool IncludeMember = true) {
3145 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3147 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3148 if (Info.keepEvaluatingAfterFailure()) {
3150 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3155 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3156 BO->getRHS(), IncludeMember);
3159 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3160 /// the provided lvalue, which currently refers to the base object.
3161 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3163 SubobjectDesignator &D = Result.Designator;
3164 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3167 QualType TargetQT = E->getType();
3168 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3169 TargetQT = PT->getPointeeType();
3171 // Check this cast lands within the final derived-to-base subobject path.
3172 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3173 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3174 << D.MostDerivedType << TargetQT;
3178 // Check the type of the final cast. We don't need to check the path,
3179 // since a cast can only be formed if the path is unique.
3180 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3181 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3182 const CXXRecordDecl *FinalType;
3183 if (NewEntriesSize == D.MostDerivedPathLength)
3184 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3186 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3187 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3188 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3189 << D.MostDerivedType << TargetQT;
3193 // Truncate the lvalue to the appropriate derived class.
3194 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3198 enum EvalStmtResult {
3199 /// Evaluation failed.
3201 /// Hit a 'return' statement.
3203 /// Evaluation succeeded.
3205 /// Hit a 'continue' statement.
3207 /// Hit a 'break' statement.
3209 /// Still scanning for 'case' or 'default' statement.
3214 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3215 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3216 // We don't need to evaluate the initializer for a static local.
3217 if (!VD->hasLocalStorage())
3221 Result.set(VD, Info.CurrentCall->Index);
3222 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3224 const Expr *InitE = VD->getInit();
3226 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3227 << false << VD->getType();
3232 if (InitE->isValueDependent())
3235 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3236 // Wipe out any partially-computed value, to allow tracking that this
3237 // evaluation failed.
3246 /// Evaluate a condition (either a variable declaration or an expression).
3247 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3248 const Expr *Cond, bool &Result) {
3249 FullExpressionRAII Scope(Info);
3250 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3252 return EvaluateAsBooleanCondition(Cond, Result, Info);
3255 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3257 const SwitchCase *SC = nullptr);
3259 /// Evaluate the body of a loop, and translate the result as appropriate.
3260 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3262 const SwitchCase *Case = nullptr) {
3263 BlockScopeRAII Scope(Info);
3264 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3266 return ESR_Succeeded;
3269 return ESR_Continue;
3272 case ESR_CaseNotFound:
3275 llvm_unreachable("Invalid EvalStmtResult!");
3278 /// Evaluate a switch statement.
3279 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3280 const SwitchStmt *SS) {
3281 BlockScopeRAII Scope(Info);
3283 // Evaluate the switch condition.
3286 FullExpressionRAII Scope(Info);
3287 if (SS->getConditionVariable() &&
3288 !EvaluateDecl(Info, SS->getConditionVariable()))
3290 if (!EvaluateInteger(SS->getCond(), Value, Info))
3294 // Find the switch case corresponding to the value of the condition.
3295 // FIXME: Cache this lookup.
3296 const SwitchCase *Found = nullptr;
3297 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3298 SC = SC->getNextSwitchCase()) {
3299 if (isa<DefaultStmt>(SC)) {
3304 const CaseStmt *CS = cast<CaseStmt>(SC);
3305 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3306 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3308 if (LHS <= Value && Value <= RHS) {
3315 return ESR_Succeeded;
3317 // Search the switch body for the switch case and evaluate it from there.
3318 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3320 return ESR_Succeeded;
3326 case ESR_CaseNotFound:
3327 // This can only happen if the switch case is nested within a statement
3328 // expression. We have no intention of supporting that.
3329 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3332 llvm_unreachable("Invalid EvalStmtResult!");
3335 // Evaluate a statement.
3336 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3337 const Stmt *S, const SwitchCase *Case) {
3338 if (!Info.nextStep(S))
3341 // If we're hunting down a 'case' or 'default' label, recurse through
3342 // substatements until we hit the label.
3344 // FIXME: We don't start the lifetime of objects whose initialization we
3345 // jump over. However, such objects must be of class type with a trivial
3346 // default constructor that initialize all subobjects, so must be empty,
3347 // so this almost never matters.
3348 switch (S->getStmtClass()) {
3349 case Stmt::CompoundStmtClass:
3350 // FIXME: Precompute which substatement of a compound statement we
3351 // would jump to, and go straight there rather than performing a
3352 // linear scan each time.
3353 case Stmt::LabelStmtClass:
3354 case Stmt::AttributedStmtClass:
3355 case Stmt::DoStmtClass:
3358 case Stmt::CaseStmtClass:
3359 case Stmt::DefaultStmtClass:
3364 case Stmt::IfStmtClass: {
3365 // FIXME: Precompute which side of an 'if' we would jump to, and go
3366 // straight there rather than scanning both sides.
3367 const IfStmt *IS = cast<IfStmt>(S);
3369 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3370 // preceded by our switch label.
3371 BlockScopeRAII Scope(Info);
3373 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3374 if (ESR != ESR_CaseNotFound || !IS->getElse())
3376 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3379 case Stmt::WhileStmtClass: {
3380 EvalStmtResult ESR =
3381 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3382 if (ESR != ESR_Continue)
3387 case Stmt::ForStmtClass: {
3388 const ForStmt *FS = cast<ForStmt>(S);
3389 EvalStmtResult ESR =
3390 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3391 if (ESR != ESR_Continue)
3394 FullExpressionRAII IncScope(Info);
3395 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3401 case Stmt::DeclStmtClass:
3402 // FIXME: If the variable has initialization that can't be jumped over,
3403 // bail out of any immediately-surrounding compound-statement too.
3405 return ESR_CaseNotFound;
3409 switch (S->getStmtClass()) {
3411 if (const Expr *E = dyn_cast<Expr>(S)) {
3412 // Don't bother evaluating beyond an expression-statement which couldn't
3414 FullExpressionRAII Scope(Info);
3415 if (!EvaluateIgnoredValue(Info, E))
3417 return ESR_Succeeded;
3420 Info.Diag(S->getLocStart());
3423 case Stmt::NullStmtClass:
3424 return ESR_Succeeded;
3426 case Stmt::DeclStmtClass: {
3427 const DeclStmt *DS = cast<DeclStmt>(S);
3428 for (const auto *DclIt : DS->decls()) {
3429 // Each declaration initialization is its own full-expression.
3430 // FIXME: This isn't quite right; if we're performing aggregate
3431 // initialization, each braced subexpression is its own full-expression.
3432 FullExpressionRAII Scope(Info);
3433 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3436 return ESR_Succeeded;
3439 case Stmt::ReturnStmtClass: {
3440 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3441 FullExpressionRAII Scope(Info);
3442 if (RetExpr && !Evaluate(Result, Info, RetExpr))
3444 return ESR_Returned;
3447 case Stmt::CompoundStmtClass: {
3448 BlockScopeRAII Scope(Info);
3450 const CompoundStmt *CS = cast<CompoundStmt>(S);
3451 for (const auto *BI : CS->body()) {
3452 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3453 if (ESR == ESR_Succeeded)
3455 else if (ESR != ESR_CaseNotFound)
3458 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3461 case Stmt::IfStmtClass: {
3462 const IfStmt *IS = cast<IfStmt>(S);
3464 // Evaluate the condition, as either a var decl or as an expression.
3465 BlockScopeRAII Scope(Info);
3467 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3470 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3471 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3472 if (ESR != ESR_Succeeded)
3475 return ESR_Succeeded;
3478 case Stmt::WhileStmtClass: {
3479 const WhileStmt *WS = cast<WhileStmt>(S);
3481 BlockScopeRAII Scope(Info);
3483 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3489 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3490 if (ESR != ESR_Continue)
3493 return ESR_Succeeded;
3496 case Stmt::DoStmtClass: {
3497 const DoStmt *DS = cast<DoStmt>(S);
3500 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3501 if (ESR != ESR_Continue)
3505 FullExpressionRAII CondScope(Info);
3506 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3509 return ESR_Succeeded;
3512 case Stmt::ForStmtClass: {
3513 const ForStmt *FS = cast<ForStmt>(S);
3514 BlockScopeRAII Scope(Info);
3515 if (FS->getInit()) {
3516 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3517 if (ESR != ESR_Succeeded)
3521 BlockScopeRAII Scope(Info);
3522 bool Continue = true;
3523 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3524 FS->getCond(), Continue))
3529 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3530 if (ESR != ESR_Continue)
3534 FullExpressionRAII IncScope(Info);
3535 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3539 return ESR_Succeeded;
3542 case Stmt::CXXForRangeStmtClass: {
3543 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3544 BlockScopeRAII Scope(Info);
3546 // Initialize the __range variable.
3547 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3548 if (ESR != ESR_Succeeded)
3551 // Create the __begin and __end iterators.
3552 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3553 if (ESR != ESR_Succeeded)
3557 // Condition: __begin != __end.
3559 bool Continue = true;
3560 FullExpressionRAII CondExpr(Info);
3561 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3567 // User's variable declaration, initialized by *__begin.
3568 BlockScopeRAII InnerScope(Info);
3569 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3570 if (ESR != ESR_Succeeded)
3574 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3575 if (ESR != ESR_Continue)
3578 // Increment: ++__begin
3579 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3583 return ESR_Succeeded;
3586 case Stmt::SwitchStmtClass:
3587 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3589 case Stmt::ContinueStmtClass:
3590 return ESR_Continue;
3592 case Stmt::BreakStmtClass:
3595 case Stmt::LabelStmtClass:
3596 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3598 case Stmt::AttributedStmtClass:
3599 // As a general principle, C++11 attributes can be ignored without
3600 // any semantic impact.
3601 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3604 case Stmt::CaseStmtClass:
3605 case Stmt::DefaultStmtClass:
3606 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3610 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3611 /// default constructor. If so, we'll fold it whether or not it's marked as
3612 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3613 /// so we need special handling.
3614 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3615 const CXXConstructorDecl *CD,
3616 bool IsValueInitialization) {
3617 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3620 // Value-initialization does not call a trivial default constructor, so such a
3621 // call is a core constant expression whether or not the constructor is
3623 if (!CD->isConstexpr() && !IsValueInitialization) {
3624 if (Info.getLangOpts().CPlusPlus11) {
3625 // FIXME: If DiagDecl is an implicitly-declared special member function,
3626 // we should be much more explicit about why it's not constexpr.
3627 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3628 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3629 Info.Note(CD->getLocation(), diag::note_declared_at);
3631 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3637 /// CheckConstexprFunction - Check that a function can be called in a constant
3639 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3640 const FunctionDecl *Declaration,
3641 const FunctionDecl *Definition) {
3642 // Potential constant expressions can contain calls to declared, but not yet
3643 // defined, constexpr functions.
3644 if (Info.checkingPotentialConstantExpression() && !Definition &&
3645 Declaration->isConstexpr())
3648 // Bail out with no diagnostic if the function declaration itself is invalid.
3649 // We will have produced a relevant diagnostic while parsing it.
3650 if (Declaration->isInvalidDecl())
3653 // Can we evaluate this function call?
3654 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3657 if (Info.getLangOpts().CPlusPlus11) {
3658 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3659 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3660 // should be much more explicit about why it's not constexpr.
3661 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3662 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3664 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3666 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3671 /// Determine if a class has any fields that might need to be copied by a
3672 /// trivial copy or move operation.
3673 static bool hasFields(const CXXRecordDecl *RD) {
3674 if (!RD || RD->isEmpty())
3676 for (auto *FD : RD->fields()) {
3677 if (FD->isUnnamedBitfield())
3681 for (auto &Base : RD->bases())
3682 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3688 typedef SmallVector<APValue, 8> ArgVector;
3691 /// EvaluateArgs - Evaluate the arguments to a function call.
3692 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3694 bool Success = true;
3695 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3697 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3698 // If we're checking for a potential constant expression, evaluate all
3699 // initializers even if some of them fail.
3700 if (!Info.keepEvaluatingAfterFailure())
3708 /// Evaluate a function call.
3709 static bool HandleFunctionCall(SourceLocation CallLoc,
3710 const FunctionDecl *Callee, const LValue *This,
3711 ArrayRef<const Expr*> Args, const Stmt *Body,
3712 EvalInfo &Info, APValue &Result) {
3713 ArgVector ArgValues(Args.size());
3714 if (!EvaluateArgs(Args, ArgValues, Info))
3717 if (!Info.CheckCallLimit(CallLoc))
3720 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3722 // For a trivial copy or move assignment, perform an APValue copy. This is
3723 // essential for unions, where the operations performed by the assignment
3724 // operator cannot be represented as statements.
3726 // Skip this for non-union classes with no fields; in that case, the defaulted
3727 // copy/move does not actually read the object.
3728 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3729 if (MD && MD->isDefaulted() && MD->isTrivial() &&
3730 (MD->getParent()->isUnion() || hasFields(MD->getParent()))) {
3732 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3734 RHS.setFrom(Info.Ctx, ArgValues[0]);
3736 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3739 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3742 This->moveInto(Result);
3746 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3747 if (ESR == ESR_Succeeded) {
3748 if (Callee->getReturnType()->isVoidType())
3750 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3752 return ESR == ESR_Returned;
3755 /// Evaluate a constructor call.
3756 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3757 ArrayRef<const Expr*> Args,
3758 const CXXConstructorDecl *Definition,
3759 EvalInfo &Info, APValue &Result) {
3760 ArgVector ArgValues(Args.size());
3761 if (!EvaluateArgs(Args, ArgValues, Info))
3764 if (!Info.CheckCallLimit(CallLoc))
3767 const CXXRecordDecl *RD = Definition->getParent();
3768 if (RD->getNumVBases()) {
3769 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3773 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3775 // If it's a delegating constructor, just delegate.
3776 if (Definition->isDelegatingConstructor()) {
3777 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3779 FullExpressionRAII InitScope(Info);
3780 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3783 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3786 // For a trivial copy or move constructor, perform an APValue copy. This is
3787 // essential for unions (or classes with anonymous union members), where the
3788 // operations performed by the constructor cannot be represented by
3789 // ctor-initializers.
3791 // Skip this for empty non-union classes; we should not perform an
3792 // lvalue-to-rvalue conversion on them because their copy constructor does not
3793 // actually read them.
3794 if (Definition->isDefaulted() &&
3795 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3796 (Definition->isMoveConstructor() && Definition->isTrivial())) &&
3797 (Definition->getParent()->isUnion() ||
3798 hasFields(Definition->getParent()))) {
3800 RHS.setFrom(Info.Ctx, ArgValues[0]);
3801 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3805 // Reserve space for the struct members.
3806 if (!RD->isUnion() && Result.isUninit())
3807 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3808 std::distance(RD->field_begin(), RD->field_end()));
3810 if (RD->isInvalidDecl()) return false;
3811 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3813 // A scope for temporaries lifetime-extended by reference members.
3814 BlockScopeRAII LifetimeExtendedScope(Info);
3816 bool Success = true;
3817 unsigned BasesSeen = 0;
3819 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3821 for (const auto *I : Definition->inits()) {
3822 LValue Subobject = This;
3823 APValue *Value = &Result;
3825 // Determine the subobject to initialize.
3826 FieldDecl *FD = nullptr;
3827 if (I->isBaseInitializer()) {
3828 QualType BaseType(I->getBaseClass(), 0);
3830 // Non-virtual base classes are initialized in the order in the class
3831 // definition. We have already checked for virtual base classes.
3832 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3833 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3834 "base class initializers not in expected order");
3837 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
3838 BaseType->getAsCXXRecordDecl(), &Layout))
3840 Value = &Result.getStructBase(BasesSeen++);
3841 } else if ((FD = I->getMember())) {
3842 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
3844 if (RD->isUnion()) {
3845 Result = APValue(FD);
3846 Value = &Result.getUnionValue();
3848 Value = &Result.getStructField(FD->getFieldIndex());
3850 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
3851 // Walk the indirect field decl's chain to find the object to initialize,
3852 // and make sure we've initialized every step along it.
3853 for (auto *C : IFD->chain()) {
3854 FD = cast<FieldDecl>(C);
3855 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3856 // Switch the union field if it differs. This happens if we had
3857 // preceding zero-initialization, and we're now initializing a union
3858 // subobject other than the first.
3859 // FIXME: In this case, the values of the other subobjects are
3860 // specified, since zero-initialization sets all padding bits to zero.
3861 if (Value->isUninit() ||
3862 (Value->isUnion() && Value->getUnionField() != FD)) {
3864 *Value = APValue(FD);
3866 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3867 std::distance(CD->field_begin(), CD->field_end()));
3869 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
3872 Value = &Value->getUnionValue();
3874 Value = &Value->getStructField(FD->getFieldIndex());
3877 llvm_unreachable("unknown base initializer kind");
3880 FullExpressionRAII InitScope(Info);
3881 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3882 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
3884 // If we're checking for a potential constant expression, evaluate all
3885 // initializers even if some of them fail.
3886 if (!Info.keepEvaluatingAfterFailure())
3893 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3896 //===----------------------------------------------------------------------===//
3897 // Generic Evaluation
3898 //===----------------------------------------------------------------------===//
3901 template <class Derived>
3902 class ExprEvaluatorBase
3903 : public ConstStmtVisitor<Derived, bool> {
3905 bool DerivedSuccess(const APValue &V, const Expr *E) {
3906 return static_cast<Derived*>(this)->Success(V, E);
3908 bool DerivedZeroInitialization(const Expr *E) {
3909 return static_cast<Derived*>(this)->ZeroInitialization(E);
3912 // Check whether a conditional operator with a non-constant condition is a
3913 // potential constant expression. If neither arm is a potential constant
3914 // expression, then the conditional operator is not either.
3915 template<typename ConditionalOperator>
3916 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3917 assert(Info.checkingPotentialConstantExpression());
3919 // Speculatively evaluate both arms.
3921 SmallVector<PartialDiagnosticAt, 8> Diag;
3922 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3924 StmtVisitorTy::Visit(E->getFalseExpr());
3929 StmtVisitorTy::Visit(E->getTrueExpr());
3934 Error(E, diag::note_constexpr_conditional_never_const);
3938 template<typename ConditionalOperator>
3939 bool HandleConditionalOperator(const ConditionalOperator *E) {
3941 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3942 if (Info.checkingPotentialConstantExpression())
3943 CheckPotentialConstantConditional(E);
3947 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3948 return StmtVisitorTy::Visit(EvalExpr);
3953 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
3954 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3956 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3957 return Info.CCEDiag(E, D);
3960 bool ZeroInitialization(const Expr *E) { return Error(E); }
3963 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3965 EvalInfo &getEvalInfo() { return Info; }
3967 /// Report an evaluation error. This should only be called when an error is
3968 /// first discovered. When propagating an error, just return false.
3969 bool Error(const Expr *E, diag::kind D) {
3973 bool Error(const Expr *E) {
3974 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3977 bool VisitStmt(const Stmt *) {
3978 llvm_unreachable("Expression evaluator should not be called on stmts");
3980 bool VisitExpr(const Expr *E) {
3984 bool VisitParenExpr(const ParenExpr *E)
3985 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3986 bool VisitUnaryExtension(const UnaryOperator *E)
3987 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3988 bool VisitUnaryPlus(const UnaryOperator *E)
3989 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3990 bool VisitChooseExpr(const ChooseExpr *E)
3991 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
3992 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3993 { return StmtVisitorTy::Visit(E->getResultExpr()); }
3994 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3995 { return StmtVisitorTy::Visit(E->getReplacement()); }
3996 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3997 { return StmtVisitorTy::Visit(E->getExpr()); }
3998 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3999 // The initializer may not have been parsed yet, or might be erroneous.
4002 return StmtVisitorTy::Visit(E->getExpr());
4004 // We cannot create any objects for which cleanups are required, so there is
4005 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4006 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4007 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4009 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4010 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4011 return static_cast<Derived*>(this)->VisitCastExpr(E);
4013 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4014 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4015 return static_cast<Derived*>(this)->VisitCastExpr(E);
4018 bool VisitBinaryOperator(const BinaryOperator *E) {
4019 switch (E->getOpcode()) {
4024 VisitIgnoredValue(E->getLHS());
4025 return StmtVisitorTy::Visit(E->getRHS());
4030 if (!HandleMemberPointerAccess(Info, E, Obj))
4033 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4035 return DerivedSuccess(Result, E);
4040 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4041 // Evaluate and cache the common expression. We treat it as a temporary,
4042 // even though it's not quite the same thing.
4043 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4044 Info, E->getCommon()))
4047 return HandleConditionalOperator(E);
4050 bool VisitConditionalOperator(const ConditionalOperator *E) {
4051 bool IsBcpCall = false;
4052 // If the condition (ignoring parens) is a __builtin_constant_p call,
4053 // the result is a constant expression if it can be folded without
4054 // side-effects. This is an important GNU extension. See GCC PR38377
4056 if (const CallExpr *CallCE =
4057 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4058 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4061 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4062 // constant expression; we can't check whether it's potentially foldable.
4063 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4066 FoldConstant Fold(Info, IsBcpCall);
4067 if (!HandleConditionalOperator(E)) {
4068 Fold.keepDiagnostics();
4075 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4076 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4077 return DerivedSuccess(*Value, E);
4079 const Expr *Source = E->getSourceExpr();
4082 if (Source == E) { // sanity checking.
4083 assert(0 && "OpaqueValueExpr recursively refers to itself");
4086 return StmtVisitorTy::Visit(Source);
4089 bool VisitCallExpr(const CallExpr *E) {
4090 const Expr *Callee = E->getCallee()->IgnoreParens();
4091 QualType CalleeType = Callee->getType();
4093 const FunctionDecl *FD = nullptr;
4094 LValue *This = nullptr, ThisVal;
4095 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4096 bool HasQualifier = false;
4098 // Extract function decl and 'this' pointer from the callee.
4099 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4100 const ValueDecl *Member = nullptr;
4101 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4102 // Explicit bound member calls, such as x.f() or p->g();
4103 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4105 Member = ME->getMemberDecl();
4107 HasQualifier = ME->hasQualifier();
4108 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4109 // Indirect bound member calls ('.*' or '->*').
4110 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4111 if (!Member) return false;
4114 return Error(Callee);
4116 FD = dyn_cast<FunctionDecl>(Member);
4118 return Error(Callee);
4119 } else if (CalleeType->isFunctionPointerType()) {
4121 if (!EvaluatePointer(Callee, Call, Info))
4124 if (!Call.getLValueOffset().isZero())
4125 return Error(Callee);
4126 FD = dyn_cast_or_null<FunctionDecl>(
4127 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4129 return Error(Callee);
4131 // Overloaded operator calls to member functions are represented as normal
4132 // calls with '*this' as the first argument.
4133 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4134 if (MD && !MD->isStatic()) {
4135 // FIXME: When selecting an implicit conversion for an overloaded
4136 // operator delete, we sometimes try to evaluate calls to conversion
4137 // operators without a 'this' parameter!
4141 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4144 Args = Args.slice(1);
4147 // Don't call function pointers which have been cast to some other type.
4148 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4153 if (This && !This->checkSubobject(Info, E, CSK_This))
4156 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4157 // calls to such functions in constant expressions.
4158 if (This && !HasQualifier &&
4159 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4160 return Error(E, diag::note_constexpr_virtual_call);
4162 const FunctionDecl *Definition = nullptr;
4163 Stmt *Body = FD->getBody(Definition);
4166 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4167 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4171 return DerivedSuccess(Result, E);
4174 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4175 return StmtVisitorTy::Visit(E->getInitializer());
4177 bool VisitInitListExpr(const InitListExpr *E) {
4178 if (E->getNumInits() == 0)
4179 return DerivedZeroInitialization(E);
4180 if (E->getNumInits() == 1)
4181 return StmtVisitorTy::Visit(E->getInit(0));
4184 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4185 return DerivedZeroInitialization(E);
4187 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4188 return DerivedZeroInitialization(E);
4190 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4191 return DerivedZeroInitialization(E);
4194 /// A member expression where the object is a prvalue is itself a prvalue.
4195 bool VisitMemberExpr(const MemberExpr *E) {
4196 assert(!E->isArrow() && "missing call to bound member function?");
4199 if (!Evaluate(Val, Info, E->getBase()))
4202 QualType BaseTy = E->getBase()->getType();
4204 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4205 if (!FD) return Error(E);
4206 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4207 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4208 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4210 CompleteObject Obj(&Val, BaseTy);
4211 SubobjectDesignator Designator(BaseTy);
4212 Designator.addDeclUnchecked(FD);
4215 return extractSubobject(Info, E, Obj, Designator, Result) &&
4216 DerivedSuccess(Result, E);
4219 bool VisitCastExpr(const CastExpr *E) {
4220 switch (E->getCastKind()) {
4224 case CK_AtomicToNonAtomic: {
4226 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4228 return DerivedSuccess(AtomicVal, E);
4232 case CK_UserDefinedConversion:
4233 return StmtVisitorTy::Visit(E->getSubExpr());
4235 case CK_LValueToRValue: {
4237 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4240 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4241 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4244 return DerivedSuccess(RVal, E);
4251 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4252 return VisitUnaryPostIncDec(UO);
4254 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4255 return VisitUnaryPostIncDec(UO);
4257 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4258 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4262 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4265 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4266 UO->isIncrementOp(), &RVal))
4268 return DerivedSuccess(RVal, UO);
4271 bool VisitStmtExpr(const StmtExpr *E) {
4272 // We will have checked the full-expressions inside the statement expression
4273 // when they were completed, and don't need to check them again now.
4274 if (Info.checkingForOverflow())
4277 BlockScopeRAII Scope(Info);
4278 const CompoundStmt *CS = E->getSubStmt();
4279 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4280 BE = CS->body_end();
4283 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4285 Info.Diag((*BI)->getLocStart(),
4286 diag::note_constexpr_stmt_expr_unsupported);
4289 return this->Visit(FinalExpr);
4292 APValue ReturnValue;
4293 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4294 if (ESR != ESR_Succeeded) {
4295 // FIXME: If the statement-expression terminated due to 'return',
4296 // 'break', or 'continue', it would be nice to propagate that to
4297 // the outer statement evaluation rather than bailing out.
4298 if (ESR != ESR_Failed)
4299 Info.Diag((*BI)->getLocStart(),
4300 diag::note_constexpr_stmt_expr_unsupported);
4306 /// Visit a value which is evaluated, but whose value is ignored.
4307 void VisitIgnoredValue(const Expr *E) {
4308 EvaluateIgnoredValue(Info, E);
4314 //===----------------------------------------------------------------------===//
4315 // Common base class for lvalue and temporary evaluation.
4316 //===----------------------------------------------------------------------===//
4318 template<class Derived>
4319 class LValueExprEvaluatorBase
4320 : public ExprEvaluatorBase<Derived> {
4323 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4324 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4326 bool Success(APValue::LValueBase B) {
4332 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4333 ExprEvaluatorBaseTy(Info), Result(Result) {}
4335 bool Success(const APValue &V, const Expr *E) {
4336 Result.setFrom(this->Info.Ctx, V);
4340 bool VisitMemberExpr(const MemberExpr *E) {
4341 // Handle non-static data members.
4344 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4346 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4347 } else if (E->getBase()->isRValue()) {
4348 assert(E->getBase()->getType()->isRecordType());
4349 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4351 BaseTy = E->getBase()->getType();
4353 if (!this->Visit(E->getBase()))
4355 BaseTy = E->getBase()->getType();
4358 const ValueDecl *MD = E->getMemberDecl();
4359 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4360 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4361 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4363 if (!HandleLValueMember(this->Info, E, Result, FD))
4365 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4366 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4369 return this->Error(E);
4371 if (MD->getType()->isReferenceType()) {
4373 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4376 return Success(RefValue, E);
4381 bool VisitBinaryOperator(const BinaryOperator *E) {
4382 switch (E->getOpcode()) {
4384 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4388 return HandleMemberPointerAccess(this->Info, E, Result);
4392 bool VisitCastExpr(const CastExpr *E) {
4393 switch (E->getCastKind()) {
4395 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4397 case CK_DerivedToBase:
4398 case CK_UncheckedDerivedToBase:
4399 if (!this->Visit(E->getSubExpr()))
4402 // Now figure out the necessary offset to add to the base LV to get from
4403 // the derived class to the base class.
4404 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4411 //===----------------------------------------------------------------------===//
4412 // LValue Evaluation
4414 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4415 // function designators (in C), decl references to void objects (in C), and
4416 // temporaries (if building with -Wno-address-of-temporary).
4418 // LValue evaluation produces values comprising a base expression of one of the
4424 // * CompoundLiteralExpr in C
4428 // * ObjCStringLiteralExpr
4432 // * CallExpr for a MakeStringConstant builtin
4433 // - Locals and temporaries
4434 // * MaterializeTemporaryExpr
4435 // * Any Expr, with a CallIndex indicating the function in which the temporary
4436 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4437 // from the AST (FIXME).
4438 // * A MaterializeTemporaryExpr that has static storage duration, with no
4439 // CallIndex, for a lifetime-extended temporary.
4440 // plus an offset in bytes.
4441 //===----------------------------------------------------------------------===//
4443 class LValueExprEvaluator
4444 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4446 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4447 LValueExprEvaluatorBaseTy(Info, Result) {}
4449 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4450 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4452 bool VisitDeclRefExpr(const DeclRefExpr *E);
4453 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4454 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4455 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4456 bool VisitMemberExpr(const MemberExpr *E);
4457 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4458 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4459 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4460 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4461 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4462 bool VisitUnaryDeref(const UnaryOperator *E);
4463 bool VisitUnaryReal(const UnaryOperator *E);
4464 bool VisitUnaryImag(const UnaryOperator *E);
4465 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4466 return VisitUnaryPreIncDec(UO);
4468 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4469 return VisitUnaryPreIncDec(UO);
4471 bool VisitBinAssign(const BinaryOperator *BO);
4472 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4474 bool VisitCastExpr(const CastExpr *E) {
4475 switch (E->getCastKind()) {
4477 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4479 case CK_LValueBitCast:
4480 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4481 if (!Visit(E->getSubExpr()))
4483 Result.Designator.setInvalid();
4486 case CK_BaseToDerived:
4487 if (!Visit(E->getSubExpr()))
4489 return HandleBaseToDerivedCast(Info, E, Result);
4493 } // end anonymous namespace
4495 /// Evaluate an expression as an lvalue. This can be legitimately called on
4496 /// expressions which are not glvalues, in two cases:
4497 /// * function designators in C, and
4498 /// * "extern void" objects
4499 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4500 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4501 E->getType()->isVoidType());
4502 return LValueExprEvaluator(Info, Result).Visit(E);
4505 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4506 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4508 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4509 return VisitVarDecl(E, VD);
4513 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4514 CallStackFrame *Frame = nullptr;
4515 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4516 Frame = Info.CurrentCall;
4518 if (!VD->getType()->isReferenceType()) {
4520 Result.set(VD, Frame->Index);
4527 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4529 if (V->isUninit()) {
4530 if (!Info.checkingPotentialConstantExpression())
4531 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4534 return Success(*V, E);
4537 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4538 const MaterializeTemporaryExpr *E) {
4539 // Walk through the expression to find the materialized temporary itself.
4540 SmallVector<const Expr *, 2> CommaLHSs;
4541 SmallVector<SubobjectAdjustment, 2> Adjustments;
4542 const Expr *Inner = E->GetTemporaryExpr()->
4543 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4545 // If we passed any comma operators, evaluate their LHSs.
4546 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4547 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4550 // A materialized temporary with static storage duration can appear within the
4551 // result of a constant expression evaluation, so we need to preserve its
4552 // value for use outside this evaluation.
4554 if (E->getStorageDuration() == SD_Static) {
4555 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4559 Value = &Info.CurrentCall->
4560 createTemporary(E, E->getStorageDuration() == SD_Automatic);
4561 Result.set(E, Info.CurrentCall->Index);
4564 QualType Type = Inner->getType();
4566 // Materialize the temporary itself.
4567 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4568 (E->getStorageDuration() == SD_Static &&
4569 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4574 // Adjust our lvalue to refer to the desired subobject.
4575 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4577 switch (Adjustments[I].Kind) {
4578 case SubobjectAdjustment::DerivedToBaseAdjustment:
4579 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4582 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4585 case SubobjectAdjustment::FieldAdjustment:
4586 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4588 Type = Adjustments[I].Field->getType();
4591 case SubobjectAdjustment::MemberPointerAdjustment:
4592 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4593 Adjustments[I].Ptr.RHS))
4595 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4604 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4605 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4606 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4607 // only see this when folding in C, so there's no standard to follow here.
4611 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4612 if (!E->isPotentiallyEvaluated())
4615 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4616 << E->getExprOperand()->getType()
4617 << E->getExprOperand()->getSourceRange();
4621 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4625 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4626 // Handle static data members.
4627 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4628 VisitIgnoredValue(E->getBase());
4629 return VisitVarDecl(E, VD);
4632 // Handle static member functions.
4633 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4634 if (MD->isStatic()) {
4635 VisitIgnoredValue(E->getBase());
4640 // Handle non-static data members.
4641 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4644 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4645 // FIXME: Deal with vectors as array subscript bases.
4646 if (E->getBase()->getType()->isVectorType())
4649 if (!EvaluatePointer(E->getBase(), Result, Info))
4653 if (!EvaluateInteger(E->getIdx(), Index, Info))
4656 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4657 getExtValue(Index));
4660 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4661 return EvaluatePointer(E->getSubExpr(), Result, Info);
4664 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4665 if (!Visit(E->getSubExpr()))
4667 // __real is a no-op on scalar lvalues.
4668 if (E->getSubExpr()->getType()->isAnyComplexType())
4669 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4673 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4674 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4675 "lvalue __imag__ on scalar?");
4676 if (!Visit(E->getSubExpr()))
4678 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4682 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4683 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4686 if (!this->Visit(UO->getSubExpr()))
4689 return handleIncDec(
4690 this->Info, UO, Result, UO->getSubExpr()->getType(),
4691 UO->isIncrementOp(), nullptr);
4694 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4695 const CompoundAssignOperator *CAO) {
4696 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4701 // The overall lvalue result is the result of evaluating the LHS.
4702 if (!this->Visit(CAO->getLHS())) {
4703 if (Info.keepEvaluatingAfterFailure())
4704 Evaluate(RHS, this->Info, CAO->getRHS());
4708 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4711 return handleCompoundAssignment(
4713 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4714 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4717 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4718 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4723 if (!this->Visit(E->getLHS())) {
4724 if (Info.keepEvaluatingAfterFailure())
4725 Evaluate(NewVal, this->Info, E->getRHS());
4729 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4732 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4736 //===----------------------------------------------------------------------===//
4737 // Pointer Evaluation
4738 //===----------------------------------------------------------------------===//
4741 class PointerExprEvaluator
4742 : public ExprEvaluatorBase<PointerExprEvaluator> {
4745 bool Success(const Expr *E) {
4751 PointerExprEvaluator(EvalInfo &info, LValue &Result)
4752 : ExprEvaluatorBaseTy(info), Result(Result) {}
4754 bool Success(const APValue &V, const Expr *E) {
4755 Result.setFrom(Info.Ctx, V);
4758 bool ZeroInitialization(const Expr *E) {
4759 return Success((Expr*)nullptr);
4762 bool VisitBinaryOperator(const BinaryOperator *E);
4763 bool VisitCastExpr(const CastExpr* E);
4764 bool VisitUnaryAddrOf(const UnaryOperator *E);
4765 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4766 { return Success(E); }
4767 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4768 { return Success(E); }
4769 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4770 { return Success(E); }
4771 bool VisitCallExpr(const CallExpr *E);
4772 bool VisitBlockExpr(const BlockExpr *E) {
4773 if (!E->getBlockDecl()->hasCaptures())
4777 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4778 // Can't look at 'this' when checking a potential constant expression.
4779 if (Info.checkingPotentialConstantExpression())
4781 if (!Info.CurrentCall->This) {
4782 if (Info.getLangOpts().CPlusPlus11)
4783 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4788 Result = *Info.CurrentCall->This;
4792 // FIXME: Missing: @protocol, @selector
4794 } // end anonymous namespace
4796 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4797 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4798 return PointerExprEvaluator(Info, Result).Visit(E);
4801 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4802 if (E->getOpcode() != BO_Add &&
4803 E->getOpcode() != BO_Sub)
4804 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4806 const Expr *PExp = E->getLHS();
4807 const Expr *IExp = E->getRHS();
4808 if (IExp->getType()->isPointerType())
4809 std::swap(PExp, IExp);
4811 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4812 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4815 llvm::APSInt Offset;
4816 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4819 int64_t AdditionalOffset = getExtValue(Offset);
4820 if (E->getOpcode() == BO_Sub)
4821 AdditionalOffset = -AdditionalOffset;
4823 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4824 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4828 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4829 return EvaluateLValue(E->getSubExpr(), Result, Info);
4832 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4833 const Expr* SubExpr = E->getSubExpr();
4835 switch (E->getCastKind()) {
4840 case CK_CPointerToObjCPointerCast:
4841 case CK_BlockPointerToObjCPointerCast:
4842 case CK_AnyPointerToBlockPointerCast:
4843 case CK_AddressSpaceConversion:
4844 if (!Visit(SubExpr))
4846 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4847 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4848 // also static_casts, but we disallow them as a resolution to DR1312.
4849 if (!E->getType()->isVoidPointerType()) {
4850 Result.Designator.setInvalid();
4851 if (SubExpr->getType()->isVoidPointerType())
4852 CCEDiag(E, diag::note_constexpr_invalid_cast)
4853 << 3 << SubExpr->getType();
4855 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4859 case CK_DerivedToBase:
4860 case CK_UncheckedDerivedToBase:
4861 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4863 if (!Result.Base && Result.Offset.isZero())
4866 // Now figure out the necessary offset to add to the base LV to get from
4867 // the derived class to the base class.
4868 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4869 castAs<PointerType>()->getPointeeType(),
4872 case CK_BaseToDerived:
4873 if (!Visit(E->getSubExpr()))
4875 if (!Result.Base && Result.Offset.isZero())
4877 return HandleBaseToDerivedCast(Info, E, Result);
4879 case CK_NullToPointer:
4880 VisitIgnoredValue(E->getSubExpr());
4881 return ZeroInitialization(E);
4883 case CK_IntegralToPointer: {
4884 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4887 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4890 if (Value.isInt()) {
4891 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4892 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4893 Result.Base = (Expr*)nullptr;
4894 Result.Offset = CharUnits::fromQuantity(N);
4895 Result.CallIndex = 0;
4896 Result.Designator.setInvalid();
4899 // Cast is of an lvalue, no need to change value.
4900 Result.setFrom(Info.Ctx, Value);
4904 case CK_ArrayToPointerDecay:
4905 if (SubExpr->isGLValue()) {
4906 if (!EvaluateLValue(SubExpr, Result, Info))
4909 Result.set(SubExpr, Info.CurrentCall->Index);
4910 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4911 Info, Result, SubExpr))
4914 // The result is a pointer to the first element of the array.
4915 if (const ConstantArrayType *CAT
4916 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4917 Result.addArray(Info, E, CAT);
4919 Result.Designator.setInvalid();
4922 case CK_FunctionToPointerDecay:
4923 return EvaluateLValue(SubExpr, Result, Info);
4926 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4929 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4930 // C++ [expr.alignof]p3:
4931 // When alignof is applied to a reference type, the result is the
4932 // alignment of the referenced type.
4933 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4934 T = Ref->getPointeeType();
4936 // __alignof is defined to return the preferred alignment.
4937 return Info.Ctx.toCharUnitsFromBits(
4938 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4941 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4942 E = E->IgnoreParens();
4944 // The kinds of expressions that we have special-case logic here for
4945 // should be kept up to date with the special checks for those
4946 // expressions in Sema.
4948 // alignof decl is always accepted, even if it doesn't make sense: we default
4949 // to 1 in those cases.
4950 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4951 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4952 /*RefAsPointee*/true);
4954 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4955 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4956 /*RefAsPointee*/true);
4958 return GetAlignOfType(Info, E->getType());
4961 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4962 if (IsStringLiteralCall(E))
4965 switch (E->getBuiltinCallee()) {
4966 case Builtin::BI__builtin_addressof:
4967 return EvaluateLValue(E->getArg(0), Result, Info);
4968 case Builtin::BI__builtin_assume_aligned: {
4969 // We need to be very careful here because: if the pointer does not have the
4970 // asserted alignment, then the behavior is undefined, and undefined
4971 // behavior is non-constant.
4972 if (!EvaluatePointer(E->getArg(0), Result, Info))
4975 LValue OffsetResult(Result);
4977 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
4979 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
4981 if (E->getNumArgs() > 2) {
4983 if (!EvaluateInteger(E->getArg(2), Offset, Info))
4986 int64_t AdditionalOffset = -getExtValue(Offset);
4987 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
4990 // If there is a base object, then it must have the correct alignment.
4991 if (OffsetResult.Base) {
4992 CharUnits BaseAlignment;
4993 if (const ValueDecl *VD =
4994 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
4995 BaseAlignment = Info.Ctx.getDeclAlign(VD);
4998 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5001 if (BaseAlignment < Align) {
5002 Result.Designator.setInvalid();
5003 // FIXME: Quantities here cast to integers because the plural modifier
5004 // does not work on APSInts yet.
5005 CCEDiag(E->getArg(0),
5006 diag::note_constexpr_baa_insufficient_alignment) << 0
5007 << (int) BaseAlignment.getQuantity()
5008 << (unsigned) getExtValue(Alignment);
5013 // The offset must also have the correct alignment.
5014 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5015 Result.Designator.setInvalid();
5016 APSInt Offset(64, false);
5017 Offset = OffsetResult.Offset.getQuantity();
5019 if (OffsetResult.Base)
5020 CCEDiag(E->getArg(0),
5021 diag::note_constexpr_baa_insufficient_alignment) << 1
5022 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5024 CCEDiag(E->getArg(0),
5025 diag::note_constexpr_baa_value_insufficient_alignment)
5026 << Offset << (unsigned) getExtValue(Alignment);
5034 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5038 //===----------------------------------------------------------------------===//
5039 // Member Pointer Evaluation
5040 //===----------------------------------------------------------------------===//
5043 class MemberPointerExprEvaluator
5044 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5047 bool Success(const ValueDecl *D) {
5048 Result = MemberPtr(D);
5053 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5054 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5056 bool Success(const APValue &V, const Expr *E) {
5060 bool ZeroInitialization(const Expr *E) {
5061 return Success((const ValueDecl*)nullptr);
5064 bool VisitCastExpr(const CastExpr *E);
5065 bool VisitUnaryAddrOf(const UnaryOperator *E);
5067 } // end anonymous namespace
5069 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5071 assert(E->isRValue() && E->getType()->isMemberPointerType());
5072 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5075 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5076 switch (E->getCastKind()) {
5078 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5080 case CK_NullToMemberPointer:
5081 VisitIgnoredValue(E->getSubExpr());
5082 return ZeroInitialization(E);
5084 case CK_BaseToDerivedMemberPointer: {
5085 if (!Visit(E->getSubExpr()))
5087 if (E->path_empty())
5089 // Base-to-derived member pointer casts store the path in derived-to-base
5090 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5091 // the wrong end of the derived->base arc, so stagger the path by one class.
5092 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5093 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5094 PathI != PathE; ++PathI) {
5095 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5096 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5097 if (!Result.castToDerived(Derived))
5100 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5101 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5106 case CK_DerivedToBaseMemberPointer:
5107 if (!Visit(E->getSubExpr()))
5109 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5110 PathE = E->path_end(); PathI != PathE; ++PathI) {
5111 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5112 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5113 if (!Result.castToBase(Base))
5120 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5121 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5122 // member can be formed.
5123 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5126 //===----------------------------------------------------------------------===//
5127 // Record Evaluation
5128 //===----------------------------------------------------------------------===//
5131 class RecordExprEvaluator
5132 : public ExprEvaluatorBase<RecordExprEvaluator> {
5137 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5138 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5140 bool Success(const APValue &V, const Expr *E) {
5144 bool ZeroInitialization(const Expr *E);
5146 bool VisitCastExpr(const CastExpr *E);
5147 bool VisitInitListExpr(const InitListExpr *E);
5148 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5149 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5153 /// Perform zero-initialization on an object of non-union class type.
5154 /// C++11 [dcl.init]p5:
5155 /// To zero-initialize an object or reference of type T means:
5157 /// -- if T is a (possibly cv-qualified) non-union class type,
5158 /// each non-static data member and each base-class subobject is
5159 /// zero-initialized
5160 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5161 const RecordDecl *RD,
5162 const LValue &This, APValue &Result) {
5163 assert(!RD->isUnion() && "Expected non-union class type");
5164 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5165 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5166 std::distance(RD->field_begin(), RD->field_end()));
5168 if (RD->isInvalidDecl()) return false;
5169 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5173 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5174 End = CD->bases_end(); I != End; ++I, ++Index) {
5175 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5176 LValue Subobject = This;
5177 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5179 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5180 Result.getStructBase(Index)))
5185 for (const auto *I : RD->fields()) {
5186 // -- if T is a reference type, no initialization is performed.
5187 if (I->getType()->isReferenceType())
5190 LValue Subobject = This;
5191 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5194 ImplicitValueInitExpr VIE(I->getType());
5195 if (!EvaluateInPlace(
5196 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5203 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5204 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5205 if (RD->isInvalidDecl()) return false;
5206 if (RD->isUnion()) {
5207 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5208 // object's first non-static named data member is zero-initialized
5209 RecordDecl::field_iterator I = RD->field_begin();
5210 if (I == RD->field_end()) {
5211 Result = APValue((const FieldDecl*)nullptr);
5215 LValue Subobject = This;
5216 if (!HandleLValueMember(Info, E, Subobject, *I))
5218 Result = APValue(*I);
5219 ImplicitValueInitExpr VIE(I->getType());
5220 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5223 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5224 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5228 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5231 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5232 switch (E->getCastKind()) {
5234 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5236 case CK_ConstructorConversion:
5237 return Visit(E->getSubExpr());
5239 case CK_DerivedToBase:
5240 case CK_UncheckedDerivedToBase: {
5241 APValue DerivedObject;
5242 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5244 if (!DerivedObject.isStruct())
5245 return Error(E->getSubExpr());
5247 // Derived-to-base rvalue conversion: just slice off the derived part.
5248 APValue *Value = &DerivedObject;
5249 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5250 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5251 PathE = E->path_end(); PathI != PathE; ++PathI) {
5252 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5253 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5254 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5263 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5264 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5265 if (RD->isInvalidDecl()) return false;
5266 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5268 if (RD->isUnion()) {
5269 const FieldDecl *Field = E->getInitializedFieldInUnion();
5270 Result = APValue(Field);
5274 // If the initializer list for a union does not contain any elements, the
5275 // first element of the union is value-initialized.
5276 // FIXME: The element should be initialized from an initializer list.
5277 // Is this difference ever observable for initializer lists which
5279 ImplicitValueInitExpr VIE(Field->getType());
5280 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5282 LValue Subobject = This;
5283 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5286 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5287 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5288 isa<CXXDefaultInitExpr>(InitExpr));
5290 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5293 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5294 "initializer list for class with base classes");
5295 Result = APValue(APValue::UninitStruct(), 0,
5296 std::distance(RD->field_begin(), RD->field_end()));
5297 unsigned ElementNo = 0;
5298 bool Success = true;
5299 for (const auto *Field : RD->fields()) {
5300 // Anonymous bit-fields are not considered members of the class for
5301 // purposes of aggregate initialization.
5302 if (Field->isUnnamedBitfield())
5305 LValue Subobject = This;
5307 bool HaveInit = ElementNo < E->getNumInits();
5309 // FIXME: Diagnostics here should point to the end of the initializer
5310 // list, not the start.
5311 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5312 Subobject, Field, &Layout))
5315 // Perform an implicit value-initialization for members beyond the end of
5316 // the initializer list.
5317 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5318 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5320 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5321 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5322 isa<CXXDefaultInitExpr>(Init));
5324 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5325 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5326 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5327 FieldVal, Field))) {
5328 if (!Info.keepEvaluatingAfterFailure())
5337 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5338 const CXXConstructorDecl *FD = E->getConstructor();
5339 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5341 bool ZeroInit = E->requiresZeroInitialization();
5342 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5343 // If we've already performed zero-initialization, we're already done.
5344 if (!Result.isUninit())
5347 // We can get here in two different ways:
5348 // 1) We're performing value-initialization, and should zero-initialize
5350 // 2) We're performing default-initialization of an object with a trivial
5351 // constexpr default constructor, in which case we should start the
5352 // lifetimes of all the base subobjects (there can be no data member
5353 // subobjects in this case) per [basic.life]p1.
5354 // Either way, ZeroInitialization is appropriate.
5355 return ZeroInitialization(E);
5358 const FunctionDecl *Definition = nullptr;
5359 FD->getBody(Definition);
5361 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5364 // Avoid materializing a temporary for an elidable copy/move constructor.
5365 if (E->isElidable() && !ZeroInit)
5366 if (const MaterializeTemporaryExpr *ME
5367 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5368 return Visit(ME->GetTemporaryExpr());
5370 if (ZeroInit && !ZeroInitialization(E))
5373 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5374 return HandleConstructorCall(E->getExprLoc(), This, Args,
5375 cast<CXXConstructorDecl>(Definition), Info,
5379 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5380 const CXXStdInitializerListExpr *E) {
5381 const ConstantArrayType *ArrayType =
5382 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5385 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5388 // Get a pointer to the first element of the array.
5389 Array.addArray(Info, E, ArrayType);
5391 // FIXME: Perform the checks on the field types in SemaInit.
5392 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5393 RecordDecl::field_iterator Field = Record->field_begin();
5394 if (Field == Record->field_end())
5398 if (!Field->getType()->isPointerType() ||
5399 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5400 ArrayType->getElementType()))
5403 // FIXME: What if the initializer_list type has base classes, etc?
5404 Result = APValue(APValue::UninitStruct(), 0, 2);
5405 Array.moveInto(Result.getStructField(0));
5407 if (++Field == Record->field_end())
5410 if (Field->getType()->isPointerType() &&
5411 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5412 ArrayType->getElementType())) {
5414 if (!HandleLValueArrayAdjustment(Info, E, Array,
5415 ArrayType->getElementType(),
5416 ArrayType->getSize().getZExtValue()))
5418 Array.moveInto(Result.getStructField(1));
5419 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5421 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5425 if (++Field != Record->field_end())
5431 static bool EvaluateRecord(const Expr *E, const LValue &This,
5432 APValue &Result, EvalInfo &Info) {
5433 assert(E->isRValue() && E->getType()->isRecordType() &&
5434 "can't evaluate expression as a record rvalue");
5435 return RecordExprEvaluator(Info, This, Result).Visit(E);
5438 //===----------------------------------------------------------------------===//
5439 // Temporary Evaluation
5441 // Temporaries are represented in the AST as rvalues, but generally behave like
5442 // lvalues. The full-object of which the temporary is a subobject is implicitly
5443 // materialized so that a reference can bind to it.
5444 //===----------------------------------------------------------------------===//
5446 class TemporaryExprEvaluator
5447 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5449 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5450 LValueExprEvaluatorBaseTy(Info, Result) {}
5452 /// Visit an expression which constructs the value of this temporary.
5453 bool VisitConstructExpr(const Expr *E) {
5454 Result.set(E, Info.CurrentCall->Index);
5455 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5459 bool VisitCastExpr(const CastExpr *E) {
5460 switch (E->getCastKind()) {
5462 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5464 case CK_ConstructorConversion:
5465 return VisitConstructExpr(E->getSubExpr());
5468 bool VisitInitListExpr(const InitListExpr *E) {
5469 return VisitConstructExpr(E);
5471 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5472 return VisitConstructExpr(E);
5474 bool VisitCallExpr(const CallExpr *E) {
5475 return VisitConstructExpr(E);
5477 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5478 return VisitConstructExpr(E);
5481 } // end anonymous namespace
5483 /// Evaluate an expression of record type as a temporary.
5484 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5485 assert(E->isRValue() && E->getType()->isRecordType());
5486 return TemporaryExprEvaluator(Info, Result).Visit(E);
5489 //===----------------------------------------------------------------------===//
5490 // Vector Evaluation
5491 //===----------------------------------------------------------------------===//
5494 class VectorExprEvaluator
5495 : public ExprEvaluatorBase<VectorExprEvaluator> {
5499 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5500 : ExprEvaluatorBaseTy(info), Result(Result) {}
5502 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5503 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5504 // FIXME: remove this APValue copy.
5505 Result = APValue(V.data(), V.size());
5508 bool Success(const APValue &V, const Expr *E) {
5509 assert(V.isVector());
5513 bool ZeroInitialization(const Expr *E);
5515 bool VisitUnaryReal(const UnaryOperator *E)
5516 { return Visit(E->getSubExpr()); }
5517 bool VisitCastExpr(const CastExpr* E);
5518 bool VisitInitListExpr(const InitListExpr *E);
5519 bool VisitUnaryImag(const UnaryOperator *E);
5520 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5521 // binary comparisons, binary and/or/xor,
5522 // shufflevector, ExtVectorElementExpr
5524 } // end anonymous namespace
5526 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5527 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5528 return VectorExprEvaluator(Info, Result).Visit(E);
5531 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5532 const VectorType *VTy = E->getType()->castAs<VectorType>();
5533 unsigned NElts = VTy->getNumElements();
5535 const Expr *SE = E->getSubExpr();
5536 QualType SETy = SE->getType();
5538 switch (E->getCastKind()) {
5539 case CK_VectorSplat: {
5540 APValue Val = APValue();
5541 if (SETy->isIntegerType()) {
5543 if (!EvaluateInteger(SE, IntResult, Info))
5545 Val = APValue(IntResult);
5546 } else if (SETy->isRealFloatingType()) {
5548 if (!EvaluateFloat(SE, F, Info))
5555 // Splat and create vector APValue.
5556 SmallVector<APValue, 4> Elts(NElts, Val);
5557 return Success(Elts, E);
5560 // Evaluate the operand into an APInt we can extract from.
5561 llvm::APInt SValInt;
5562 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5564 // Extract the elements
5565 QualType EltTy = VTy->getElementType();
5566 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5567 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5568 SmallVector<APValue, 4> Elts;
5569 if (EltTy->isRealFloatingType()) {
5570 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5571 unsigned FloatEltSize = EltSize;
5572 if (&Sem == &APFloat::x87DoubleExtended)
5574 for (unsigned i = 0; i < NElts; i++) {
5577 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5579 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5580 Elts.push_back(APValue(APFloat(Sem, Elt)));
5582 } else if (EltTy->isIntegerType()) {
5583 for (unsigned i = 0; i < NElts; i++) {
5586 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5588 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5589 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5594 return Success(Elts, E);
5597 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5602 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5603 const VectorType *VT = E->getType()->castAs<VectorType>();
5604 unsigned NumInits = E->getNumInits();
5605 unsigned NumElements = VT->getNumElements();
5607 QualType EltTy = VT->getElementType();
5608 SmallVector<APValue, 4> Elements;
5610 // The number of initializers can be less than the number of
5611 // vector elements. For OpenCL, this can be due to nested vector
5612 // initialization. For GCC compatibility, missing trailing elements
5613 // should be initialized with zeroes.
5614 unsigned CountInits = 0, CountElts = 0;
5615 while (CountElts < NumElements) {
5616 // Handle nested vector initialization.
5617 if (CountInits < NumInits
5618 && E->getInit(CountInits)->getType()->isVectorType()) {
5620 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5622 unsigned vlen = v.getVectorLength();
5623 for (unsigned j = 0; j < vlen; j++)
5624 Elements.push_back(v.getVectorElt(j));
5626 } else if (EltTy->isIntegerType()) {
5627 llvm::APSInt sInt(32);
5628 if (CountInits < NumInits) {
5629 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5631 } else // trailing integer zero.
5632 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5633 Elements.push_back(APValue(sInt));
5636 llvm::APFloat f(0.0);
5637 if (CountInits < NumInits) {
5638 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5640 } else // trailing float zero.
5641 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5642 Elements.push_back(APValue(f));
5647 return Success(Elements, E);
5651 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5652 const VectorType *VT = E->getType()->getAs<VectorType>();
5653 QualType EltTy = VT->getElementType();
5654 APValue ZeroElement;
5655 if (EltTy->isIntegerType())
5656 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5659 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5661 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5662 return Success(Elements, E);
5665 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5666 VisitIgnoredValue(E->getSubExpr());
5667 return ZeroInitialization(E);
5670 //===----------------------------------------------------------------------===//
5672 //===----------------------------------------------------------------------===//
5675 class ArrayExprEvaluator
5676 : public ExprEvaluatorBase<ArrayExprEvaluator> {
5681 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5682 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5684 bool Success(const APValue &V, const Expr *E) {
5685 assert((V.isArray() || V.isLValue()) &&
5686 "expected array or string literal");
5691 bool ZeroInitialization(const Expr *E) {
5692 const ConstantArrayType *CAT =
5693 Info.Ctx.getAsConstantArrayType(E->getType());
5697 Result = APValue(APValue::UninitArray(), 0,
5698 CAT->getSize().getZExtValue());
5699 if (!Result.hasArrayFiller()) return true;
5701 // Zero-initialize all elements.
5702 LValue Subobject = This;
5703 Subobject.addArray(Info, E, CAT);
5704 ImplicitValueInitExpr VIE(CAT->getElementType());
5705 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5708 bool VisitInitListExpr(const InitListExpr *E);
5709 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5710 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5711 const LValue &Subobject,
5712 APValue *Value, QualType Type);
5714 } // end anonymous namespace
5716 static bool EvaluateArray(const Expr *E, const LValue &This,
5717 APValue &Result, EvalInfo &Info) {
5718 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5719 return ArrayExprEvaluator(Info, This, Result).Visit(E);
5722 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5723 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5727 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5728 // an appropriately-typed string literal enclosed in braces.
5729 if (E->isStringLiteralInit()) {
5731 if (!EvaluateLValue(E->getInit(0), LV, Info))
5735 return Success(Val, E);
5738 bool Success = true;
5740 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5741 "zero-initialized array shouldn't have any initialized elts");
5743 if (Result.isArray() && Result.hasArrayFiller())
5744 Filler = Result.getArrayFiller();
5746 unsigned NumEltsToInit = E->getNumInits();
5747 unsigned NumElts = CAT->getSize().getZExtValue();
5748 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5750 // If the initializer might depend on the array index, run it for each
5751 // array element. For now, just whitelist non-class value-initialization.
5752 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5753 NumEltsToInit = NumElts;
5755 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5757 // If the array was previously zero-initialized, preserve the
5758 // zero-initialized values.
5759 if (!Filler.isUninit()) {
5760 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5761 Result.getArrayInitializedElt(I) = Filler;
5762 if (Result.hasArrayFiller())
5763 Result.getArrayFiller() = Filler;
5766 LValue Subobject = This;
5767 Subobject.addArray(Info, E, CAT);
5768 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5770 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5771 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5772 Info, Subobject, Init) ||
5773 !HandleLValueArrayAdjustment(Info, Init, Subobject,
5774 CAT->getElementType(), 1)) {
5775 if (!Info.keepEvaluatingAfterFailure())
5781 if (!Result.hasArrayFiller())
5784 // If we get here, we have a trivial filler, which we can just evaluate
5785 // once and splat over the rest of the array elements.
5786 assert(FillerExpr && "no array filler for incomplete init list");
5787 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5788 FillerExpr) && Success;
5791 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5792 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5795 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5796 const LValue &Subobject,
5799 bool HadZeroInit = !Value->isUninit();
5801 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5802 unsigned N = CAT->getSize().getZExtValue();
5804 // Preserve the array filler if we had prior zero-initialization.
5806 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5809 *Value = APValue(APValue::UninitArray(), N, N);
5812 for (unsigned I = 0; I != N; ++I)
5813 Value->getArrayInitializedElt(I) = Filler;
5815 // Initialize the elements.
5816 LValue ArrayElt = Subobject;
5817 ArrayElt.addArray(Info, E, CAT);
5818 for (unsigned I = 0; I != N; ++I)
5819 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5820 CAT->getElementType()) ||
5821 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5822 CAT->getElementType(), 1))
5828 if (!Type->isRecordType())
5831 const CXXConstructorDecl *FD = E->getConstructor();
5833 bool ZeroInit = E->requiresZeroInitialization();
5834 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5838 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5839 ImplicitValueInitExpr VIE(Type);
5840 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5843 const FunctionDecl *Definition = nullptr;
5844 FD->getBody(Definition);
5846 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5849 if (ZeroInit && !HadZeroInit) {
5850 ImplicitValueInitExpr VIE(Type);
5851 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5855 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5856 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5857 cast<CXXConstructorDecl>(Definition),
5861 //===----------------------------------------------------------------------===//
5862 // Integer Evaluation
5864 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5865 // types and back in constant folding. Integer values are thus represented
5866 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5867 //===----------------------------------------------------------------------===//
5870 class IntExprEvaluator
5871 : public ExprEvaluatorBase<IntExprEvaluator> {
5874 IntExprEvaluator(EvalInfo &info, APValue &result)
5875 : ExprEvaluatorBaseTy(info), Result(result) {}
5877 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5878 assert(E->getType()->isIntegralOrEnumerationType() &&
5879 "Invalid evaluation result.");
5880 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5881 "Invalid evaluation result.");
5882 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5883 "Invalid evaluation result.");
5884 Result = APValue(SI);
5887 bool Success(const llvm::APSInt &SI, const Expr *E) {
5888 return Success(SI, E, Result);
5891 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5892 assert(E->getType()->isIntegralOrEnumerationType() &&
5893 "Invalid evaluation result.");
5894 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5895 "Invalid evaluation result.");
5896 Result = APValue(APSInt(I));
5897 Result.getInt().setIsUnsigned(
5898 E->getType()->isUnsignedIntegerOrEnumerationType());
5901 bool Success(const llvm::APInt &I, const Expr *E) {
5902 return Success(I, E, Result);
5905 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5906 assert(E->getType()->isIntegralOrEnumerationType() &&
5907 "Invalid evaluation result.");
5908 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5911 bool Success(uint64_t Value, const Expr *E) {
5912 return Success(Value, E, Result);
5915 bool Success(CharUnits Size, const Expr *E) {
5916 return Success(Size.getQuantity(), E);
5919 bool Success(const APValue &V, const Expr *E) {
5920 if (V.isLValue() || V.isAddrLabelDiff()) {
5924 return Success(V.getInt(), E);
5927 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5929 //===--------------------------------------------------------------------===//
5931 //===--------------------------------------------------------------------===//
5933 bool VisitIntegerLiteral(const IntegerLiteral *E) {
5934 return Success(E->getValue(), E);
5936 bool VisitCharacterLiteral(const CharacterLiteral *E) {
5937 return Success(E->getValue(), E);
5940 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5941 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5942 if (CheckReferencedDecl(E, E->getDecl()))
5945 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5947 bool VisitMemberExpr(const MemberExpr *E) {
5948 if (CheckReferencedDecl(E, E->getMemberDecl())) {
5949 VisitIgnoredValue(E->getBase());
5953 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5956 bool VisitCallExpr(const CallExpr *E);
5957 bool VisitBinaryOperator(const BinaryOperator *E);
5958 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5959 bool VisitUnaryOperator(const UnaryOperator *E);
5961 bool VisitCastExpr(const CastExpr* E);
5962 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5964 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5965 return Success(E->getValue(), E);
5968 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5969 return Success(E->getValue(), E);
5972 // Note, GNU defines __null as an integer, not a pointer.
5973 bool VisitGNUNullExpr(const GNUNullExpr *E) {
5974 return ZeroInitialization(E);
5977 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5978 return Success(E->getValue(), E);
5981 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5982 return Success(E->getValue(), E);
5985 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5986 return Success(E->getValue(), E);
5989 bool VisitUnaryReal(const UnaryOperator *E);
5990 bool VisitUnaryImag(const UnaryOperator *E);
5992 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5993 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
5996 static QualType GetObjectType(APValue::LValueBase B);
5997 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
5998 // FIXME: Missing: array subscript of vector, member of vector
6000 } // end anonymous namespace
6002 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6003 /// produce either the integer value or a pointer.
6005 /// GCC has a heinous extension which folds casts between pointer types and
6006 /// pointer-sized integral types. We support this by allowing the evaluation of
6007 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6008 /// Some simple arithmetic on such values is supported (they are treated much
6010 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6012 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6013 return IntExprEvaluator(Info, Result).Visit(E);
6016 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6018 if (!EvaluateIntegerOrLValue(E, Val, Info))
6021 // FIXME: It would be better to produce the diagnostic for casting
6022 // a pointer to an integer.
6023 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6026 Result = Val.getInt();
6030 /// Check whether the given declaration can be directly converted to an integral
6031 /// rvalue. If not, no diagnostic is produced; there are other things we can
6033 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6034 // Enums are integer constant exprs.
6035 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6036 // Check for signedness/width mismatches between E type and ECD value.
6037 bool SameSign = (ECD->getInitVal().isSigned()
6038 == E->getType()->isSignedIntegerOrEnumerationType());
6039 bool SameWidth = (ECD->getInitVal().getBitWidth()
6040 == Info.Ctx.getIntWidth(E->getType()));
6041 if (SameSign && SameWidth)
6042 return Success(ECD->getInitVal(), E);
6044 // Get rid of mismatch (otherwise Success assertions will fail)
6045 // by computing a new value matching the type of E.
6046 llvm::APSInt Val = ECD->getInitVal();
6048 Val.setIsSigned(!ECD->getInitVal().isSigned());
6050 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6051 return Success(Val, E);
6057 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6059 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6060 // The following enum mimics the values returned by GCC.
6061 // FIXME: Does GCC differ between lvalue and rvalue references here?
6062 enum gcc_type_class {
6064 void_type_class, integer_type_class, char_type_class,
6065 enumeral_type_class, boolean_type_class,
6066 pointer_type_class, reference_type_class, offset_type_class,
6067 real_type_class, complex_type_class,
6068 function_type_class, method_type_class,
6069 record_type_class, union_type_class,
6070 array_type_class, string_type_class,
6074 // If no argument was supplied, default to "no_type_class". This isn't
6075 // ideal, however it is what gcc does.
6076 if (E->getNumArgs() == 0)
6077 return no_type_class;
6079 QualType ArgTy = E->getArg(0)->getType();
6080 if (ArgTy->isVoidType())
6081 return void_type_class;
6082 else if (ArgTy->isEnumeralType())
6083 return enumeral_type_class;
6084 else if (ArgTy->isBooleanType())
6085 return boolean_type_class;
6086 else if (ArgTy->isCharType())
6087 return string_type_class; // gcc doesn't appear to use char_type_class
6088 else if (ArgTy->isIntegerType())
6089 return integer_type_class;
6090 else if (ArgTy->isPointerType())
6091 return pointer_type_class;
6092 else if (ArgTy->isReferenceType())
6093 return reference_type_class;
6094 else if (ArgTy->isRealType())
6095 return real_type_class;
6096 else if (ArgTy->isComplexType())
6097 return complex_type_class;
6098 else if (ArgTy->isFunctionType())
6099 return function_type_class;
6100 else if (ArgTy->isStructureOrClassType())
6101 return record_type_class;
6102 else if (ArgTy->isUnionType())
6103 return union_type_class;
6104 else if (ArgTy->isArrayType())
6105 return array_type_class;
6106 else if (ArgTy->isUnionType())
6107 return union_type_class;
6108 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
6109 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6112 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6113 /// __builtin_constant_p when applied to the given lvalue.
6115 /// An lvalue is only "constant" if it is a pointer or reference to the first
6116 /// character of a string literal.
6117 template<typename LValue>
6118 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6119 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6120 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6123 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6124 /// GCC as we can manage.
6125 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6126 QualType ArgType = Arg->getType();
6128 // __builtin_constant_p always has one operand. The rules which gcc follows
6129 // are not precisely documented, but are as follows:
6131 // - If the operand is of integral, floating, complex or enumeration type,
6132 // and can be folded to a known value of that type, it returns 1.
6133 // - If the operand and can be folded to a pointer to the first character
6134 // of a string literal (or such a pointer cast to an integral type), it
6137 // Otherwise, it returns 0.
6139 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6140 // its support for this does not currently work.
6141 if (ArgType->isIntegralOrEnumerationType()) {
6142 Expr::EvalResult Result;
6143 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6146 APValue &V = Result.Val;
6147 if (V.getKind() == APValue::Int)
6150 return EvaluateBuiltinConstantPForLValue(V);
6151 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6152 return Arg->isEvaluatable(Ctx);
6153 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6155 Expr::EvalStatus Status;
6156 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6157 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6158 : EvaluatePointer(Arg, LV, Info)) &&
6159 !Status.HasSideEffects)
6160 return EvaluateBuiltinConstantPForLValue(LV);
6163 // Anything else isn't considered to be sufficiently constant.
6167 /// Retrieves the "underlying object type" of the given expression,
6168 /// as used by __builtin_object_size.
6169 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6170 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6171 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6172 return VD->getType();
6173 } else if (const Expr *E = B.get<const Expr*>()) {
6174 if (isa<CompoundLiteralExpr>(E))
6175 return E->getType();
6181 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
6185 // The operand of __builtin_object_size is never evaluated for side-effects.
6186 // If there are any, but we can determine the pointed-to object anyway, then
6187 // ignore the side-effects.
6188 SpeculativeEvaluationRAII SpeculativeEval(Info);
6189 if (!EvaluatePointer(E->getArg(0), Base, Info))
6193 if (!Base.getLValueBase()) {
6194 // It is not possible to determine which objects ptr points to at compile time,
6195 // __builtin_object_size should return (size_t) -1 for type 0 or 1
6196 // and (size_t) 0 for type 2 or 3.
6197 llvm::APSInt TypeIntVaue;
6198 const Expr *ExprType = E->getArg(1);
6199 if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6201 if (TypeIntVaue == 0 || TypeIntVaue == 1)
6202 return Success(-1, E);
6203 if (TypeIntVaue == 2 || TypeIntVaue == 3)
6204 return Success(0, E);
6208 QualType T = GetObjectType(Base.getLValueBase());
6210 T->isIncompleteType() ||
6211 T->isFunctionType() ||
6212 T->isVariablyModifiedType() ||
6213 T->isDependentType())
6216 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6217 CharUnits Offset = Base.getLValueOffset();
6219 if (!Offset.isNegative() && Offset <= Size)
6222 Size = CharUnits::Zero();
6223 return Success(Size, E);
6226 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6227 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6229 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6231 case Builtin::BI__builtin_object_size: {
6232 if (TryEvaluateBuiltinObjectSize(E))
6235 // If evaluating the argument has side-effects, we can't determine the size
6236 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6237 // handle all cases where the expression has side-effects.
6238 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
6239 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
6240 return Success(-1ULL, E);
6241 return Success(0, E);
6244 // Expression had no side effects, but we couldn't statically determine the
6245 // size of the referenced object.
6246 switch (Info.EvalMode) {
6247 case EvalInfo::EM_ConstantExpression:
6248 case EvalInfo::EM_PotentialConstantExpression:
6249 case EvalInfo::EM_ConstantFold:
6250 case EvalInfo::EM_EvaluateForOverflow:
6251 case EvalInfo::EM_IgnoreSideEffects:
6253 case EvalInfo::EM_ConstantExpressionUnevaluated:
6254 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6255 return Success(-1ULL, E);
6259 case Builtin::BI__builtin_bswap16:
6260 case Builtin::BI__builtin_bswap32:
6261 case Builtin::BI__builtin_bswap64: {
6263 if (!EvaluateInteger(E->getArg(0), Val, Info))
6266 return Success(Val.byteSwap(), E);
6269 case Builtin::BI__builtin_classify_type:
6270 return Success(EvaluateBuiltinClassifyType(E), E);
6272 // FIXME: BI__builtin_clrsb
6273 // FIXME: BI__builtin_clrsbl
6274 // FIXME: BI__builtin_clrsbll
6276 case Builtin::BI__builtin_clz:
6277 case Builtin::BI__builtin_clzl:
6278 case Builtin::BI__builtin_clzll:
6279 case Builtin::BI__builtin_clzs: {
6281 if (!EvaluateInteger(E->getArg(0), Val, Info))
6286 return Success(Val.countLeadingZeros(), E);
6289 case Builtin::BI__builtin_constant_p:
6290 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6292 case Builtin::BI__builtin_ctz:
6293 case Builtin::BI__builtin_ctzl:
6294 case Builtin::BI__builtin_ctzll:
6295 case Builtin::BI__builtin_ctzs: {
6297 if (!EvaluateInteger(E->getArg(0), Val, Info))
6302 return Success(Val.countTrailingZeros(), E);
6305 case Builtin::BI__builtin_eh_return_data_regno: {
6306 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6307 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6308 return Success(Operand, E);
6311 case Builtin::BI__builtin_expect:
6312 return Visit(E->getArg(0));
6314 case Builtin::BI__builtin_ffs:
6315 case Builtin::BI__builtin_ffsl:
6316 case Builtin::BI__builtin_ffsll: {
6318 if (!EvaluateInteger(E->getArg(0), Val, Info))
6321 unsigned N = Val.countTrailingZeros();
6322 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6325 case Builtin::BI__builtin_fpclassify: {
6327 if (!EvaluateFloat(E->getArg(5), Val, Info))
6330 switch (Val.getCategory()) {
6331 case APFloat::fcNaN: Arg = 0; break;
6332 case APFloat::fcInfinity: Arg = 1; break;
6333 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6334 case APFloat::fcZero: Arg = 4; break;
6336 return Visit(E->getArg(Arg));
6339 case Builtin::BI__builtin_isinf_sign: {
6341 return EvaluateFloat(E->getArg(0), Val, Info) &&
6342 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6345 case Builtin::BI__builtin_isinf: {
6347 return EvaluateFloat(E->getArg(0), Val, Info) &&
6348 Success(Val.isInfinity() ? 1 : 0, E);
6351 case Builtin::BI__builtin_isfinite: {
6353 return EvaluateFloat(E->getArg(0), Val, Info) &&
6354 Success(Val.isFinite() ? 1 : 0, E);
6357 case Builtin::BI__builtin_isnan: {
6359 return EvaluateFloat(E->getArg(0), Val, Info) &&
6360 Success(Val.isNaN() ? 1 : 0, E);
6363 case Builtin::BI__builtin_isnormal: {
6365 return EvaluateFloat(E->getArg(0), Val, Info) &&
6366 Success(Val.isNormal() ? 1 : 0, E);
6369 case Builtin::BI__builtin_parity:
6370 case Builtin::BI__builtin_parityl:
6371 case Builtin::BI__builtin_parityll: {
6373 if (!EvaluateInteger(E->getArg(0), Val, Info))
6376 return Success(Val.countPopulation() % 2, E);
6379 case Builtin::BI__builtin_popcount:
6380 case Builtin::BI__builtin_popcountl:
6381 case Builtin::BI__builtin_popcountll: {
6383 if (!EvaluateInteger(E->getArg(0), Val, Info))
6386 return Success(Val.countPopulation(), E);
6389 case Builtin::BIstrlen:
6390 // A call to strlen is not a constant expression.
6391 if (Info.getLangOpts().CPlusPlus11)
6392 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6393 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6395 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6397 case Builtin::BI__builtin_strlen: {
6398 // As an extension, we support __builtin_strlen() as a constant expression,
6399 // and support folding strlen() to a constant.
6401 if (!EvaluatePointer(E->getArg(0), String, Info))
6404 // Fast path: if it's a string literal, search the string value.
6405 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6406 String.getLValueBase().dyn_cast<const Expr *>())) {
6407 // The string literal may have embedded null characters. Find the first
6408 // one and truncate there.
6409 StringRef Str = S->getBytes();
6410 int64_t Off = String.Offset.getQuantity();
6411 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6412 S->getCharByteWidth() == 1) {
6413 Str = Str.substr(Off);
6415 StringRef::size_type Pos = Str.find(0);
6416 if (Pos != StringRef::npos)
6417 Str = Str.substr(0, Pos);
6419 return Success(Str.size(), E);
6422 // Fall through to slow path to issue appropriate diagnostic.
6425 // Slow path: scan the bytes of the string looking for the terminating 0.
6426 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6427 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6429 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6433 return Success(Strlen, E);
6434 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6439 case Builtin::BI__atomic_always_lock_free:
6440 case Builtin::BI__atomic_is_lock_free:
6441 case Builtin::BI__c11_atomic_is_lock_free: {
6443 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6446 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6447 // of two less than the maximum inline atomic width, we know it is
6448 // lock-free. If the size isn't a power of two, or greater than the
6449 // maximum alignment where we promote atomics, we know it is not lock-free
6450 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6451 // the answer can only be determined at runtime; for example, 16-byte
6452 // atomics have lock-free implementations on some, but not all,
6453 // x86-64 processors.
6455 // Check power-of-two.
6456 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6457 if (Size.isPowerOfTwo()) {
6458 // Check against inlining width.
6459 unsigned InlineWidthBits =
6460 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6461 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6462 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6463 Size == CharUnits::One() ||
6464 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6465 Expr::NPC_NeverValueDependent))
6466 // OK, we will inline appropriately-aligned operations of this size,
6467 // and _Atomic(T) is appropriately-aligned.
6468 return Success(1, E);
6470 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6471 castAs<PointerType>()->getPointeeType();
6472 if (!PointeeType->isIncompleteType() &&
6473 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6474 // OK, we will inline operations on this object.
6475 return Success(1, E);
6480 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6481 Success(0, E) : Error(E);
6486 static bool HasSameBase(const LValue &A, const LValue &B) {
6487 if (!A.getLValueBase())
6488 return !B.getLValueBase();
6489 if (!B.getLValueBase())
6492 if (A.getLValueBase().getOpaqueValue() !=
6493 B.getLValueBase().getOpaqueValue()) {
6494 const Decl *ADecl = GetLValueBaseDecl(A);
6497 const Decl *BDecl = GetLValueBaseDecl(B);
6498 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6502 return IsGlobalLValue(A.getLValueBase()) ||
6503 A.getLValueCallIndex() == B.getLValueCallIndex();
6506 /// \brief Determine whether this is a pointer past the end of the complete
6507 /// object referred to by the lvalue.
6508 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6510 // A null pointer can be viewed as being "past the end" but we don't
6511 // choose to look at it that way here.
6512 if (!LV.getLValueBase())
6515 // If the designator is valid and refers to a subobject, we're not pointing
6517 if (!LV.getLValueDesignator().Invalid &&
6518 !LV.getLValueDesignator().isOnePastTheEnd())
6521 // We're a past-the-end pointer if we point to the byte after the object,
6522 // no matter what our type or path is.
6523 auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
6524 return LV.getLValueOffset() == Size;
6529 /// \brief Data recursive integer evaluator of certain binary operators.
6531 /// We use a data recursive algorithm for binary operators so that we are able
6532 /// to handle extreme cases of chained binary operators without causing stack
6534 class DataRecursiveIntBinOpEvaluator {
6539 EvalResult() : Failed(false) { }
6541 void swap(EvalResult &RHS) {
6543 Failed = RHS.Failed;
6550 EvalResult LHSResult; // meaningful only for binary operator expression.
6551 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6553 Job() : StoredInfo(nullptr) {}
6554 void startSpeculativeEval(EvalInfo &Info) {
6555 OldEvalStatus = Info.EvalStatus;
6556 Info.EvalStatus.Diag = nullptr;
6561 StoredInfo->EvalStatus = OldEvalStatus;
6565 EvalInfo *StoredInfo; // non-null if status changed.
6566 Expr::EvalStatus OldEvalStatus;
6569 SmallVector<Job, 16> Queue;
6571 IntExprEvaluator &IntEval;
6573 APValue &FinalResult;
6576 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6577 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6579 /// \brief True if \param E is a binary operator that we are going to handle
6580 /// data recursively.
6581 /// We handle binary operators that are comma, logical, or that have operands
6582 /// with integral or enumeration type.
6583 static bool shouldEnqueue(const BinaryOperator *E) {
6584 return E->getOpcode() == BO_Comma ||
6586 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6587 E->getRHS()->getType()->isIntegralOrEnumerationType());
6590 bool Traverse(const BinaryOperator *E) {
6592 EvalResult PrevResult;
6593 while (!Queue.empty())
6594 process(PrevResult);
6596 if (PrevResult.Failed) return false;
6598 FinalResult.swap(PrevResult.Val);
6603 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6604 return IntEval.Success(Value, E, Result);
6606 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6607 return IntEval.Success(Value, E, Result);
6609 bool Error(const Expr *E) {
6610 return IntEval.Error(E);
6612 bool Error(const Expr *E, diag::kind D) {
6613 return IntEval.Error(E, D);
6616 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6617 return Info.CCEDiag(E, D);
6620 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6621 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6622 bool &SuppressRHSDiags);
6624 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6625 const BinaryOperator *E, APValue &Result);
6627 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6628 Result.Failed = !Evaluate(Result.Val, Info, E);
6630 Result.Val = APValue();
6633 void process(EvalResult &Result);
6635 void enqueue(const Expr *E) {
6636 E = E->IgnoreParens();
6637 Queue.resize(Queue.size()+1);
6639 Queue.back().Kind = Job::AnyExprKind;
6645 bool DataRecursiveIntBinOpEvaluator::
6646 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6647 bool &SuppressRHSDiags) {
6648 if (E->getOpcode() == BO_Comma) {
6649 // Ignore LHS but note if we could not evaluate it.
6650 if (LHSResult.Failed)
6651 return Info.noteSideEffect();
6655 if (E->isLogicalOp()) {
6657 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6658 // We were able to evaluate the LHS, see if we can get away with not
6659 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6660 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6661 Success(LHSAsBool, E, LHSResult.Val);
6662 return false; // Ignore RHS
6665 LHSResult.Failed = true;
6667 // Since we weren't able to evaluate the left hand side, it
6668 // must have had side effects.
6669 if (!Info.noteSideEffect())
6672 // We can't evaluate the LHS; however, sometimes the result
6673 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6674 // Don't ignore RHS and suppress diagnostics from this arm.
6675 SuppressRHSDiags = true;
6681 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6682 E->getRHS()->getType()->isIntegralOrEnumerationType());
6684 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6685 return false; // Ignore RHS;
6690 bool DataRecursiveIntBinOpEvaluator::
6691 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6692 const BinaryOperator *E, APValue &Result) {
6693 if (E->getOpcode() == BO_Comma) {
6694 if (RHSResult.Failed)
6696 Result = RHSResult.Val;
6700 if (E->isLogicalOp()) {
6701 bool lhsResult, rhsResult;
6702 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6703 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6707 if (E->getOpcode() == BO_LOr)
6708 return Success(lhsResult || rhsResult, E, Result);
6710 return Success(lhsResult && rhsResult, E, Result);
6714 // We can't evaluate the LHS; however, sometimes the result
6715 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6716 if (rhsResult == (E->getOpcode() == BO_LOr))
6717 return Success(rhsResult, E, Result);
6724 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6725 E->getRHS()->getType()->isIntegralOrEnumerationType());
6727 if (LHSResult.Failed || RHSResult.Failed)
6730 const APValue &LHSVal = LHSResult.Val;
6731 const APValue &RHSVal = RHSResult.Val;
6733 // Handle cases like (unsigned long)&a + 4.
6734 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6736 CharUnits AdditionalOffset =
6737 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6738 if (E->getOpcode() == BO_Add)
6739 Result.getLValueOffset() += AdditionalOffset;
6741 Result.getLValueOffset() -= AdditionalOffset;
6745 // Handle cases like 4 + (unsigned long)&a
6746 if (E->getOpcode() == BO_Add &&
6747 RHSVal.isLValue() && LHSVal.isInt()) {
6749 Result.getLValueOffset() +=
6750 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6754 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6755 // Handle (intptr_t)&&A - (intptr_t)&&B.
6756 if (!LHSVal.getLValueOffset().isZero() ||
6757 !RHSVal.getLValueOffset().isZero())
6759 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6760 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6761 if (!LHSExpr || !RHSExpr)
6763 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6764 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6765 if (!LHSAddrExpr || !RHSAddrExpr)
6767 // Make sure both labels come from the same function.
6768 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6769 RHSAddrExpr->getLabel()->getDeclContext())
6771 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6775 // All the remaining cases expect both operands to be an integer
6776 if (!LHSVal.isInt() || !RHSVal.isInt())
6779 // Set up the width and signedness manually, in case it can't be deduced
6780 // from the operation we're performing.
6781 // FIXME: Don't do this in the cases where we can deduce it.
6782 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6783 E->getType()->isUnsignedIntegerOrEnumerationType());
6784 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6785 RHSVal.getInt(), Value))
6787 return Success(Value, E, Result);
6790 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6791 Job &job = Queue.back();
6794 case Job::AnyExprKind: {
6795 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6796 if (shouldEnqueue(Bop)) {
6797 job.Kind = Job::BinOpKind;
6798 enqueue(Bop->getLHS());
6803 EvaluateExpr(job.E, Result);
6808 case Job::BinOpKind: {
6809 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6810 bool SuppressRHSDiags = false;
6811 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6815 if (SuppressRHSDiags)
6816 job.startSpeculativeEval(Info);
6817 job.LHSResult.swap(Result);
6818 job.Kind = Job::BinOpVisitedLHSKind;
6819 enqueue(Bop->getRHS());
6823 case Job::BinOpVisitedLHSKind: {
6824 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6827 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6833 llvm_unreachable("Invalid Job::Kind!");
6836 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6837 if (E->isAssignmentOp())
6840 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6841 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6843 QualType LHSTy = E->getLHS()->getType();
6844 QualType RHSTy = E->getRHS()->getType();
6846 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
6847 ComplexValue LHS, RHS;
6849 if (E->getLHS()->getType()->isRealFloatingType()) {
6850 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
6852 LHS.makeComplexFloat();
6853 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
6856 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6858 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6861 if (E->getRHS()->getType()->isRealFloatingType()) {
6862 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
6864 RHS.makeComplexFloat();
6865 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
6866 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6869 if (LHS.isComplexFloat()) {
6870 APFloat::cmpResult CR_r =
6871 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6872 APFloat::cmpResult CR_i =
6873 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6875 if (E->getOpcode() == BO_EQ)
6876 return Success((CR_r == APFloat::cmpEqual &&
6877 CR_i == APFloat::cmpEqual), E);
6879 assert(E->getOpcode() == BO_NE &&
6880 "Invalid complex comparison.");
6881 return Success(((CR_r == APFloat::cmpGreaterThan ||
6882 CR_r == APFloat::cmpLessThan ||
6883 CR_r == APFloat::cmpUnordered) ||
6884 (CR_i == APFloat::cmpGreaterThan ||
6885 CR_i == APFloat::cmpLessThan ||
6886 CR_i == APFloat::cmpUnordered)), E);
6889 if (E->getOpcode() == BO_EQ)
6890 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6891 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6893 assert(E->getOpcode() == BO_NE &&
6894 "Invalid compex comparison.");
6895 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6896 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6901 if (LHSTy->isRealFloatingType() &&
6902 RHSTy->isRealFloatingType()) {
6903 APFloat RHS(0.0), LHS(0.0);
6905 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6906 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6909 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6912 APFloat::cmpResult CR = LHS.compare(RHS);
6914 switch (E->getOpcode()) {
6916 llvm_unreachable("Invalid binary operator!");
6918 return Success(CR == APFloat::cmpLessThan, E);
6920 return Success(CR == APFloat::cmpGreaterThan, E);
6922 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6924 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6927 return Success(CR == APFloat::cmpEqual, E);
6929 return Success(CR == APFloat::cmpGreaterThan
6930 || CR == APFloat::cmpLessThan
6931 || CR == APFloat::cmpUnordered, E);
6935 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6936 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6937 LValue LHSValue, RHSValue;
6939 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6940 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6943 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6946 // Reject differing bases from the normal codepath; we special-case
6947 // comparisons to null.
6948 if (!HasSameBase(LHSValue, RHSValue)) {
6949 if (E->getOpcode() == BO_Sub) {
6950 // Handle &&A - &&B.
6951 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6953 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6954 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6955 if (!LHSExpr || !RHSExpr)
6957 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6958 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6959 if (!LHSAddrExpr || !RHSAddrExpr)
6961 // Make sure both labels come from the same function.
6962 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6963 RHSAddrExpr->getLabel()->getDeclContext())
6965 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6968 // Inequalities and subtractions between unrelated pointers have
6969 // unspecified or undefined behavior.
6970 if (!E->isEqualityOp())
6972 // A constant address may compare equal to the address of a symbol.
6973 // The one exception is that address of an object cannot compare equal
6974 // to a null pointer constant.
6975 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6976 (!RHSValue.Base && !RHSValue.Offset.isZero()))
6978 // It's implementation-defined whether distinct literals will have
6979 // distinct addresses. In clang, the result of such a comparison is
6980 // unspecified, so it is not a constant expression. However, we do know
6981 // that the address of a literal will be non-null.
6982 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6983 LHSValue.Base && RHSValue.Base)
6985 // We can't tell whether weak symbols will end up pointing to the same
6987 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6989 // We can't compare the address of the start of one object with the
6990 // past-the-end address of another object, per C++ DR1652.
6991 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
6992 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
6993 (RHSValue.Base && RHSValue.Offset.isZero() &&
6994 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
6996 // We can't tell whether an object is at the same address as another
6997 // zero sized object.
6998 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
6999 (LHSValue.Base && isZeroSized(RHSValue)))
7001 // Pointers with different bases cannot represent the same object.
7002 // (Note that clang defaults to -fmerge-all-constants, which can
7003 // lead to inconsistent results for comparisons involving the address
7004 // of a constant; this generally doesn't matter in practice.)
7005 return Success(E->getOpcode() == BO_NE, E);
7008 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7009 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7011 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7012 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7014 if (E->getOpcode() == BO_Sub) {
7015 // C++11 [expr.add]p6:
7016 // Unless both pointers point to elements of the same array object, or
7017 // one past the last element of the array object, the behavior is
7019 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7020 !AreElementsOfSameArray(getType(LHSValue.Base),
7021 LHSDesignator, RHSDesignator))
7022 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7024 QualType Type = E->getLHS()->getType();
7025 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7027 CharUnits ElementSize;
7028 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7031 // As an extension, a type may have zero size (empty struct or union in
7032 // C, array of zero length). Pointer subtraction in such cases has
7033 // undefined behavior, so is not constant.
7034 if (ElementSize.isZero()) {
7035 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7040 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7041 // and produce incorrect results when it overflows. Such behavior
7042 // appears to be non-conforming, but is common, so perhaps we should
7043 // assume the standard intended for such cases to be undefined behavior
7044 // and check for them.
7046 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7047 // overflow in the final conversion to ptrdiff_t.
7049 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7051 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7053 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7054 APSInt TrueResult = (LHS - RHS) / ElemSize;
7055 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7057 if (Result.extend(65) != TrueResult)
7058 HandleOverflow(Info, E, TrueResult, E->getType());
7059 return Success(Result, E);
7062 // C++11 [expr.rel]p3:
7063 // Pointers to void (after pointer conversions) can be compared, with a
7064 // result defined as follows: If both pointers represent the same
7065 // address or are both the null pointer value, the result is true if the
7066 // operator is <= or >= and false otherwise; otherwise the result is
7068 // We interpret this as applying to pointers to *cv* void.
7069 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7070 E->isRelationalOp())
7071 CCEDiag(E, diag::note_constexpr_void_comparison);
7073 // C++11 [expr.rel]p2:
7074 // - If two pointers point to non-static data members of the same object,
7075 // or to subobjects or array elements fo such members, recursively, the
7076 // pointer to the later declared member compares greater provided the
7077 // two members have the same access control and provided their class is
7080 // - Otherwise pointer comparisons are unspecified.
7081 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7082 E->isRelationalOp()) {
7085 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7086 RHSDesignator, WasArrayIndex);
7087 // At the point where the designators diverge, the comparison has a
7088 // specified value if:
7089 // - we are comparing array indices
7090 // - we are comparing fields of a union, or fields with the same access
7091 // Otherwise, the result is unspecified and thus the comparison is not a
7092 // constant expression.
7093 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7094 Mismatch < RHSDesignator.Entries.size()) {
7095 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7096 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7098 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7100 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7101 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7102 << RF->getParent() << RF;
7104 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7105 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7106 << LF->getParent() << LF;
7107 else if (!LF->getParent()->isUnion() &&
7108 LF->getAccess() != RF->getAccess())
7109 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7110 << LF << LF->getAccess() << RF << RF->getAccess()
7115 // The comparison here must be unsigned, and performed with the same
7116 // width as the pointer.
7117 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7118 uint64_t CompareLHS = LHSOffset.getQuantity();
7119 uint64_t CompareRHS = RHSOffset.getQuantity();
7120 assert(PtrSize <= 64 && "Unexpected pointer width");
7121 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7125 // If there is a base and this is a relational operator, we can only
7126 // compare pointers within the object in question; otherwise, the result
7127 // depends on where the object is located in memory.
7128 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7129 QualType BaseTy = getType(LHSValue.Base);
7130 if (BaseTy->isIncompleteType())
7132 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7133 uint64_t OffsetLimit = Size.getQuantity();
7134 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7138 switch (E->getOpcode()) {
7139 default: llvm_unreachable("missing comparison operator");
7140 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7141 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7142 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7143 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7144 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7145 case BO_NE: return Success(CompareLHS != CompareRHS, E);
7150 if (LHSTy->isMemberPointerType()) {
7151 assert(E->isEqualityOp() && "unexpected member pointer operation");
7152 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7154 MemberPtr LHSValue, RHSValue;
7156 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7157 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7160 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7163 // C++11 [expr.eq]p2:
7164 // If both operands are null, they compare equal. Otherwise if only one is
7165 // null, they compare unequal.
7166 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7167 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7168 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7171 // Otherwise if either is a pointer to a virtual member function, the
7172 // result is unspecified.
7173 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7174 if (MD->isVirtual())
7175 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7176 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7177 if (MD->isVirtual())
7178 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7180 // Otherwise they compare equal if and only if they would refer to the
7181 // same member of the same most derived object or the same subobject if
7182 // they were dereferenced with a hypothetical object of the associated
7184 bool Equal = LHSValue == RHSValue;
7185 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7188 if (LHSTy->isNullPtrType()) {
7189 assert(E->isComparisonOp() && "unexpected nullptr operation");
7190 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7191 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7192 // are compared, the result is true of the operator is <=, >= or ==, and
7194 BinaryOperator::Opcode Opcode = E->getOpcode();
7195 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7198 assert((!LHSTy->isIntegralOrEnumerationType() ||
7199 !RHSTy->isIntegralOrEnumerationType()) &&
7200 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7201 // We can't continue from here for non-integral types.
7202 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7205 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7206 /// a result as the expression's type.
7207 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7208 const UnaryExprOrTypeTraitExpr *E) {
7209 switch(E->getKind()) {
7210 case UETT_AlignOf: {
7211 if (E->isArgumentType())
7212 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7214 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7217 case UETT_VecStep: {
7218 QualType Ty = E->getTypeOfArgument();
7220 if (Ty->isVectorType()) {
7221 unsigned n = Ty->castAs<VectorType>()->getNumElements();
7223 // The vec_step built-in functions that take a 3-component
7224 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7228 return Success(n, E);
7230 return Success(1, E);
7234 QualType SrcTy = E->getTypeOfArgument();
7235 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7236 // the result is the size of the referenced type."
7237 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7238 SrcTy = Ref->getPointeeType();
7241 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7243 return Success(Sizeof, E);
7247 llvm_unreachable("unknown expr/type trait");
7250 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7252 unsigned n = OOE->getNumComponents();
7255 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7256 for (unsigned i = 0; i != n; ++i) {
7257 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7258 switch (ON.getKind()) {
7259 case OffsetOfExpr::OffsetOfNode::Array: {
7260 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7262 if (!EvaluateInteger(Idx, IdxResult, Info))
7264 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7267 CurrentType = AT->getElementType();
7268 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7269 Result += IdxResult.getSExtValue() * ElementSize;
7273 case OffsetOfExpr::OffsetOfNode::Field: {
7274 FieldDecl *MemberDecl = ON.getField();
7275 const RecordType *RT = CurrentType->getAs<RecordType>();
7278 RecordDecl *RD = RT->getDecl();
7279 if (RD->isInvalidDecl()) return false;
7280 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7281 unsigned i = MemberDecl->getFieldIndex();
7282 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7283 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7284 CurrentType = MemberDecl->getType().getNonReferenceType();
7288 case OffsetOfExpr::OffsetOfNode::Identifier:
7289 llvm_unreachable("dependent __builtin_offsetof");
7291 case OffsetOfExpr::OffsetOfNode::Base: {
7292 CXXBaseSpecifier *BaseSpec = ON.getBase();
7293 if (BaseSpec->isVirtual())
7296 // Find the layout of the class whose base we are looking into.
7297 const RecordType *RT = CurrentType->getAs<RecordType>();
7300 RecordDecl *RD = RT->getDecl();
7301 if (RD->isInvalidDecl()) return false;
7302 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7304 // Find the base class itself.
7305 CurrentType = BaseSpec->getType();
7306 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7310 // Add the offset to the base.
7311 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7316 return Success(Result, OOE);
7319 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7320 switch (E->getOpcode()) {
7322 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7326 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7327 // If so, we could clear the diagnostic ID.
7328 return Visit(E->getSubExpr());
7330 // The result is just the value.
7331 return Visit(E->getSubExpr());
7333 if (!Visit(E->getSubExpr()))
7335 if (!Result.isInt()) return Error(E);
7336 const APSInt &Value = Result.getInt();
7337 if (Value.isSigned() && Value.isMinSignedValue())
7338 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7340 return Success(-Value, E);
7343 if (!Visit(E->getSubExpr()))
7345 if (!Result.isInt()) return Error(E);
7346 return Success(~Result.getInt(), E);
7350 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7352 return Success(!bres, E);
7357 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7358 /// result type is integer.
7359 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7360 const Expr *SubExpr = E->getSubExpr();
7361 QualType DestType = E->getType();
7362 QualType SrcType = SubExpr->getType();
7364 switch (E->getCastKind()) {
7365 case CK_BaseToDerived:
7366 case CK_DerivedToBase:
7367 case CK_UncheckedDerivedToBase:
7370 case CK_ArrayToPointerDecay:
7371 case CK_FunctionToPointerDecay:
7372 case CK_NullToPointer:
7373 case CK_NullToMemberPointer:
7374 case CK_BaseToDerivedMemberPointer:
7375 case CK_DerivedToBaseMemberPointer:
7376 case CK_ReinterpretMemberPointer:
7377 case CK_ConstructorConversion:
7378 case CK_IntegralToPointer:
7380 case CK_VectorSplat:
7381 case CK_IntegralToFloating:
7382 case CK_FloatingCast:
7383 case CK_CPointerToObjCPointerCast:
7384 case CK_BlockPointerToObjCPointerCast:
7385 case CK_AnyPointerToBlockPointerCast:
7386 case CK_ObjCObjectLValueCast:
7387 case CK_FloatingRealToComplex:
7388 case CK_FloatingComplexToReal:
7389 case CK_FloatingComplexCast:
7390 case CK_FloatingComplexToIntegralComplex:
7391 case CK_IntegralRealToComplex:
7392 case CK_IntegralComplexCast:
7393 case CK_IntegralComplexToFloatingComplex:
7394 case CK_BuiltinFnToFnPtr:
7395 case CK_ZeroToOCLEvent:
7396 case CK_NonAtomicToAtomic:
7397 case CK_AddressSpaceConversion:
7398 llvm_unreachable("invalid cast kind for integral value");
7402 case CK_LValueBitCast:
7403 case CK_ARCProduceObject:
7404 case CK_ARCConsumeObject:
7405 case CK_ARCReclaimReturnedObject:
7406 case CK_ARCExtendBlockObject:
7407 case CK_CopyAndAutoreleaseBlockObject:
7410 case CK_UserDefinedConversion:
7411 case CK_LValueToRValue:
7412 case CK_AtomicToNonAtomic:
7414 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7416 case CK_MemberPointerToBoolean:
7417 case CK_PointerToBoolean:
7418 case CK_IntegralToBoolean:
7419 case CK_FloatingToBoolean:
7420 case CK_FloatingComplexToBoolean:
7421 case CK_IntegralComplexToBoolean: {
7423 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7425 return Success(BoolResult, E);
7428 case CK_IntegralCast: {
7429 if (!Visit(SubExpr))
7432 if (!Result.isInt()) {
7433 // Allow casts of address-of-label differences if they are no-ops
7434 // or narrowing. (The narrowing case isn't actually guaranteed to
7435 // be constant-evaluatable except in some narrow cases which are hard
7436 // to detect here. We let it through on the assumption the user knows
7437 // what they are doing.)
7438 if (Result.isAddrLabelDiff())
7439 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7440 // Only allow casts of lvalues if they are lossless.
7441 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7444 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7445 Result.getInt()), E);
7448 case CK_PointerToIntegral: {
7449 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7452 if (!EvaluatePointer(SubExpr, LV, Info))
7455 if (LV.getLValueBase()) {
7456 // Only allow based lvalue casts if they are lossless.
7457 // FIXME: Allow a larger integer size than the pointer size, and allow
7458 // narrowing back down to pointer width in subsequent integral casts.
7459 // FIXME: Check integer type's active bits, not its type size.
7460 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7463 LV.Designator.setInvalid();
7464 LV.moveInto(Result);
7468 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7470 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7473 case CK_IntegralComplexToReal: {
7475 if (!EvaluateComplex(SubExpr, C, Info))
7477 return Success(C.getComplexIntReal(), E);
7480 case CK_FloatingToIntegral: {
7482 if (!EvaluateFloat(SubExpr, F, Info))
7486 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7488 return Success(Value, E);
7492 llvm_unreachable("unknown cast resulting in integral value");
7495 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7496 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7498 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7500 if (!LV.isComplexInt())
7502 return Success(LV.getComplexIntReal(), E);
7505 return Visit(E->getSubExpr());
7508 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7509 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7511 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7513 if (!LV.isComplexInt())
7515 return Success(LV.getComplexIntImag(), E);
7518 VisitIgnoredValue(E->getSubExpr());
7519 return Success(0, E);
7522 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7523 return Success(E->getPackLength(), E);
7526 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7527 return Success(E->getValue(), E);
7530 //===----------------------------------------------------------------------===//
7532 //===----------------------------------------------------------------------===//
7535 class FloatExprEvaluator
7536 : public ExprEvaluatorBase<FloatExprEvaluator> {
7539 FloatExprEvaluator(EvalInfo &info, APFloat &result)
7540 : ExprEvaluatorBaseTy(info), Result(result) {}
7542 bool Success(const APValue &V, const Expr *e) {
7543 Result = V.getFloat();
7547 bool ZeroInitialization(const Expr *E) {
7548 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7552 bool VisitCallExpr(const CallExpr *E);
7554 bool VisitUnaryOperator(const UnaryOperator *E);
7555 bool VisitBinaryOperator(const BinaryOperator *E);
7556 bool VisitFloatingLiteral(const FloatingLiteral *E);
7557 bool VisitCastExpr(const CastExpr *E);
7559 bool VisitUnaryReal(const UnaryOperator *E);
7560 bool VisitUnaryImag(const UnaryOperator *E);
7562 // FIXME: Missing: array subscript of vector, member of vector
7564 } // end anonymous namespace
7566 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7567 assert(E->isRValue() && E->getType()->isRealFloatingType());
7568 return FloatExprEvaluator(Info, Result).Visit(E);
7571 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7575 llvm::APFloat &Result) {
7576 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7577 if (!S) return false;
7579 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7583 // Treat empty strings as if they were zero.
7584 if (S->getString().empty())
7585 fill = llvm::APInt(32, 0);
7586 else if (S->getString().getAsInteger(0, fill))
7590 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7592 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7596 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7597 switch (E->getBuiltinCallee()) {
7599 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7601 case Builtin::BI__builtin_huge_val:
7602 case Builtin::BI__builtin_huge_valf:
7603 case Builtin::BI__builtin_huge_vall:
7604 case Builtin::BI__builtin_inf:
7605 case Builtin::BI__builtin_inff:
7606 case Builtin::BI__builtin_infl: {
7607 const llvm::fltSemantics &Sem =
7608 Info.Ctx.getFloatTypeSemantics(E->getType());
7609 Result = llvm::APFloat::getInf(Sem);
7613 case Builtin::BI__builtin_nans:
7614 case Builtin::BI__builtin_nansf:
7615 case Builtin::BI__builtin_nansl:
7616 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7621 case Builtin::BI__builtin_nan:
7622 case Builtin::BI__builtin_nanf:
7623 case Builtin::BI__builtin_nanl:
7624 // If this is __builtin_nan() turn this into a nan, otherwise we
7625 // can't constant fold it.
7626 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7631 case Builtin::BI__builtin_fabs:
7632 case Builtin::BI__builtin_fabsf:
7633 case Builtin::BI__builtin_fabsl:
7634 if (!EvaluateFloat(E->getArg(0), Result, Info))
7637 if (Result.isNegative())
7638 Result.changeSign();
7641 // FIXME: Builtin::BI__builtin_powi
7642 // FIXME: Builtin::BI__builtin_powif
7643 // FIXME: Builtin::BI__builtin_powil
7645 case Builtin::BI__builtin_copysign:
7646 case Builtin::BI__builtin_copysignf:
7647 case Builtin::BI__builtin_copysignl: {
7649 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7650 !EvaluateFloat(E->getArg(1), RHS, Info))
7652 Result.copySign(RHS);
7658 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7659 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7661 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7663 Result = CV.FloatReal;
7667 return Visit(E->getSubExpr());
7670 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7671 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7673 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7675 Result = CV.FloatImag;
7679 VisitIgnoredValue(E->getSubExpr());
7680 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7681 Result = llvm::APFloat::getZero(Sem);
7685 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7686 switch (E->getOpcode()) {
7687 default: return Error(E);
7689 return EvaluateFloat(E->getSubExpr(), Result, Info);
7691 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7693 Result.changeSign();
7698 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7699 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7700 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7703 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7704 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7706 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7707 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7710 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7711 Result = E->getValue();
7715 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7716 const Expr* SubExpr = E->getSubExpr();
7718 switch (E->getCastKind()) {
7720 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7722 case CK_IntegralToFloating: {
7724 return EvaluateInteger(SubExpr, IntResult, Info) &&
7725 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7726 E->getType(), Result);
7729 case CK_FloatingCast: {
7730 if (!Visit(SubExpr))
7732 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7736 case CK_FloatingComplexToReal: {
7738 if (!EvaluateComplex(SubExpr, V, Info))
7740 Result = V.getComplexFloatReal();
7746 //===----------------------------------------------------------------------===//
7747 // Complex Evaluation (for float and integer)
7748 //===----------------------------------------------------------------------===//
7751 class ComplexExprEvaluator
7752 : public ExprEvaluatorBase<ComplexExprEvaluator> {
7753 ComplexValue &Result;
7756 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7757 : ExprEvaluatorBaseTy(info), Result(Result) {}
7759 bool Success(const APValue &V, const Expr *e) {
7764 bool ZeroInitialization(const Expr *E);
7766 //===--------------------------------------------------------------------===//
7768 //===--------------------------------------------------------------------===//
7770 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7771 bool VisitCastExpr(const CastExpr *E);
7772 bool VisitBinaryOperator(const BinaryOperator *E);
7773 bool VisitUnaryOperator(const UnaryOperator *E);
7774 bool VisitInitListExpr(const InitListExpr *E);
7776 } // end anonymous namespace
7778 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7780 assert(E->isRValue() && E->getType()->isAnyComplexType());
7781 return ComplexExprEvaluator(Info, Result).Visit(E);
7784 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7785 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7786 if (ElemTy->isRealFloatingType()) {
7787 Result.makeComplexFloat();
7788 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7789 Result.FloatReal = Zero;
7790 Result.FloatImag = Zero;
7792 Result.makeComplexInt();
7793 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7794 Result.IntReal = Zero;
7795 Result.IntImag = Zero;
7800 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7801 const Expr* SubExpr = E->getSubExpr();
7803 if (SubExpr->getType()->isRealFloatingType()) {
7804 Result.makeComplexFloat();
7805 APFloat &Imag = Result.FloatImag;
7806 if (!EvaluateFloat(SubExpr, Imag, Info))
7809 Result.FloatReal = APFloat(Imag.getSemantics());
7812 assert(SubExpr->getType()->isIntegerType() &&
7813 "Unexpected imaginary literal.");
7815 Result.makeComplexInt();
7816 APSInt &Imag = Result.IntImag;
7817 if (!EvaluateInteger(SubExpr, Imag, Info))
7820 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7825 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7827 switch (E->getCastKind()) {
7829 case CK_BaseToDerived:
7830 case CK_DerivedToBase:
7831 case CK_UncheckedDerivedToBase:
7834 case CK_ArrayToPointerDecay:
7835 case CK_FunctionToPointerDecay:
7836 case CK_NullToPointer:
7837 case CK_NullToMemberPointer:
7838 case CK_BaseToDerivedMemberPointer:
7839 case CK_DerivedToBaseMemberPointer:
7840 case CK_MemberPointerToBoolean:
7841 case CK_ReinterpretMemberPointer:
7842 case CK_ConstructorConversion:
7843 case CK_IntegralToPointer:
7844 case CK_PointerToIntegral:
7845 case CK_PointerToBoolean:
7847 case CK_VectorSplat:
7848 case CK_IntegralCast:
7849 case CK_IntegralToBoolean:
7850 case CK_IntegralToFloating:
7851 case CK_FloatingToIntegral:
7852 case CK_FloatingToBoolean:
7853 case CK_FloatingCast:
7854 case CK_CPointerToObjCPointerCast:
7855 case CK_BlockPointerToObjCPointerCast:
7856 case CK_AnyPointerToBlockPointerCast:
7857 case CK_ObjCObjectLValueCast:
7858 case CK_FloatingComplexToReal:
7859 case CK_FloatingComplexToBoolean:
7860 case CK_IntegralComplexToReal:
7861 case CK_IntegralComplexToBoolean:
7862 case CK_ARCProduceObject:
7863 case CK_ARCConsumeObject:
7864 case CK_ARCReclaimReturnedObject:
7865 case CK_ARCExtendBlockObject:
7866 case CK_CopyAndAutoreleaseBlockObject:
7867 case CK_BuiltinFnToFnPtr:
7868 case CK_ZeroToOCLEvent:
7869 case CK_NonAtomicToAtomic:
7870 case CK_AddressSpaceConversion:
7871 llvm_unreachable("invalid cast kind for complex value");
7873 case CK_LValueToRValue:
7874 case CK_AtomicToNonAtomic:
7876 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7879 case CK_LValueBitCast:
7880 case CK_UserDefinedConversion:
7883 case CK_FloatingRealToComplex: {
7884 APFloat &Real = Result.FloatReal;
7885 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7888 Result.makeComplexFloat();
7889 Result.FloatImag = APFloat(Real.getSemantics());
7893 case CK_FloatingComplexCast: {
7894 if (!Visit(E->getSubExpr()))
7897 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7899 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7901 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7902 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7905 case CK_FloatingComplexToIntegralComplex: {
7906 if (!Visit(E->getSubExpr()))
7909 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7911 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7912 Result.makeComplexInt();
7913 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7914 To, Result.IntReal) &&
7915 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7916 To, Result.IntImag);
7919 case CK_IntegralRealToComplex: {
7920 APSInt &Real = Result.IntReal;
7921 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7924 Result.makeComplexInt();
7925 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7929 case CK_IntegralComplexCast: {
7930 if (!Visit(E->getSubExpr()))
7933 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7935 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7937 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7938 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7942 case CK_IntegralComplexToFloatingComplex: {
7943 if (!Visit(E->getSubExpr()))
7946 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
7948 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
7949 Result.makeComplexFloat();
7950 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7951 To, Result.FloatReal) &&
7952 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7953 To, Result.FloatImag);
7957 llvm_unreachable("unknown cast resulting in complex value");
7960 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7961 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7962 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7964 // Track whether the LHS or RHS is real at the type system level. When this is
7965 // the case we can simplify our evaluation strategy.
7966 bool LHSReal = false, RHSReal = false;
7969 if (E->getLHS()->getType()->isRealFloatingType()) {
7971 APFloat &Real = Result.FloatReal;
7972 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
7974 Result.makeComplexFloat();
7975 Result.FloatImag = APFloat(Real.getSemantics());
7978 LHSOK = Visit(E->getLHS());
7980 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7984 if (E->getRHS()->getType()->isRealFloatingType()) {
7986 APFloat &Real = RHS.FloatReal;
7987 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
7989 RHS.makeComplexFloat();
7990 RHS.FloatImag = APFloat(Real.getSemantics());
7991 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7994 assert(!(LHSReal && RHSReal) &&
7995 "Cannot have both operands of a complex operation be real.");
7996 switch (E->getOpcode()) {
7997 default: return Error(E);
7999 if (Result.isComplexFloat()) {
8000 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8001 APFloat::rmNearestTiesToEven);
8003 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8005 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8006 APFloat::rmNearestTiesToEven);
8008 Result.getComplexIntReal() += RHS.getComplexIntReal();
8009 Result.getComplexIntImag() += RHS.getComplexIntImag();
8013 if (Result.isComplexFloat()) {
8014 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8015 APFloat::rmNearestTiesToEven);
8017 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8018 Result.getComplexFloatImag().changeSign();
8019 } else if (!RHSReal) {
8020 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8021 APFloat::rmNearestTiesToEven);
8024 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8025 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8029 if (Result.isComplexFloat()) {
8030 // This is an implementation of complex multiplication according to the
8031 // constraints laid out in C11 Annex G. The implemantion uses the
8032 // following naming scheme:
8033 // (a + ib) * (c + id)
8034 ComplexValue LHS = Result;
8035 APFloat &A = LHS.getComplexFloatReal();
8036 APFloat &B = LHS.getComplexFloatImag();
8037 APFloat &C = RHS.getComplexFloatReal();
8038 APFloat &D = RHS.getComplexFloatImag();
8039 APFloat &ResR = Result.getComplexFloatReal();
8040 APFloat &ResI = Result.getComplexFloatImag();
8042 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8045 } else if (RHSReal) {
8049 // In the fully general case, we need to handle NaNs and infinities
8057 if (ResR.isNaN() && ResI.isNaN()) {
8058 bool Recalc = false;
8059 if (A.isInfinity() || B.isInfinity()) {
8060 A = APFloat::copySign(
8061 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8062 B = APFloat::copySign(
8063 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8065 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8067 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8070 if (C.isInfinity() || D.isInfinity()) {
8071 C = APFloat::copySign(
8072 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8073 D = APFloat::copySign(
8074 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8076 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8078 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8081 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8082 AD.isInfinity() || BC.isInfinity())) {
8084 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8086 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8088 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8090 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8094 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8095 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8100 ComplexValue LHS = Result;
8101 Result.getComplexIntReal() =
8102 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8103 LHS.getComplexIntImag() * RHS.getComplexIntImag());
8104 Result.getComplexIntImag() =
8105 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8106 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8110 if (Result.isComplexFloat()) {
8111 // This is an implementation of complex division according to the
8112 // constraints laid out in C11 Annex G. The implemantion uses the
8113 // following naming scheme:
8114 // (a + ib) / (c + id)
8115 ComplexValue LHS = Result;
8116 APFloat &A = LHS.getComplexFloatReal();
8117 APFloat &B = LHS.getComplexFloatImag();
8118 APFloat &C = RHS.getComplexFloatReal();
8119 APFloat &D = RHS.getComplexFloatImag();
8120 APFloat &ResR = Result.getComplexFloatReal();
8121 APFloat &ResI = Result.getComplexFloatImag();
8127 // No real optimizations we can do here, stub out with zero.
8128 B = APFloat::getZero(A.getSemantics());
8131 APFloat MaxCD = maxnum(abs(C), abs(D));
8132 if (MaxCD.isFinite()) {
8133 DenomLogB = ilogb(MaxCD);
8134 C = scalbn(C, -DenomLogB);
8135 D = scalbn(D, -DenomLogB);
8137 APFloat Denom = C * C + D * D;
8138 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8139 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8140 if (ResR.isNaN() && ResI.isNaN()) {
8141 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8142 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8143 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8144 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8146 A = APFloat::copySign(
8147 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8148 B = APFloat::copySign(
8149 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8150 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8151 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8152 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8153 C = APFloat::copySign(
8154 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8155 D = APFloat::copySign(
8156 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8157 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8158 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8163 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8164 return Error(E, diag::note_expr_divide_by_zero);
8166 ComplexValue LHS = Result;
8167 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8168 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8169 Result.getComplexIntReal() =
8170 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8171 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8172 Result.getComplexIntImag() =
8173 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8174 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8182 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8183 // Get the operand value into 'Result'.
8184 if (!Visit(E->getSubExpr()))
8187 switch (E->getOpcode()) {
8193 // The result is always just the subexpr.
8196 if (Result.isComplexFloat()) {
8197 Result.getComplexFloatReal().changeSign();
8198 Result.getComplexFloatImag().changeSign();
8201 Result.getComplexIntReal() = -Result.getComplexIntReal();
8202 Result.getComplexIntImag() = -Result.getComplexIntImag();
8206 if (Result.isComplexFloat())
8207 Result.getComplexFloatImag().changeSign();
8209 Result.getComplexIntImag() = -Result.getComplexIntImag();
8214 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8215 if (E->getNumInits() == 2) {
8216 if (E->getType()->isComplexType()) {
8217 Result.makeComplexFloat();
8218 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8220 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8223 Result.makeComplexInt();
8224 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8226 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8231 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8234 //===----------------------------------------------------------------------===//
8235 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8236 // implicit conversion.
8237 //===----------------------------------------------------------------------===//
8240 class AtomicExprEvaluator :
8241 public ExprEvaluatorBase<AtomicExprEvaluator> {
8244 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8245 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8247 bool Success(const APValue &V, const Expr *E) {
8252 bool ZeroInitialization(const Expr *E) {
8253 ImplicitValueInitExpr VIE(
8254 E->getType()->castAs<AtomicType>()->getValueType());
8255 return Evaluate(Result, Info, &VIE);
8258 bool VisitCastExpr(const CastExpr *E) {
8259 switch (E->getCastKind()) {
8261 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8262 case CK_NonAtomicToAtomic:
8263 return Evaluate(Result, Info, E->getSubExpr());
8267 } // end anonymous namespace
8269 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8270 assert(E->isRValue() && E->getType()->isAtomicType());
8271 return AtomicExprEvaluator(Info, Result).Visit(E);
8274 //===----------------------------------------------------------------------===//
8275 // Void expression evaluation, primarily for a cast to void on the LHS of a
8277 //===----------------------------------------------------------------------===//
8280 class VoidExprEvaluator
8281 : public ExprEvaluatorBase<VoidExprEvaluator> {
8283 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8285 bool Success(const APValue &V, const Expr *e) { return true; }
8287 bool VisitCastExpr(const CastExpr *E) {
8288 switch (E->getCastKind()) {
8290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8292 VisitIgnoredValue(E->getSubExpr());
8297 bool VisitCallExpr(const CallExpr *E) {
8298 switch (E->getBuiltinCallee()) {
8300 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8301 case Builtin::BI__assume:
8302 case Builtin::BI__builtin_assume:
8303 // The argument is not evaluated!
8308 } // end anonymous namespace
8310 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8311 assert(E->isRValue() && E->getType()->isVoidType());
8312 return VoidExprEvaluator(Info).Visit(E);
8315 //===----------------------------------------------------------------------===//
8316 // Top level Expr::EvaluateAsRValue method.
8317 //===----------------------------------------------------------------------===//
8319 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
8320 // In C, function designators are not lvalues, but we evaluate them as if they
8322 QualType T = E->getType();
8323 if (E->isGLValue() || T->isFunctionType()) {
8325 if (!EvaluateLValue(E, LV, Info))
8327 LV.moveInto(Result);
8328 } else if (T->isVectorType()) {
8329 if (!EvaluateVector(E, Result, Info))
8331 } else if (T->isIntegralOrEnumerationType()) {
8332 if (!IntExprEvaluator(Info, Result).Visit(E))
8334 } else if (T->hasPointerRepresentation()) {
8336 if (!EvaluatePointer(E, LV, Info))
8338 LV.moveInto(Result);
8339 } else if (T->isRealFloatingType()) {
8340 llvm::APFloat F(0.0);
8341 if (!EvaluateFloat(E, F, Info))
8343 Result = APValue(F);
8344 } else if (T->isAnyComplexType()) {
8346 if (!EvaluateComplex(E, C, Info))
8349 } else if (T->isMemberPointerType()) {
8351 if (!EvaluateMemberPointer(E, P, Info))
8355 } else if (T->isArrayType()) {
8357 LV.set(E, Info.CurrentCall->Index);
8358 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8359 if (!EvaluateArray(E, LV, Value, Info))
8362 } else if (T->isRecordType()) {
8364 LV.set(E, Info.CurrentCall->Index);
8365 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8366 if (!EvaluateRecord(E, LV, Value, Info))
8369 } else if (T->isVoidType()) {
8370 if (!Info.getLangOpts().CPlusPlus11)
8371 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8373 if (!EvaluateVoid(E, Info))
8375 } else if (T->isAtomicType()) {
8376 if (!EvaluateAtomic(E, Result, Info))
8378 } else if (Info.getLangOpts().CPlusPlus11) {
8379 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8382 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8389 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8390 /// cases, the in-place evaluation is essential, since later initializers for
8391 /// an object can indirectly refer to subobjects which were initialized earlier.
8392 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8393 const Expr *E, bool AllowNonLiteralTypes) {
8394 assert(!E->isValueDependent());
8396 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8399 if (E->isRValue()) {
8400 // Evaluate arrays and record types in-place, so that later initializers can
8401 // refer to earlier-initialized members of the object.
8402 if (E->getType()->isArrayType())
8403 return EvaluateArray(E, This, Result, Info);
8404 else if (E->getType()->isRecordType())
8405 return EvaluateRecord(E, This, Result, Info);
8408 // For any other type, in-place evaluation is unimportant.
8409 return Evaluate(Result, Info, E);
8412 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8413 /// lvalue-to-rvalue cast if it is an lvalue.
8414 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8415 if (E->getType().isNull())
8418 if (!CheckLiteralType(Info, E))
8421 if (!::Evaluate(Result, Info, E))
8424 if (E->isGLValue()) {
8426 LV.setFrom(Info.Ctx, Result);
8427 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8431 // Check this core constant expression is a constant expression.
8432 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8435 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8436 const ASTContext &Ctx, bool &IsConst) {
8437 // Fast-path evaluations of integer literals, since we sometimes see files
8438 // containing vast quantities of these.
8439 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8440 Result.Val = APValue(APSInt(L->getValue(),
8441 L->getType()->isUnsignedIntegerType()));
8446 // This case should be rare, but we need to check it before we check on
8448 if (Exp->getType().isNull()) {
8453 // FIXME: Evaluating values of large array and record types can cause
8454 // performance problems. Only do so in C++11 for now.
8455 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8456 Exp->getType()->isRecordType()) &&
8457 !Ctx.getLangOpts().CPlusPlus11) {
8465 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8466 /// any crazy technique (that has nothing to do with language standards) that
8467 /// we want to. If this function returns true, it returns the folded constant
8468 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8469 /// will be applied to the result.
8470 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8472 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8475 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8476 return ::EvaluateAsRValue(Info, this, Result.Val);
8479 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8480 const ASTContext &Ctx) const {
8482 return EvaluateAsRValue(Scratch, Ctx) &&
8483 HandleConversionToBool(Scratch.Val, Result);
8486 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8487 SideEffectsKind AllowSideEffects) const {
8488 if (!getType()->isIntegralOrEnumerationType())
8491 EvalResult ExprResult;
8492 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8493 (!AllowSideEffects && ExprResult.HasSideEffects))
8496 Result = ExprResult.Val.getInt();
8500 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8501 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8504 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8505 !CheckLValueConstantExpression(Info, getExprLoc(),
8506 Ctx.getLValueReferenceType(getType()), LV))
8509 LV.moveInto(Result.Val);
8513 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8515 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8516 // FIXME: Evaluating initializers for large array and record types can cause
8517 // performance problems. Only do so in C++11 for now.
8518 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8519 !Ctx.getLangOpts().CPlusPlus11)
8522 Expr::EvalStatus EStatus;
8523 EStatus.Diag = &Notes;
8525 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8526 InitInfo.setEvaluatingDecl(VD, Value);
8531 // C++11 [basic.start.init]p2:
8532 // Variables with static storage duration or thread storage duration shall be
8533 // zero-initialized before any other initialization takes place.
8534 // This behavior is not present in C.
8535 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8536 !VD->getType()->isReferenceType()) {
8537 ImplicitValueInitExpr VIE(VD->getType());
8538 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8539 /*AllowNonLiteralTypes=*/true))
8543 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8544 /*AllowNonLiteralTypes=*/true) ||
8545 EStatus.HasSideEffects)
8548 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8552 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8553 /// constant folded, but discard the result.
8554 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8556 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8559 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8560 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8561 EvalResult EvalResult;
8562 EvalResult.Diag = Diag;
8563 bool Result = EvaluateAsRValue(EvalResult, Ctx);
8565 assert(Result && "Could not evaluate expression");
8566 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8568 return EvalResult.Val.getInt();
8571 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8573 EvalResult EvalResult;
8574 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8575 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8576 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8580 bool Expr::EvalResult::isGlobalLValue() const {
8581 assert(Val.isLValue());
8582 return IsGlobalLValue(Val.getLValueBase());
8586 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8587 /// an integer constant expression.
8589 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8592 // CheckICE - This function does the fundamental ICE checking: the returned
8593 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8594 // and a (possibly null) SourceLocation indicating the location of the problem.
8596 // Note that to reduce code duplication, this helper does no evaluation
8597 // itself; the caller checks whether the expression is evaluatable, and
8598 // in the rare cases where CheckICE actually cares about the evaluated
8599 // value, it calls into Evalute.
8604 /// This expression is an ICE.
8606 /// This expression is not an ICE, but if it isn't evaluated, it's
8607 /// a legal subexpression for an ICE. This return value is used to handle
8608 /// the comma operator in C99 mode, and non-constant subexpressions.
8609 IK_ICEIfUnevaluated,
8610 /// This expression is not an ICE, and is not a legal subexpression for one.
8618 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8623 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8625 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8627 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8628 Expr::EvalResult EVResult;
8629 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8630 !EVResult.Val.isInt())
8631 return ICEDiag(IK_NotICE, E->getLocStart());
8636 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8637 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8638 if (!E->getType()->isIntegralOrEnumerationType())
8639 return ICEDiag(IK_NotICE, E->getLocStart());
8641 switch (E->getStmtClass()) {
8642 #define ABSTRACT_STMT(Node)
8643 #define STMT(Node, Base) case Expr::Node##Class:
8644 #define EXPR(Node, Base)
8645 #include "clang/AST/StmtNodes.inc"
8646 case Expr::PredefinedExprClass:
8647 case Expr::FloatingLiteralClass:
8648 case Expr::ImaginaryLiteralClass:
8649 case Expr::StringLiteralClass:
8650 case Expr::ArraySubscriptExprClass:
8651 case Expr::MemberExprClass:
8652 case Expr::CompoundAssignOperatorClass:
8653 case Expr::CompoundLiteralExprClass:
8654 case Expr::ExtVectorElementExprClass:
8655 case Expr::DesignatedInitExprClass:
8656 case Expr::ImplicitValueInitExprClass:
8657 case Expr::ParenListExprClass:
8658 case Expr::VAArgExprClass:
8659 case Expr::AddrLabelExprClass:
8660 case Expr::StmtExprClass:
8661 case Expr::CXXMemberCallExprClass:
8662 case Expr::CUDAKernelCallExprClass:
8663 case Expr::CXXDynamicCastExprClass:
8664 case Expr::CXXTypeidExprClass:
8665 case Expr::CXXUuidofExprClass:
8666 case Expr::MSPropertyRefExprClass:
8667 case Expr::CXXNullPtrLiteralExprClass:
8668 case Expr::UserDefinedLiteralClass:
8669 case Expr::CXXThisExprClass:
8670 case Expr::CXXThrowExprClass:
8671 case Expr::CXXNewExprClass:
8672 case Expr::CXXDeleteExprClass:
8673 case Expr::CXXPseudoDestructorExprClass:
8674 case Expr::UnresolvedLookupExprClass:
8675 case Expr::TypoExprClass:
8676 case Expr::DependentScopeDeclRefExprClass:
8677 case Expr::CXXConstructExprClass:
8678 case Expr::CXXStdInitializerListExprClass:
8679 case Expr::CXXBindTemporaryExprClass:
8680 case Expr::ExprWithCleanupsClass:
8681 case Expr::CXXTemporaryObjectExprClass:
8682 case Expr::CXXUnresolvedConstructExprClass:
8683 case Expr::CXXDependentScopeMemberExprClass:
8684 case Expr::UnresolvedMemberExprClass:
8685 case Expr::ObjCStringLiteralClass:
8686 case Expr::ObjCBoxedExprClass:
8687 case Expr::ObjCArrayLiteralClass:
8688 case Expr::ObjCDictionaryLiteralClass:
8689 case Expr::ObjCEncodeExprClass:
8690 case Expr::ObjCMessageExprClass:
8691 case Expr::ObjCSelectorExprClass:
8692 case Expr::ObjCProtocolExprClass:
8693 case Expr::ObjCIvarRefExprClass:
8694 case Expr::ObjCPropertyRefExprClass:
8695 case Expr::ObjCSubscriptRefExprClass:
8696 case Expr::ObjCIsaExprClass:
8697 case Expr::ShuffleVectorExprClass:
8698 case Expr::ConvertVectorExprClass:
8699 case Expr::BlockExprClass:
8700 case Expr::NoStmtClass:
8701 case Expr::OpaqueValueExprClass:
8702 case Expr::PackExpansionExprClass:
8703 case Expr::SubstNonTypeTemplateParmPackExprClass:
8704 case Expr::FunctionParmPackExprClass:
8705 case Expr::AsTypeExprClass:
8706 case Expr::ObjCIndirectCopyRestoreExprClass:
8707 case Expr::MaterializeTemporaryExprClass:
8708 case Expr::PseudoObjectExprClass:
8709 case Expr::AtomicExprClass:
8710 case Expr::LambdaExprClass:
8711 case Expr::CXXFoldExprClass:
8712 return ICEDiag(IK_NotICE, E->getLocStart());
8714 case Expr::InitListExprClass: {
8715 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8716 // form "T x = { a };" is equivalent to "T x = a;".
8717 // Unless we're initializing a reference, T is a scalar as it is known to be
8718 // of integral or enumeration type.
8720 if (cast<InitListExpr>(E)->getNumInits() == 1)
8721 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8722 return ICEDiag(IK_NotICE, E->getLocStart());
8725 case Expr::SizeOfPackExprClass:
8726 case Expr::GNUNullExprClass:
8727 // GCC considers the GNU __null value to be an integral constant expression.
8730 case Expr::SubstNonTypeTemplateParmExprClass:
8732 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8734 case Expr::ParenExprClass:
8735 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8736 case Expr::GenericSelectionExprClass:
8737 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8738 case Expr::IntegerLiteralClass:
8739 case Expr::CharacterLiteralClass:
8740 case Expr::ObjCBoolLiteralExprClass:
8741 case Expr::CXXBoolLiteralExprClass:
8742 case Expr::CXXScalarValueInitExprClass:
8743 case Expr::TypeTraitExprClass:
8744 case Expr::ArrayTypeTraitExprClass:
8745 case Expr::ExpressionTraitExprClass:
8746 case Expr::CXXNoexceptExprClass:
8748 case Expr::CallExprClass:
8749 case Expr::CXXOperatorCallExprClass: {
8750 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8751 // constant expressions, but they can never be ICEs because an ICE cannot
8752 // contain an operand of (pointer to) function type.
8753 const CallExpr *CE = cast<CallExpr>(E);
8754 if (CE->getBuiltinCallee())
8755 return CheckEvalInICE(E, Ctx);
8756 return ICEDiag(IK_NotICE, E->getLocStart());
8758 case Expr::DeclRefExprClass: {
8759 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8761 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8762 if (Ctx.getLangOpts().CPlusPlus &&
8763 D && IsConstNonVolatile(D->getType())) {
8764 // Parameter variables are never constants. Without this check,
8765 // getAnyInitializer() can find a default argument, which leads
8767 if (isa<ParmVarDecl>(D))
8768 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8771 // A variable of non-volatile const-qualified integral or enumeration
8772 // type initialized by an ICE can be used in ICEs.
8773 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8774 if (!Dcl->getType()->isIntegralOrEnumerationType())
8775 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8778 // Look for a declaration of this variable that has an initializer, and
8779 // check whether it is an ICE.
8780 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8783 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8786 return ICEDiag(IK_NotICE, E->getLocStart());
8788 case Expr::UnaryOperatorClass: {
8789 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8790 switch (Exp->getOpcode()) {
8797 // C99 6.6/3 allows increment and decrement within unevaluated
8798 // subexpressions of constant expressions, but they can never be ICEs
8799 // because an ICE cannot contain an lvalue operand.
8800 return ICEDiag(IK_NotICE, E->getLocStart());
8808 return CheckICE(Exp->getSubExpr(), Ctx);
8811 // OffsetOf falls through here.
8813 case Expr::OffsetOfExprClass: {
8814 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8815 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8816 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8817 // compliance: we should warn earlier for offsetof expressions with
8818 // array subscripts that aren't ICEs, and if the array subscripts
8819 // are ICEs, the value of the offsetof must be an integer constant.
8820 return CheckEvalInICE(E, Ctx);
8822 case Expr::UnaryExprOrTypeTraitExprClass: {
8823 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8824 if ((Exp->getKind() == UETT_SizeOf) &&
8825 Exp->getTypeOfArgument()->isVariableArrayType())
8826 return ICEDiag(IK_NotICE, E->getLocStart());
8829 case Expr::BinaryOperatorClass: {
8830 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8831 switch (Exp->getOpcode()) {
8845 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8846 // constant expressions, but they can never be ICEs because an ICE cannot
8847 // contain an lvalue operand.
8848 return ICEDiag(IK_NotICE, E->getLocStart());
8867 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8868 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8869 if (Exp->getOpcode() == BO_Div ||
8870 Exp->getOpcode() == BO_Rem) {
8871 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8872 // we don't evaluate one.
8873 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8874 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8876 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8877 if (REval.isSigned() && REval.isAllOnesValue()) {
8878 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8879 if (LEval.isMinSignedValue())
8880 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8884 if (Exp->getOpcode() == BO_Comma) {
8885 if (Ctx.getLangOpts().C99) {
8886 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8887 // if it isn't evaluated.
8888 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8889 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8891 // In both C89 and C++, commas in ICEs are illegal.
8892 return ICEDiag(IK_NotICE, E->getLocStart());
8895 return Worst(LHSResult, RHSResult);
8899 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8900 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8901 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8902 // Rare case where the RHS has a comma "side-effect"; we need
8903 // to actually check the condition to see whether the side
8904 // with the comma is evaluated.
8905 if ((Exp->getOpcode() == BO_LAnd) !=
8906 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8911 return Worst(LHSResult, RHSResult);
8915 case Expr::ImplicitCastExprClass:
8916 case Expr::CStyleCastExprClass:
8917 case Expr::CXXFunctionalCastExprClass:
8918 case Expr::CXXStaticCastExprClass:
8919 case Expr::CXXReinterpretCastExprClass:
8920 case Expr::CXXConstCastExprClass:
8921 case Expr::ObjCBridgedCastExprClass: {
8922 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8923 if (isa<ExplicitCastExpr>(E)) {
8924 if (const FloatingLiteral *FL
8925 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8926 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8927 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8928 APSInt IgnoredVal(DestWidth, !DestSigned);
8930 // If the value does not fit in the destination type, the behavior is
8931 // undefined, so we are not required to treat it as a constant
8933 if (FL->getValue().convertToInteger(IgnoredVal,
8934 llvm::APFloat::rmTowardZero,
8935 &Ignored) & APFloat::opInvalidOp)
8936 return ICEDiag(IK_NotICE, E->getLocStart());
8940 switch (cast<CastExpr>(E)->getCastKind()) {
8941 case CK_LValueToRValue:
8942 case CK_AtomicToNonAtomic:
8943 case CK_NonAtomicToAtomic:
8945 case CK_IntegralToBoolean:
8946 case CK_IntegralCast:
8947 return CheckICE(SubExpr, Ctx);
8949 return ICEDiag(IK_NotICE, E->getLocStart());
8952 case Expr::BinaryConditionalOperatorClass: {
8953 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8954 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8955 if (CommonResult.Kind == IK_NotICE) return CommonResult;
8956 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8957 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8958 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8959 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8960 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8963 case Expr::ConditionalOperatorClass: {
8964 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8965 // If the condition (ignoring parens) is a __builtin_constant_p call,
8966 // then only the true side is actually considered in an integer constant
8967 // expression, and it is fully evaluated. This is an important GNU
8968 // extension. See GCC PR38377 for discussion.
8969 if (const CallExpr *CallCE
8970 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
8971 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8972 return CheckEvalInICE(E, Ctx);
8973 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
8974 if (CondResult.Kind == IK_NotICE)
8977 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8978 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8980 if (TrueResult.Kind == IK_NotICE)
8982 if (FalseResult.Kind == IK_NotICE)
8984 if (CondResult.Kind == IK_ICEIfUnevaluated)
8986 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
8988 // Rare case where the diagnostics depend on which side is evaluated
8989 // Note that if we get here, CondResult is 0, and at least one of
8990 // TrueResult and FalseResult is non-zero.
8991 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
8995 case Expr::CXXDefaultArgExprClass:
8996 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
8997 case Expr::CXXDefaultInitExprClass:
8998 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
8999 case Expr::ChooseExprClass: {
9000 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9004 llvm_unreachable("Invalid StmtClass!");
9007 /// Evaluate an expression as a C++11 integral constant expression.
9008 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
9010 llvm::APSInt *Value,
9011 SourceLocation *Loc) {
9012 if (!E->getType()->isIntegralOrEnumerationType()) {
9013 if (Loc) *Loc = E->getExprLoc();
9018 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9021 if (!Result.isInt()) {
9022 if (Loc) *Loc = E->getExprLoc();
9026 if (Value) *Value = Result.getInt();
9030 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9031 SourceLocation *Loc) const {
9032 if (Ctx.getLangOpts().CPlusPlus11)
9033 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9035 ICEDiag D = CheckICE(this, Ctx);
9036 if (D.Kind != IK_ICE) {
9037 if (Loc) *Loc = D.Loc;
9043 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9044 SourceLocation *Loc, bool isEvaluated) const {
9045 if (Ctx.getLangOpts().CPlusPlus11)
9046 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9048 if (!isIntegerConstantExpr(Ctx, Loc))
9050 if (!EvaluateAsInt(Value, Ctx))
9051 llvm_unreachable("ICE cannot be evaluated!");
9055 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
9056 return CheckICE(this, Ctx).Kind == IK_ICE;
9059 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
9060 SourceLocation *Loc) const {
9061 // We support this checking in C++98 mode in order to diagnose compatibility
9063 assert(Ctx.getLangOpts().CPlusPlus);
9065 // Build evaluation settings.
9066 Expr::EvalStatus Status;
9067 SmallVector<PartialDiagnosticAt, 8> Diags;
9068 Status.Diag = &Diags;
9069 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9072 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9074 if (!Diags.empty()) {
9075 IsConstExpr = false;
9076 if (Loc) *Loc = Diags[0].first;
9077 } else if (!IsConstExpr) {
9078 // FIXME: This shouldn't happen.
9079 if (Loc) *Loc = getExprLoc();
9085 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9086 const FunctionDecl *Callee,
9087 ArrayRef<const Expr*> Args) const {
9088 Expr::EvalStatus Status;
9089 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9091 ArgVector ArgValues(Args.size());
9092 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9094 if ((*I)->isValueDependent() ||
9095 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9096 // If evaluation fails, throw away the argument entirely.
9097 ArgValues[I - Args.begin()] = APValue();
9098 if (Info.EvalStatus.HasSideEffects)
9102 // Build fake call to Callee.
9103 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9105 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9108 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
9110 PartialDiagnosticAt> &Diags) {
9111 // FIXME: It would be useful to check constexpr function templates, but at the
9112 // moment the constant expression evaluator cannot cope with the non-rigorous
9113 // ASTs which we build for dependent expressions.
9114 if (FD->isDependentContext())
9117 Expr::EvalStatus Status;
9118 Status.Diag = &Diags;
9120 EvalInfo Info(FD->getASTContext(), Status,
9121 EvalInfo::EM_PotentialConstantExpression);
9123 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9124 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9126 // Fabricate an arbitrary expression on the stack and pretend that it
9127 // is a temporary being used as the 'this' pointer.
9129 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9130 This.set(&VIE, Info.CurrentCall->Index);
9132 ArrayRef<const Expr*> Args;
9134 SourceLocation Loc = FD->getLocation();
9137 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9138 // Evaluate the call as a constant initializer, to allow the construction
9139 // of objects of non-literal types.
9140 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9141 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
9143 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9144 Args, FD->getBody(), Info, Scratch);
9146 return Diags.empty();
9149 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9150 const FunctionDecl *FD,
9152 PartialDiagnosticAt> &Diags) {
9153 Expr::EvalStatus Status;
9154 Status.Diag = &Diags;
9156 EvalInfo Info(FD->getASTContext(), Status,
9157 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9159 // Fabricate a call stack frame to give the arguments a plausible cover story.
9160 ArrayRef<const Expr*> Args;
9161 ArgVector ArgValues(0);
9162 bool Success = EvaluateArgs(Args, ArgValues, Info);
9165 "Failed to set up arguments for potential constant evaluation");
9166 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9168 APValue ResultScratch;
9169 Evaluate(ResultScratch, Info, E);
9170 return Diags.empty();