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 static 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 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 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2506 AccessKinds AK, const LValue &LVal,
2507 QualType LValType) {
2509 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2510 return CompleteObject();
2513 CallStackFrame *Frame = nullptr;
2514 if (LVal.CallIndex) {
2515 Frame = Info.getCallFrame(LVal.CallIndex);
2517 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2518 << AK << LVal.Base.is<const ValueDecl*>();
2519 NoteLValueLocation(Info, LVal.Base);
2520 return CompleteObject();
2524 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2525 // is not a constant expression (even if the object is non-volatile). We also
2526 // apply this rule to C++98, in order to conform to the expected 'volatile'
2528 if (LValType.isVolatileQualified()) {
2529 if (Info.getLangOpts().CPlusPlus)
2530 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2534 return CompleteObject();
2537 // Compute value storage location and type of base object.
2538 APValue *BaseVal = nullptr;
2539 QualType BaseType = getType(LVal.Base);
2541 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2542 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2543 // In C++11, constexpr, non-volatile variables initialized with constant
2544 // expressions are constant expressions too. Inside constexpr functions,
2545 // parameters are constant expressions even if they're non-const.
2546 // In C++1y, objects local to a constant expression (those with a Frame) are
2547 // both readable and writable inside constant expressions.
2548 // In C, such things can also be folded, although they are not ICEs.
2549 const VarDecl *VD = dyn_cast<VarDecl>(D);
2551 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2554 if (!VD || VD->isInvalidDecl()) {
2556 return CompleteObject();
2559 // Accesses of volatile-qualified objects are not allowed.
2560 if (BaseType.isVolatileQualified()) {
2561 if (Info.getLangOpts().CPlusPlus) {
2562 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2564 Info.Note(VD->getLocation(), diag::note_declared_at);
2568 return CompleteObject();
2571 // Unless we're looking at a local variable or argument in a constexpr call,
2572 // the variable we're reading must be const.
2574 if (Info.getLangOpts().CPlusPlus14 &&
2575 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2576 // OK, we can read and modify an object if we're in the process of
2577 // evaluating its initializer, because its lifetime began in this
2579 } else if (AK != AK_Read) {
2580 // All the remaining cases only permit reading.
2581 Info.Diag(E, diag::note_constexpr_modify_global);
2582 return CompleteObject();
2583 } else if (VD->isConstexpr()) {
2584 // OK, we can read this variable.
2585 } else if (BaseType->isIntegralOrEnumerationType()) {
2586 if (!BaseType.isConstQualified()) {
2587 if (Info.getLangOpts().CPlusPlus) {
2588 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2589 Info.Note(VD->getLocation(), diag::note_declared_at);
2593 return CompleteObject();
2595 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2596 // We support folding of const floating-point types, in order to make
2597 // static const data members of such types (supported as an extension)
2599 if (Info.getLangOpts().CPlusPlus11) {
2600 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2601 Info.Note(VD->getLocation(), diag::note_declared_at);
2606 // FIXME: Allow folding of values of any literal type in all languages.
2607 if (Info.getLangOpts().CPlusPlus11) {
2608 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2609 Info.Note(VD->getLocation(), diag::note_declared_at);
2613 return CompleteObject();
2617 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2618 return CompleteObject();
2620 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2623 if (const MaterializeTemporaryExpr *MTE =
2624 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2625 assert(MTE->getStorageDuration() == SD_Static &&
2626 "should have a frame for a non-global materialized temporary");
2628 // Per C++1y [expr.const]p2:
2629 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2630 // - a [...] glvalue of integral or enumeration type that refers to
2631 // a non-volatile const object [...]
2633 // - a [...] glvalue of literal type that refers to a non-volatile
2634 // object whose lifetime began within the evaluation of e.
2636 // C++11 misses the 'began within the evaluation of e' check and
2637 // instead allows all temporaries, including things like:
2640 // constexpr int k = r;
2641 // Therefore we use the C++1y rules in C++11 too.
2642 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2643 const ValueDecl *ED = MTE->getExtendingDecl();
2644 if (!(BaseType.isConstQualified() &&
2645 BaseType->isIntegralOrEnumerationType()) &&
2646 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2647 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2648 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2649 return CompleteObject();
2652 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2653 assert(BaseVal && "got reference to unevaluated temporary");
2656 return CompleteObject();
2659 BaseVal = Frame->getTemporary(Base);
2660 assert(BaseVal && "missing value for temporary");
2663 // Volatile temporary objects cannot be accessed in constant expressions.
2664 if (BaseType.isVolatileQualified()) {
2665 if (Info.getLangOpts().CPlusPlus) {
2666 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2668 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2672 return CompleteObject();
2676 // During the construction of an object, it is not yet 'const'.
2677 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2678 // and this doesn't do quite the right thing for const subobjects of the
2679 // object under construction.
2680 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2681 BaseType = Info.Ctx.getCanonicalType(BaseType);
2682 BaseType.removeLocalConst();
2685 // In C++1y, we can't safely access any mutable state when we might be
2686 // evaluating after an unmodeled side effect or an evaluation failure.
2688 // FIXME: Not all local state is mutable. Allow local constant subobjects
2689 // to be read here (but take care with 'mutable' fields).
2690 if (Frame && Info.getLangOpts().CPlusPlus14 &&
2691 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2692 return CompleteObject();
2694 return CompleteObject(BaseVal, BaseType);
2697 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2698 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2699 /// glvalue referred to by an entity of reference type.
2701 /// \param Info - Information about the ongoing evaluation.
2702 /// \param Conv - The expression for which we are performing the conversion.
2703 /// Used for diagnostics.
2704 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2705 /// case of a non-class type).
2706 /// \param LVal - The glvalue on which we are attempting to perform this action.
2707 /// \param RVal - The produced value will be placed here.
2708 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2710 const LValue &LVal, APValue &RVal) {
2711 if (LVal.Designator.Invalid)
2714 // Check for special cases where there is no existing APValue to look at.
2715 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2716 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2717 !Type.isVolatileQualified()) {
2718 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2719 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2720 // initializer until now for such expressions. Such an expression can't be
2721 // an ICE in C, so this only matters for fold.
2722 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2723 if (Type.isVolatileQualified()) {
2728 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2730 CompleteObject LitObj(&Lit, Base->getType());
2731 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2732 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
2733 // We represent a string literal array as an lvalue pointing at the
2734 // corresponding expression, rather than building an array of chars.
2735 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2736 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2737 CompleteObject StrObj(&Str, Base->getType());
2738 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2742 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2743 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2746 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2747 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2748 QualType LValType, APValue &Val) {
2749 if (LVal.Designator.Invalid)
2752 if (!Info.getLangOpts().CPlusPlus14) {
2757 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2758 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2761 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2762 return T->isSignedIntegerType() &&
2763 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2767 struct CompoundAssignSubobjectHandler {
2770 QualType PromotedLHSType;
2771 BinaryOperatorKind Opcode;
2774 static const AccessKinds AccessKind = AK_Assign;
2776 typedef bool result_type;
2778 bool checkConst(QualType QT) {
2779 // Assigning to a const object has undefined behavior.
2780 if (QT.isConstQualified()) {
2781 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2787 bool failed() { return false; }
2788 bool found(APValue &Subobj, QualType SubobjType) {
2789 switch (Subobj.getKind()) {
2791 return found(Subobj.getInt(), SubobjType);
2792 case APValue::Float:
2793 return found(Subobj.getFloat(), SubobjType);
2794 case APValue::ComplexInt:
2795 case APValue::ComplexFloat:
2796 // FIXME: Implement complex compound assignment.
2799 case APValue::LValue:
2800 return foundPointer(Subobj, SubobjType);
2802 // FIXME: can this happen?
2807 bool found(APSInt &Value, QualType SubobjType) {
2808 if (!checkConst(SubobjType))
2811 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2812 // We don't support compound assignment on integer-cast-to-pointer
2818 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2820 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2822 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2825 bool found(APFloat &Value, QualType SubobjType) {
2826 return checkConst(SubobjType) &&
2827 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2829 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2830 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2832 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2833 if (!checkConst(SubobjType))
2836 QualType PointeeType;
2837 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2838 PointeeType = PT->getPointeeType();
2840 if (PointeeType.isNull() || !RHS.isInt() ||
2841 (Opcode != BO_Add && Opcode != BO_Sub)) {
2846 int64_t Offset = getExtValue(RHS.getInt());
2847 if (Opcode == BO_Sub)
2851 LVal.setFrom(Info.Ctx, Subobj);
2852 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2854 LVal.moveInto(Subobj);
2857 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2858 llvm_unreachable("shouldn't encounter string elements here");
2861 } // end anonymous namespace
2863 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2865 /// Perform a compound assignment of LVal <op>= RVal.
2866 static bool handleCompoundAssignment(
2867 EvalInfo &Info, const Expr *E,
2868 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2869 BinaryOperatorKind Opcode, const APValue &RVal) {
2870 if (LVal.Designator.Invalid)
2873 if (!Info.getLangOpts().CPlusPlus14) {
2878 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2879 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2881 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2885 struct IncDecSubobjectHandler {
2888 AccessKinds AccessKind;
2891 typedef bool result_type;
2893 bool checkConst(QualType QT) {
2894 // Assigning to a const object has undefined behavior.
2895 if (QT.isConstQualified()) {
2896 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2902 bool failed() { return false; }
2903 bool found(APValue &Subobj, QualType SubobjType) {
2904 // Stash the old value. Also clear Old, so we don't clobber it later
2905 // if we're post-incrementing a complex.
2911 switch (Subobj.getKind()) {
2913 return found(Subobj.getInt(), SubobjType);
2914 case APValue::Float:
2915 return found(Subobj.getFloat(), SubobjType);
2916 case APValue::ComplexInt:
2917 return found(Subobj.getComplexIntReal(),
2918 SubobjType->castAs<ComplexType>()->getElementType()
2919 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2920 case APValue::ComplexFloat:
2921 return found(Subobj.getComplexFloatReal(),
2922 SubobjType->castAs<ComplexType>()->getElementType()
2923 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2924 case APValue::LValue:
2925 return foundPointer(Subobj, SubobjType);
2927 // FIXME: can this happen?
2932 bool found(APSInt &Value, QualType SubobjType) {
2933 if (!checkConst(SubobjType))
2936 if (!SubobjType->isIntegerType()) {
2937 // We don't support increment / decrement on integer-cast-to-pointer
2943 if (Old) *Old = APValue(Value);
2945 // bool arithmetic promotes to int, and the conversion back to bool
2946 // doesn't reduce mod 2^n, so special-case it.
2947 if (SubobjType->isBooleanType()) {
2948 if (AccessKind == AK_Increment)
2955 bool WasNegative = Value.isNegative();
2956 if (AccessKind == AK_Increment) {
2959 if (!WasNegative && Value.isNegative() &&
2960 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2961 APSInt ActualValue(Value, /*IsUnsigned*/true);
2962 HandleOverflow(Info, E, ActualValue, SubobjType);
2967 if (WasNegative && !Value.isNegative() &&
2968 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2969 unsigned BitWidth = Value.getBitWidth();
2970 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2971 ActualValue.setBit(BitWidth);
2972 HandleOverflow(Info, E, ActualValue, SubobjType);
2977 bool found(APFloat &Value, QualType SubobjType) {
2978 if (!checkConst(SubobjType))
2981 if (Old) *Old = APValue(Value);
2983 APFloat One(Value.getSemantics(), 1);
2984 if (AccessKind == AK_Increment)
2985 Value.add(One, APFloat::rmNearestTiesToEven);
2987 Value.subtract(One, APFloat::rmNearestTiesToEven);
2990 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2991 if (!checkConst(SubobjType))
2994 QualType PointeeType;
2995 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2996 PointeeType = PT->getPointeeType();
3003 LVal.setFrom(Info.Ctx, Subobj);
3004 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3005 AccessKind == AK_Increment ? 1 : -1))
3007 LVal.moveInto(Subobj);
3010 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3011 llvm_unreachable("shouldn't encounter string elements here");
3014 } // end anonymous namespace
3016 /// Perform an increment or decrement on LVal.
3017 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3018 QualType LValType, bool IsIncrement, APValue *Old) {
3019 if (LVal.Designator.Invalid)
3022 if (!Info.getLangOpts().CPlusPlus14) {
3027 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3028 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3029 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3030 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3033 /// Build an lvalue for the object argument of a member function call.
3034 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3036 if (Object->getType()->isPointerType())
3037 return EvaluatePointer(Object, This, Info);
3039 if (Object->isGLValue())
3040 return EvaluateLValue(Object, This, Info);
3042 if (Object->getType()->isLiteralType(Info.Ctx))
3043 return EvaluateTemporary(Object, This, Info);
3045 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3049 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3050 /// lvalue referring to the result.
3052 /// \param Info - Information about the ongoing evaluation.
3053 /// \param LV - An lvalue referring to the base of the member pointer.
3054 /// \param RHS - The member pointer expression.
3055 /// \param IncludeMember - Specifies whether the member itself is included in
3056 /// the resulting LValue subobject designator. This is not possible when
3057 /// creating a bound member function.
3058 /// \return The field or method declaration to which the member pointer refers,
3059 /// or 0 if evaluation fails.
3060 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3064 bool IncludeMember = true) {
3066 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3069 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3070 // member value, the behavior is undefined.
3071 if (!MemPtr.getDecl()) {
3072 // FIXME: Specific diagnostic.
3077 if (MemPtr.isDerivedMember()) {
3078 // This is a member of some derived class. Truncate LV appropriately.
3079 // The end of the derived-to-base path for the base object must match the
3080 // derived-to-base path for the member pointer.
3081 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3082 LV.Designator.Entries.size()) {
3086 unsigned PathLengthToMember =
3087 LV.Designator.Entries.size() - MemPtr.Path.size();
3088 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3089 const CXXRecordDecl *LVDecl = getAsBaseClass(
3090 LV.Designator.Entries[PathLengthToMember + I]);
3091 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3092 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3098 // Truncate the lvalue to the appropriate derived class.
3099 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3100 PathLengthToMember))
3102 } else if (!MemPtr.Path.empty()) {
3103 // Extend the LValue path with the member pointer's path.
3104 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3105 MemPtr.Path.size() + IncludeMember);
3107 // Walk down to the appropriate base class.
3108 if (const PointerType *PT = LVType->getAs<PointerType>())
3109 LVType = PT->getPointeeType();
3110 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3111 assert(RD && "member pointer access on non-class-type expression");
3112 // The first class in the path is that of the lvalue.
3113 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3114 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3115 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3119 // Finally cast to the class containing the member.
3120 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3121 MemPtr.getContainingRecord()))
3125 // Add the member. Note that we cannot build bound member functions here.
3126 if (IncludeMember) {
3127 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3128 if (!HandleLValueMember(Info, RHS, LV, FD))
3130 } else if (const IndirectFieldDecl *IFD =
3131 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3132 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3135 llvm_unreachable("can't construct reference to bound member function");
3139 return MemPtr.getDecl();
3142 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3143 const BinaryOperator *BO,
3145 bool IncludeMember = true) {
3146 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3148 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3149 if (Info.keepEvaluatingAfterFailure()) {
3151 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3156 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3157 BO->getRHS(), IncludeMember);
3160 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3161 /// the provided lvalue, which currently refers to the base object.
3162 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3164 SubobjectDesignator &D = Result.Designator;
3165 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3168 QualType TargetQT = E->getType();
3169 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3170 TargetQT = PT->getPointeeType();
3172 // Check this cast lands within the final derived-to-base subobject path.
3173 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3174 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3175 << D.MostDerivedType << TargetQT;
3179 // Check the type of the final cast. We don't need to check the path,
3180 // since a cast can only be formed if the path is unique.
3181 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3182 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3183 const CXXRecordDecl *FinalType;
3184 if (NewEntriesSize == D.MostDerivedPathLength)
3185 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3187 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3188 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3189 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3190 << D.MostDerivedType << TargetQT;
3194 // Truncate the lvalue to the appropriate derived class.
3195 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3199 enum EvalStmtResult {
3200 /// Evaluation failed.
3202 /// Hit a 'return' statement.
3204 /// Evaluation succeeded.
3206 /// Hit a 'continue' statement.
3208 /// Hit a 'break' statement.
3210 /// Still scanning for 'case' or 'default' statement.
3215 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3216 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3217 // We don't need to evaluate the initializer for a static local.
3218 if (!VD->hasLocalStorage())
3222 Result.set(VD, Info.CurrentCall->Index);
3223 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3225 const Expr *InitE = VD->getInit();
3227 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3228 << false << VD->getType();
3233 if (InitE->isValueDependent())
3236 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3237 // Wipe out any partially-computed value, to allow tracking that this
3238 // evaluation failed.
3247 /// Evaluate a condition (either a variable declaration or an expression).
3248 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3249 const Expr *Cond, bool &Result) {
3250 FullExpressionRAII Scope(Info);
3251 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3253 return EvaluateAsBooleanCondition(Cond, Result, Info);
3256 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3258 const SwitchCase *SC = nullptr);
3260 /// Evaluate the body of a loop, and translate the result as appropriate.
3261 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3263 const SwitchCase *Case = nullptr) {
3264 BlockScopeRAII Scope(Info);
3265 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3267 return ESR_Succeeded;
3270 return ESR_Continue;
3273 case ESR_CaseNotFound:
3276 llvm_unreachable("Invalid EvalStmtResult!");
3279 /// Evaluate a switch statement.
3280 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3281 const SwitchStmt *SS) {
3282 BlockScopeRAII Scope(Info);
3284 // Evaluate the switch condition.
3287 FullExpressionRAII Scope(Info);
3288 if (SS->getConditionVariable() &&
3289 !EvaluateDecl(Info, SS->getConditionVariable()))
3291 if (!EvaluateInteger(SS->getCond(), Value, Info))
3295 // Find the switch case corresponding to the value of the condition.
3296 // FIXME: Cache this lookup.
3297 const SwitchCase *Found = nullptr;
3298 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3299 SC = SC->getNextSwitchCase()) {
3300 if (isa<DefaultStmt>(SC)) {
3305 const CaseStmt *CS = cast<CaseStmt>(SC);
3306 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3307 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3309 if (LHS <= Value && Value <= RHS) {
3316 return ESR_Succeeded;
3318 // Search the switch body for the switch case and evaluate it from there.
3319 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3321 return ESR_Succeeded;
3327 case ESR_CaseNotFound:
3328 // This can only happen if the switch case is nested within a statement
3329 // expression. We have no intention of supporting that.
3330 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3333 llvm_unreachable("Invalid EvalStmtResult!");
3336 // Evaluate a statement.
3337 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3338 const Stmt *S, const SwitchCase *Case) {
3339 if (!Info.nextStep(S))
3342 // If we're hunting down a 'case' or 'default' label, recurse through
3343 // substatements until we hit the label.
3345 // FIXME: We don't start the lifetime of objects whose initialization we
3346 // jump over. However, such objects must be of class type with a trivial
3347 // default constructor that initialize all subobjects, so must be empty,
3348 // so this almost never matters.
3349 switch (S->getStmtClass()) {
3350 case Stmt::CompoundStmtClass:
3351 // FIXME: Precompute which substatement of a compound statement we
3352 // would jump to, and go straight there rather than performing a
3353 // linear scan each time.
3354 case Stmt::LabelStmtClass:
3355 case Stmt::AttributedStmtClass:
3356 case Stmt::DoStmtClass:
3359 case Stmt::CaseStmtClass:
3360 case Stmt::DefaultStmtClass:
3365 case Stmt::IfStmtClass: {
3366 // FIXME: Precompute which side of an 'if' we would jump to, and go
3367 // straight there rather than scanning both sides.
3368 const IfStmt *IS = cast<IfStmt>(S);
3370 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3371 // preceded by our switch label.
3372 BlockScopeRAII Scope(Info);
3374 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3375 if (ESR != ESR_CaseNotFound || !IS->getElse())
3377 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3380 case Stmt::WhileStmtClass: {
3381 EvalStmtResult ESR =
3382 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3383 if (ESR != ESR_Continue)
3388 case Stmt::ForStmtClass: {
3389 const ForStmt *FS = cast<ForStmt>(S);
3390 EvalStmtResult ESR =
3391 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3392 if (ESR != ESR_Continue)
3395 FullExpressionRAII IncScope(Info);
3396 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3402 case Stmt::DeclStmtClass:
3403 // FIXME: If the variable has initialization that can't be jumped over,
3404 // bail out of any immediately-surrounding compound-statement too.
3406 return ESR_CaseNotFound;
3410 switch (S->getStmtClass()) {
3412 if (const Expr *E = dyn_cast<Expr>(S)) {
3413 // Don't bother evaluating beyond an expression-statement which couldn't
3415 FullExpressionRAII Scope(Info);
3416 if (!EvaluateIgnoredValue(Info, E))
3418 return ESR_Succeeded;
3421 Info.Diag(S->getLocStart());
3424 case Stmt::NullStmtClass:
3425 return ESR_Succeeded;
3427 case Stmt::DeclStmtClass: {
3428 const DeclStmt *DS = cast<DeclStmt>(S);
3429 for (const auto *DclIt : DS->decls()) {
3430 // Each declaration initialization is its own full-expression.
3431 // FIXME: This isn't quite right; if we're performing aggregate
3432 // initialization, each braced subexpression is its own full-expression.
3433 FullExpressionRAII Scope(Info);
3434 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
3437 return ESR_Succeeded;
3440 case Stmt::ReturnStmtClass: {
3441 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3442 FullExpressionRAII Scope(Info);
3443 if (RetExpr && !Evaluate(Result, Info, RetExpr))
3445 return ESR_Returned;
3448 case Stmt::CompoundStmtClass: {
3449 BlockScopeRAII Scope(Info);
3451 const CompoundStmt *CS = cast<CompoundStmt>(S);
3452 for (const auto *BI : CS->body()) {
3453 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3454 if (ESR == ESR_Succeeded)
3456 else if (ESR != ESR_CaseNotFound)
3459 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3462 case Stmt::IfStmtClass: {
3463 const IfStmt *IS = cast<IfStmt>(S);
3465 // Evaluate the condition, as either a var decl or as an expression.
3466 BlockScopeRAII Scope(Info);
3468 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3471 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3472 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3473 if (ESR != ESR_Succeeded)
3476 return ESR_Succeeded;
3479 case Stmt::WhileStmtClass: {
3480 const WhileStmt *WS = cast<WhileStmt>(S);
3482 BlockScopeRAII Scope(Info);
3484 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3490 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3491 if (ESR != ESR_Continue)
3494 return ESR_Succeeded;
3497 case Stmt::DoStmtClass: {
3498 const DoStmt *DS = cast<DoStmt>(S);
3501 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3502 if (ESR != ESR_Continue)
3506 FullExpressionRAII CondScope(Info);
3507 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3510 return ESR_Succeeded;
3513 case Stmt::ForStmtClass: {
3514 const ForStmt *FS = cast<ForStmt>(S);
3515 BlockScopeRAII Scope(Info);
3516 if (FS->getInit()) {
3517 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3518 if (ESR != ESR_Succeeded)
3522 BlockScopeRAII Scope(Info);
3523 bool Continue = true;
3524 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3525 FS->getCond(), Continue))
3530 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3531 if (ESR != ESR_Continue)
3535 FullExpressionRAII IncScope(Info);
3536 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3540 return ESR_Succeeded;
3543 case Stmt::CXXForRangeStmtClass: {
3544 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3545 BlockScopeRAII Scope(Info);
3547 // Initialize the __range variable.
3548 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3549 if (ESR != ESR_Succeeded)
3552 // Create the __begin and __end iterators.
3553 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3554 if (ESR != ESR_Succeeded)
3558 // Condition: __begin != __end.
3560 bool Continue = true;
3561 FullExpressionRAII CondExpr(Info);
3562 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3568 // User's variable declaration, initialized by *__begin.
3569 BlockScopeRAII InnerScope(Info);
3570 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3571 if (ESR != ESR_Succeeded)
3575 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3576 if (ESR != ESR_Continue)
3579 // Increment: ++__begin
3580 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3584 return ESR_Succeeded;
3587 case Stmt::SwitchStmtClass:
3588 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3590 case Stmt::ContinueStmtClass:
3591 return ESR_Continue;
3593 case Stmt::BreakStmtClass:
3596 case Stmt::LabelStmtClass:
3597 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3599 case Stmt::AttributedStmtClass:
3600 // As a general principle, C++11 attributes can be ignored without
3601 // any semantic impact.
3602 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3605 case Stmt::CaseStmtClass:
3606 case Stmt::DefaultStmtClass:
3607 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3611 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3612 /// default constructor. If so, we'll fold it whether or not it's marked as
3613 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3614 /// so we need special handling.
3615 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3616 const CXXConstructorDecl *CD,
3617 bool IsValueInitialization) {
3618 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3621 // Value-initialization does not call a trivial default constructor, so such a
3622 // call is a core constant expression whether or not the constructor is
3624 if (!CD->isConstexpr() && !IsValueInitialization) {
3625 if (Info.getLangOpts().CPlusPlus11) {
3626 // FIXME: If DiagDecl is an implicitly-declared special member function,
3627 // we should be much more explicit about why it's not constexpr.
3628 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3629 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3630 Info.Note(CD->getLocation(), diag::note_declared_at);
3632 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3638 /// CheckConstexprFunction - Check that a function can be called in a constant
3640 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3641 const FunctionDecl *Declaration,
3642 const FunctionDecl *Definition) {
3643 // Potential constant expressions can contain calls to declared, but not yet
3644 // defined, constexpr functions.
3645 if (Info.checkingPotentialConstantExpression() && !Definition &&
3646 Declaration->isConstexpr())
3649 // Bail out with no diagnostic if the function declaration itself is invalid.
3650 // We will have produced a relevant diagnostic while parsing it.
3651 if (Declaration->isInvalidDecl())
3654 // Can we evaluate this function call?
3655 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3658 if (Info.getLangOpts().CPlusPlus11) {
3659 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3660 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3661 // should be much more explicit about why it's not constexpr.
3662 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3663 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3665 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3667 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3672 /// Determine if a class has any fields that might need to be copied by a
3673 /// trivial copy or move operation.
3674 static bool hasFields(const CXXRecordDecl *RD) {
3675 if (!RD || RD->isEmpty())
3677 for (auto *FD : RD->fields()) {
3678 if (FD->isUnnamedBitfield())
3682 for (auto &Base : RD->bases())
3683 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3689 typedef SmallVector<APValue, 8> ArgVector;
3692 /// EvaluateArgs - Evaluate the arguments to a function call.
3693 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3695 bool Success = true;
3696 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3698 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3699 // If we're checking for a potential constant expression, evaluate all
3700 // initializers even if some of them fail.
3701 if (!Info.keepEvaluatingAfterFailure())
3709 /// Evaluate a function call.
3710 static bool HandleFunctionCall(SourceLocation CallLoc,
3711 const FunctionDecl *Callee, const LValue *This,
3712 ArrayRef<const Expr*> Args, const Stmt *Body,
3713 EvalInfo &Info, APValue &Result) {
3714 ArgVector ArgValues(Args.size());
3715 if (!EvaluateArgs(Args, ArgValues, Info))
3718 if (!Info.CheckCallLimit(CallLoc))
3721 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3723 // For a trivial copy or move assignment, perform an APValue copy. This is
3724 // essential for unions, where the operations performed by the assignment
3725 // operator cannot be represented as statements.
3727 // Skip this for non-union classes with no fields; in that case, the defaulted
3728 // copy/move does not actually read the object.
3729 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3730 if (MD && MD->isDefaulted() &&
3731 (MD->getParent()->isUnion() ||
3732 (MD->isTrivial() && hasFields(MD->getParent())))) {
3734 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3736 RHS.setFrom(Info.Ctx, ArgValues[0]);
3738 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3741 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3744 This->moveInto(Result);
3748 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3749 if (ESR == ESR_Succeeded) {
3750 if (Callee->getReturnType()->isVoidType())
3752 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3754 return ESR == ESR_Returned;
3757 /// Evaluate a constructor call.
3758 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3759 ArrayRef<const Expr*> Args,
3760 const CXXConstructorDecl *Definition,
3761 EvalInfo &Info, APValue &Result) {
3762 ArgVector ArgValues(Args.size());
3763 if (!EvaluateArgs(Args, ArgValues, Info))
3766 if (!Info.CheckCallLimit(CallLoc))
3769 const CXXRecordDecl *RD = Definition->getParent();
3770 if (RD->getNumVBases()) {
3771 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3775 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3777 // If it's a delegating constructor, just delegate.
3778 if (Definition->isDelegatingConstructor()) {
3779 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3781 FullExpressionRAII InitScope(Info);
3782 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3785 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3788 // For a trivial copy or move constructor, perform an APValue copy. This is
3789 // essential for unions (or classes with anonymous union members), where the
3790 // operations performed by the constructor cannot be represented by
3791 // ctor-initializers.
3793 // Skip this for empty non-union classes; we should not perform an
3794 // lvalue-to-rvalue conversion on them because their copy constructor does not
3795 // actually read them.
3796 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
3797 (Definition->getParent()->isUnion() ||
3798 (Definition->isTrivial() && 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 if (CS->body_empty())
4282 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4283 BE = CS->body_end();
4286 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4288 Info.Diag((*BI)->getLocStart(),
4289 diag::note_constexpr_stmt_expr_unsupported);
4292 return this->Visit(FinalExpr);
4295 APValue ReturnValue;
4296 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4297 if (ESR != ESR_Succeeded) {
4298 // FIXME: If the statement-expression terminated due to 'return',
4299 // 'break', or 'continue', it would be nice to propagate that to
4300 // the outer statement evaluation rather than bailing out.
4301 if (ESR != ESR_Failed)
4302 Info.Diag((*BI)->getLocStart(),
4303 diag::note_constexpr_stmt_expr_unsupported);
4308 llvm_unreachable("Return from function from the loop above.");
4311 /// Visit a value which is evaluated, but whose value is ignored.
4312 void VisitIgnoredValue(const Expr *E) {
4313 EvaluateIgnoredValue(Info, E);
4319 //===----------------------------------------------------------------------===//
4320 // Common base class for lvalue and temporary evaluation.
4321 //===----------------------------------------------------------------------===//
4323 template<class Derived>
4324 class LValueExprEvaluatorBase
4325 : public ExprEvaluatorBase<Derived> {
4328 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4329 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4331 bool Success(APValue::LValueBase B) {
4337 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4338 ExprEvaluatorBaseTy(Info), Result(Result) {}
4340 bool Success(const APValue &V, const Expr *E) {
4341 Result.setFrom(this->Info.Ctx, V);
4345 bool VisitMemberExpr(const MemberExpr *E) {
4346 // Handle non-static data members.
4349 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4351 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4352 } else if (E->getBase()->isRValue()) {
4353 assert(E->getBase()->getType()->isRecordType());
4354 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4356 BaseTy = E->getBase()->getType();
4358 if (!this->Visit(E->getBase()))
4360 BaseTy = E->getBase()->getType();
4363 const ValueDecl *MD = E->getMemberDecl();
4364 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4365 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4366 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4368 if (!HandleLValueMember(this->Info, E, Result, FD))
4370 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4371 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4374 return this->Error(E);
4376 if (MD->getType()->isReferenceType()) {
4378 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4381 return Success(RefValue, E);
4386 bool VisitBinaryOperator(const BinaryOperator *E) {
4387 switch (E->getOpcode()) {
4389 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4393 return HandleMemberPointerAccess(this->Info, E, Result);
4397 bool VisitCastExpr(const CastExpr *E) {
4398 switch (E->getCastKind()) {
4400 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4402 case CK_DerivedToBase:
4403 case CK_UncheckedDerivedToBase:
4404 if (!this->Visit(E->getSubExpr()))
4407 // Now figure out the necessary offset to add to the base LV to get from
4408 // the derived class to the base class.
4409 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4416 //===----------------------------------------------------------------------===//
4417 // LValue Evaluation
4419 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4420 // function designators (in C), decl references to void objects (in C), and
4421 // temporaries (if building with -Wno-address-of-temporary).
4423 // LValue evaluation produces values comprising a base expression of one of the
4429 // * CompoundLiteralExpr in C
4433 // * ObjCStringLiteralExpr
4437 // * CallExpr for a MakeStringConstant builtin
4438 // - Locals and temporaries
4439 // * MaterializeTemporaryExpr
4440 // * Any Expr, with a CallIndex indicating the function in which the temporary
4441 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4442 // from the AST (FIXME).
4443 // * A MaterializeTemporaryExpr that has static storage duration, with no
4444 // CallIndex, for a lifetime-extended temporary.
4445 // plus an offset in bytes.
4446 //===----------------------------------------------------------------------===//
4448 class LValueExprEvaluator
4449 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4451 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4452 LValueExprEvaluatorBaseTy(Info, Result) {}
4454 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4455 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4457 bool VisitDeclRefExpr(const DeclRefExpr *E);
4458 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4459 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4460 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4461 bool VisitMemberExpr(const MemberExpr *E);
4462 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4463 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4464 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4465 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4466 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4467 bool VisitUnaryDeref(const UnaryOperator *E);
4468 bool VisitUnaryReal(const UnaryOperator *E);
4469 bool VisitUnaryImag(const UnaryOperator *E);
4470 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4471 return VisitUnaryPreIncDec(UO);
4473 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4474 return VisitUnaryPreIncDec(UO);
4476 bool VisitBinAssign(const BinaryOperator *BO);
4477 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4479 bool VisitCastExpr(const CastExpr *E) {
4480 switch (E->getCastKind()) {
4482 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4484 case CK_LValueBitCast:
4485 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4486 if (!Visit(E->getSubExpr()))
4488 Result.Designator.setInvalid();
4491 case CK_BaseToDerived:
4492 if (!Visit(E->getSubExpr()))
4494 return HandleBaseToDerivedCast(Info, E, Result);
4498 } // end anonymous namespace
4500 /// Evaluate an expression as an lvalue. This can be legitimately called on
4501 /// expressions which are not glvalues, in two cases:
4502 /// * function designators in C, and
4503 /// * "extern void" objects
4504 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4505 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4506 E->getType()->isVoidType());
4507 return LValueExprEvaluator(Info, Result).Visit(E);
4510 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4511 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4513 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4514 return VisitVarDecl(E, VD);
4518 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4519 CallStackFrame *Frame = nullptr;
4520 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4521 Frame = Info.CurrentCall;
4523 if (!VD->getType()->isReferenceType()) {
4525 Result.set(VD, Frame->Index);
4532 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4534 if (V->isUninit()) {
4535 if (!Info.checkingPotentialConstantExpression())
4536 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4539 return Success(*V, E);
4542 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4543 const MaterializeTemporaryExpr *E) {
4544 // Walk through the expression to find the materialized temporary itself.
4545 SmallVector<const Expr *, 2> CommaLHSs;
4546 SmallVector<SubobjectAdjustment, 2> Adjustments;
4547 const Expr *Inner = E->GetTemporaryExpr()->
4548 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4550 // If we passed any comma operators, evaluate their LHSs.
4551 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4552 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4555 // A materialized temporary with static storage duration can appear within the
4556 // result of a constant expression evaluation, so we need to preserve its
4557 // value for use outside this evaluation.
4559 if (E->getStorageDuration() == SD_Static) {
4560 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4564 Value = &Info.CurrentCall->
4565 createTemporary(E, E->getStorageDuration() == SD_Automatic);
4566 Result.set(E, Info.CurrentCall->Index);
4569 QualType Type = Inner->getType();
4571 // Materialize the temporary itself.
4572 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4573 (E->getStorageDuration() == SD_Static &&
4574 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4579 // Adjust our lvalue to refer to the desired subobject.
4580 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4582 switch (Adjustments[I].Kind) {
4583 case SubobjectAdjustment::DerivedToBaseAdjustment:
4584 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4587 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4590 case SubobjectAdjustment::FieldAdjustment:
4591 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4593 Type = Adjustments[I].Field->getType();
4596 case SubobjectAdjustment::MemberPointerAdjustment:
4597 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4598 Adjustments[I].Ptr.RHS))
4600 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4609 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4610 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4611 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4612 // only see this when folding in C, so there's no standard to follow here.
4616 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4617 if (!E->isPotentiallyEvaluated())
4620 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4621 << E->getExprOperand()->getType()
4622 << E->getExprOperand()->getSourceRange();
4626 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4630 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4631 // Handle static data members.
4632 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4633 VisitIgnoredValue(E->getBase());
4634 return VisitVarDecl(E, VD);
4637 // Handle static member functions.
4638 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4639 if (MD->isStatic()) {
4640 VisitIgnoredValue(E->getBase());
4645 // Handle non-static data members.
4646 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4649 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4650 // FIXME: Deal with vectors as array subscript bases.
4651 if (E->getBase()->getType()->isVectorType())
4654 if (!EvaluatePointer(E->getBase(), Result, Info))
4658 if (!EvaluateInteger(E->getIdx(), Index, Info))
4661 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4662 getExtValue(Index));
4665 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4666 return EvaluatePointer(E->getSubExpr(), Result, Info);
4669 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4670 if (!Visit(E->getSubExpr()))
4672 // __real is a no-op on scalar lvalues.
4673 if (E->getSubExpr()->getType()->isAnyComplexType())
4674 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4678 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4679 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4680 "lvalue __imag__ on scalar?");
4681 if (!Visit(E->getSubExpr()))
4683 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4687 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4688 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4691 if (!this->Visit(UO->getSubExpr()))
4694 return handleIncDec(
4695 this->Info, UO, Result, UO->getSubExpr()->getType(),
4696 UO->isIncrementOp(), nullptr);
4699 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4700 const CompoundAssignOperator *CAO) {
4701 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4706 // The overall lvalue result is the result of evaluating the LHS.
4707 if (!this->Visit(CAO->getLHS())) {
4708 if (Info.keepEvaluatingAfterFailure())
4709 Evaluate(RHS, this->Info, CAO->getRHS());
4713 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4716 return handleCompoundAssignment(
4718 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4719 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4722 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4723 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4728 if (!this->Visit(E->getLHS())) {
4729 if (Info.keepEvaluatingAfterFailure())
4730 Evaluate(NewVal, this->Info, E->getRHS());
4734 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4737 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4741 //===----------------------------------------------------------------------===//
4742 // Pointer Evaluation
4743 //===----------------------------------------------------------------------===//
4746 class PointerExprEvaluator
4747 : public ExprEvaluatorBase<PointerExprEvaluator> {
4750 bool Success(const Expr *E) {
4756 PointerExprEvaluator(EvalInfo &info, LValue &Result)
4757 : ExprEvaluatorBaseTy(info), Result(Result) {}
4759 bool Success(const APValue &V, const Expr *E) {
4760 Result.setFrom(Info.Ctx, V);
4763 bool ZeroInitialization(const Expr *E) {
4764 return Success((Expr*)nullptr);
4767 bool VisitBinaryOperator(const BinaryOperator *E);
4768 bool VisitCastExpr(const CastExpr* E);
4769 bool VisitUnaryAddrOf(const UnaryOperator *E);
4770 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4771 { return Success(E); }
4772 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4773 { return Success(E); }
4774 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4775 { return Success(E); }
4776 bool VisitCallExpr(const CallExpr *E);
4777 bool VisitBlockExpr(const BlockExpr *E) {
4778 if (!E->getBlockDecl()->hasCaptures())
4782 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4783 // Can't look at 'this' when checking a potential constant expression.
4784 if (Info.checkingPotentialConstantExpression())
4786 if (!Info.CurrentCall->This) {
4787 if (Info.getLangOpts().CPlusPlus11)
4788 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4793 Result = *Info.CurrentCall->This;
4797 // FIXME: Missing: @protocol, @selector
4799 } // end anonymous namespace
4801 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4802 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4803 return PointerExprEvaluator(Info, Result).Visit(E);
4806 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4807 if (E->getOpcode() != BO_Add &&
4808 E->getOpcode() != BO_Sub)
4809 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4811 const Expr *PExp = E->getLHS();
4812 const Expr *IExp = E->getRHS();
4813 if (IExp->getType()->isPointerType())
4814 std::swap(PExp, IExp);
4816 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4817 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4820 llvm::APSInt Offset;
4821 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4824 int64_t AdditionalOffset = getExtValue(Offset);
4825 if (E->getOpcode() == BO_Sub)
4826 AdditionalOffset = -AdditionalOffset;
4828 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4829 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4833 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4834 return EvaluateLValue(E->getSubExpr(), Result, Info);
4837 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4838 const Expr* SubExpr = E->getSubExpr();
4840 switch (E->getCastKind()) {
4845 case CK_CPointerToObjCPointerCast:
4846 case CK_BlockPointerToObjCPointerCast:
4847 case CK_AnyPointerToBlockPointerCast:
4848 case CK_AddressSpaceConversion:
4849 if (!Visit(SubExpr))
4851 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4852 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4853 // also static_casts, but we disallow them as a resolution to DR1312.
4854 if (!E->getType()->isVoidPointerType()) {
4855 Result.Designator.setInvalid();
4856 if (SubExpr->getType()->isVoidPointerType())
4857 CCEDiag(E, diag::note_constexpr_invalid_cast)
4858 << 3 << SubExpr->getType();
4860 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4864 case CK_DerivedToBase:
4865 case CK_UncheckedDerivedToBase:
4866 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4868 if (!Result.Base && Result.Offset.isZero())
4871 // Now figure out the necessary offset to add to the base LV to get from
4872 // the derived class to the base class.
4873 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4874 castAs<PointerType>()->getPointeeType(),
4877 case CK_BaseToDerived:
4878 if (!Visit(E->getSubExpr()))
4880 if (!Result.Base && Result.Offset.isZero())
4882 return HandleBaseToDerivedCast(Info, E, Result);
4884 case CK_NullToPointer:
4885 VisitIgnoredValue(E->getSubExpr());
4886 return ZeroInitialization(E);
4888 case CK_IntegralToPointer: {
4889 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4892 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4895 if (Value.isInt()) {
4896 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4897 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4898 Result.Base = (Expr*)nullptr;
4899 Result.Offset = CharUnits::fromQuantity(N);
4900 Result.CallIndex = 0;
4901 Result.Designator.setInvalid();
4904 // Cast is of an lvalue, no need to change value.
4905 Result.setFrom(Info.Ctx, Value);
4909 case CK_ArrayToPointerDecay:
4910 if (SubExpr->isGLValue()) {
4911 if (!EvaluateLValue(SubExpr, Result, Info))
4914 Result.set(SubExpr, Info.CurrentCall->Index);
4915 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4916 Info, Result, SubExpr))
4919 // The result is a pointer to the first element of the array.
4920 if (const ConstantArrayType *CAT
4921 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4922 Result.addArray(Info, E, CAT);
4924 Result.Designator.setInvalid();
4927 case CK_FunctionToPointerDecay:
4928 return EvaluateLValue(SubExpr, Result, Info);
4931 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4934 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4935 // C++ [expr.alignof]p3:
4936 // When alignof is applied to a reference type, the result is the
4937 // alignment of the referenced type.
4938 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4939 T = Ref->getPointeeType();
4941 // __alignof is defined to return the preferred alignment.
4942 return Info.Ctx.toCharUnitsFromBits(
4943 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4946 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
4947 E = E->IgnoreParens();
4949 // The kinds of expressions that we have special-case logic here for
4950 // should be kept up to date with the special checks for those
4951 // expressions in Sema.
4953 // alignof decl is always accepted, even if it doesn't make sense: we default
4954 // to 1 in those cases.
4955 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4956 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4957 /*RefAsPointee*/true);
4959 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4960 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4961 /*RefAsPointee*/true);
4963 return GetAlignOfType(Info, E->getType());
4966 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4967 if (IsStringLiteralCall(E))
4970 switch (E->getBuiltinCallee()) {
4971 case Builtin::BI__builtin_addressof:
4972 return EvaluateLValue(E->getArg(0), Result, Info);
4973 case Builtin::BI__builtin_assume_aligned: {
4974 // We need to be very careful here because: if the pointer does not have the
4975 // asserted alignment, then the behavior is undefined, and undefined
4976 // behavior is non-constant.
4977 if (!EvaluatePointer(E->getArg(0), Result, Info))
4980 LValue OffsetResult(Result);
4982 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
4984 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
4986 if (E->getNumArgs() > 2) {
4988 if (!EvaluateInteger(E->getArg(2), Offset, Info))
4991 int64_t AdditionalOffset = -getExtValue(Offset);
4992 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
4995 // If there is a base object, then it must have the correct alignment.
4996 if (OffsetResult.Base) {
4997 CharUnits BaseAlignment;
4998 if (const ValueDecl *VD =
4999 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5000 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5003 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5006 if (BaseAlignment < Align) {
5007 Result.Designator.setInvalid();
5008 // FIXME: Quantities here cast to integers because the plural modifier
5009 // does not work on APSInts yet.
5010 CCEDiag(E->getArg(0),
5011 diag::note_constexpr_baa_insufficient_alignment) << 0
5012 << (int) BaseAlignment.getQuantity()
5013 << (unsigned) getExtValue(Alignment);
5018 // The offset must also have the correct alignment.
5019 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5020 Result.Designator.setInvalid();
5021 APSInt Offset(64, false);
5022 Offset = OffsetResult.Offset.getQuantity();
5024 if (OffsetResult.Base)
5025 CCEDiag(E->getArg(0),
5026 diag::note_constexpr_baa_insufficient_alignment) << 1
5027 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5029 CCEDiag(E->getArg(0),
5030 diag::note_constexpr_baa_value_insufficient_alignment)
5031 << Offset << (unsigned) getExtValue(Alignment);
5039 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5043 //===----------------------------------------------------------------------===//
5044 // Member Pointer Evaluation
5045 //===----------------------------------------------------------------------===//
5048 class MemberPointerExprEvaluator
5049 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5052 bool Success(const ValueDecl *D) {
5053 Result = MemberPtr(D);
5058 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5059 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5061 bool Success(const APValue &V, const Expr *E) {
5065 bool ZeroInitialization(const Expr *E) {
5066 return Success((const ValueDecl*)nullptr);
5069 bool VisitCastExpr(const CastExpr *E);
5070 bool VisitUnaryAddrOf(const UnaryOperator *E);
5072 } // end anonymous namespace
5074 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5076 assert(E->isRValue() && E->getType()->isMemberPointerType());
5077 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5080 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5081 switch (E->getCastKind()) {
5083 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5085 case CK_NullToMemberPointer:
5086 VisitIgnoredValue(E->getSubExpr());
5087 return ZeroInitialization(E);
5089 case CK_BaseToDerivedMemberPointer: {
5090 if (!Visit(E->getSubExpr()))
5092 if (E->path_empty())
5094 // Base-to-derived member pointer casts store the path in derived-to-base
5095 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5096 // the wrong end of the derived->base arc, so stagger the path by one class.
5097 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5098 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5099 PathI != PathE; ++PathI) {
5100 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5101 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5102 if (!Result.castToDerived(Derived))
5105 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5106 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5111 case CK_DerivedToBaseMemberPointer:
5112 if (!Visit(E->getSubExpr()))
5114 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5115 PathE = E->path_end(); PathI != PathE; ++PathI) {
5116 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5117 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5118 if (!Result.castToBase(Base))
5125 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5126 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5127 // member can be formed.
5128 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5131 //===----------------------------------------------------------------------===//
5132 // Record Evaluation
5133 //===----------------------------------------------------------------------===//
5136 class RecordExprEvaluator
5137 : public ExprEvaluatorBase<RecordExprEvaluator> {
5142 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5143 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5145 bool Success(const APValue &V, const Expr *E) {
5149 bool ZeroInitialization(const Expr *E);
5151 bool VisitCastExpr(const CastExpr *E);
5152 bool VisitInitListExpr(const InitListExpr *E);
5153 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5154 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5158 /// Perform zero-initialization on an object of non-union class type.
5159 /// C++11 [dcl.init]p5:
5160 /// To zero-initialize an object or reference of type T means:
5162 /// -- if T is a (possibly cv-qualified) non-union class type,
5163 /// each non-static data member and each base-class subobject is
5164 /// zero-initialized
5165 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5166 const RecordDecl *RD,
5167 const LValue &This, APValue &Result) {
5168 assert(!RD->isUnion() && "Expected non-union class type");
5169 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5170 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5171 std::distance(RD->field_begin(), RD->field_end()));
5173 if (RD->isInvalidDecl()) return false;
5174 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5178 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5179 End = CD->bases_end(); I != End; ++I, ++Index) {
5180 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5181 LValue Subobject = This;
5182 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5184 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5185 Result.getStructBase(Index)))
5190 for (const auto *I : RD->fields()) {
5191 // -- if T is a reference type, no initialization is performed.
5192 if (I->getType()->isReferenceType())
5195 LValue Subobject = This;
5196 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5199 ImplicitValueInitExpr VIE(I->getType());
5200 if (!EvaluateInPlace(
5201 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5208 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5209 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5210 if (RD->isInvalidDecl()) return false;
5211 if (RD->isUnion()) {
5212 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5213 // object's first non-static named data member is zero-initialized
5214 RecordDecl::field_iterator I = RD->field_begin();
5215 if (I == RD->field_end()) {
5216 Result = APValue((const FieldDecl*)nullptr);
5220 LValue Subobject = This;
5221 if (!HandleLValueMember(Info, E, Subobject, *I))
5223 Result = APValue(*I);
5224 ImplicitValueInitExpr VIE(I->getType());
5225 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5228 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5229 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
5233 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5236 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5237 switch (E->getCastKind()) {
5239 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5241 case CK_ConstructorConversion:
5242 return Visit(E->getSubExpr());
5244 case CK_DerivedToBase:
5245 case CK_UncheckedDerivedToBase: {
5246 APValue DerivedObject;
5247 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5249 if (!DerivedObject.isStruct())
5250 return Error(E->getSubExpr());
5252 // Derived-to-base rvalue conversion: just slice off the derived part.
5253 APValue *Value = &DerivedObject;
5254 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5255 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5256 PathE = E->path_end(); PathI != PathE; ++PathI) {
5257 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5258 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5259 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5268 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5269 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5270 if (RD->isInvalidDecl()) return false;
5271 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5273 if (RD->isUnion()) {
5274 const FieldDecl *Field = E->getInitializedFieldInUnion();
5275 Result = APValue(Field);
5279 // If the initializer list for a union does not contain any elements, the
5280 // first element of the union is value-initialized.
5281 // FIXME: The element should be initialized from an initializer list.
5282 // Is this difference ever observable for initializer lists which
5284 ImplicitValueInitExpr VIE(Field->getType());
5285 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5287 LValue Subobject = This;
5288 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5291 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5292 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5293 isa<CXXDefaultInitExpr>(InitExpr));
5295 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5298 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5299 "initializer list for class with base classes");
5300 Result = APValue(APValue::UninitStruct(), 0,
5301 std::distance(RD->field_begin(), RD->field_end()));
5302 unsigned ElementNo = 0;
5303 bool Success = true;
5304 for (const auto *Field : RD->fields()) {
5305 // Anonymous bit-fields are not considered members of the class for
5306 // purposes of aggregate initialization.
5307 if (Field->isUnnamedBitfield())
5310 LValue Subobject = This;
5312 bool HaveInit = ElementNo < E->getNumInits();
5314 // FIXME: Diagnostics here should point to the end of the initializer
5315 // list, not the start.
5316 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5317 Subobject, Field, &Layout))
5320 // Perform an implicit value-initialization for members beyond the end of
5321 // the initializer list.
5322 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5323 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5325 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5326 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5327 isa<CXXDefaultInitExpr>(Init));
5329 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5330 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5331 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5332 FieldVal, Field))) {
5333 if (!Info.keepEvaluatingAfterFailure())
5342 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5343 const CXXConstructorDecl *FD = E->getConstructor();
5344 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5346 bool ZeroInit = E->requiresZeroInitialization();
5347 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5348 // If we've already performed zero-initialization, we're already done.
5349 if (!Result.isUninit())
5352 // We can get here in two different ways:
5353 // 1) We're performing value-initialization, and should zero-initialize
5355 // 2) We're performing default-initialization of an object with a trivial
5356 // constexpr default constructor, in which case we should start the
5357 // lifetimes of all the base subobjects (there can be no data member
5358 // subobjects in this case) per [basic.life]p1.
5359 // Either way, ZeroInitialization is appropriate.
5360 return ZeroInitialization(E);
5363 const FunctionDecl *Definition = nullptr;
5364 FD->getBody(Definition);
5366 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5369 // Avoid materializing a temporary for an elidable copy/move constructor.
5370 if (E->isElidable() && !ZeroInit)
5371 if (const MaterializeTemporaryExpr *ME
5372 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5373 return Visit(ME->GetTemporaryExpr());
5375 if (ZeroInit && !ZeroInitialization(E))
5378 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5379 return HandleConstructorCall(E->getExprLoc(), This, Args,
5380 cast<CXXConstructorDecl>(Definition), Info,
5384 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5385 const CXXStdInitializerListExpr *E) {
5386 const ConstantArrayType *ArrayType =
5387 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5390 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5393 // Get a pointer to the first element of the array.
5394 Array.addArray(Info, E, ArrayType);
5396 // FIXME: Perform the checks on the field types in SemaInit.
5397 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5398 RecordDecl::field_iterator Field = Record->field_begin();
5399 if (Field == Record->field_end())
5403 if (!Field->getType()->isPointerType() ||
5404 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5405 ArrayType->getElementType()))
5408 // FIXME: What if the initializer_list type has base classes, etc?
5409 Result = APValue(APValue::UninitStruct(), 0, 2);
5410 Array.moveInto(Result.getStructField(0));
5412 if (++Field == Record->field_end())
5415 if (Field->getType()->isPointerType() &&
5416 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5417 ArrayType->getElementType())) {
5419 if (!HandleLValueArrayAdjustment(Info, E, Array,
5420 ArrayType->getElementType(),
5421 ArrayType->getSize().getZExtValue()))
5423 Array.moveInto(Result.getStructField(1));
5424 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5426 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5430 if (++Field != Record->field_end())
5436 static bool EvaluateRecord(const Expr *E, const LValue &This,
5437 APValue &Result, EvalInfo &Info) {
5438 assert(E->isRValue() && E->getType()->isRecordType() &&
5439 "can't evaluate expression as a record rvalue");
5440 return RecordExprEvaluator(Info, This, Result).Visit(E);
5443 //===----------------------------------------------------------------------===//
5444 // Temporary Evaluation
5446 // Temporaries are represented in the AST as rvalues, but generally behave like
5447 // lvalues. The full-object of which the temporary is a subobject is implicitly
5448 // materialized so that a reference can bind to it.
5449 //===----------------------------------------------------------------------===//
5451 class TemporaryExprEvaluator
5452 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5454 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5455 LValueExprEvaluatorBaseTy(Info, Result) {}
5457 /// Visit an expression which constructs the value of this temporary.
5458 bool VisitConstructExpr(const Expr *E) {
5459 Result.set(E, Info.CurrentCall->Index);
5460 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5464 bool VisitCastExpr(const CastExpr *E) {
5465 switch (E->getCastKind()) {
5467 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5469 case CK_ConstructorConversion:
5470 return VisitConstructExpr(E->getSubExpr());
5473 bool VisitInitListExpr(const InitListExpr *E) {
5474 return VisitConstructExpr(E);
5476 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5477 return VisitConstructExpr(E);
5479 bool VisitCallExpr(const CallExpr *E) {
5480 return VisitConstructExpr(E);
5482 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5483 return VisitConstructExpr(E);
5486 } // end anonymous namespace
5488 /// Evaluate an expression of record type as a temporary.
5489 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5490 assert(E->isRValue() && E->getType()->isRecordType());
5491 return TemporaryExprEvaluator(Info, Result).Visit(E);
5494 //===----------------------------------------------------------------------===//
5495 // Vector Evaluation
5496 //===----------------------------------------------------------------------===//
5499 class VectorExprEvaluator
5500 : public ExprEvaluatorBase<VectorExprEvaluator> {
5504 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5505 : ExprEvaluatorBaseTy(info), Result(Result) {}
5507 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5508 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5509 // FIXME: remove this APValue copy.
5510 Result = APValue(V.data(), V.size());
5513 bool Success(const APValue &V, const Expr *E) {
5514 assert(V.isVector());
5518 bool ZeroInitialization(const Expr *E);
5520 bool VisitUnaryReal(const UnaryOperator *E)
5521 { return Visit(E->getSubExpr()); }
5522 bool VisitCastExpr(const CastExpr* E);
5523 bool VisitInitListExpr(const InitListExpr *E);
5524 bool VisitUnaryImag(const UnaryOperator *E);
5525 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5526 // binary comparisons, binary and/or/xor,
5527 // shufflevector, ExtVectorElementExpr
5529 } // end anonymous namespace
5531 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5532 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5533 return VectorExprEvaluator(Info, Result).Visit(E);
5536 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5537 const VectorType *VTy = E->getType()->castAs<VectorType>();
5538 unsigned NElts = VTy->getNumElements();
5540 const Expr *SE = E->getSubExpr();
5541 QualType SETy = SE->getType();
5543 switch (E->getCastKind()) {
5544 case CK_VectorSplat: {
5545 APValue Val = APValue();
5546 if (SETy->isIntegerType()) {
5548 if (!EvaluateInteger(SE, IntResult, Info))
5550 Val = APValue(IntResult);
5551 } else if (SETy->isRealFloatingType()) {
5553 if (!EvaluateFloat(SE, F, Info))
5560 // Splat and create vector APValue.
5561 SmallVector<APValue, 4> Elts(NElts, Val);
5562 return Success(Elts, E);
5565 // Evaluate the operand into an APInt we can extract from.
5566 llvm::APInt SValInt;
5567 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5569 // Extract the elements
5570 QualType EltTy = VTy->getElementType();
5571 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5572 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5573 SmallVector<APValue, 4> Elts;
5574 if (EltTy->isRealFloatingType()) {
5575 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5576 unsigned FloatEltSize = EltSize;
5577 if (&Sem == &APFloat::x87DoubleExtended)
5579 for (unsigned i = 0; i < NElts; i++) {
5582 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5584 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5585 Elts.push_back(APValue(APFloat(Sem, Elt)));
5587 } else if (EltTy->isIntegerType()) {
5588 for (unsigned i = 0; i < NElts; i++) {
5591 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5593 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5594 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5599 return Success(Elts, E);
5602 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5607 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5608 const VectorType *VT = E->getType()->castAs<VectorType>();
5609 unsigned NumInits = E->getNumInits();
5610 unsigned NumElements = VT->getNumElements();
5612 QualType EltTy = VT->getElementType();
5613 SmallVector<APValue, 4> Elements;
5615 // The number of initializers can be less than the number of
5616 // vector elements. For OpenCL, this can be due to nested vector
5617 // initialization. For GCC compatibility, missing trailing elements
5618 // should be initialized with zeroes.
5619 unsigned CountInits = 0, CountElts = 0;
5620 while (CountElts < NumElements) {
5621 // Handle nested vector initialization.
5622 if (CountInits < NumInits
5623 && E->getInit(CountInits)->getType()->isVectorType()) {
5625 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5627 unsigned vlen = v.getVectorLength();
5628 for (unsigned j = 0; j < vlen; j++)
5629 Elements.push_back(v.getVectorElt(j));
5631 } else if (EltTy->isIntegerType()) {
5632 llvm::APSInt sInt(32);
5633 if (CountInits < NumInits) {
5634 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5636 } else // trailing integer zero.
5637 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5638 Elements.push_back(APValue(sInt));
5641 llvm::APFloat f(0.0);
5642 if (CountInits < NumInits) {
5643 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5645 } else // trailing float zero.
5646 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5647 Elements.push_back(APValue(f));
5652 return Success(Elements, E);
5656 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5657 const VectorType *VT = E->getType()->getAs<VectorType>();
5658 QualType EltTy = VT->getElementType();
5659 APValue ZeroElement;
5660 if (EltTy->isIntegerType())
5661 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5664 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5666 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5667 return Success(Elements, E);
5670 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5671 VisitIgnoredValue(E->getSubExpr());
5672 return ZeroInitialization(E);
5675 //===----------------------------------------------------------------------===//
5677 //===----------------------------------------------------------------------===//
5680 class ArrayExprEvaluator
5681 : public ExprEvaluatorBase<ArrayExprEvaluator> {
5686 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5687 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5689 bool Success(const APValue &V, const Expr *E) {
5690 assert((V.isArray() || V.isLValue()) &&
5691 "expected array or string literal");
5696 bool ZeroInitialization(const Expr *E) {
5697 const ConstantArrayType *CAT =
5698 Info.Ctx.getAsConstantArrayType(E->getType());
5702 Result = APValue(APValue::UninitArray(), 0,
5703 CAT->getSize().getZExtValue());
5704 if (!Result.hasArrayFiller()) return true;
5706 // Zero-initialize all elements.
5707 LValue Subobject = This;
5708 Subobject.addArray(Info, E, CAT);
5709 ImplicitValueInitExpr VIE(CAT->getElementType());
5710 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5713 bool VisitInitListExpr(const InitListExpr *E);
5714 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5715 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5716 const LValue &Subobject,
5717 APValue *Value, QualType Type);
5719 } // end anonymous namespace
5721 static bool EvaluateArray(const Expr *E, const LValue &This,
5722 APValue &Result, EvalInfo &Info) {
5723 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5724 return ArrayExprEvaluator(Info, This, Result).Visit(E);
5727 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5728 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5732 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5733 // an appropriately-typed string literal enclosed in braces.
5734 if (E->isStringLiteralInit()) {
5736 if (!EvaluateLValue(E->getInit(0), LV, Info))
5740 return Success(Val, E);
5743 bool Success = true;
5745 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5746 "zero-initialized array shouldn't have any initialized elts");
5748 if (Result.isArray() && Result.hasArrayFiller())
5749 Filler = Result.getArrayFiller();
5751 unsigned NumEltsToInit = E->getNumInits();
5752 unsigned NumElts = CAT->getSize().getZExtValue();
5753 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
5755 // If the initializer might depend on the array index, run it for each
5756 // array element. For now, just whitelist non-class value-initialization.
5757 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5758 NumEltsToInit = NumElts;
5760 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5762 // If the array was previously zero-initialized, preserve the
5763 // zero-initialized values.
5764 if (!Filler.isUninit()) {
5765 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5766 Result.getArrayInitializedElt(I) = Filler;
5767 if (Result.hasArrayFiller())
5768 Result.getArrayFiller() = Filler;
5771 LValue Subobject = This;
5772 Subobject.addArray(Info, E, CAT);
5773 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5775 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5776 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5777 Info, Subobject, Init) ||
5778 !HandleLValueArrayAdjustment(Info, Init, Subobject,
5779 CAT->getElementType(), 1)) {
5780 if (!Info.keepEvaluatingAfterFailure())
5786 if (!Result.hasArrayFiller())
5789 // If we get here, we have a trivial filler, which we can just evaluate
5790 // once and splat over the rest of the array elements.
5791 assert(FillerExpr && "no array filler for incomplete init list");
5792 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5793 FillerExpr) && Success;
5796 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5797 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5800 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5801 const LValue &Subobject,
5804 bool HadZeroInit = !Value->isUninit();
5806 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5807 unsigned N = CAT->getSize().getZExtValue();
5809 // Preserve the array filler if we had prior zero-initialization.
5811 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5814 *Value = APValue(APValue::UninitArray(), N, N);
5817 for (unsigned I = 0; I != N; ++I)
5818 Value->getArrayInitializedElt(I) = Filler;
5820 // Initialize the elements.
5821 LValue ArrayElt = Subobject;
5822 ArrayElt.addArray(Info, E, CAT);
5823 for (unsigned I = 0; I != N; ++I)
5824 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5825 CAT->getElementType()) ||
5826 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5827 CAT->getElementType(), 1))
5833 if (!Type->isRecordType())
5836 const CXXConstructorDecl *FD = E->getConstructor();
5838 bool ZeroInit = E->requiresZeroInitialization();
5839 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5843 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5844 ImplicitValueInitExpr VIE(Type);
5845 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5848 const FunctionDecl *Definition = nullptr;
5849 FD->getBody(Definition);
5851 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5854 if (ZeroInit && !HadZeroInit) {
5855 ImplicitValueInitExpr VIE(Type);
5856 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5860 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5861 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5862 cast<CXXConstructorDecl>(Definition),
5866 //===----------------------------------------------------------------------===//
5867 // Integer Evaluation
5869 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5870 // types and back in constant folding. Integer values are thus represented
5871 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5872 //===----------------------------------------------------------------------===//
5875 class IntExprEvaluator
5876 : public ExprEvaluatorBase<IntExprEvaluator> {
5879 IntExprEvaluator(EvalInfo &info, APValue &result)
5880 : ExprEvaluatorBaseTy(info), Result(result) {}
5882 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5883 assert(E->getType()->isIntegralOrEnumerationType() &&
5884 "Invalid evaluation result.");
5885 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5886 "Invalid evaluation result.");
5887 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5888 "Invalid evaluation result.");
5889 Result = APValue(SI);
5892 bool Success(const llvm::APSInt &SI, const Expr *E) {
5893 return Success(SI, E, Result);
5896 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5897 assert(E->getType()->isIntegralOrEnumerationType() &&
5898 "Invalid evaluation result.");
5899 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5900 "Invalid evaluation result.");
5901 Result = APValue(APSInt(I));
5902 Result.getInt().setIsUnsigned(
5903 E->getType()->isUnsignedIntegerOrEnumerationType());
5906 bool Success(const llvm::APInt &I, const Expr *E) {
5907 return Success(I, E, Result);
5910 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5911 assert(E->getType()->isIntegralOrEnumerationType() &&
5912 "Invalid evaluation result.");
5913 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5916 bool Success(uint64_t Value, const Expr *E) {
5917 return Success(Value, E, Result);
5920 bool Success(CharUnits Size, const Expr *E) {
5921 return Success(Size.getQuantity(), E);
5924 bool Success(const APValue &V, const Expr *E) {
5925 if (V.isLValue() || V.isAddrLabelDiff()) {
5929 return Success(V.getInt(), E);
5932 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5934 //===--------------------------------------------------------------------===//
5936 //===--------------------------------------------------------------------===//
5938 bool VisitIntegerLiteral(const IntegerLiteral *E) {
5939 return Success(E->getValue(), E);
5941 bool VisitCharacterLiteral(const CharacterLiteral *E) {
5942 return Success(E->getValue(), E);
5945 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5946 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5947 if (CheckReferencedDecl(E, E->getDecl()))
5950 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5952 bool VisitMemberExpr(const MemberExpr *E) {
5953 if (CheckReferencedDecl(E, E->getMemberDecl())) {
5954 VisitIgnoredValue(E->getBase());
5958 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5961 bool VisitCallExpr(const CallExpr *E);
5962 bool VisitBinaryOperator(const BinaryOperator *E);
5963 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5964 bool VisitUnaryOperator(const UnaryOperator *E);
5966 bool VisitCastExpr(const CastExpr* E);
5967 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5969 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5970 return Success(E->getValue(), E);
5973 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5974 return Success(E->getValue(), E);
5977 // Note, GNU defines __null as an integer, not a pointer.
5978 bool VisitGNUNullExpr(const GNUNullExpr *E) {
5979 return ZeroInitialization(E);
5982 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5983 return Success(E->getValue(), E);
5986 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5987 return Success(E->getValue(), E);
5990 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5991 return Success(E->getValue(), E);
5994 bool VisitUnaryReal(const UnaryOperator *E);
5995 bool VisitUnaryImag(const UnaryOperator *E);
5997 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5998 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6001 static QualType GetObjectType(APValue::LValueBase B);
6002 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
6003 // FIXME: Missing: array subscript of vector, member of vector
6005 } // end anonymous namespace
6007 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6008 /// produce either the integer value or a pointer.
6010 /// GCC has a heinous extension which folds casts between pointer types and
6011 /// pointer-sized integral types. We support this by allowing the evaluation of
6012 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6013 /// Some simple arithmetic on such values is supported (they are treated much
6015 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6017 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6018 return IntExprEvaluator(Info, Result).Visit(E);
6021 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6023 if (!EvaluateIntegerOrLValue(E, Val, Info))
6026 // FIXME: It would be better to produce the diagnostic for casting
6027 // a pointer to an integer.
6028 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6031 Result = Val.getInt();
6035 /// Check whether the given declaration can be directly converted to an integral
6036 /// rvalue. If not, no diagnostic is produced; there are other things we can
6038 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6039 // Enums are integer constant exprs.
6040 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6041 // Check for signedness/width mismatches between E type and ECD value.
6042 bool SameSign = (ECD->getInitVal().isSigned()
6043 == E->getType()->isSignedIntegerOrEnumerationType());
6044 bool SameWidth = (ECD->getInitVal().getBitWidth()
6045 == Info.Ctx.getIntWidth(E->getType()));
6046 if (SameSign && SameWidth)
6047 return Success(ECD->getInitVal(), E);
6049 // Get rid of mismatch (otherwise Success assertions will fail)
6050 // by computing a new value matching the type of E.
6051 llvm::APSInt Val = ECD->getInitVal();
6053 Val.setIsSigned(!ECD->getInitVal().isSigned());
6055 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6056 return Success(Val, E);
6062 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6064 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6065 // The following enum mimics the values returned by GCC.
6066 // FIXME: Does GCC differ between lvalue and rvalue references here?
6067 enum gcc_type_class {
6069 void_type_class, integer_type_class, char_type_class,
6070 enumeral_type_class, boolean_type_class,
6071 pointer_type_class, reference_type_class, offset_type_class,
6072 real_type_class, complex_type_class,
6073 function_type_class, method_type_class,
6074 record_type_class, union_type_class,
6075 array_type_class, string_type_class,
6079 // If no argument was supplied, default to "no_type_class". This isn't
6080 // ideal, however it is what gcc does.
6081 if (E->getNumArgs() == 0)
6082 return no_type_class;
6084 QualType ArgTy = E->getArg(0)->getType();
6085 if (ArgTy->isVoidType())
6086 return void_type_class;
6087 else if (ArgTy->isEnumeralType())
6088 return enumeral_type_class;
6089 else if (ArgTy->isBooleanType())
6090 return boolean_type_class;
6091 else if (ArgTy->isCharType())
6092 return string_type_class; // gcc doesn't appear to use char_type_class
6093 else if (ArgTy->isIntegerType())
6094 return integer_type_class;
6095 else if (ArgTy->isPointerType())
6096 return pointer_type_class;
6097 else if (ArgTy->isReferenceType())
6098 return reference_type_class;
6099 else if (ArgTy->isRealType())
6100 return real_type_class;
6101 else if (ArgTy->isComplexType())
6102 return complex_type_class;
6103 else if (ArgTy->isFunctionType())
6104 return function_type_class;
6105 else if (ArgTy->isStructureOrClassType())
6106 return record_type_class;
6107 else if (ArgTy->isUnionType())
6108 return union_type_class;
6109 else if (ArgTy->isArrayType())
6110 return array_type_class;
6111 else if (ArgTy->isUnionType())
6112 return union_type_class;
6113 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
6114 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6117 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6118 /// __builtin_constant_p when applied to the given lvalue.
6120 /// An lvalue is only "constant" if it is a pointer or reference to the first
6121 /// character of a string literal.
6122 template<typename LValue>
6123 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6124 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6125 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6128 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6129 /// GCC as we can manage.
6130 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6131 QualType ArgType = Arg->getType();
6133 // __builtin_constant_p always has one operand. The rules which gcc follows
6134 // are not precisely documented, but are as follows:
6136 // - If the operand is of integral, floating, complex or enumeration type,
6137 // and can be folded to a known value of that type, it returns 1.
6138 // - If the operand and can be folded to a pointer to the first character
6139 // of a string literal (or such a pointer cast to an integral type), it
6142 // Otherwise, it returns 0.
6144 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6145 // its support for this does not currently work.
6146 if (ArgType->isIntegralOrEnumerationType()) {
6147 Expr::EvalResult Result;
6148 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6151 APValue &V = Result.Val;
6152 if (V.getKind() == APValue::Int)
6155 return EvaluateBuiltinConstantPForLValue(V);
6156 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6157 return Arg->isEvaluatable(Ctx);
6158 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6160 Expr::EvalStatus Status;
6161 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6162 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6163 : EvaluatePointer(Arg, LV, Info)) &&
6164 !Status.HasSideEffects)
6165 return EvaluateBuiltinConstantPForLValue(LV);
6168 // Anything else isn't considered to be sufficiently constant.
6172 /// Retrieves the "underlying object type" of the given expression,
6173 /// as used by __builtin_object_size.
6174 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6175 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6176 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6177 return VD->getType();
6178 } else if (const Expr *E = B.get<const Expr*>()) {
6179 if (isa<CompoundLiteralExpr>(E))
6180 return E->getType();
6186 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
6190 // The operand of __builtin_object_size is never evaluated for side-effects.
6191 // If there are any, but we can determine the pointed-to object anyway, then
6192 // ignore the side-effects.
6193 SpeculativeEvaluationRAII SpeculativeEval(Info);
6194 if (!EvaluatePointer(E->getArg(0), Base, Info))
6198 if (!Base.getLValueBase()) {
6199 // It is not possible to determine which objects ptr points to at compile time,
6200 // __builtin_object_size should return (size_t) -1 for type 0 or 1
6201 // and (size_t) 0 for type 2 or 3.
6202 llvm::APSInt TypeIntVaue;
6203 const Expr *ExprType = E->getArg(1);
6204 if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6206 if (TypeIntVaue == 0 || TypeIntVaue == 1)
6207 return Success(-1, E);
6208 if (TypeIntVaue == 2 || TypeIntVaue == 3)
6209 return Success(0, E);
6213 QualType T = GetObjectType(Base.getLValueBase());
6215 T->isIncompleteType() ||
6216 T->isFunctionType() ||
6217 T->isVariablyModifiedType() ||
6218 T->isDependentType())
6221 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6222 CharUnits Offset = Base.getLValueOffset();
6224 if (!Offset.isNegative() && Offset <= Size)
6227 Size = CharUnits::Zero();
6228 return Success(Size, E);
6231 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6232 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6234 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6236 case Builtin::BI__builtin_object_size: {
6237 if (TryEvaluateBuiltinObjectSize(E))
6240 // If evaluating the argument has side-effects, we can't determine the size
6241 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6242 // handle all cases where the expression has side-effects.
6243 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
6244 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
6245 return Success(-1ULL, E);
6246 return Success(0, E);
6249 // Expression had no side effects, but we couldn't statically determine the
6250 // size of the referenced object.
6251 switch (Info.EvalMode) {
6252 case EvalInfo::EM_ConstantExpression:
6253 case EvalInfo::EM_PotentialConstantExpression:
6254 case EvalInfo::EM_ConstantFold:
6255 case EvalInfo::EM_EvaluateForOverflow:
6256 case EvalInfo::EM_IgnoreSideEffects:
6258 case EvalInfo::EM_ConstantExpressionUnevaluated:
6259 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6260 return Success(-1ULL, E);
6264 case Builtin::BI__builtin_bswap16:
6265 case Builtin::BI__builtin_bswap32:
6266 case Builtin::BI__builtin_bswap64: {
6268 if (!EvaluateInteger(E->getArg(0), Val, Info))
6271 return Success(Val.byteSwap(), E);
6274 case Builtin::BI__builtin_classify_type:
6275 return Success(EvaluateBuiltinClassifyType(E), E);
6277 // FIXME: BI__builtin_clrsb
6278 // FIXME: BI__builtin_clrsbl
6279 // FIXME: BI__builtin_clrsbll
6281 case Builtin::BI__builtin_clz:
6282 case Builtin::BI__builtin_clzl:
6283 case Builtin::BI__builtin_clzll:
6284 case Builtin::BI__builtin_clzs: {
6286 if (!EvaluateInteger(E->getArg(0), Val, Info))
6291 return Success(Val.countLeadingZeros(), E);
6294 case Builtin::BI__builtin_constant_p:
6295 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6297 case Builtin::BI__builtin_ctz:
6298 case Builtin::BI__builtin_ctzl:
6299 case Builtin::BI__builtin_ctzll:
6300 case Builtin::BI__builtin_ctzs: {
6302 if (!EvaluateInteger(E->getArg(0), Val, Info))
6307 return Success(Val.countTrailingZeros(), E);
6310 case Builtin::BI__builtin_eh_return_data_regno: {
6311 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6312 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6313 return Success(Operand, E);
6316 case Builtin::BI__builtin_expect:
6317 return Visit(E->getArg(0));
6319 case Builtin::BI__builtin_ffs:
6320 case Builtin::BI__builtin_ffsl:
6321 case Builtin::BI__builtin_ffsll: {
6323 if (!EvaluateInteger(E->getArg(0), Val, Info))
6326 unsigned N = Val.countTrailingZeros();
6327 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6330 case Builtin::BI__builtin_fpclassify: {
6332 if (!EvaluateFloat(E->getArg(5), Val, Info))
6335 switch (Val.getCategory()) {
6336 case APFloat::fcNaN: Arg = 0; break;
6337 case APFloat::fcInfinity: Arg = 1; break;
6338 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6339 case APFloat::fcZero: Arg = 4; break;
6341 return Visit(E->getArg(Arg));
6344 case Builtin::BI__builtin_isinf_sign: {
6346 return EvaluateFloat(E->getArg(0), Val, Info) &&
6347 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6350 case Builtin::BI__builtin_isinf: {
6352 return EvaluateFloat(E->getArg(0), Val, Info) &&
6353 Success(Val.isInfinity() ? 1 : 0, E);
6356 case Builtin::BI__builtin_isfinite: {
6358 return EvaluateFloat(E->getArg(0), Val, Info) &&
6359 Success(Val.isFinite() ? 1 : 0, E);
6362 case Builtin::BI__builtin_isnan: {
6364 return EvaluateFloat(E->getArg(0), Val, Info) &&
6365 Success(Val.isNaN() ? 1 : 0, E);
6368 case Builtin::BI__builtin_isnormal: {
6370 return EvaluateFloat(E->getArg(0), Val, Info) &&
6371 Success(Val.isNormal() ? 1 : 0, E);
6374 case Builtin::BI__builtin_parity:
6375 case Builtin::BI__builtin_parityl:
6376 case Builtin::BI__builtin_parityll: {
6378 if (!EvaluateInteger(E->getArg(0), Val, Info))
6381 return Success(Val.countPopulation() % 2, E);
6384 case Builtin::BI__builtin_popcount:
6385 case Builtin::BI__builtin_popcountl:
6386 case Builtin::BI__builtin_popcountll: {
6388 if (!EvaluateInteger(E->getArg(0), Val, Info))
6391 return Success(Val.countPopulation(), E);
6394 case Builtin::BIstrlen:
6395 // A call to strlen is not a constant expression.
6396 if (Info.getLangOpts().CPlusPlus11)
6397 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6398 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6400 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6402 case Builtin::BI__builtin_strlen: {
6403 // As an extension, we support __builtin_strlen() as a constant expression,
6404 // and support folding strlen() to a constant.
6406 if (!EvaluatePointer(E->getArg(0), String, Info))
6409 // Fast path: if it's a string literal, search the string value.
6410 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6411 String.getLValueBase().dyn_cast<const Expr *>())) {
6412 // The string literal may have embedded null characters. Find the first
6413 // one and truncate there.
6414 StringRef Str = S->getBytes();
6415 int64_t Off = String.Offset.getQuantity();
6416 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6417 S->getCharByteWidth() == 1) {
6418 Str = Str.substr(Off);
6420 StringRef::size_type Pos = Str.find(0);
6421 if (Pos != StringRef::npos)
6422 Str = Str.substr(0, Pos);
6424 return Success(Str.size(), E);
6427 // Fall through to slow path to issue appropriate diagnostic.
6430 // Slow path: scan the bytes of the string looking for the terminating 0.
6431 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6432 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6434 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6438 return Success(Strlen, E);
6439 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6444 case Builtin::BI__atomic_always_lock_free:
6445 case Builtin::BI__atomic_is_lock_free:
6446 case Builtin::BI__c11_atomic_is_lock_free: {
6448 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6451 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6452 // of two less than the maximum inline atomic width, we know it is
6453 // lock-free. If the size isn't a power of two, or greater than the
6454 // maximum alignment where we promote atomics, we know it is not lock-free
6455 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6456 // the answer can only be determined at runtime; for example, 16-byte
6457 // atomics have lock-free implementations on some, but not all,
6458 // x86-64 processors.
6460 // Check power-of-two.
6461 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6462 if (Size.isPowerOfTwo()) {
6463 // Check against inlining width.
6464 unsigned InlineWidthBits =
6465 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6466 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6467 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6468 Size == CharUnits::One() ||
6469 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6470 Expr::NPC_NeverValueDependent))
6471 // OK, we will inline appropriately-aligned operations of this size,
6472 // and _Atomic(T) is appropriately-aligned.
6473 return Success(1, E);
6475 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6476 castAs<PointerType>()->getPointeeType();
6477 if (!PointeeType->isIncompleteType() &&
6478 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6479 // OK, we will inline operations on this object.
6480 return Success(1, E);
6485 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6486 Success(0, E) : Error(E);
6491 static bool HasSameBase(const LValue &A, const LValue &B) {
6492 if (!A.getLValueBase())
6493 return !B.getLValueBase();
6494 if (!B.getLValueBase())
6497 if (A.getLValueBase().getOpaqueValue() !=
6498 B.getLValueBase().getOpaqueValue()) {
6499 const Decl *ADecl = GetLValueBaseDecl(A);
6502 const Decl *BDecl = GetLValueBaseDecl(B);
6503 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6507 return IsGlobalLValue(A.getLValueBase()) ||
6508 A.getLValueCallIndex() == B.getLValueCallIndex();
6511 /// \brief Determine whether this is a pointer past the end of the complete
6512 /// object referred to by the lvalue.
6513 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6515 // A null pointer can be viewed as being "past the end" but we don't
6516 // choose to look at it that way here.
6517 if (!LV.getLValueBase())
6520 // If the designator is valid and refers to a subobject, we're not pointing
6522 if (!LV.getLValueDesignator().Invalid &&
6523 !LV.getLValueDesignator().isOnePastTheEnd())
6526 // We're a past-the-end pointer if we point to the byte after the object,
6527 // no matter what our type or path is.
6528 auto Size = Ctx.getTypeSizeInChars(getType(LV.getLValueBase()));
6529 return LV.getLValueOffset() == Size;
6534 /// \brief Data recursive integer evaluator of certain binary operators.
6536 /// We use a data recursive algorithm for binary operators so that we are able
6537 /// to handle extreme cases of chained binary operators without causing stack
6539 class DataRecursiveIntBinOpEvaluator {
6544 EvalResult() : Failed(false) { }
6546 void swap(EvalResult &RHS) {
6548 Failed = RHS.Failed;
6555 EvalResult LHSResult; // meaningful only for binary operator expression.
6556 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6558 Job() : StoredInfo(nullptr) {}
6559 void startSpeculativeEval(EvalInfo &Info) {
6560 OldEvalStatus = Info.EvalStatus;
6561 Info.EvalStatus.Diag = nullptr;
6566 StoredInfo->EvalStatus = OldEvalStatus;
6570 EvalInfo *StoredInfo; // non-null if status changed.
6571 Expr::EvalStatus OldEvalStatus;
6574 SmallVector<Job, 16> Queue;
6576 IntExprEvaluator &IntEval;
6578 APValue &FinalResult;
6581 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6582 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6584 /// \brief True if \param E is a binary operator that we are going to handle
6585 /// data recursively.
6586 /// We handle binary operators that are comma, logical, or that have operands
6587 /// with integral or enumeration type.
6588 static bool shouldEnqueue(const BinaryOperator *E) {
6589 return E->getOpcode() == BO_Comma ||
6591 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6592 E->getRHS()->getType()->isIntegralOrEnumerationType());
6595 bool Traverse(const BinaryOperator *E) {
6597 EvalResult PrevResult;
6598 while (!Queue.empty())
6599 process(PrevResult);
6601 if (PrevResult.Failed) return false;
6603 FinalResult.swap(PrevResult.Val);
6608 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6609 return IntEval.Success(Value, E, Result);
6611 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6612 return IntEval.Success(Value, E, Result);
6614 bool Error(const Expr *E) {
6615 return IntEval.Error(E);
6617 bool Error(const Expr *E, diag::kind D) {
6618 return IntEval.Error(E, D);
6621 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6622 return Info.CCEDiag(E, D);
6625 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6626 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6627 bool &SuppressRHSDiags);
6629 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6630 const BinaryOperator *E, APValue &Result);
6632 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6633 Result.Failed = !Evaluate(Result.Val, Info, E);
6635 Result.Val = APValue();
6638 void process(EvalResult &Result);
6640 void enqueue(const Expr *E) {
6641 E = E->IgnoreParens();
6642 Queue.resize(Queue.size()+1);
6644 Queue.back().Kind = Job::AnyExprKind;
6650 bool DataRecursiveIntBinOpEvaluator::
6651 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6652 bool &SuppressRHSDiags) {
6653 if (E->getOpcode() == BO_Comma) {
6654 // Ignore LHS but note if we could not evaluate it.
6655 if (LHSResult.Failed)
6656 return Info.noteSideEffect();
6660 if (E->isLogicalOp()) {
6662 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6663 // We were able to evaluate the LHS, see if we can get away with not
6664 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6665 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6666 Success(LHSAsBool, E, LHSResult.Val);
6667 return false; // Ignore RHS
6670 LHSResult.Failed = true;
6672 // Since we weren't able to evaluate the left hand side, it
6673 // must have had side effects.
6674 if (!Info.noteSideEffect())
6677 // We can't evaluate the LHS; however, sometimes the result
6678 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6679 // Don't ignore RHS and suppress diagnostics from this arm.
6680 SuppressRHSDiags = true;
6686 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6687 E->getRHS()->getType()->isIntegralOrEnumerationType());
6689 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6690 return false; // Ignore RHS;
6695 bool DataRecursiveIntBinOpEvaluator::
6696 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6697 const BinaryOperator *E, APValue &Result) {
6698 if (E->getOpcode() == BO_Comma) {
6699 if (RHSResult.Failed)
6701 Result = RHSResult.Val;
6705 if (E->isLogicalOp()) {
6706 bool lhsResult, rhsResult;
6707 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6708 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6712 if (E->getOpcode() == BO_LOr)
6713 return Success(lhsResult || rhsResult, E, Result);
6715 return Success(lhsResult && rhsResult, E, Result);
6719 // We can't evaluate the LHS; however, sometimes the result
6720 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6721 if (rhsResult == (E->getOpcode() == BO_LOr))
6722 return Success(rhsResult, E, Result);
6729 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6730 E->getRHS()->getType()->isIntegralOrEnumerationType());
6732 if (LHSResult.Failed || RHSResult.Failed)
6735 const APValue &LHSVal = LHSResult.Val;
6736 const APValue &RHSVal = RHSResult.Val;
6738 // Handle cases like (unsigned long)&a + 4.
6739 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6741 CharUnits AdditionalOffset =
6742 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6743 if (E->getOpcode() == BO_Add)
6744 Result.getLValueOffset() += AdditionalOffset;
6746 Result.getLValueOffset() -= AdditionalOffset;
6750 // Handle cases like 4 + (unsigned long)&a
6751 if (E->getOpcode() == BO_Add &&
6752 RHSVal.isLValue() && LHSVal.isInt()) {
6754 Result.getLValueOffset() +=
6755 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6759 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6760 // Handle (intptr_t)&&A - (intptr_t)&&B.
6761 if (!LHSVal.getLValueOffset().isZero() ||
6762 !RHSVal.getLValueOffset().isZero())
6764 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6765 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6766 if (!LHSExpr || !RHSExpr)
6768 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6769 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6770 if (!LHSAddrExpr || !RHSAddrExpr)
6772 // Make sure both labels come from the same function.
6773 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6774 RHSAddrExpr->getLabel()->getDeclContext())
6776 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6780 // All the remaining cases expect both operands to be an integer
6781 if (!LHSVal.isInt() || !RHSVal.isInt())
6784 // Set up the width and signedness manually, in case it can't be deduced
6785 // from the operation we're performing.
6786 // FIXME: Don't do this in the cases where we can deduce it.
6787 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6788 E->getType()->isUnsignedIntegerOrEnumerationType());
6789 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6790 RHSVal.getInt(), Value))
6792 return Success(Value, E, Result);
6795 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6796 Job &job = Queue.back();
6799 case Job::AnyExprKind: {
6800 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6801 if (shouldEnqueue(Bop)) {
6802 job.Kind = Job::BinOpKind;
6803 enqueue(Bop->getLHS());
6808 EvaluateExpr(job.E, Result);
6813 case Job::BinOpKind: {
6814 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6815 bool SuppressRHSDiags = false;
6816 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6820 if (SuppressRHSDiags)
6821 job.startSpeculativeEval(Info);
6822 job.LHSResult.swap(Result);
6823 job.Kind = Job::BinOpVisitedLHSKind;
6824 enqueue(Bop->getRHS());
6828 case Job::BinOpVisitedLHSKind: {
6829 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6832 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6838 llvm_unreachable("Invalid Job::Kind!");
6841 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6842 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
6845 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6846 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6848 QualType LHSTy = E->getLHS()->getType();
6849 QualType RHSTy = E->getRHS()->getType();
6851 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
6852 ComplexValue LHS, RHS;
6854 if (E->isAssignmentOp()) {
6856 EvaluateLValue(E->getLHS(), LV, Info);
6858 } else if (LHSTy->isRealFloatingType()) {
6859 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
6861 LHS.makeComplexFloat();
6862 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
6865 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6867 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6870 if (E->getRHS()->getType()->isRealFloatingType()) {
6871 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
6873 RHS.makeComplexFloat();
6874 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
6875 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6878 if (LHS.isComplexFloat()) {
6879 APFloat::cmpResult CR_r =
6880 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6881 APFloat::cmpResult CR_i =
6882 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6884 if (E->getOpcode() == BO_EQ)
6885 return Success((CR_r == APFloat::cmpEqual &&
6886 CR_i == APFloat::cmpEqual), E);
6888 assert(E->getOpcode() == BO_NE &&
6889 "Invalid complex comparison.");
6890 return Success(((CR_r == APFloat::cmpGreaterThan ||
6891 CR_r == APFloat::cmpLessThan ||
6892 CR_r == APFloat::cmpUnordered) ||
6893 (CR_i == APFloat::cmpGreaterThan ||
6894 CR_i == APFloat::cmpLessThan ||
6895 CR_i == APFloat::cmpUnordered)), E);
6898 if (E->getOpcode() == BO_EQ)
6899 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6900 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6902 assert(E->getOpcode() == BO_NE &&
6903 "Invalid compex comparison.");
6904 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6905 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6910 if (LHSTy->isRealFloatingType() &&
6911 RHSTy->isRealFloatingType()) {
6912 APFloat RHS(0.0), LHS(0.0);
6914 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6915 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6918 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6921 APFloat::cmpResult CR = LHS.compare(RHS);
6923 switch (E->getOpcode()) {
6925 llvm_unreachable("Invalid binary operator!");
6927 return Success(CR == APFloat::cmpLessThan, E);
6929 return Success(CR == APFloat::cmpGreaterThan, E);
6931 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6933 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6936 return Success(CR == APFloat::cmpEqual, E);
6938 return Success(CR == APFloat::cmpGreaterThan
6939 || CR == APFloat::cmpLessThan
6940 || CR == APFloat::cmpUnordered, E);
6944 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6945 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6946 LValue LHSValue, RHSValue;
6948 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6949 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6952 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6955 // Reject differing bases from the normal codepath; we special-case
6956 // comparisons to null.
6957 if (!HasSameBase(LHSValue, RHSValue)) {
6958 if (E->getOpcode() == BO_Sub) {
6959 // Handle &&A - &&B.
6960 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6962 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6963 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6964 if (!LHSExpr || !RHSExpr)
6966 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6967 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6968 if (!LHSAddrExpr || !RHSAddrExpr)
6970 // Make sure both labels come from the same function.
6971 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6972 RHSAddrExpr->getLabel()->getDeclContext())
6974 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6977 // Inequalities and subtractions between unrelated pointers have
6978 // unspecified or undefined behavior.
6979 if (!E->isEqualityOp())
6981 // A constant address may compare equal to the address of a symbol.
6982 // The one exception is that address of an object cannot compare equal
6983 // to a null pointer constant.
6984 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6985 (!RHSValue.Base && !RHSValue.Offset.isZero()))
6987 // It's implementation-defined whether distinct literals will have
6988 // distinct addresses. In clang, the result of such a comparison is
6989 // unspecified, so it is not a constant expression. However, we do know
6990 // that the address of a literal will be non-null.
6991 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6992 LHSValue.Base && RHSValue.Base)
6994 // We can't tell whether weak symbols will end up pointing to the same
6996 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6998 // We can't compare the address of the start of one object with the
6999 // past-the-end address of another object, per C++ DR1652.
7000 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7001 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7002 (RHSValue.Base && RHSValue.Offset.isZero() &&
7003 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7005 // We can't tell whether an object is at the same address as another
7006 // zero sized object.
7007 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7008 (LHSValue.Base && isZeroSized(RHSValue)))
7010 // Pointers with different bases cannot represent the same object.
7011 // (Note that clang defaults to -fmerge-all-constants, which can
7012 // lead to inconsistent results for comparisons involving the address
7013 // of a constant; this generally doesn't matter in practice.)
7014 return Success(E->getOpcode() == BO_NE, E);
7017 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7018 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7020 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7021 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7023 if (E->getOpcode() == BO_Sub) {
7024 // C++11 [expr.add]p6:
7025 // Unless both pointers point to elements of the same array object, or
7026 // one past the last element of the array object, the behavior is
7028 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7029 !AreElementsOfSameArray(getType(LHSValue.Base),
7030 LHSDesignator, RHSDesignator))
7031 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7033 QualType Type = E->getLHS()->getType();
7034 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7036 CharUnits ElementSize;
7037 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7040 // As an extension, a type may have zero size (empty struct or union in
7041 // C, array of zero length). Pointer subtraction in such cases has
7042 // undefined behavior, so is not constant.
7043 if (ElementSize.isZero()) {
7044 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7049 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7050 // and produce incorrect results when it overflows. Such behavior
7051 // appears to be non-conforming, but is common, so perhaps we should
7052 // assume the standard intended for such cases to be undefined behavior
7053 // and check for them.
7055 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7056 // overflow in the final conversion to ptrdiff_t.
7058 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7060 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7062 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7063 APSInt TrueResult = (LHS - RHS) / ElemSize;
7064 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7066 if (Result.extend(65) != TrueResult)
7067 HandleOverflow(Info, E, TrueResult, E->getType());
7068 return Success(Result, E);
7071 // C++11 [expr.rel]p3:
7072 // Pointers to void (after pointer conversions) can be compared, with a
7073 // result defined as follows: If both pointers represent the same
7074 // address or are both the null pointer value, the result is true if the
7075 // operator is <= or >= and false otherwise; otherwise the result is
7077 // We interpret this as applying to pointers to *cv* void.
7078 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7079 E->isRelationalOp())
7080 CCEDiag(E, diag::note_constexpr_void_comparison);
7082 // C++11 [expr.rel]p2:
7083 // - If two pointers point to non-static data members of the same object,
7084 // or to subobjects or array elements fo such members, recursively, the
7085 // pointer to the later declared member compares greater provided the
7086 // two members have the same access control and provided their class is
7089 // - Otherwise pointer comparisons are unspecified.
7090 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7091 E->isRelationalOp()) {
7094 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7095 RHSDesignator, WasArrayIndex);
7096 // At the point where the designators diverge, the comparison has a
7097 // specified value if:
7098 // - we are comparing array indices
7099 // - we are comparing fields of a union, or fields with the same access
7100 // Otherwise, the result is unspecified and thus the comparison is not a
7101 // constant expression.
7102 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7103 Mismatch < RHSDesignator.Entries.size()) {
7104 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7105 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7107 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7109 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7110 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7111 << RF->getParent() << RF;
7113 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7114 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7115 << LF->getParent() << LF;
7116 else if (!LF->getParent()->isUnion() &&
7117 LF->getAccess() != RF->getAccess())
7118 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7119 << LF << LF->getAccess() << RF << RF->getAccess()
7124 // The comparison here must be unsigned, and performed with the same
7125 // width as the pointer.
7126 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7127 uint64_t CompareLHS = LHSOffset.getQuantity();
7128 uint64_t CompareRHS = RHSOffset.getQuantity();
7129 assert(PtrSize <= 64 && "Unexpected pointer width");
7130 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7134 // If there is a base and this is a relational operator, we can only
7135 // compare pointers within the object in question; otherwise, the result
7136 // depends on where the object is located in memory.
7137 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7138 QualType BaseTy = getType(LHSValue.Base);
7139 if (BaseTy->isIncompleteType())
7141 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7142 uint64_t OffsetLimit = Size.getQuantity();
7143 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7147 switch (E->getOpcode()) {
7148 default: llvm_unreachable("missing comparison operator");
7149 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7150 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7151 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7152 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7153 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7154 case BO_NE: return Success(CompareLHS != CompareRHS, E);
7159 if (LHSTy->isMemberPointerType()) {
7160 assert(E->isEqualityOp() && "unexpected member pointer operation");
7161 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7163 MemberPtr LHSValue, RHSValue;
7165 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7166 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7169 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7172 // C++11 [expr.eq]p2:
7173 // If both operands are null, they compare equal. Otherwise if only one is
7174 // null, they compare unequal.
7175 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7176 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7177 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7180 // Otherwise if either is a pointer to a virtual member function, the
7181 // result is unspecified.
7182 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7183 if (MD->isVirtual())
7184 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7185 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7186 if (MD->isVirtual())
7187 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7189 // Otherwise they compare equal if and only if they would refer to the
7190 // same member of the same most derived object or the same subobject if
7191 // they were dereferenced with a hypothetical object of the associated
7193 bool Equal = LHSValue == RHSValue;
7194 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7197 if (LHSTy->isNullPtrType()) {
7198 assert(E->isComparisonOp() && "unexpected nullptr operation");
7199 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7200 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7201 // are compared, the result is true of the operator is <=, >= or ==, and
7203 BinaryOperator::Opcode Opcode = E->getOpcode();
7204 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7207 assert((!LHSTy->isIntegralOrEnumerationType() ||
7208 !RHSTy->isIntegralOrEnumerationType()) &&
7209 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7210 // We can't continue from here for non-integral types.
7211 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7214 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7215 /// a result as the expression's type.
7216 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7217 const UnaryExprOrTypeTraitExpr *E) {
7218 switch(E->getKind()) {
7219 case UETT_AlignOf: {
7220 if (E->isArgumentType())
7221 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7223 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7226 case UETT_VecStep: {
7227 QualType Ty = E->getTypeOfArgument();
7229 if (Ty->isVectorType()) {
7230 unsigned n = Ty->castAs<VectorType>()->getNumElements();
7232 // The vec_step built-in functions that take a 3-component
7233 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7237 return Success(n, E);
7239 return Success(1, E);
7243 QualType SrcTy = E->getTypeOfArgument();
7244 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7245 // the result is the size of the referenced type."
7246 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7247 SrcTy = Ref->getPointeeType();
7250 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7252 return Success(Sizeof, E);
7254 case UETT_OpenMPRequiredSimdAlign:
7255 assert(E->isArgumentType());
7257 Info.Ctx.toCharUnitsFromBits(
7258 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7263 llvm_unreachable("unknown expr/type trait");
7266 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7268 unsigned n = OOE->getNumComponents();
7271 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7272 for (unsigned i = 0; i != n; ++i) {
7273 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7274 switch (ON.getKind()) {
7275 case OffsetOfExpr::OffsetOfNode::Array: {
7276 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7278 if (!EvaluateInteger(Idx, IdxResult, Info))
7280 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7283 CurrentType = AT->getElementType();
7284 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7285 Result += IdxResult.getSExtValue() * ElementSize;
7289 case OffsetOfExpr::OffsetOfNode::Field: {
7290 FieldDecl *MemberDecl = ON.getField();
7291 const RecordType *RT = CurrentType->getAs<RecordType>();
7294 RecordDecl *RD = RT->getDecl();
7295 if (RD->isInvalidDecl()) return false;
7296 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7297 unsigned i = MemberDecl->getFieldIndex();
7298 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7299 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7300 CurrentType = MemberDecl->getType().getNonReferenceType();
7304 case OffsetOfExpr::OffsetOfNode::Identifier:
7305 llvm_unreachable("dependent __builtin_offsetof");
7307 case OffsetOfExpr::OffsetOfNode::Base: {
7308 CXXBaseSpecifier *BaseSpec = ON.getBase();
7309 if (BaseSpec->isVirtual())
7312 // Find the layout of the class whose base we are looking into.
7313 const RecordType *RT = CurrentType->getAs<RecordType>();
7316 RecordDecl *RD = RT->getDecl();
7317 if (RD->isInvalidDecl()) return false;
7318 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7320 // Find the base class itself.
7321 CurrentType = BaseSpec->getType();
7322 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7326 // Add the offset to the base.
7327 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7332 return Success(Result, OOE);
7335 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7336 switch (E->getOpcode()) {
7338 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7342 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7343 // If so, we could clear the diagnostic ID.
7344 return Visit(E->getSubExpr());
7346 // The result is just the value.
7347 return Visit(E->getSubExpr());
7349 if (!Visit(E->getSubExpr()))
7351 if (!Result.isInt()) return Error(E);
7352 const APSInt &Value = Result.getInt();
7353 if (Value.isSigned() && Value.isMinSignedValue())
7354 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7356 return Success(-Value, E);
7359 if (!Visit(E->getSubExpr()))
7361 if (!Result.isInt()) return Error(E);
7362 return Success(~Result.getInt(), E);
7366 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7368 return Success(!bres, E);
7373 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7374 /// result type is integer.
7375 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7376 const Expr *SubExpr = E->getSubExpr();
7377 QualType DestType = E->getType();
7378 QualType SrcType = SubExpr->getType();
7380 switch (E->getCastKind()) {
7381 case CK_BaseToDerived:
7382 case CK_DerivedToBase:
7383 case CK_UncheckedDerivedToBase:
7386 case CK_ArrayToPointerDecay:
7387 case CK_FunctionToPointerDecay:
7388 case CK_NullToPointer:
7389 case CK_NullToMemberPointer:
7390 case CK_BaseToDerivedMemberPointer:
7391 case CK_DerivedToBaseMemberPointer:
7392 case CK_ReinterpretMemberPointer:
7393 case CK_ConstructorConversion:
7394 case CK_IntegralToPointer:
7396 case CK_VectorSplat:
7397 case CK_IntegralToFloating:
7398 case CK_FloatingCast:
7399 case CK_CPointerToObjCPointerCast:
7400 case CK_BlockPointerToObjCPointerCast:
7401 case CK_AnyPointerToBlockPointerCast:
7402 case CK_ObjCObjectLValueCast:
7403 case CK_FloatingRealToComplex:
7404 case CK_FloatingComplexToReal:
7405 case CK_FloatingComplexCast:
7406 case CK_FloatingComplexToIntegralComplex:
7407 case CK_IntegralRealToComplex:
7408 case CK_IntegralComplexCast:
7409 case CK_IntegralComplexToFloatingComplex:
7410 case CK_BuiltinFnToFnPtr:
7411 case CK_ZeroToOCLEvent:
7412 case CK_NonAtomicToAtomic:
7413 case CK_AddressSpaceConversion:
7414 llvm_unreachable("invalid cast kind for integral value");
7418 case CK_LValueBitCast:
7419 case CK_ARCProduceObject:
7420 case CK_ARCConsumeObject:
7421 case CK_ARCReclaimReturnedObject:
7422 case CK_ARCExtendBlockObject:
7423 case CK_CopyAndAutoreleaseBlockObject:
7426 case CK_UserDefinedConversion:
7427 case CK_LValueToRValue:
7428 case CK_AtomicToNonAtomic:
7430 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7432 case CK_MemberPointerToBoolean:
7433 case CK_PointerToBoolean:
7434 case CK_IntegralToBoolean:
7435 case CK_FloatingToBoolean:
7436 case CK_FloatingComplexToBoolean:
7437 case CK_IntegralComplexToBoolean: {
7439 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7441 return Success(BoolResult, E);
7444 case CK_IntegralCast: {
7445 if (!Visit(SubExpr))
7448 if (!Result.isInt()) {
7449 // Allow casts of address-of-label differences if they are no-ops
7450 // or narrowing. (The narrowing case isn't actually guaranteed to
7451 // be constant-evaluatable except in some narrow cases which are hard
7452 // to detect here. We let it through on the assumption the user knows
7453 // what they are doing.)
7454 if (Result.isAddrLabelDiff())
7455 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7456 // Only allow casts of lvalues if they are lossless.
7457 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7460 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7461 Result.getInt()), E);
7464 case CK_PointerToIntegral: {
7465 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7468 if (!EvaluatePointer(SubExpr, LV, Info))
7471 if (LV.getLValueBase()) {
7472 // Only allow based lvalue casts if they are lossless.
7473 // FIXME: Allow a larger integer size than the pointer size, and allow
7474 // narrowing back down to pointer width in subsequent integral casts.
7475 // FIXME: Check integer type's active bits, not its type size.
7476 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7479 LV.Designator.setInvalid();
7480 LV.moveInto(Result);
7484 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7486 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7489 case CK_IntegralComplexToReal: {
7491 if (!EvaluateComplex(SubExpr, C, Info))
7493 return Success(C.getComplexIntReal(), E);
7496 case CK_FloatingToIntegral: {
7498 if (!EvaluateFloat(SubExpr, F, Info))
7502 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7504 return Success(Value, E);
7508 llvm_unreachable("unknown cast resulting in integral value");
7511 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7512 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7514 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7516 if (!LV.isComplexInt())
7518 return Success(LV.getComplexIntReal(), E);
7521 return Visit(E->getSubExpr());
7524 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7525 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7527 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7529 if (!LV.isComplexInt())
7531 return Success(LV.getComplexIntImag(), E);
7534 VisitIgnoredValue(E->getSubExpr());
7535 return Success(0, E);
7538 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7539 return Success(E->getPackLength(), E);
7542 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7543 return Success(E->getValue(), E);
7546 //===----------------------------------------------------------------------===//
7548 //===----------------------------------------------------------------------===//
7551 class FloatExprEvaluator
7552 : public ExprEvaluatorBase<FloatExprEvaluator> {
7555 FloatExprEvaluator(EvalInfo &info, APFloat &result)
7556 : ExprEvaluatorBaseTy(info), Result(result) {}
7558 bool Success(const APValue &V, const Expr *e) {
7559 Result = V.getFloat();
7563 bool ZeroInitialization(const Expr *E) {
7564 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7568 bool VisitCallExpr(const CallExpr *E);
7570 bool VisitUnaryOperator(const UnaryOperator *E);
7571 bool VisitBinaryOperator(const BinaryOperator *E);
7572 bool VisitFloatingLiteral(const FloatingLiteral *E);
7573 bool VisitCastExpr(const CastExpr *E);
7575 bool VisitUnaryReal(const UnaryOperator *E);
7576 bool VisitUnaryImag(const UnaryOperator *E);
7578 // FIXME: Missing: array subscript of vector, member of vector
7580 } // end anonymous namespace
7582 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7583 assert(E->isRValue() && E->getType()->isRealFloatingType());
7584 return FloatExprEvaluator(Info, Result).Visit(E);
7587 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7591 llvm::APFloat &Result) {
7592 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7593 if (!S) return false;
7595 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7599 // Treat empty strings as if they were zero.
7600 if (S->getString().empty())
7601 fill = llvm::APInt(32, 0);
7602 else if (S->getString().getAsInteger(0, fill))
7605 if (Context.getTargetInfo().isNan2008()) {
7607 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7609 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7611 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7612 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7613 // a different encoding to what became a standard in 2008, and for pre-
7614 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7615 // sNaN. This is now known as "legacy NaN" encoding.
7617 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7619 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7625 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7626 switch (E->getBuiltinCallee()) {
7628 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7630 case Builtin::BI__builtin_huge_val:
7631 case Builtin::BI__builtin_huge_valf:
7632 case Builtin::BI__builtin_huge_vall:
7633 case Builtin::BI__builtin_inf:
7634 case Builtin::BI__builtin_inff:
7635 case Builtin::BI__builtin_infl: {
7636 const llvm::fltSemantics &Sem =
7637 Info.Ctx.getFloatTypeSemantics(E->getType());
7638 Result = llvm::APFloat::getInf(Sem);
7642 case Builtin::BI__builtin_nans:
7643 case Builtin::BI__builtin_nansf:
7644 case Builtin::BI__builtin_nansl:
7645 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7650 case Builtin::BI__builtin_nan:
7651 case Builtin::BI__builtin_nanf:
7652 case Builtin::BI__builtin_nanl:
7653 // If this is __builtin_nan() turn this into a nan, otherwise we
7654 // can't constant fold it.
7655 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7660 case Builtin::BI__builtin_fabs:
7661 case Builtin::BI__builtin_fabsf:
7662 case Builtin::BI__builtin_fabsl:
7663 if (!EvaluateFloat(E->getArg(0), Result, Info))
7666 if (Result.isNegative())
7667 Result.changeSign();
7670 // FIXME: Builtin::BI__builtin_powi
7671 // FIXME: Builtin::BI__builtin_powif
7672 // FIXME: Builtin::BI__builtin_powil
7674 case Builtin::BI__builtin_copysign:
7675 case Builtin::BI__builtin_copysignf:
7676 case Builtin::BI__builtin_copysignl: {
7678 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7679 !EvaluateFloat(E->getArg(1), RHS, Info))
7681 Result.copySign(RHS);
7687 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7688 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7690 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7692 Result = CV.FloatReal;
7696 return Visit(E->getSubExpr());
7699 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7700 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7702 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7704 Result = CV.FloatImag;
7708 VisitIgnoredValue(E->getSubExpr());
7709 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7710 Result = llvm::APFloat::getZero(Sem);
7714 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7715 switch (E->getOpcode()) {
7716 default: return Error(E);
7718 return EvaluateFloat(E->getSubExpr(), Result, Info);
7720 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7722 Result.changeSign();
7727 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7728 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7729 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7732 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7733 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7735 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7736 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7739 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7740 Result = E->getValue();
7744 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7745 const Expr* SubExpr = E->getSubExpr();
7747 switch (E->getCastKind()) {
7749 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7751 case CK_IntegralToFloating: {
7753 return EvaluateInteger(SubExpr, IntResult, Info) &&
7754 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7755 E->getType(), Result);
7758 case CK_FloatingCast: {
7759 if (!Visit(SubExpr))
7761 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7765 case CK_FloatingComplexToReal: {
7767 if (!EvaluateComplex(SubExpr, V, Info))
7769 Result = V.getComplexFloatReal();
7775 //===----------------------------------------------------------------------===//
7776 // Complex Evaluation (for float and integer)
7777 //===----------------------------------------------------------------------===//
7780 class ComplexExprEvaluator
7781 : public ExprEvaluatorBase<ComplexExprEvaluator> {
7782 ComplexValue &Result;
7785 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7786 : ExprEvaluatorBaseTy(info), Result(Result) {}
7788 bool Success(const APValue &V, const Expr *e) {
7793 bool ZeroInitialization(const Expr *E);
7795 //===--------------------------------------------------------------------===//
7797 //===--------------------------------------------------------------------===//
7799 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7800 bool VisitCastExpr(const CastExpr *E);
7801 bool VisitBinaryOperator(const BinaryOperator *E);
7802 bool VisitUnaryOperator(const UnaryOperator *E);
7803 bool VisitInitListExpr(const InitListExpr *E);
7805 } // end anonymous namespace
7807 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7809 assert(E->isRValue() && E->getType()->isAnyComplexType());
7810 return ComplexExprEvaluator(Info, Result).Visit(E);
7813 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7814 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7815 if (ElemTy->isRealFloatingType()) {
7816 Result.makeComplexFloat();
7817 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7818 Result.FloatReal = Zero;
7819 Result.FloatImag = Zero;
7821 Result.makeComplexInt();
7822 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7823 Result.IntReal = Zero;
7824 Result.IntImag = Zero;
7829 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7830 const Expr* SubExpr = E->getSubExpr();
7832 if (SubExpr->getType()->isRealFloatingType()) {
7833 Result.makeComplexFloat();
7834 APFloat &Imag = Result.FloatImag;
7835 if (!EvaluateFloat(SubExpr, Imag, Info))
7838 Result.FloatReal = APFloat(Imag.getSemantics());
7841 assert(SubExpr->getType()->isIntegerType() &&
7842 "Unexpected imaginary literal.");
7844 Result.makeComplexInt();
7845 APSInt &Imag = Result.IntImag;
7846 if (!EvaluateInteger(SubExpr, Imag, Info))
7849 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7854 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7856 switch (E->getCastKind()) {
7858 case CK_BaseToDerived:
7859 case CK_DerivedToBase:
7860 case CK_UncheckedDerivedToBase:
7863 case CK_ArrayToPointerDecay:
7864 case CK_FunctionToPointerDecay:
7865 case CK_NullToPointer:
7866 case CK_NullToMemberPointer:
7867 case CK_BaseToDerivedMemberPointer:
7868 case CK_DerivedToBaseMemberPointer:
7869 case CK_MemberPointerToBoolean:
7870 case CK_ReinterpretMemberPointer:
7871 case CK_ConstructorConversion:
7872 case CK_IntegralToPointer:
7873 case CK_PointerToIntegral:
7874 case CK_PointerToBoolean:
7876 case CK_VectorSplat:
7877 case CK_IntegralCast:
7878 case CK_IntegralToBoolean:
7879 case CK_IntegralToFloating:
7880 case CK_FloatingToIntegral:
7881 case CK_FloatingToBoolean:
7882 case CK_FloatingCast:
7883 case CK_CPointerToObjCPointerCast:
7884 case CK_BlockPointerToObjCPointerCast:
7885 case CK_AnyPointerToBlockPointerCast:
7886 case CK_ObjCObjectLValueCast:
7887 case CK_FloatingComplexToReal:
7888 case CK_FloatingComplexToBoolean:
7889 case CK_IntegralComplexToReal:
7890 case CK_IntegralComplexToBoolean:
7891 case CK_ARCProduceObject:
7892 case CK_ARCConsumeObject:
7893 case CK_ARCReclaimReturnedObject:
7894 case CK_ARCExtendBlockObject:
7895 case CK_CopyAndAutoreleaseBlockObject:
7896 case CK_BuiltinFnToFnPtr:
7897 case CK_ZeroToOCLEvent:
7898 case CK_NonAtomicToAtomic:
7899 case CK_AddressSpaceConversion:
7900 llvm_unreachable("invalid cast kind for complex value");
7902 case CK_LValueToRValue:
7903 case CK_AtomicToNonAtomic:
7905 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7908 case CK_LValueBitCast:
7909 case CK_UserDefinedConversion:
7912 case CK_FloatingRealToComplex: {
7913 APFloat &Real = Result.FloatReal;
7914 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7917 Result.makeComplexFloat();
7918 Result.FloatImag = APFloat(Real.getSemantics());
7922 case CK_FloatingComplexCast: {
7923 if (!Visit(E->getSubExpr()))
7926 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7928 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7930 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7931 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7934 case CK_FloatingComplexToIntegralComplex: {
7935 if (!Visit(E->getSubExpr()))
7938 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7940 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7941 Result.makeComplexInt();
7942 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7943 To, Result.IntReal) &&
7944 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7945 To, Result.IntImag);
7948 case CK_IntegralRealToComplex: {
7949 APSInt &Real = Result.IntReal;
7950 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7953 Result.makeComplexInt();
7954 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7958 case CK_IntegralComplexCast: {
7959 if (!Visit(E->getSubExpr()))
7962 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7964 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7966 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7967 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7971 case CK_IntegralComplexToFloatingComplex: {
7972 if (!Visit(E->getSubExpr()))
7975 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
7977 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
7978 Result.makeComplexFloat();
7979 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7980 To, Result.FloatReal) &&
7981 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7982 To, Result.FloatImag);
7986 llvm_unreachable("unknown cast resulting in complex value");
7989 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7990 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7991 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7993 // Track whether the LHS or RHS is real at the type system level. When this is
7994 // the case we can simplify our evaluation strategy.
7995 bool LHSReal = false, RHSReal = false;
7998 if (E->getLHS()->getType()->isRealFloatingType()) {
8000 APFloat &Real = Result.FloatReal;
8001 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8003 Result.makeComplexFloat();
8004 Result.FloatImag = APFloat(Real.getSemantics());
8007 LHSOK = Visit(E->getLHS());
8009 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
8013 if (E->getRHS()->getType()->isRealFloatingType()) {
8015 APFloat &Real = RHS.FloatReal;
8016 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8018 RHS.makeComplexFloat();
8019 RHS.FloatImag = APFloat(Real.getSemantics());
8020 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8023 assert(!(LHSReal && RHSReal) &&
8024 "Cannot have both operands of a complex operation be real.");
8025 switch (E->getOpcode()) {
8026 default: return Error(E);
8028 if (Result.isComplexFloat()) {
8029 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8030 APFloat::rmNearestTiesToEven);
8032 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8034 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8035 APFloat::rmNearestTiesToEven);
8037 Result.getComplexIntReal() += RHS.getComplexIntReal();
8038 Result.getComplexIntImag() += RHS.getComplexIntImag();
8042 if (Result.isComplexFloat()) {
8043 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8044 APFloat::rmNearestTiesToEven);
8046 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8047 Result.getComplexFloatImag().changeSign();
8048 } else if (!RHSReal) {
8049 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8050 APFloat::rmNearestTiesToEven);
8053 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8054 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8058 if (Result.isComplexFloat()) {
8059 // This is an implementation of complex multiplication according to the
8060 // constraints laid out in C11 Annex G. The implemantion uses the
8061 // following naming scheme:
8062 // (a + ib) * (c + id)
8063 ComplexValue LHS = Result;
8064 APFloat &A = LHS.getComplexFloatReal();
8065 APFloat &B = LHS.getComplexFloatImag();
8066 APFloat &C = RHS.getComplexFloatReal();
8067 APFloat &D = RHS.getComplexFloatImag();
8068 APFloat &ResR = Result.getComplexFloatReal();
8069 APFloat &ResI = Result.getComplexFloatImag();
8071 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8074 } else if (RHSReal) {
8078 // In the fully general case, we need to handle NaNs and infinities
8086 if (ResR.isNaN() && ResI.isNaN()) {
8087 bool Recalc = false;
8088 if (A.isInfinity() || B.isInfinity()) {
8089 A = APFloat::copySign(
8090 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8091 B = APFloat::copySign(
8092 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8094 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8096 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8099 if (C.isInfinity() || D.isInfinity()) {
8100 C = APFloat::copySign(
8101 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8102 D = APFloat::copySign(
8103 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8105 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8107 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8110 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8111 AD.isInfinity() || BC.isInfinity())) {
8113 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8115 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8117 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8119 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8123 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8124 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8129 ComplexValue LHS = Result;
8130 Result.getComplexIntReal() =
8131 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8132 LHS.getComplexIntImag() * RHS.getComplexIntImag());
8133 Result.getComplexIntImag() =
8134 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8135 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8139 if (Result.isComplexFloat()) {
8140 // This is an implementation of complex division according to the
8141 // constraints laid out in C11 Annex G. The implemantion uses the
8142 // following naming scheme:
8143 // (a + ib) / (c + id)
8144 ComplexValue LHS = Result;
8145 APFloat &A = LHS.getComplexFloatReal();
8146 APFloat &B = LHS.getComplexFloatImag();
8147 APFloat &C = RHS.getComplexFloatReal();
8148 APFloat &D = RHS.getComplexFloatImag();
8149 APFloat &ResR = Result.getComplexFloatReal();
8150 APFloat &ResI = Result.getComplexFloatImag();
8156 // No real optimizations we can do here, stub out with zero.
8157 B = APFloat::getZero(A.getSemantics());
8160 APFloat MaxCD = maxnum(abs(C), abs(D));
8161 if (MaxCD.isFinite()) {
8162 DenomLogB = ilogb(MaxCD);
8163 C = scalbn(C, -DenomLogB);
8164 D = scalbn(D, -DenomLogB);
8166 APFloat Denom = C * C + D * D;
8167 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8168 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8169 if (ResR.isNaN() && ResI.isNaN()) {
8170 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8171 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8172 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8173 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8175 A = APFloat::copySign(
8176 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8177 B = APFloat::copySign(
8178 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8179 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8180 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8181 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8182 C = APFloat::copySign(
8183 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8184 D = APFloat::copySign(
8185 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8186 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8187 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8192 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8193 return Error(E, diag::note_expr_divide_by_zero);
8195 ComplexValue LHS = Result;
8196 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8197 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8198 Result.getComplexIntReal() =
8199 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8200 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8201 Result.getComplexIntImag() =
8202 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8203 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8211 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8212 // Get the operand value into 'Result'.
8213 if (!Visit(E->getSubExpr()))
8216 switch (E->getOpcode()) {
8222 // The result is always just the subexpr.
8225 if (Result.isComplexFloat()) {
8226 Result.getComplexFloatReal().changeSign();
8227 Result.getComplexFloatImag().changeSign();
8230 Result.getComplexIntReal() = -Result.getComplexIntReal();
8231 Result.getComplexIntImag() = -Result.getComplexIntImag();
8235 if (Result.isComplexFloat())
8236 Result.getComplexFloatImag().changeSign();
8238 Result.getComplexIntImag() = -Result.getComplexIntImag();
8243 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8244 if (E->getNumInits() == 2) {
8245 if (E->getType()->isComplexType()) {
8246 Result.makeComplexFloat();
8247 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8249 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8252 Result.makeComplexInt();
8253 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8255 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8260 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8263 //===----------------------------------------------------------------------===//
8264 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8265 // implicit conversion.
8266 //===----------------------------------------------------------------------===//
8269 class AtomicExprEvaluator :
8270 public ExprEvaluatorBase<AtomicExprEvaluator> {
8273 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8274 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8276 bool Success(const APValue &V, const Expr *E) {
8281 bool ZeroInitialization(const Expr *E) {
8282 ImplicitValueInitExpr VIE(
8283 E->getType()->castAs<AtomicType>()->getValueType());
8284 return Evaluate(Result, Info, &VIE);
8287 bool VisitCastExpr(const CastExpr *E) {
8288 switch (E->getCastKind()) {
8290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8291 case CK_NonAtomicToAtomic:
8292 return Evaluate(Result, Info, E->getSubExpr());
8296 } // end anonymous namespace
8298 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8299 assert(E->isRValue() && E->getType()->isAtomicType());
8300 return AtomicExprEvaluator(Info, Result).Visit(E);
8303 //===----------------------------------------------------------------------===//
8304 // Void expression evaluation, primarily for a cast to void on the LHS of a
8306 //===----------------------------------------------------------------------===//
8309 class VoidExprEvaluator
8310 : public ExprEvaluatorBase<VoidExprEvaluator> {
8312 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8314 bool Success(const APValue &V, const Expr *e) { return true; }
8316 bool VisitCastExpr(const CastExpr *E) {
8317 switch (E->getCastKind()) {
8319 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8321 VisitIgnoredValue(E->getSubExpr());
8326 bool VisitCallExpr(const CallExpr *E) {
8327 switch (E->getBuiltinCallee()) {
8329 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8330 case Builtin::BI__assume:
8331 case Builtin::BI__builtin_assume:
8332 // The argument is not evaluated!
8337 } // end anonymous namespace
8339 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8340 assert(E->isRValue() && E->getType()->isVoidType());
8341 return VoidExprEvaluator(Info).Visit(E);
8344 //===----------------------------------------------------------------------===//
8345 // Top level Expr::EvaluateAsRValue method.
8346 //===----------------------------------------------------------------------===//
8348 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
8349 // In C, function designators are not lvalues, but we evaluate them as if they
8351 QualType T = E->getType();
8352 if (E->isGLValue() || T->isFunctionType()) {
8354 if (!EvaluateLValue(E, LV, Info))
8356 LV.moveInto(Result);
8357 } else if (T->isVectorType()) {
8358 if (!EvaluateVector(E, Result, Info))
8360 } else if (T->isIntegralOrEnumerationType()) {
8361 if (!IntExprEvaluator(Info, Result).Visit(E))
8363 } else if (T->hasPointerRepresentation()) {
8365 if (!EvaluatePointer(E, LV, Info))
8367 LV.moveInto(Result);
8368 } else if (T->isRealFloatingType()) {
8369 llvm::APFloat F(0.0);
8370 if (!EvaluateFloat(E, F, Info))
8372 Result = APValue(F);
8373 } else if (T->isAnyComplexType()) {
8375 if (!EvaluateComplex(E, C, Info))
8378 } else if (T->isMemberPointerType()) {
8380 if (!EvaluateMemberPointer(E, P, Info))
8384 } else if (T->isArrayType()) {
8386 LV.set(E, Info.CurrentCall->Index);
8387 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8388 if (!EvaluateArray(E, LV, Value, Info))
8391 } else if (T->isRecordType()) {
8393 LV.set(E, Info.CurrentCall->Index);
8394 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8395 if (!EvaluateRecord(E, LV, Value, Info))
8398 } else if (T->isVoidType()) {
8399 if (!Info.getLangOpts().CPlusPlus11)
8400 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
8402 if (!EvaluateVoid(E, Info))
8404 } else if (T->isAtomicType()) {
8405 if (!EvaluateAtomic(E, Result, Info))
8407 } else if (Info.getLangOpts().CPlusPlus11) {
8408 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
8411 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
8418 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8419 /// cases, the in-place evaluation is essential, since later initializers for
8420 /// an object can indirectly refer to subobjects which were initialized earlier.
8421 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
8422 const Expr *E, bool AllowNonLiteralTypes) {
8423 assert(!E->isValueDependent());
8425 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
8428 if (E->isRValue()) {
8429 // Evaluate arrays and record types in-place, so that later initializers can
8430 // refer to earlier-initialized members of the object.
8431 if (E->getType()->isArrayType())
8432 return EvaluateArray(E, This, Result, Info);
8433 else if (E->getType()->isRecordType())
8434 return EvaluateRecord(E, This, Result, Info);
8437 // For any other type, in-place evaluation is unimportant.
8438 return Evaluate(Result, Info, E);
8441 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8442 /// lvalue-to-rvalue cast if it is an lvalue.
8443 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8444 if (E->getType().isNull())
8447 if (!CheckLiteralType(Info, E))
8450 if (!::Evaluate(Result, Info, E))
8453 if (E->isGLValue()) {
8455 LV.setFrom(Info.Ctx, Result);
8456 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8460 // Check this core constant expression is a constant expression.
8461 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8464 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8465 const ASTContext &Ctx, bool &IsConst) {
8466 // Fast-path evaluations of integer literals, since we sometimes see files
8467 // containing vast quantities of these.
8468 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8469 Result.Val = APValue(APSInt(L->getValue(),
8470 L->getType()->isUnsignedIntegerType()));
8475 // This case should be rare, but we need to check it before we check on
8477 if (Exp->getType().isNull()) {
8482 // FIXME: Evaluating values of large array and record types can cause
8483 // performance problems. Only do so in C++11 for now.
8484 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8485 Exp->getType()->isRecordType()) &&
8486 !Ctx.getLangOpts().CPlusPlus11) {
8494 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8495 /// any crazy technique (that has nothing to do with language standards) that
8496 /// we want to. If this function returns true, it returns the folded constant
8497 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8498 /// will be applied to the result.
8499 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8501 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8504 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8505 return ::EvaluateAsRValue(Info, this, Result.Val);
8508 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8509 const ASTContext &Ctx) const {
8511 return EvaluateAsRValue(Scratch, Ctx) &&
8512 HandleConversionToBool(Scratch.Val, Result);
8515 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8516 SideEffectsKind AllowSideEffects) const {
8517 if (!getType()->isIntegralOrEnumerationType())
8520 EvalResult ExprResult;
8521 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8522 (!AllowSideEffects && ExprResult.HasSideEffects))
8525 Result = ExprResult.Val.getInt();
8529 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8530 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8533 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8534 !CheckLValueConstantExpression(Info, getExprLoc(),
8535 Ctx.getLValueReferenceType(getType()), LV))
8538 LV.moveInto(Result.Val);
8542 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8544 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8545 // FIXME: Evaluating initializers for large array and record types can cause
8546 // performance problems. Only do so in C++11 for now.
8547 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8548 !Ctx.getLangOpts().CPlusPlus11)
8551 Expr::EvalStatus EStatus;
8552 EStatus.Diag = &Notes;
8554 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8555 InitInfo.setEvaluatingDecl(VD, Value);
8560 // C++11 [basic.start.init]p2:
8561 // Variables with static storage duration or thread storage duration shall be
8562 // zero-initialized before any other initialization takes place.
8563 // This behavior is not present in C.
8564 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8565 !VD->getType()->isReferenceType()) {
8566 ImplicitValueInitExpr VIE(VD->getType());
8567 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8568 /*AllowNonLiteralTypes=*/true))
8572 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8573 /*AllowNonLiteralTypes=*/true) ||
8574 EStatus.HasSideEffects)
8577 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8581 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8582 /// constant folded, but discard the result.
8583 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8585 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8588 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8589 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8590 EvalResult EvalResult;
8591 EvalResult.Diag = Diag;
8592 bool Result = EvaluateAsRValue(EvalResult, Ctx);
8594 assert(Result && "Could not evaluate expression");
8595 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8597 return EvalResult.Val.getInt();
8600 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8602 EvalResult EvalResult;
8603 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8604 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8605 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8609 bool Expr::EvalResult::isGlobalLValue() const {
8610 assert(Val.isLValue());
8611 return IsGlobalLValue(Val.getLValueBase());
8615 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8616 /// an integer constant expression.
8618 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8621 // CheckICE - This function does the fundamental ICE checking: the returned
8622 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8623 // and a (possibly null) SourceLocation indicating the location of the problem.
8625 // Note that to reduce code duplication, this helper does no evaluation
8626 // itself; the caller checks whether the expression is evaluatable, and
8627 // in the rare cases where CheckICE actually cares about the evaluated
8628 // value, it calls into Evalute.
8633 /// This expression is an ICE.
8635 /// This expression is not an ICE, but if it isn't evaluated, it's
8636 /// a legal subexpression for an ICE. This return value is used to handle
8637 /// the comma operator in C99 mode, and non-constant subexpressions.
8638 IK_ICEIfUnevaluated,
8639 /// This expression is not an ICE, and is not a legal subexpression for one.
8647 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8652 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8654 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8656 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8657 Expr::EvalResult EVResult;
8658 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8659 !EVResult.Val.isInt())
8660 return ICEDiag(IK_NotICE, E->getLocStart());
8665 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8666 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8667 if (!E->getType()->isIntegralOrEnumerationType())
8668 return ICEDiag(IK_NotICE, E->getLocStart());
8670 switch (E->getStmtClass()) {
8671 #define ABSTRACT_STMT(Node)
8672 #define STMT(Node, Base) case Expr::Node##Class:
8673 #define EXPR(Node, Base)
8674 #include "clang/AST/StmtNodes.inc"
8675 case Expr::PredefinedExprClass:
8676 case Expr::FloatingLiteralClass:
8677 case Expr::ImaginaryLiteralClass:
8678 case Expr::StringLiteralClass:
8679 case Expr::ArraySubscriptExprClass:
8680 case Expr::MemberExprClass:
8681 case Expr::CompoundAssignOperatorClass:
8682 case Expr::CompoundLiteralExprClass:
8683 case Expr::ExtVectorElementExprClass:
8684 case Expr::DesignatedInitExprClass:
8685 case Expr::NoInitExprClass:
8686 case Expr::DesignatedInitUpdateExprClass:
8687 case Expr::ImplicitValueInitExprClass:
8688 case Expr::ParenListExprClass:
8689 case Expr::VAArgExprClass:
8690 case Expr::AddrLabelExprClass:
8691 case Expr::StmtExprClass:
8692 case Expr::CXXMemberCallExprClass:
8693 case Expr::CUDAKernelCallExprClass:
8694 case Expr::CXXDynamicCastExprClass:
8695 case Expr::CXXTypeidExprClass:
8696 case Expr::CXXUuidofExprClass:
8697 case Expr::MSPropertyRefExprClass:
8698 case Expr::CXXNullPtrLiteralExprClass:
8699 case Expr::UserDefinedLiteralClass:
8700 case Expr::CXXThisExprClass:
8701 case Expr::CXXThrowExprClass:
8702 case Expr::CXXNewExprClass:
8703 case Expr::CXXDeleteExprClass:
8704 case Expr::CXXPseudoDestructorExprClass:
8705 case Expr::UnresolvedLookupExprClass:
8706 case Expr::TypoExprClass:
8707 case Expr::DependentScopeDeclRefExprClass:
8708 case Expr::CXXConstructExprClass:
8709 case Expr::CXXStdInitializerListExprClass:
8710 case Expr::CXXBindTemporaryExprClass:
8711 case Expr::ExprWithCleanupsClass:
8712 case Expr::CXXTemporaryObjectExprClass:
8713 case Expr::CXXUnresolvedConstructExprClass:
8714 case Expr::CXXDependentScopeMemberExprClass:
8715 case Expr::UnresolvedMemberExprClass:
8716 case Expr::ObjCStringLiteralClass:
8717 case Expr::ObjCBoxedExprClass:
8718 case Expr::ObjCArrayLiteralClass:
8719 case Expr::ObjCDictionaryLiteralClass:
8720 case Expr::ObjCEncodeExprClass:
8721 case Expr::ObjCMessageExprClass:
8722 case Expr::ObjCSelectorExprClass:
8723 case Expr::ObjCProtocolExprClass:
8724 case Expr::ObjCIvarRefExprClass:
8725 case Expr::ObjCPropertyRefExprClass:
8726 case Expr::ObjCSubscriptRefExprClass:
8727 case Expr::ObjCIsaExprClass:
8728 case Expr::ShuffleVectorExprClass:
8729 case Expr::ConvertVectorExprClass:
8730 case Expr::BlockExprClass:
8731 case Expr::NoStmtClass:
8732 case Expr::OpaqueValueExprClass:
8733 case Expr::PackExpansionExprClass:
8734 case Expr::SubstNonTypeTemplateParmPackExprClass:
8735 case Expr::FunctionParmPackExprClass:
8736 case Expr::AsTypeExprClass:
8737 case Expr::ObjCIndirectCopyRestoreExprClass:
8738 case Expr::MaterializeTemporaryExprClass:
8739 case Expr::PseudoObjectExprClass:
8740 case Expr::AtomicExprClass:
8741 case Expr::LambdaExprClass:
8742 case Expr::CXXFoldExprClass:
8743 return ICEDiag(IK_NotICE, E->getLocStart());
8745 case Expr::InitListExprClass: {
8746 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8747 // form "T x = { a };" is equivalent to "T x = a;".
8748 // Unless we're initializing a reference, T is a scalar as it is known to be
8749 // of integral or enumeration type.
8751 if (cast<InitListExpr>(E)->getNumInits() == 1)
8752 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8753 return ICEDiag(IK_NotICE, E->getLocStart());
8756 case Expr::SizeOfPackExprClass:
8757 case Expr::GNUNullExprClass:
8758 // GCC considers the GNU __null value to be an integral constant expression.
8761 case Expr::SubstNonTypeTemplateParmExprClass:
8763 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8765 case Expr::ParenExprClass:
8766 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8767 case Expr::GenericSelectionExprClass:
8768 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8769 case Expr::IntegerLiteralClass:
8770 case Expr::CharacterLiteralClass:
8771 case Expr::ObjCBoolLiteralExprClass:
8772 case Expr::CXXBoolLiteralExprClass:
8773 case Expr::CXXScalarValueInitExprClass:
8774 case Expr::TypeTraitExprClass:
8775 case Expr::ArrayTypeTraitExprClass:
8776 case Expr::ExpressionTraitExprClass:
8777 case Expr::CXXNoexceptExprClass:
8779 case Expr::CallExprClass:
8780 case Expr::CXXOperatorCallExprClass: {
8781 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8782 // constant expressions, but they can never be ICEs because an ICE cannot
8783 // contain an operand of (pointer to) function type.
8784 const CallExpr *CE = cast<CallExpr>(E);
8785 if (CE->getBuiltinCallee())
8786 return CheckEvalInICE(E, Ctx);
8787 return ICEDiag(IK_NotICE, E->getLocStart());
8789 case Expr::DeclRefExprClass: {
8790 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8792 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8793 if (Ctx.getLangOpts().CPlusPlus &&
8794 D && IsConstNonVolatile(D->getType())) {
8795 // Parameter variables are never constants. Without this check,
8796 // getAnyInitializer() can find a default argument, which leads
8798 if (isa<ParmVarDecl>(D))
8799 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8802 // A variable of non-volatile const-qualified integral or enumeration
8803 // type initialized by an ICE can be used in ICEs.
8804 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8805 if (!Dcl->getType()->isIntegralOrEnumerationType())
8806 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8809 // Look for a declaration of this variable that has an initializer, and
8810 // check whether it is an ICE.
8811 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8814 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8817 return ICEDiag(IK_NotICE, E->getLocStart());
8819 case Expr::UnaryOperatorClass: {
8820 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8821 switch (Exp->getOpcode()) {
8828 // C99 6.6/3 allows increment and decrement within unevaluated
8829 // subexpressions of constant expressions, but they can never be ICEs
8830 // because an ICE cannot contain an lvalue operand.
8831 return ICEDiag(IK_NotICE, E->getLocStart());
8839 return CheckICE(Exp->getSubExpr(), Ctx);
8842 // OffsetOf falls through here.
8844 case Expr::OffsetOfExprClass: {
8845 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8846 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8847 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8848 // compliance: we should warn earlier for offsetof expressions with
8849 // array subscripts that aren't ICEs, and if the array subscripts
8850 // are ICEs, the value of the offsetof must be an integer constant.
8851 return CheckEvalInICE(E, Ctx);
8853 case Expr::UnaryExprOrTypeTraitExprClass: {
8854 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8855 if ((Exp->getKind() == UETT_SizeOf) &&
8856 Exp->getTypeOfArgument()->isVariableArrayType())
8857 return ICEDiag(IK_NotICE, E->getLocStart());
8860 case Expr::BinaryOperatorClass: {
8861 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8862 switch (Exp->getOpcode()) {
8876 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8877 // constant expressions, but they can never be ICEs because an ICE cannot
8878 // contain an lvalue operand.
8879 return ICEDiag(IK_NotICE, E->getLocStart());
8898 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8899 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8900 if (Exp->getOpcode() == BO_Div ||
8901 Exp->getOpcode() == BO_Rem) {
8902 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8903 // we don't evaluate one.
8904 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8905 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8907 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8908 if (REval.isSigned() && REval.isAllOnesValue()) {
8909 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8910 if (LEval.isMinSignedValue())
8911 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8915 if (Exp->getOpcode() == BO_Comma) {
8916 if (Ctx.getLangOpts().C99) {
8917 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8918 // if it isn't evaluated.
8919 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8920 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8922 // In both C89 and C++, commas in ICEs are illegal.
8923 return ICEDiag(IK_NotICE, E->getLocStart());
8926 return Worst(LHSResult, RHSResult);
8930 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8931 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8932 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8933 // Rare case where the RHS has a comma "side-effect"; we need
8934 // to actually check the condition to see whether the side
8935 // with the comma is evaluated.
8936 if ((Exp->getOpcode() == BO_LAnd) !=
8937 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8942 return Worst(LHSResult, RHSResult);
8946 case Expr::ImplicitCastExprClass:
8947 case Expr::CStyleCastExprClass:
8948 case Expr::CXXFunctionalCastExprClass:
8949 case Expr::CXXStaticCastExprClass:
8950 case Expr::CXXReinterpretCastExprClass:
8951 case Expr::CXXConstCastExprClass:
8952 case Expr::ObjCBridgedCastExprClass: {
8953 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8954 if (isa<ExplicitCastExpr>(E)) {
8955 if (const FloatingLiteral *FL
8956 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8957 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8958 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8959 APSInt IgnoredVal(DestWidth, !DestSigned);
8961 // If the value does not fit in the destination type, the behavior is
8962 // undefined, so we are not required to treat it as a constant
8964 if (FL->getValue().convertToInteger(IgnoredVal,
8965 llvm::APFloat::rmTowardZero,
8966 &Ignored) & APFloat::opInvalidOp)
8967 return ICEDiag(IK_NotICE, E->getLocStart());
8971 switch (cast<CastExpr>(E)->getCastKind()) {
8972 case CK_LValueToRValue:
8973 case CK_AtomicToNonAtomic:
8974 case CK_NonAtomicToAtomic:
8976 case CK_IntegralToBoolean:
8977 case CK_IntegralCast:
8978 return CheckICE(SubExpr, Ctx);
8980 return ICEDiag(IK_NotICE, E->getLocStart());
8983 case Expr::BinaryConditionalOperatorClass: {
8984 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8985 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8986 if (CommonResult.Kind == IK_NotICE) return CommonResult;
8987 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8988 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8989 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8990 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8991 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8994 case Expr::ConditionalOperatorClass: {
8995 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8996 // If the condition (ignoring parens) is a __builtin_constant_p call,
8997 // then only the true side is actually considered in an integer constant
8998 // expression, and it is fully evaluated. This is an important GNU
8999 // extension. See GCC PR38377 for discussion.
9000 if (const CallExpr *CallCE
9001 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
9002 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
9003 return CheckEvalInICE(E, Ctx);
9004 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
9005 if (CondResult.Kind == IK_NotICE)
9008 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9009 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9011 if (TrueResult.Kind == IK_NotICE)
9013 if (FalseResult.Kind == IK_NotICE)
9015 if (CondResult.Kind == IK_ICEIfUnevaluated)
9017 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
9019 // Rare case where the diagnostics depend on which side is evaluated
9020 // Note that if we get here, CondResult is 0, and at least one of
9021 // TrueResult and FalseResult is non-zero.
9022 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
9026 case Expr::CXXDefaultArgExprClass:
9027 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
9028 case Expr::CXXDefaultInitExprClass:
9029 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
9030 case Expr::ChooseExprClass: {
9031 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9035 llvm_unreachable("Invalid StmtClass!");
9038 /// Evaluate an expression as a C++11 integral constant expression.
9039 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
9041 llvm::APSInt *Value,
9042 SourceLocation *Loc) {
9043 if (!E->getType()->isIntegralOrEnumerationType()) {
9044 if (Loc) *Loc = E->getExprLoc();
9049 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9052 if (!Result.isInt()) {
9053 if (Loc) *Loc = E->getExprLoc();
9057 if (Value) *Value = Result.getInt();
9061 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9062 SourceLocation *Loc) const {
9063 if (Ctx.getLangOpts().CPlusPlus11)
9064 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9066 ICEDiag D = CheckICE(this, Ctx);
9067 if (D.Kind != IK_ICE) {
9068 if (Loc) *Loc = D.Loc;
9074 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9075 SourceLocation *Loc, bool isEvaluated) const {
9076 if (Ctx.getLangOpts().CPlusPlus11)
9077 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9079 if (!isIntegerConstantExpr(Ctx, Loc))
9081 if (!EvaluateAsInt(Value, Ctx))
9082 llvm_unreachable("ICE cannot be evaluated!");
9086 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
9087 return CheckICE(this, Ctx).Kind == IK_ICE;
9090 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
9091 SourceLocation *Loc) const {
9092 // We support this checking in C++98 mode in order to diagnose compatibility
9094 assert(Ctx.getLangOpts().CPlusPlus);
9096 // Build evaluation settings.
9097 Expr::EvalStatus Status;
9098 SmallVector<PartialDiagnosticAt, 8> Diags;
9099 Status.Diag = &Diags;
9100 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9103 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9105 if (!Diags.empty()) {
9106 IsConstExpr = false;
9107 if (Loc) *Loc = Diags[0].first;
9108 } else if (!IsConstExpr) {
9109 // FIXME: This shouldn't happen.
9110 if (Loc) *Loc = getExprLoc();
9116 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9117 const FunctionDecl *Callee,
9118 ArrayRef<const Expr*> Args) const {
9119 Expr::EvalStatus Status;
9120 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9122 ArgVector ArgValues(Args.size());
9123 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9125 if ((*I)->isValueDependent() ||
9126 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9127 // If evaluation fails, throw away the argument entirely.
9128 ArgValues[I - Args.begin()] = APValue();
9129 if (Info.EvalStatus.HasSideEffects)
9133 // Build fake call to Callee.
9134 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9136 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9139 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
9141 PartialDiagnosticAt> &Diags) {
9142 // FIXME: It would be useful to check constexpr function templates, but at the
9143 // moment the constant expression evaluator cannot cope with the non-rigorous
9144 // ASTs which we build for dependent expressions.
9145 if (FD->isDependentContext())
9148 Expr::EvalStatus Status;
9149 Status.Diag = &Diags;
9151 EvalInfo Info(FD->getASTContext(), Status,
9152 EvalInfo::EM_PotentialConstantExpression);
9154 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9155 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9157 // Fabricate an arbitrary expression on the stack and pretend that it
9158 // is a temporary being used as the 'this' pointer.
9160 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9161 This.set(&VIE, Info.CurrentCall->Index);
9163 ArrayRef<const Expr*> Args;
9165 SourceLocation Loc = FD->getLocation();
9168 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9169 // Evaluate the call as a constant initializer, to allow the construction
9170 // of objects of non-literal types.
9171 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9172 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
9174 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9175 Args, FD->getBody(), Info, Scratch);
9177 return Diags.empty();
9180 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9181 const FunctionDecl *FD,
9183 PartialDiagnosticAt> &Diags) {
9184 Expr::EvalStatus Status;
9185 Status.Diag = &Diags;
9187 EvalInfo Info(FD->getASTContext(), Status,
9188 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9190 // Fabricate a call stack frame to give the arguments a plausible cover story.
9191 ArrayRef<const Expr*> Args;
9192 ArgVector ArgValues(0);
9193 bool Success = EvaluateArgs(Args, ArgValues, Info);
9196 "Failed to set up arguments for potential constant evaluation");
9197 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9199 APValue ResultScratch;
9200 Evaluate(ResultScratch, Info, E);
9201 return Diags.empty();