1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr constant evaluator.
12 // Constant expression evaluation produces four main results:
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
19 // * An evaluated result, valid only if constant folding has not failed.
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
34 //===----------------------------------------------------------------------===//
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
55 static bool IsGlobalLValue(APValue::LValueBase B);
59 struct CallStackFrame;
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67 const Expr *Base = B.get<const Expr*>();
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 // Keep any cv-qualifiers from the reference if we generated a temporary
81 return Inner->getType();
84 return Base->getType();
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field or base class.
90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
106 /// Determine whether this LValue path entry for a base class names a virtual
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return getAsBaseOrMember(E).getInt();
112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type,
119 unsigned MostDerivedLength = 0;
121 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
122 if (Type->isArrayType()) {
123 const ConstantArrayType *CAT =
124 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
125 Type = CAT->getElementType();
126 ArraySize = CAT->getSize().getZExtValue();
127 MostDerivedLength = I + 1;
129 } else if (Type->isAnyComplexType()) {
130 const ComplexType *CT = Type->castAs<ComplexType>();
131 Type = CT->getElementType();
133 MostDerivedLength = I + 1;
135 } else if (const FieldDecl *FD = getAsField(Path[I])) {
136 Type = FD->getType();
138 MostDerivedLength = I + 1;
141 // Path[I] describes a base class.
146 return MostDerivedLength;
149 // The order of this enum is important for diagnostics.
150 enum CheckSubobjectKind {
151 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
152 CSK_This, CSK_Real, CSK_Imag
155 /// A path from a glvalue to a subobject of that glvalue.
156 struct SubobjectDesignator {
157 /// True if the subobject was named in a manner not supported by C++11. Such
158 /// lvalues can still be folded, but they are not core constant expressions
159 /// and we cannot perform lvalue-to-rvalue conversions on them.
160 unsigned Invalid : 1;
162 /// Is this a pointer one past the end of an object?
163 unsigned IsOnePastTheEnd : 1;
165 /// Indicator of whether the most-derived object is an array element.
166 unsigned MostDerivedIsArrayElement : 1;
168 /// The length of the path to the most-derived object of which this is a
170 unsigned MostDerivedPathLength : 29;
172 /// The size of the array of which the most-derived object is an element.
173 /// This will always be 0 if the most-derived object is not an array
174 /// element. 0 is not an indicator of whether or not the most-derived object
175 /// is an array, however, because 0-length arrays are allowed.
176 uint64_t MostDerivedArraySize;
178 /// The type of the most derived object referred to by this address.
179 QualType MostDerivedType;
181 typedef APValue::LValuePathEntry PathEntry;
183 /// The entries on the path from the glvalue to the designated subobject.
184 SmallVector<PathEntry, 8> Entries;
186 SubobjectDesignator() : Invalid(true) {}
188 explicit SubobjectDesignator(QualType T)
189 : Invalid(false), IsOnePastTheEnd(false),
190 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
191 MostDerivedArraySize(0), MostDerivedType(T) {}
193 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
194 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
195 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
196 MostDerivedArraySize(0) {
198 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
199 ArrayRef<PathEntry> VEntries = V.getLValuePath();
200 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
201 if (V.getLValueBase()) {
202 bool IsArray = false;
203 MostDerivedPathLength =
204 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
205 V.getLValuePath(), MostDerivedArraySize,
206 MostDerivedType, IsArray);
207 MostDerivedIsArrayElement = IsArray;
217 /// Determine whether this is a one-past-the-end pointer.
218 bool isOnePastTheEnd() const {
222 if (MostDerivedIsArrayElement &&
223 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
228 /// Check that this refers to a valid subobject.
229 bool isValidSubobject() const {
232 return !isOnePastTheEnd();
234 /// Check that this refers to a valid subobject, and if not, produce a
235 /// relevant diagnostic and set the designator as invalid.
236 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
238 /// Update this designator to refer to the first element within this array.
239 void addArrayUnchecked(const ConstantArrayType *CAT) {
241 Entry.ArrayIndex = 0;
242 Entries.push_back(Entry);
244 // This is a most-derived object.
245 MostDerivedType = CAT->getElementType();
246 MostDerivedIsArrayElement = true;
247 MostDerivedArraySize = CAT->getSize().getZExtValue();
248 MostDerivedPathLength = Entries.size();
250 /// Update this designator to refer to the given base or member of this
252 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
254 APValue::BaseOrMemberType Value(D, Virtual);
255 Entry.BaseOrMember = Value.getOpaqueValue();
256 Entries.push_back(Entry);
258 // If this isn't a base class, it's a new most-derived object.
259 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
260 MostDerivedType = FD->getType();
261 MostDerivedIsArrayElement = false;
262 MostDerivedArraySize = 0;
263 MostDerivedPathLength = Entries.size();
266 /// Update this designator to refer to the given complex component.
267 void addComplexUnchecked(QualType EltTy, bool Imag) {
269 Entry.ArrayIndex = Imag;
270 Entries.push_back(Entry);
272 // This is technically a most-derived object, though in practice this
273 // is unlikely to matter.
274 MostDerivedType = EltTy;
275 MostDerivedIsArrayElement = true;
276 MostDerivedArraySize = 2;
277 MostDerivedPathLength = Entries.size();
279 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
280 /// Add N to the address of this subobject.
281 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
283 if (MostDerivedPathLength == Entries.size() &&
284 MostDerivedIsArrayElement) {
285 Entries.back().ArrayIndex += N;
286 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
287 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
292 // [expr.add]p4: For the purposes of these operators, a pointer to a
293 // nonarray object behaves the same as a pointer to the first element of
294 // an array of length one with the type of the object as its element type.
295 if (IsOnePastTheEnd && N == (uint64_t)-1)
296 IsOnePastTheEnd = false;
297 else if (!IsOnePastTheEnd && N == 1)
298 IsOnePastTheEnd = true;
300 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
306 /// A stack frame in the constexpr call stack.
307 struct CallStackFrame {
310 /// Parent - The caller of this stack frame.
311 CallStackFrame *Caller;
313 /// CallLoc - The location of the call expression for this call.
314 SourceLocation CallLoc;
316 /// Callee - The function which was called.
317 const FunctionDecl *Callee;
319 /// Index - The call index of this call.
322 /// This - The binding for the this pointer in this call, if any.
325 /// Arguments - Parameter bindings for this function call, indexed by
326 /// parameters' function scope indices.
329 // Note that we intentionally use std::map here so that references to
330 // values are stable.
331 typedef std::map<const void*, APValue> MapTy;
332 typedef MapTy::const_iterator temp_iterator;
333 /// Temporaries - Temporary lvalues materialized within this stack frame.
336 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
337 const FunctionDecl *Callee, const LValue *This,
341 APValue *getTemporary(const void *Key) {
342 MapTy::iterator I = Temporaries.find(Key);
343 return I == Temporaries.end() ? nullptr : &I->second;
345 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
348 /// Temporarily override 'this'.
349 class ThisOverrideRAII {
351 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
352 : Frame(Frame), OldThis(Frame.This) {
354 Frame.This = NewThis;
356 ~ThisOverrideRAII() {
357 Frame.This = OldThis;
360 CallStackFrame &Frame;
361 const LValue *OldThis;
364 /// A partial diagnostic which we might know in advance that we are not going
366 class OptionalDiagnostic {
367 PartialDiagnostic *Diag;
370 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
374 OptionalDiagnostic &operator<<(const T &v) {
380 OptionalDiagnostic &operator<<(const APSInt &I) {
382 SmallVector<char, 32> Buffer;
384 *Diag << StringRef(Buffer.data(), Buffer.size());
389 OptionalDiagnostic &operator<<(const APFloat &F) {
391 // FIXME: Force the precision of the source value down so we don't
392 // print digits which are usually useless (we don't really care here if
393 // we truncate a digit by accident in edge cases). Ideally,
394 // APFloat::toString would automatically print the shortest
395 // representation which rounds to the correct value, but it's a bit
396 // tricky to implement.
398 llvm::APFloat::semanticsPrecision(F.getSemantics());
399 precision = (precision * 59 + 195) / 196;
400 SmallVector<char, 32> Buffer;
401 F.toString(Buffer, precision);
402 *Diag << StringRef(Buffer.data(), Buffer.size());
408 /// A cleanup, and a flag indicating whether it is lifetime-extended.
410 llvm::PointerIntPair<APValue*, 1, bool> Value;
413 Cleanup(APValue *Val, bool IsLifetimeExtended)
414 : Value(Val, IsLifetimeExtended) {}
416 bool isLifetimeExtended() const { return Value.getInt(); }
418 *Value.getPointer() = APValue();
422 /// EvalInfo - This is a private struct used by the evaluator to capture
423 /// information about a subexpression as it is folded. It retains information
424 /// about the AST context, but also maintains information about the folded
427 /// If an expression could be evaluated, it is still possible it is not a C
428 /// "integer constant expression" or constant expression. If not, this struct
429 /// captures information about how and why not.
431 /// One bit of information passed *into* the request for constant folding
432 /// indicates whether the subexpression is "evaluated" or not according to C
433 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
434 /// evaluate the expression regardless of what the RHS is, but C only allows
435 /// certain things in certain situations.
439 /// EvalStatus - Contains information about the evaluation.
440 Expr::EvalStatus &EvalStatus;
442 /// CurrentCall - The top of the constexpr call stack.
443 CallStackFrame *CurrentCall;
445 /// CallStackDepth - The number of calls in the call stack right now.
446 unsigned CallStackDepth;
448 /// NextCallIndex - The next call index to assign.
449 unsigned NextCallIndex;
451 /// StepsLeft - The remaining number of evaluation steps we're permitted
452 /// to perform. This is essentially a limit for the number of statements
453 /// we will evaluate.
456 /// BottomFrame - The frame in which evaluation started. This must be
457 /// initialized after CurrentCall and CallStackDepth.
458 CallStackFrame BottomFrame;
460 /// A stack of values whose lifetimes end at the end of some surrounding
461 /// evaluation frame.
462 llvm::SmallVector<Cleanup, 16> CleanupStack;
464 /// EvaluatingDecl - This is the declaration whose initializer is being
465 /// evaluated, if any.
466 APValue::LValueBase EvaluatingDecl;
468 /// EvaluatingDeclValue - This is the value being constructed for the
469 /// declaration whose initializer is being evaluated, if any.
470 APValue *EvaluatingDeclValue;
472 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
473 /// notes attached to it will also be stored, otherwise they will not be.
474 bool HasActiveDiagnostic;
476 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
477 /// fold (not just why it's not strictly a constant expression)?
478 bool HasFoldFailureDiagnostic;
480 /// \brief Whether or not we're currently speculatively evaluating.
481 bool IsSpeculativelyEvaluating;
483 enum EvaluationMode {
484 /// Evaluate as a constant expression. Stop if we find that the expression
485 /// is not a constant expression.
486 EM_ConstantExpression,
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.
492 EM_PotentialConstantExpression,
494 /// Fold the expression to a constant. Stop if we hit a side-effect that
498 /// Evaluate the expression looking for integer overflow and similar
499 /// issues. Don't worry about side-effects, and try to visit all
501 EM_EvaluateForOverflow,
503 /// Evaluate in any way we know how. Don't worry about side-effects that
504 /// can't be modeled.
505 EM_IgnoreSideEffects,
507 /// Evaluate as a constant expression. Stop if we find that the expression
508 /// is not a constant expression. Some expressions can be retried in the
509 /// optimizer if we don't constant fold them here, but in an unevaluated
510 /// context we try to fold them immediately since the optimizer never
511 /// gets a chance to look at it.
512 EM_ConstantExpressionUnevaluated,
514 /// Evaluate as a potential constant expression. Keep going if we hit a
515 /// construct that we can't evaluate yet (because we don't yet know the
516 /// value of something) but stop if we hit something that could never be
517 /// a constant expression. Some expressions can be retried in the
518 /// optimizer if we don't constant fold them here, but in an unevaluated
519 /// context we try to fold them immediately since the optimizer never
520 /// gets a chance to look at it.
521 EM_PotentialConstantExpressionUnevaluated,
523 /// Evaluate as a constant expression. Continue evaluating if we find a
524 /// MemberExpr with a base that can't be evaluated.
528 /// Are we checking whether the expression is a potential constant
530 bool checkingPotentialConstantExpression() const {
531 return EvalMode == EM_PotentialConstantExpression ||
532 EvalMode == EM_PotentialConstantExpressionUnevaluated;
535 /// Are we checking an expression for overflow?
536 // FIXME: We should check for any kind of undefined or suspicious behavior
537 // in such constructs, not just overflow.
538 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
540 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
541 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
542 CallStackDepth(0), NextCallIndex(1),
543 StepsLeft(getLangOpts().ConstexprStepLimit),
544 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
545 EvaluatingDecl((const ValueDecl *)nullptr),
546 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
547 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
550 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
551 EvaluatingDecl = Base;
552 EvaluatingDeclValue = &Value;
555 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
557 bool CheckCallLimit(SourceLocation Loc) {
558 // Don't perform any constexpr calls (other than the call we're checking)
559 // when checking a potential constant expression.
560 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
562 if (NextCallIndex == 0) {
563 // NextCallIndex has wrapped around.
564 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
567 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
569 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
570 << getLangOpts().ConstexprCallDepth;
574 CallStackFrame *getCallFrame(unsigned CallIndex) {
575 assert(CallIndex && "no call index in getCallFrame");
576 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
577 // be null in this loop.
578 CallStackFrame *Frame = CurrentCall;
579 while (Frame->Index > CallIndex)
580 Frame = Frame->Caller;
581 return (Frame->Index == CallIndex) ? Frame : nullptr;
584 bool nextStep(const Stmt *S) {
586 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
594 /// Add a diagnostic to the diagnostics list.
595 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
596 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
597 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
598 return EvalStatus.Diag->back().second;
601 /// Add notes containing a call stack to the current point of evaluation.
602 void addCallStack(unsigned Limit);
605 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
606 unsigned ExtraNotes, bool IsCCEDiag) {
608 if (EvalStatus.Diag) {
609 // If we have a prior diagnostic, it will be noting that the expression
610 // isn't a constant expression. This diagnostic is more important,
611 // unless we require this evaluation to produce a constant expression.
613 // FIXME: We might want to show both diagnostics to the user in
614 // EM_ConstantFold mode.
615 if (!EvalStatus.Diag->empty()) {
617 case EM_ConstantFold:
618 case EM_IgnoreSideEffects:
619 case EM_EvaluateForOverflow:
620 if (!HasFoldFailureDiagnostic)
622 // We've already failed to fold something. Keep that diagnostic.
623 case EM_ConstantExpression:
624 case EM_PotentialConstantExpression:
625 case EM_ConstantExpressionUnevaluated:
626 case EM_PotentialConstantExpressionUnevaluated:
627 case EM_DesignatorFold:
628 HasActiveDiagnostic = false;
629 return OptionalDiagnostic();
633 unsigned CallStackNotes = CallStackDepth - 1;
634 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
636 CallStackNotes = std::min(CallStackNotes, Limit + 1);
637 if (checkingPotentialConstantExpression())
640 HasActiveDiagnostic = true;
641 HasFoldFailureDiagnostic = !IsCCEDiag;
642 EvalStatus.Diag->clear();
643 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
644 addDiag(Loc, DiagId);
645 if (!checkingPotentialConstantExpression())
647 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
649 HasActiveDiagnostic = false;
650 return OptionalDiagnostic();
653 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
655 FFDiag(SourceLocation Loc,
656 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
657 unsigned ExtraNotes = 0) {
658 return Diag(Loc, DiagId, ExtraNotes, false);
661 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
662 = diag::note_invalid_subexpr_in_const_expr,
663 unsigned ExtraNotes = 0) {
665 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
666 HasActiveDiagnostic = false;
667 return OptionalDiagnostic();
670 /// Diagnose that the evaluation does not produce a C++11 core constant
673 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
674 /// EM_PotentialConstantExpression mode and we produce one of these.
675 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
676 = diag::note_invalid_subexpr_in_const_expr,
677 unsigned ExtraNotes = 0) {
678 // Don't override a previous diagnostic. Don't bother collecting
679 // diagnostics if we're evaluating for overflow.
680 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
681 HasActiveDiagnostic = false;
682 return OptionalDiagnostic();
684 return Diag(Loc, DiagId, ExtraNotes, true);
686 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
687 = diag::note_invalid_subexpr_in_const_expr,
688 unsigned ExtraNotes = 0) {
689 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
691 /// Add a note to a prior diagnostic.
692 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
693 if (!HasActiveDiagnostic)
694 return OptionalDiagnostic();
695 return OptionalDiagnostic(&addDiag(Loc, DiagId));
698 /// Add a stack of notes to a prior diagnostic.
699 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
700 if (HasActiveDiagnostic) {
701 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
702 Diags.begin(), Diags.end());
706 /// Should we continue evaluation after encountering a side-effect that we
708 bool keepEvaluatingAfterSideEffect() {
710 case EM_PotentialConstantExpression:
711 case EM_PotentialConstantExpressionUnevaluated:
712 case EM_EvaluateForOverflow:
713 case EM_IgnoreSideEffects:
716 case EM_ConstantExpression:
717 case EM_ConstantExpressionUnevaluated:
718 case EM_ConstantFold:
719 case EM_DesignatorFold:
722 llvm_unreachable("Missed EvalMode case");
725 /// Note that we have had a side-effect, and determine whether we should
727 bool noteSideEffect() {
728 EvalStatus.HasSideEffects = true;
729 return keepEvaluatingAfterSideEffect();
732 /// Should we continue evaluation after encountering undefined behavior?
733 bool keepEvaluatingAfterUndefinedBehavior() {
735 case EM_EvaluateForOverflow:
736 case EM_IgnoreSideEffects:
737 case EM_ConstantFold:
738 case EM_DesignatorFold:
741 case EM_PotentialConstantExpression:
742 case EM_PotentialConstantExpressionUnevaluated:
743 case EM_ConstantExpression:
744 case EM_ConstantExpressionUnevaluated:
747 llvm_unreachable("Missed EvalMode case");
750 /// Note that we hit something that was technically undefined behavior, but
751 /// that we can evaluate past it (such as signed overflow or floating-point
752 /// division by zero.)
753 bool noteUndefinedBehavior() {
754 EvalStatus.HasUndefinedBehavior = true;
755 return keepEvaluatingAfterUndefinedBehavior();
758 /// Should we continue evaluation as much as possible after encountering a
759 /// construct which can't be reduced to a value?
760 bool keepEvaluatingAfterFailure() {
765 case EM_PotentialConstantExpression:
766 case EM_PotentialConstantExpressionUnevaluated:
767 case EM_EvaluateForOverflow:
770 case EM_ConstantExpression:
771 case EM_ConstantExpressionUnevaluated:
772 case EM_ConstantFold:
773 case EM_IgnoreSideEffects:
774 case EM_DesignatorFold:
777 llvm_unreachable("Missed EvalMode case");
780 /// Notes that we failed to evaluate an expression that other expressions
781 /// directly depend on, and determine if we should keep evaluating. This
782 /// should only be called if we actually intend to keep evaluating.
784 /// Call noteSideEffect() instead if we may be able to ignore the value that
785 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
787 /// (Foo(), 1) // use noteSideEffect
788 /// (Foo() || true) // use noteSideEffect
789 /// Foo() + 1 // use noteFailure
790 LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
791 // Failure when evaluating some expression often means there is some
792 // subexpression whose evaluation was skipped. Therefore, (because we
793 // don't track whether we skipped an expression when unwinding after an
794 // evaluation failure) every evaluation failure that bubbles up from a
795 // subexpression implies that a side-effect has potentially happened. We
796 // skip setting the HasSideEffects flag to true until we decide to
797 // continue evaluating after that point, which happens here.
798 bool KeepGoing = keepEvaluatingAfterFailure();
799 EvalStatus.HasSideEffects |= KeepGoing;
803 bool allowInvalidBaseExpr() const {
804 return EvalMode == EM_DesignatorFold;
808 /// Object used to treat all foldable expressions as constant expressions.
809 struct FoldConstant {
812 bool HadNoPriorDiags;
813 EvalInfo::EvaluationMode OldMode;
815 explicit FoldConstant(EvalInfo &Info, bool Enabled)
818 HadNoPriorDiags(Info.EvalStatus.Diag &&
819 Info.EvalStatus.Diag->empty() &&
820 !Info.EvalStatus.HasSideEffects),
821 OldMode(Info.EvalMode) {
823 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
824 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
825 Info.EvalMode = EvalInfo::EM_ConstantFold;
827 void keepDiagnostics() { Enabled = false; }
829 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
830 !Info.EvalStatus.HasSideEffects)
831 Info.EvalStatus.Diag->clear();
832 Info.EvalMode = OldMode;
836 /// RAII object used to treat the current evaluation as the correct pointer
837 /// offset fold for the current EvalMode
838 struct FoldOffsetRAII {
840 EvalInfo::EvaluationMode OldMode;
841 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
842 : Info(Info), OldMode(Info.EvalMode) {
843 if (!Info.checkingPotentialConstantExpression())
844 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
845 : EvalInfo::EM_ConstantFold;
848 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
851 /// RAII object used to optionally suppress diagnostics and side-effects from
852 /// a speculative evaluation.
853 class SpeculativeEvaluationRAII {
854 /// Pair of EvalInfo, and a bit that stores whether or not we were
855 /// speculatively evaluating when we created this RAII.
856 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
857 Expr::EvalStatus Old;
859 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
860 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
862 Other.InfoAndOldSpecEval.setPointer(nullptr);
865 void maybeRestoreState() {
866 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
870 Info->EvalStatus = Old;
871 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
875 SpeculativeEvaluationRAII() = default;
877 SpeculativeEvaluationRAII(
878 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
879 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
880 Old(Info.EvalStatus) {
881 Info.EvalStatus.Diag = NewDiag;
882 Info.IsSpeculativelyEvaluating = true;
885 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
886 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
887 moveFromAndCancel(std::move(Other));
890 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
892 moveFromAndCancel(std::move(Other));
896 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
899 /// RAII object wrapping a full-expression or block scope, and handling
900 /// the ending of the lifetime of temporaries created within it.
901 template<bool IsFullExpression>
904 unsigned OldStackSize;
906 ScopeRAII(EvalInfo &Info)
907 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
909 // Body moved to a static method to encourage the compiler to inline away
910 // instances of this class.
911 cleanup(Info, OldStackSize);
914 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
915 unsigned NewEnd = OldStackSize;
916 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
918 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
919 // Full-expression cleanup of a lifetime-extended temporary: nothing
920 // to do, just move this cleanup to the right place in the stack.
921 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
924 // End the lifetime of the object.
925 Info.CleanupStack[I].endLifetime();
928 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
929 Info.CleanupStack.end());
932 typedef ScopeRAII<false> BlockScopeRAII;
933 typedef ScopeRAII<true> FullExpressionRAII;
936 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
937 CheckSubobjectKind CSK) {
940 if (isOnePastTheEnd()) {
941 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
949 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
950 const Expr *E, uint64_t N) {
951 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
952 Info.CCEDiag(E, diag::note_constexpr_array_index)
953 << static_cast<int>(N) << /*array*/ 0
954 << static_cast<unsigned>(MostDerivedArraySize);
956 Info.CCEDiag(E, diag::note_constexpr_array_index)
957 << static_cast<int>(N) << /*non-array*/ 1;
961 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
962 const FunctionDecl *Callee, const LValue *This,
964 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
965 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
966 Info.CurrentCall = this;
967 ++Info.CallStackDepth;
970 CallStackFrame::~CallStackFrame() {
971 assert(Info.CurrentCall == this && "calls retired out of order");
972 --Info.CallStackDepth;
973 Info.CurrentCall = Caller;
976 APValue &CallStackFrame::createTemporary(const void *Key,
977 bool IsLifetimeExtended) {
978 APValue &Result = Temporaries[Key];
979 assert(Result.isUninit() && "temporary created multiple times");
980 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
984 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
986 void EvalInfo::addCallStack(unsigned Limit) {
987 // Determine which calls to skip, if any.
988 unsigned ActiveCalls = CallStackDepth - 1;
989 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
990 if (Limit && Limit < ActiveCalls) {
991 SkipStart = Limit / 2 + Limit % 2;
992 SkipEnd = ActiveCalls - Limit / 2;
995 // Walk the call stack and add the diagnostics.
996 unsigned CallIdx = 0;
997 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
998 Frame = Frame->Caller, ++CallIdx) {
1000 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1001 if (CallIdx == SkipStart) {
1002 // Note that we're skipping calls.
1003 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1004 << unsigned(ActiveCalls - Limit);
1009 // Use a different note for an inheriting constructor, because from the
1010 // user's perspective it's not really a function at all.
1011 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1012 if (CD->isInheritingConstructor()) {
1013 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1019 SmallVector<char, 128> Buffer;
1020 llvm::raw_svector_ostream Out(Buffer);
1021 describeCall(Frame, Out);
1022 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1027 struct ComplexValue {
1032 APSInt IntReal, IntImag;
1033 APFloat FloatReal, FloatImag;
1035 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1037 void makeComplexFloat() { IsInt = false; }
1038 bool isComplexFloat() const { return !IsInt; }
1039 APFloat &getComplexFloatReal() { return FloatReal; }
1040 APFloat &getComplexFloatImag() { return FloatImag; }
1042 void makeComplexInt() { IsInt = true; }
1043 bool isComplexInt() const { return IsInt; }
1044 APSInt &getComplexIntReal() { return IntReal; }
1045 APSInt &getComplexIntImag() { return IntImag; }
1047 void moveInto(APValue &v) const {
1048 if (isComplexFloat())
1049 v = APValue(FloatReal, FloatImag);
1051 v = APValue(IntReal, IntImag);
1053 void setFrom(const APValue &v) {
1054 assert(v.isComplexFloat() || v.isComplexInt());
1055 if (v.isComplexFloat()) {
1057 FloatReal = v.getComplexFloatReal();
1058 FloatImag = v.getComplexFloatImag();
1061 IntReal = v.getComplexIntReal();
1062 IntImag = v.getComplexIntImag();
1068 APValue::LValueBase Base;
1070 unsigned InvalidBase : 1;
1071 unsigned CallIndex : 31;
1072 SubobjectDesignator Designator;
1074 const APValue::LValueBase getLValueBase() const { return Base; }
1075 CharUnits &getLValueOffset() { return Offset; }
1076 const CharUnits &getLValueOffset() const { return Offset; }
1077 unsigned getLValueCallIndex() const { return CallIndex; }
1078 SubobjectDesignator &getLValueDesignator() { return Designator; }
1079 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1081 void moveInto(APValue &V) const {
1082 if (Designator.Invalid)
1083 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1085 V = APValue(Base, Offset, Designator.Entries,
1086 Designator.IsOnePastTheEnd, CallIndex);
1088 void setFrom(ASTContext &Ctx, const APValue &V) {
1089 assert(V.isLValue());
1090 Base = V.getLValueBase();
1091 Offset = V.getLValueOffset();
1092 InvalidBase = false;
1093 CallIndex = V.getLValueCallIndex();
1094 Designator = SubobjectDesignator(Ctx, V);
1097 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1099 Offset = CharUnits::Zero();
1100 InvalidBase = BInvalid;
1102 Designator = SubobjectDesignator(getType(B));
1105 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1109 // Check that this LValue is not based on a null pointer. If it is, produce
1110 // a diagnostic and mark the designator as invalid.
1111 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1112 CheckSubobjectKind CSK) {
1113 if (Designator.Invalid)
1116 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1118 Designator.setInvalid();
1124 // Check this LValue refers to an object. If not, set the designator to be
1125 // invalid and emit a diagnostic.
1126 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1127 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1128 Designator.checkSubobject(Info, E, CSK);
1131 void addDecl(EvalInfo &Info, const Expr *E,
1132 const Decl *D, bool Virtual = false) {
1133 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1134 Designator.addDeclUnchecked(D, Virtual);
1136 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1137 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1138 Designator.addArrayUnchecked(CAT);
1140 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1141 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1142 Designator.addComplexUnchecked(EltTy, Imag);
1144 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
1145 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
1146 Designator.adjustIndex(Info, E, N);
1152 explicit MemberPtr(const ValueDecl *Decl) :
1153 DeclAndIsDerivedMember(Decl, false), Path() {}
1155 /// The member or (direct or indirect) field referred to by this member
1156 /// pointer, or 0 if this is a null member pointer.
1157 const ValueDecl *getDecl() const {
1158 return DeclAndIsDerivedMember.getPointer();
1160 /// Is this actually a member of some type derived from the relevant class?
1161 bool isDerivedMember() const {
1162 return DeclAndIsDerivedMember.getInt();
1164 /// Get the class which the declaration actually lives in.
1165 const CXXRecordDecl *getContainingRecord() const {
1166 return cast<CXXRecordDecl>(
1167 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1170 void moveInto(APValue &V) const {
1171 V = APValue(getDecl(), isDerivedMember(), Path);
1173 void setFrom(const APValue &V) {
1174 assert(V.isMemberPointer());
1175 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1176 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1178 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1179 Path.insert(Path.end(), P.begin(), P.end());
1182 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1183 /// whether the member is a member of some class derived from the class type
1184 /// of the member pointer.
1185 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1186 /// Path - The path of base/derived classes from the member declaration's
1187 /// class (exclusive) to the class type of the member pointer (inclusive).
1188 SmallVector<const CXXRecordDecl*, 4> Path;
1190 /// Perform a cast towards the class of the Decl (either up or down the
1192 bool castBack(const CXXRecordDecl *Class) {
1193 assert(!Path.empty());
1194 const CXXRecordDecl *Expected;
1195 if (Path.size() >= 2)
1196 Expected = Path[Path.size() - 2];
1198 Expected = getContainingRecord();
1199 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1200 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1201 // if B does not contain the original member and is not a base or
1202 // derived class of the class containing the original member, the result
1203 // of the cast is undefined.
1204 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1205 // (D::*). We consider that to be a language defect.
1211 /// Perform a base-to-derived member pointer cast.
1212 bool castToDerived(const CXXRecordDecl *Derived) {
1215 if (!isDerivedMember()) {
1216 Path.push_back(Derived);
1219 if (!castBack(Derived))
1222 DeclAndIsDerivedMember.setInt(false);
1225 /// Perform a derived-to-base member pointer cast.
1226 bool castToBase(const CXXRecordDecl *Base) {
1230 DeclAndIsDerivedMember.setInt(true);
1231 if (isDerivedMember()) {
1232 Path.push_back(Base);
1235 return castBack(Base);
1239 /// Compare two member pointers, which are assumed to be of the same type.
1240 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1241 if (!LHS.getDecl() || !RHS.getDecl())
1242 return !LHS.getDecl() && !RHS.getDecl();
1243 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1245 return LHS.Path == RHS.Path;
1249 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1250 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1251 const LValue &This, const Expr *E,
1252 bool AllowNonLiteralTypes = false);
1253 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1254 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1255 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1257 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1258 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1259 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1261 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1262 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1263 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1264 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1266 //===----------------------------------------------------------------------===//
1268 //===----------------------------------------------------------------------===//
1270 /// Produce a string describing the given constexpr call.
1271 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1272 unsigned ArgIndex = 0;
1273 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1274 !isa<CXXConstructorDecl>(Frame->Callee) &&
1275 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1278 Out << *Frame->Callee << '(';
1280 if (Frame->This && IsMemberCall) {
1282 Frame->This->moveInto(Val);
1283 Val.printPretty(Out, Frame->Info.Ctx,
1284 Frame->This->Designator.MostDerivedType);
1285 // FIXME: Add parens around Val if needed.
1286 Out << "->" << *Frame->Callee << '(';
1287 IsMemberCall = false;
1290 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1291 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1292 if (ArgIndex > (unsigned)IsMemberCall)
1295 const ParmVarDecl *Param = *I;
1296 const APValue &Arg = Frame->Arguments[ArgIndex];
1297 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1299 if (ArgIndex == 0 && IsMemberCall)
1300 Out << "->" << *Frame->Callee << '(';
1306 /// Evaluate an expression to see if it had side-effects, and discard its
1308 /// \return \c true if the caller should keep evaluating.
1309 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1311 if (!Evaluate(Scratch, Info, E))
1312 // We don't need the value, but we might have skipped a side effect here.
1313 return Info.noteSideEffect();
1317 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1318 /// return its existing value.
1319 static int64_t getExtValue(const APSInt &Value) {
1320 return Value.isSigned() ? Value.getSExtValue()
1321 : static_cast<int64_t>(Value.getZExtValue());
1324 /// Should this call expression be treated as a string literal?
1325 static bool IsStringLiteralCall(const CallExpr *E) {
1326 unsigned Builtin = E->getBuiltinCallee();
1327 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1328 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1331 static bool IsGlobalLValue(APValue::LValueBase B) {
1332 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1333 // constant expression of pointer type that evaluates to...
1335 // ... a null pointer value, or a prvalue core constant expression of type
1337 if (!B) return true;
1339 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1340 // ... the address of an object with static storage duration,
1341 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1342 return VD->hasGlobalStorage();
1343 // ... the address of a function,
1344 return isa<FunctionDecl>(D);
1347 const Expr *E = B.get<const Expr*>();
1348 switch (E->getStmtClass()) {
1351 case Expr::CompoundLiteralExprClass: {
1352 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1353 return CLE->isFileScope() && CLE->isLValue();
1355 case Expr::MaterializeTemporaryExprClass:
1356 // A materialized temporary might have been lifetime-extended to static
1357 // storage duration.
1358 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1359 // A string literal has static storage duration.
1360 case Expr::StringLiteralClass:
1361 case Expr::PredefinedExprClass:
1362 case Expr::ObjCStringLiteralClass:
1363 case Expr::ObjCEncodeExprClass:
1364 case Expr::CXXTypeidExprClass:
1365 case Expr::CXXUuidofExprClass:
1367 case Expr::CallExprClass:
1368 return IsStringLiteralCall(cast<CallExpr>(E));
1369 // For GCC compatibility, &&label has static storage duration.
1370 case Expr::AddrLabelExprClass:
1372 // A Block literal expression may be used as the initialization value for
1373 // Block variables at global or local static scope.
1374 case Expr::BlockExprClass:
1375 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1376 case Expr::ImplicitValueInitExprClass:
1378 // We can never form an lvalue with an implicit value initialization as its
1379 // base through expression evaluation, so these only appear in one case: the
1380 // implicit variable declaration we invent when checking whether a constexpr
1381 // constructor can produce a constant expression. We must assume that such
1382 // an expression might be a global lvalue.
1387 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1388 assert(Base && "no location for a null lvalue");
1389 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1391 Info.Note(VD->getLocation(), diag::note_declared_at);
1393 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1394 diag::note_constexpr_temporary_here);
1397 /// Check that this reference or pointer core constant expression is a valid
1398 /// value for an address or reference constant expression. Return true if we
1399 /// can fold this expression, whether or not it's a constant expression.
1400 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1401 QualType Type, const LValue &LVal) {
1402 bool IsReferenceType = Type->isReferenceType();
1404 APValue::LValueBase Base = LVal.getLValueBase();
1405 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1407 // Check that the object is a global. Note that the fake 'this' object we
1408 // manufacture when checking potential constant expressions is conservatively
1409 // assumed to be global here.
1410 if (!IsGlobalLValue(Base)) {
1411 if (Info.getLangOpts().CPlusPlus11) {
1412 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1413 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1414 << IsReferenceType << !Designator.Entries.empty()
1416 NoteLValueLocation(Info, Base);
1420 // Don't allow references to temporaries to escape.
1423 assert((Info.checkingPotentialConstantExpression() ||
1424 LVal.getLValueCallIndex() == 0) &&
1425 "have call index for global lvalue");
1427 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1428 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1429 // Check if this is a thread-local variable.
1430 if (Var->getTLSKind())
1433 // A dllimport variable never acts like a constant.
1434 if (Var->hasAttr<DLLImportAttr>())
1437 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1438 // __declspec(dllimport) must be handled very carefully:
1439 // We must never initialize an expression with the thunk in C++.
1440 // Doing otherwise would allow the same id-expression to yield
1441 // different addresses for the same function in different translation
1442 // units. However, this means that we must dynamically initialize the
1443 // expression with the contents of the import address table at runtime.
1445 // The C language has no notion of ODR; furthermore, it has no notion of
1446 // dynamic initialization. This means that we are permitted to
1447 // perform initialization with the address of the thunk.
1448 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1453 // Allow address constant expressions to be past-the-end pointers. This is
1454 // an extension: the standard requires them to point to an object.
1455 if (!IsReferenceType)
1458 // A reference constant expression must refer to an object.
1460 // FIXME: diagnostic
1465 // Does this refer one past the end of some object?
1466 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1467 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1468 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1469 << !Designator.Entries.empty() << !!VD << VD;
1470 NoteLValueLocation(Info, Base);
1476 /// Check that this core constant expression is of literal type, and if not,
1477 /// produce an appropriate diagnostic.
1478 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1479 const LValue *This = nullptr) {
1480 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1483 // C++1y: A constant initializer for an object o [...] may also invoke
1484 // constexpr constructors for o and its subobjects even if those objects
1485 // are of non-literal class types.
1486 if (Info.getLangOpts().CPlusPlus14 && This &&
1487 Info.EvaluatingDecl == This->getLValueBase())
1490 // Prvalue constant expressions must be of literal types.
1491 if (Info.getLangOpts().CPlusPlus11)
1492 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1495 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1499 /// Check that this core constant expression value is a valid value for a
1500 /// constant expression. If not, report an appropriate diagnostic. Does not
1501 /// check that the expression is of literal type.
1502 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1503 QualType Type, const APValue &Value) {
1504 if (Value.isUninit()) {
1505 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1510 // We allow _Atomic(T) to be initialized from anything that T can be
1511 // initialized from.
1512 if (const AtomicType *AT = Type->getAs<AtomicType>())
1513 Type = AT->getValueType();
1515 // Core issue 1454: For a literal constant expression of array or class type,
1516 // each subobject of its value shall have been initialized by a constant
1518 if (Value.isArray()) {
1519 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1520 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1521 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1522 Value.getArrayInitializedElt(I)))
1525 if (!Value.hasArrayFiller())
1527 return CheckConstantExpression(Info, DiagLoc, EltTy,
1528 Value.getArrayFiller());
1530 if (Value.isUnion() && Value.getUnionField()) {
1531 return CheckConstantExpression(Info, DiagLoc,
1532 Value.getUnionField()->getType(),
1533 Value.getUnionValue());
1535 if (Value.isStruct()) {
1536 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1537 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1538 unsigned BaseIndex = 0;
1539 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1540 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1541 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1542 Value.getStructBase(BaseIndex)))
1546 for (const auto *I : RD->fields()) {
1547 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1548 Value.getStructField(I->getFieldIndex())))
1553 if (Value.isLValue()) {
1555 LVal.setFrom(Info.Ctx, Value);
1556 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1559 // Everything else is fine.
1563 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1564 return LVal.Base.dyn_cast<const ValueDecl*>();
1567 static bool IsLiteralLValue(const LValue &Value) {
1568 if (Value.CallIndex)
1570 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1571 return E && !isa<MaterializeTemporaryExpr>(E);
1574 static bool IsWeakLValue(const LValue &Value) {
1575 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1576 return Decl && Decl->isWeak();
1579 static bool isZeroSized(const LValue &Value) {
1580 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1581 if (Decl && isa<VarDecl>(Decl)) {
1582 QualType Ty = Decl->getType();
1583 if (Ty->isArrayType())
1584 return Ty->isIncompleteType() ||
1585 Decl->getASTContext().getTypeSize(Ty) == 0;
1590 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1591 // A null base expression indicates a null pointer. These are always
1592 // evaluatable, and they are false unless the offset is zero.
1593 if (!Value.getLValueBase()) {
1594 Result = !Value.getLValueOffset().isZero();
1598 // We have a non-null base. These are generally known to be true, but if it's
1599 // a weak declaration it can be null at runtime.
1601 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1602 return !Decl || !Decl->isWeak();
1605 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1606 switch (Val.getKind()) {
1607 case APValue::Uninitialized:
1610 Result = Val.getInt().getBoolValue();
1612 case APValue::Float:
1613 Result = !Val.getFloat().isZero();
1615 case APValue::ComplexInt:
1616 Result = Val.getComplexIntReal().getBoolValue() ||
1617 Val.getComplexIntImag().getBoolValue();
1619 case APValue::ComplexFloat:
1620 Result = !Val.getComplexFloatReal().isZero() ||
1621 !Val.getComplexFloatImag().isZero();
1623 case APValue::LValue:
1624 return EvalPointerValueAsBool(Val, Result);
1625 case APValue::MemberPointer:
1626 Result = Val.getMemberPointerDecl();
1628 case APValue::Vector:
1629 case APValue::Array:
1630 case APValue::Struct:
1631 case APValue::Union:
1632 case APValue::AddrLabelDiff:
1636 llvm_unreachable("unknown APValue kind");
1639 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1641 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1643 if (!Evaluate(Val, Info, E))
1645 return HandleConversionToBool(Val, Result);
1648 template<typename T>
1649 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1650 const T &SrcValue, QualType DestType) {
1651 Info.CCEDiag(E, diag::note_constexpr_overflow)
1652 << SrcValue << DestType;
1653 return Info.noteUndefinedBehavior();
1656 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1657 QualType SrcType, const APFloat &Value,
1658 QualType DestType, APSInt &Result) {
1659 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1660 // Determine whether we are converting to unsigned or signed.
1661 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1663 Result = APSInt(DestWidth, !DestSigned);
1665 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1666 & APFloat::opInvalidOp)
1667 return HandleOverflow(Info, E, Value, DestType);
1671 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1672 QualType SrcType, QualType DestType,
1674 APFloat Value = Result;
1676 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1677 APFloat::rmNearestTiesToEven, &ignored)
1678 & APFloat::opOverflow)
1679 return HandleOverflow(Info, E, Value, DestType);
1683 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1684 QualType DestType, QualType SrcType,
1685 const APSInt &Value) {
1686 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1687 APSInt Result = Value;
1688 // Figure out if this is a truncate, extend or noop cast.
1689 // If the input is signed, do a sign extend, noop, or truncate.
1690 Result = Result.extOrTrunc(DestWidth);
1691 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1695 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1696 QualType SrcType, const APSInt &Value,
1697 QualType DestType, APFloat &Result) {
1698 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1699 if (Result.convertFromAPInt(Value, Value.isSigned(),
1700 APFloat::rmNearestTiesToEven)
1701 & APFloat::opOverflow)
1702 return HandleOverflow(Info, E, Value, DestType);
1706 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1707 APValue &Value, const FieldDecl *FD) {
1708 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1710 if (!Value.isInt()) {
1711 // Trying to store a pointer-cast-to-integer into a bitfield.
1712 // FIXME: In this case, we should provide the diagnostic for casting
1713 // a pointer to an integer.
1714 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1719 APSInt &Int = Value.getInt();
1720 unsigned OldBitWidth = Int.getBitWidth();
1721 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1722 if (NewBitWidth < OldBitWidth)
1723 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1727 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1730 if (!Evaluate(SVal, Info, E))
1733 Res = SVal.getInt();
1736 if (SVal.isFloat()) {
1737 Res = SVal.getFloat().bitcastToAPInt();
1740 if (SVal.isVector()) {
1741 QualType VecTy = E->getType();
1742 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1743 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1744 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1745 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1746 Res = llvm::APInt::getNullValue(VecSize);
1747 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1748 APValue &Elt = SVal.getVectorElt(i);
1749 llvm::APInt EltAsInt;
1751 EltAsInt = Elt.getInt();
1752 } else if (Elt.isFloat()) {
1753 EltAsInt = Elt.getFloat().bitcastToAPInt();
1755 // Don't try to handle vectors of anything other than int or float
1756 // (not sure if it's possible to hit this case).
1757 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1760 unsigned BaseEltSize = EltAsInt.getBitWidth();
1762 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1764 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1768 // Give up if the input isn't an int, float, or vector. For example, we
1769 // reject "(v4i16)(intptr_t)&a".
1770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1774 /// Perform the given integer operation, which is known to need at most BitWidth
1775 /// bits, and check for overflow in the original type (if that type was not an
1777 template<typename Operation>
1778 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1779 const APSInt &LHS, const APSInt &RHS,
1780 unsigned BitWidth, Operation Op,
1782 if (LHS.isUnsigned()) {
1783 Result = Op(LHS, RHS);
1787 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1788 Result = Value.trunc(LHS.getBitWidth());
1789 if (Result.extend(BitWidth) != Value) {
1790 if (Info.checkingForOverflow())
1791 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1792 diag::warn_integer_constant_overflow)
1793 << Result.toString(10) << E->getType();
1795 return HandleOverflow(Info, E, Value, E->getType());
1800 /// Perform the given binary integer operation.
1801 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1802 BinaryOperatorKind Opcode, APSInt RHS,
1809 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1810 std::multiplies<APSInt>(), Result);
1812 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1813 std::plus<APSInt>(), Result);
1815 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1816 std::minus<APSInt>(), Result);
1817 case BO_And: Result = LHS & RHS; return true;
1818 case BO_Xor: Result = LHS ^ RHS; return true;
1819 case BO_Or: Result = LHS | RHS; return true;
1823 Info.FFDiag(E, diag::note_expr_divide_by_zero);
1826 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1827 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1828 // this operation and gives the two's complement result.
1829 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1830 LHS.isSigned() && LHS.isMinSignedValue())
1831 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1835 if (Info.getLangOpts().OpenCL)
1836 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1837 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1838 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1840 else if (RHS.isSigned() && RHS.isNegative()) {
1841 // During constant-folding, a negative shift is an opposite shift. Such
1842 // a shift is not a constant expression.
1843 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1848 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1849 // the shifted type.
1850 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1852 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1853 << RHS << E->getType() << LHS.getBitWidth();
1854 } else if (LHS.isSigned()) {
1855 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1856 // operand, and must not overflow the corresponding unsigned type.
1857 if (LHS.isNegative())
1858 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1859 else if (LHS.countLeadingZeros() < SA)
1860 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1866 if (Info.getLangOpts().OpenCL)
1867 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1868 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1869 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1871 else if (RHS.isSigned() && RHS.isNegative()) {
1872 // During constant-folding, a negative shift is an opposite shift. Such a
1873 // shift is not a constant expression.
1874 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1879 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1881 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1883 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1884 << RHS << E->getType() << LHS.getBitWidth();
1889 case BO_LT: Result = LHS < RHS; return true;
1890 case BO_GT: Result = LHS > RHS; return true;
1891 case BO_LE: Result = LHS <= RHS; return true;
1892 case BO_GE: Result = LHS >= RHS; return true;
1893 case BO_EQ: Result = LHS == RHS; return true;
1894 case BO_NE: Result = LHS != RHS; return true;
1898 /// Perform the given binary floating-point operation, in-place, on LHS.
1899 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1900 APFloat &LHS, BinaryOperatorKind Opcode,
1901 const APFloat &RHS) {
1907 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1910 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1913 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1916 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1920 if (LHS.isInfinity() || LHS.isNaN()) {
1921 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1922 return Info.noteUndefinedBehavior();
1927 /// Cast an lvalue referring to a base subobject to a derived class, by
1928 /// truncating the lvalue's path to the given length.
1929 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1930 const RecordDecl *TruncatedType,
1931 unsigned TruncatedElements) {
1932 SubobjectDesignator &D = Result.Designator;
1934 // Check we actually point to a derived class object.
1935 if (TruncatedElements == D.Entries.size())
1937 assert(TruncatedElements >= D.MostDerivedPathLength &&
1938 "not casting to a derived class");
1939 if (!Result.checkSubobject(Info, E, CSK_Derived))
1942 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1943 const RecordDecl *RD = TruncatedType;
1944 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1945 if (RD->isInvalidDecl()) return false;
1946 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1947 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1948 if (isVirtualBaseClass(D.Entries[I]))
1949 Result.Offset -= Layout.getVBaseClassOffset(Base);
1951 Result.Offset -= Layout.getBaseClassOffset(Base);
1954 D.Entries.resize(TruncatedElements);
1958 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1959 const CXXRecordDecl *Derived,
1960 const CXXRecordDecl *Base,
1961 const ASTRecordLayout *RL = nullptr) {
1963 if (Derived->isInvalidDecl()) return false;
1964 RL = &Info.Ctx.getASTRecordLayout(Derived);
1967 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1968 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1972 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1973 const CXXRecordDecl *DerivedDecl,
1974 const CXXBaseSpecifier *Base) {
1975 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1977 if (!Base->isVirtual())
1978 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1980 SubobjectDesignator &D = Obj.Designator;
1984 // Extract most-derived object and corresponding type.
1985 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1986 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1989 // Find the virtual base class.
1990 if (DerivedDecl->isInvalidDecl()) return false;
1991 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1992 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1993 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1997 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1998 QualType Type, LValue &Result) {
1999 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2000 PathE = E->path_end();
2001 PathI != PathE; ++PathI) {
2002 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2005 Type = (*PathI)->getType();
2010 /// Update LVal to refer to the given field, which must be a member of the type
2011 /// currently described by LVal.
2012 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2013 const FieldDecl *FD,
2014 const ASTRecordLayout *RL = nullptr) {
2016 if (FD->getParent()->isInvalidDecl()) return false;
2017 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2020 unsigned I = FD->getFieldIndex();
2021 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
2022 LVal.addDecl(Info, E, FD);
2026 /// Update LVal to refer to the given indirect field.
2027 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2029 const IndirectFieldDecl *IFD) {
2030 for (const auto *C : IFD->chain())
2031 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2036 /// Get the size of the given type in char units.
2037 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2038 QualType Type, CharUnits &Size) {
2039 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2041 if (Type->isVoidType() || Type->isFunctionType()) {
2042 Size = CharUnits::One();
2046 if (Type->isDependentType()) {
2051 if (!Type->isConstantSizeType()) {
2052 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2053 // FIXME: Better diagnostic.
2058 Size = Info.Ctx.getTypeSizeInChars(Type);
2062 /// Update a pointer value to model pointer arithmetic.
2063 /// \param Info - Information about the ongoing evaluation.
2064 /// \param E - The expression being evaluated, for diagnostic purposes.
2065 /// \param LVal - The pointer value to be updated.
2066 /// \param EltTy - The pointee type represented by LVal.
2067 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2068 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2069 LValue &LVal, QualType EltTy,
2070 int64_t Adjustment) {
2071 CharUnits SizeOfPointee;
2072 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2075 // Compute the new offset in the appropriate width.
2076 LVal.Offset += Adjustment * SizeOfPointee;
2077 LVal.adjustIndex(Info, E, Adjustment);
2081 /// Update an lvalue to refer to a component of a complex number.
2082 /// \param Info - Information about the ongoing evaluation.
2083 /// \param LVal - The lvalue to be updated.
2084 /// \param EltTy - The complex number's component type.
2085 /// \param Imag - False for the real component, true for the imaginary.
2086 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2087 LValue &LVal, QualType EltTy,
2090 CharUnits SizeOfComponent;
2091 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2093 LVal.Offset += SizeOfComponent;
2095 LVal.addComplex(Info, E, EltTy, Imag);
2099 /// Try to evaluate the initializer for a variable declaration.
2101 /// \param Info Information about the ongoing evaluation.
2102 /// \param E An expression to be used when printing diagnostics.
2103 /// \param VD The variable whose initializer should be obtained.
2104 /// \param Frame The frame in which the variable was created. Must be null
2105 /// if this variable is not local to the evaluation.
2106 /// \param Result Filled in with a pointer to the value of the variable.
2107 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2108 const VarDecl *VD, CallStackFrame *Frame,
2110 // If this is a parameter to an active constexpr function call, perform
2111 // argument substitution.
2112 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2113 // Assume arguments of a potential constant expression are unknown
2114 // constant expressions.
2115 if (Info.checkingPotentialConstantExpression())
2117 if (!Frame || !Frame->Arguments) {
2118 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2121 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2125 // If this is a local variable, dig out its value.
2127 Result = Frame->getTemporary(VD);
2128 assert(Result && "missing value for local variable");
2132 // Dig out the initializer, and use the declaration which it's attached to.
2133 const Expr *Init = VD->getAnyInitializer(VD);
2134 if (!Init || Init->isValueDependent()) {
2135 // If we're checking a potential constant expression, the variable could be
2136 // initialized later.
2137 if (!Info.checkingPotentialConstantExpression())
2138 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2142 // If we're currently evaluating the initializer of this declaration, use that
2144 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2145 Result = Info.EvaluatingDeclValue;
2149 // Never evaluate the initializer of a weak variable. We can't be sure that
2150 // this is the definition which will be used.
2152 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2156 // Check that we can fold the initializer. In C++, we will have already done
2157 // this in the cases where it matters for conformance.
2158 SmallVector<PartialDiagnosticAt, 8> Notes;
2159 if (!VD->evaluateValue(Notes)) {
2160 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2161 Notes.size() + 1) << VD;
2162 Info.Note(VD->getLocation(), diag::note_declared_at);
2163 Info.addNotes(Notes);
2165 } else if (!VD->checkInitIsICE()) {
2166 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2167 Notes.size() + 1) << VD;
2168 Info.Note(VD->getLocation(), diag::note_declared_at);
2169 Info.addNotes(Notes);
2172 Result = VD->getEvaluatedValue();
2176 static bool IsConstNonVolatile(QualType T) {
2177 Qualifiers Quals = T.getQualifiers();
2178 return Quals.hasConst() && !Quals.hasVolatile();
2181 /// Get the base index of the given base class within an APValue representing
2182 /// the given derived class.
2183 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2184 const CXXRecordDecl *Base) {
2185 Base = Base->getCanonicalDecl();
2187 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2188 E = Derived->bases_end(); I != E; ++I, ++Index) {
2189 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2193 llvm_unreachable("base class missing from derived class's bases list");
2196 /// Extract the value of a character from a string literal.
2197 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2199 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2200 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2201 Lit = PE->getFunctionName();
2202 const StringLiteral *S = cast<StringLiteral>(Lit);
2203 const ConstantArrayType *CAT =
2204 Info.Ctx.getAsConstantArrayType(S->getType());
2205 assert(CAT && "string literal isn't an array");
2206 QualType CharType = CAT->getElementType();
2207 assert(CharType->isIntegerType() && "unexpected character type");
2209 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2210 CharType->isUnsignedIntegerType());
2211 if (Index < S->getLength())
2212 Value = S->getCodeUnit(Index);
2216 // Expand a string literal into an array of characters.
2217 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2219 const StringLiteral *S = cast<StringLiteral>(Lit);
2220 const ConstantArrayType *CAT =
2221 Info.Ctx.getAsConstantArrayType(S->getType());
2222 assert(CAT && "string literal isn't an array");
2223 QualType CharType = CAT->getElementType();
2224 assert(CharType->isIntegerType() && "unexpected character type");
2226 unsigned Elts = CAT->getSize().getZExtValue();
2227 Result = APValue(APValue::UninitArray(),
2228 std::min(S->getLength(), Elts), Elts);
2229 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2230 CharType->isUnsignedIntegerType());
2231 if (Result.hasArrayFiller())
2232 Result.getArrayFiller() = APValue(Value);
2233 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2234 Value = S->getCodeUnit(I);
2235 Result.getArrayInitializedElt(I) = APValue(Value);
2239 // Expand an array so that it has more than Index filled elements.
2240 static void expandArray(APValue &Array, unsigned Index) {
2241 unsigned Size = Array.getArraySize();
2242 assert(Index < Size);
2244 // Always at least double the number of elements for which we store a value.
2245 unsigned OldElts = Array.getArrayInitializedElts();
2246 unsigned NewElts = std::max(Index+1, OldElts * 2);
2247 NewElts = std::min(Size, std::max(NewElts, 8u));
2249 // Copy the data across.
2250 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2251 for (unsigned I = 0; I != OldElts; ++I)
2252 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2253 for (unsigned I = OldElts; I != NewElts; ++I)
2254 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2255 if (NewValue.hasArrayFiller())
2256 NewValue.getArrayFiller() = Array.getArrayFiller();
2257 Array.swap(NewValue);
2260 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2261 /// conversion. If it's of class type, we may assume that the copy operation
2262 /// is trivial. Note that this is never true for a union type with fields
2263 /// (because the copy always "reads" the active member) and always true for
2264 /// a non-class type.
2265 static bool isReadByLvalueToRvalueConversion(QualType T) {
2266 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2267 if (!RD || (RD->isUnion() && !RD->field_empty()))
2272 for (auto *Field : RD->fields())
2273 if (isReadByLvalueToRvalueConversion(Field->getType()))
2276 for (auto &BaseSpec : RD->bases())
2277 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2283 /// Diagnose an attempt to read from any unreadable field within the specified
2284 /// type, which might be a class type.
2285 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2287 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2291 if (!RD->hasMutableFields())
2294 for (auto *Field : RD->fields()) {
2295 // If we're actually going to read this field in some way, then it can't
2296 // be mutable. If we're in a union, then assigning to a mutable field
2297 // (even an empty one) can change the active member, so that's not OK.
2298 // FIXME: Add core issue number for the union case.
2299 if (Field->isMutable() &&
2300 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2301 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2302 Info.Note(Field->getLocation(), diag::note_declared_at);
2306 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2310 for (auto &BaseSpec : RD->bases())
2311 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2314 // All mutable fields were empty, and thus not actually read.
2318 /// Kinds of access we can perform on an object, for diagnostics.
2327 /// A handle to a complete object (an object that is not a subobject of
2328 /// another object).
2329 struct CompleteObject {
2330 /// The value of the complete object.
2332 /// The type of the complete object.
2335 CompleteObject() : Value(nullptr) {}
2336 CompleteObject(APValue *Value, QualType Type)
2337 : Value(Value), Type(Type) {
2338 assert(Value && "missing value for complete object");
2341 explicit operator bool() const { return Value; }
2343 } // end anonymous namespace
2345 /// Find the designated sub-object of an rvalue.
2346 template<typename SubobjectHandler>
2347 typename SubobjectHandler::result_type
2348 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2349 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2351 // A diagnostic will have already been produced.
2352 return handler.failed();
2353 if (Sub.isOnePastTheEnd()) {
2354 if (Info.getLangOpts().CPlusPlus11)
2355 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2356 << handler.AccessKind;
2359 return handler.failed();
2362 APValue *O = Obj.Value;
2363 QualType ObjType = Obj.Type;
2364 const FieldDecl *LastField = nullptr;
2366 // Walk the designator's path to find the subobject.
2367 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2368 if (O->isUninit()) {
2369 if (!Info.checkingPotentialConstantExpression())
2370 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2371 return handler.failed();
2375 // If we are reading an object of class type, there may still be more
2376 // things we need to check: if there are any mutable subobjects, we
2377 // cannot perform this read. (This only happens when performing a trivial
2378 // copy or assignment.)
2379 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2380 diagnoseUnreadableFields(Info, E, ObjType))
2381 return handler.failed();
2383 if (!handler.found(*O, ObjType))
2386 // If we modified a bit-field, truncate it to the right width.
2387 if (handler.AccessKind != AK_Read &&
2388 LastField && LastField->isBitField() &&
2389 !truncateBitfieldValue(Info, E, *O, LastField))
2395 LastField = nullptr;
2396 if (ObjType->isArrayType()) {
2397 // Next subobject is an array element.
2398 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2399 assert(CAT && "vla in literal type?");
2400 uint64_t Index = Sub.Entries[I].ArrayIndex;
2401 if (CAT->getSize().ule(Index)) {
2402 // Note, it should not be possible to form a pointer with a valid
2403 // designator which points more than one past the end of the array.
2404 if (Info.getLangOpts().CPlusPlus11)
2405 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2406 << handler.AccessKind;
2409 return handler.failed();
2412 ObjType = CAT->getElementType();
2414 // An array object is represented as either an Array APValue or as an
2415 // LValue which refers to a string literal.
2416 if (O->isLValue()) {
2417 assert(I == N - 1 && "extracting subobject of character?");
2418 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2419 if (handler.AccessKind != AK_Read)
2420 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2423 return handler.foundString(*O, ObjType, Index);
2426 if (O->getArrayInitializedElts() > Index)
2427 O = &O->getArrayInitializedElt(Index);
2428 else if (handler.AccessKind != AK_Read) {
2429 expandArray(*O, Index);
2430 O = &O->getArrayInitializedElt(Index);
2432 O = &O->getArrayFiller();
2433 } else if (ObjType->isAnyComplexType()) {
2434 // Next subobject is a complex number.
2435 uint64_t Index = Sub.Entries[I].ArrayIndex;
2437 if (Info.getLangOpts().CPlusPlus11)
2438 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2439 << handler.AccessKind;
2442 return handler.failed();
2445 bool WasConstQualified = ObjType.isConstQualified();
2446 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2447 if (WasConstQualified)
2450 assert(I == N - 1 && "extracting subobject of scalar?");
2451 if (O->isComplexInt()) {
2452 return handler.found(Index ? O->getComplexIntImag()
2453 : O->getComplexIntReal(), ObjType);
2455 assert(O->isComplexFloat());
2456 return handler.found(Index ? O->getComplexFloatImag()
2457 : O->getComplexFloatReal(), ObjType);
2459 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2460 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2461 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2463 Info.Note(Field->getLocation(), diag::note_declared_at);
2464 return handler.failed();
2467 // Next subobject is a class, struct or union field.
2468 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2469 if (RD->isUnion()) {
2470 const FieldDecl *UnionField = O->getUnionField();
2472 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2473 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2474 << handler.AccessKind << Field << !UnionField << UnionField;
2475 return handler.failed();
2477 O = &O->getUnionValue();
2479 O = &O->getStructField(Field->getFieldIndex());
2481 bool WasConstQualified = ObjType.isConstQualified();
2482 ObjType = Field->getType();
2483 if (WasConstQualified && !Field->isMutable())
2486 if (ObjType.isVolatileQualified()) {
2487 if (Info.getLangOpts().CPlusPlus) {
2488 // FIXME: Include a description of the path to the volatile subobject.
2489 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2490 << handler.AccessKind << 2 << Field;
2491 Info.Note(Field->getLocation(), diag::note_declared_at);
2493 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2495 return handler.failed();
2500 // Next subobject is a base class.
2501 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2502 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2503 O = &O->getStructBase(getBaseIndex(Derived, Base));
2505 bool WasConstQualified = ObjType.isConstQualified();
2506 ObjType = Info.Ctx.getRecordType(Base);
2507 if (WasConstQualified)
2514 struct ExtractSubobjectHandler {
2518 static const AccessKinds AccessKind = AK_Read;
2520 typedef bool result_type;
2521 bool failed() { return false; }
2522 bool found(APValue &Subobj, QualType SubobjType) {
2526 bool found(APSInt &Value, QualType SubobjType) {
2527 Result = APValue(Value);
2530 bool found(APFloat &Value, QualType SubobjType) {
2531 Result = APValue(Value);
2534 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2535 Result = APValue(extractStringLiteralCharacter(
2536 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2540 } // end anonymous namespace
2542 const AccessKinds ExtractSubobjectHandler::AccessKind;
2544 /// Extract the designated sub-object of an rvalue.
2545 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2546 const CompleteObject &Obj,
2547 const SubobjectDesignator &Sub,
2549 ExtractSubobjectHandler Handler = { Info, Result };
2550 return findSubobject(Info, E, Obj, Sub, Handler);
2554 struct ModifySubobjectHandler {
2559 typedef bool result_type;
2560 static const AccessKinds AccessKind = AK_Assign;
2562 bool checkConst(QualType QT) {
2563 // Assigning to a const object has undefined behavior.
2564 if (QT.isConstQualified()) {
2565 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2571 bool failed() { return false; }
2572 bool found(APValue &Subobj, QualType SubobjType) {
2573 if (!checkConst(SubobjType))
2575 // We've been given ownership of NewVal, so just swap it in.
2576 Subobj.swap(NewVal);
2579 bool found(APSInt &Value, QualType SubobjType) {
2580 if (!checkConst(SubobjType))
2582 if (!NewVal.isInt()) {
2583 // Maybe trying to write a cast pointer value into a complex?
2587 Value = NewVal.getInt();
2590 bool found(APFloat &Value, QualType SubobjType) {
2591 if (!checkConst(SubobjType))
2593 Value = NewVal.getFloat();
2596 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2597 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2600 } // end anonymous namespace
2602 const AccessKinds ModifySubobjectHandler::AccessKind;
2604 /// Update the designated sub-object of an rvalue to the given value.
2605 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2606 const CompleteObject &Obj,
2607 const SubobjectDesignator &Sub,
2609 ModifySubobjectHandler Handler = { Info, NewVal, E };
2610 return findSubobject(Info, E, Obj, Sub, Handler);
2613 /// Find the position where two subobject designators diverge, or equivalently
2614 /// the length of the common initial subsequence.
2615 static unsigned FindDesignatorMismatch(QualType ObjType,
2616 const SubobjectDesignator &A,
2617 const SubobjectDesignator &B,
2618 bool &WasArrayIndex) {
2619 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2620 for (/**/; I != N; ++I) {
2621 if (!ObjType.isNull() &&
2622 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2623 // Next subobject is an array element.
2624 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2625 WasArrayIndex = true;
2628 if (ObjType->isAnyComplexType())
2629 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2631 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2633 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2634 WasArrayIndex = false;
2637 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2638 // Next subobject is a field.
2639 ObjType = FD->getType();
2641 // Next subobject is a base class.
2642 ObjType = QualType();
2645 WasArrayIndex = false;
2649 /// Determine whether the given subobject designators refer to elements of the
2650 /// same array object.
2651 static bool AreElementsOfSameArray(QualType ObjType,
2652 const SubobjectDesignator &A,
2653 const SubobjectDesignator &B) {
2654 if (A.Entries.size() != B.Entries.size())
2657 bool IsArray = A.MostDerivedIsArrayElement;
2658 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2659 // A is a subobject of the array element.
2662 // If A (and B) designates an array element, the last entry will be the array
2663 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2664 // of length 1' case, and the entire path must match.
2666 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2667 return CommonLength >= A.Entries.size() - IsArray;
2670 /// Find the complete object to which an LValue refers.
2671 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2672 AccessKinds AK, const LValue &LVal,
2673 QualType LValType) {
2675 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2676 return CompleteObject();
2679 CallStackFrame *Frame = nullptr;
2680 if (LVal.CallIndex) {
2681 Frame = Info.getCallFrame(LVal.CallIndex);
2683 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2684 << AK << LVal.Base.is<const ValueDecl*>();
2685 NoteLValueLocation(Info, LVal.Base);
2686 return CompleteObject();
2690 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2691 // is not a constant expression (even if the object is non-volatile). We also
2692 // apply this rule to C++98, in order to conform to the expected 'volatile'
2694 if (LValType.isVolatileQualified()) {
2695 if (Info.getLangOpts().CPlusPlus)
2696 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2700 return CompleteObject();
2703 // Compute value storage location and type of base object.
2704 APValue *BaseVal = nullptr;
2705 QualType BaseType = getType(LVal.Base);
2707 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2708 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2709 // In C++11, constexpr, non-volatile variables initialized with constant
2710 // expressions are constant expressions too. Inside constexpr functions,
2711 // parameters are constant expressions even if they're non-const.
2712 // In C++1y, objects local to a constant expression (those with a Frame) are
2713 // both readable and writable inside constant expressions.
2714 // In C, such things can also be folded, although they are not ICEs.
2715 const VarDecl *VD = dyn_cast<VarDecl>(D);
2717 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2720 if (!VD || VD->isInvalidDecl()) {
2722 return CompleteObject();
2725 // Accesses of volatile-qualified objects are not allowed.
2726 if (BaseType.isVolatileQualified()) {
2727 if (Info.getLangOpts().CPlusPlus) {
2728 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2730 Info.Note(VD->getLocation(), diag::note_declared_at);
2734 return CompleteObject();
2737 // Unless we're looking at a local variable or argument in a constexpr call,
2738 // the variable we're reading must be const.
2740 if (Info.getLangOpts().CPlusPlus14 &&
2741 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2742 // OK, we can read and modify an object if we're in the process of
2743 // evaluating its initializer, because its lifetime began in this
2745 } else if (AK != AK_Read) {
2746 // All the remaining cases only permit reading.
2747 Info.FFDiag(E, diag::note_constexpr_modify_global);
2748 return CompleteObject();
2749 } else if (VD->isConstexpr()) {
2750 // OK, we can read this variable.
2751 } else if (BaseType->isIntegralOrEnumerationType()) {
2752 // In OpenCL if a variable is in constant address space it is a const value.
2753 if (!(BaseType.isConstQualified() ||
2754 (Info.getLangOpts().OpenCL &&
2755 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
2756 if (Info.getLangOpts().CPlusPlus) {
2757 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2758 Info.Note(VD->getLocation(), diag::note_declared_at);
2762 return CompleteObject();
2764 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2765 // We support folding of const floating-point types, in order to make
2766 // static const data members of such types (supported as an extension)
2768 if (Info.getLangOpts().CPlusPlus11) {
2769 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2770 Info.Note(VD->getLocation(), diag::note_declared_at);
2775 // FIXME: Allow folding of values of any literal type in all languages.
2776 if (Info.checkingPotentialConstantExpression() &&
2777 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2778 // The definition of this variable could be constexpr. We can't
2779 // access it right now, but may be able to in future.
2780 } else if (Info.getLangOpts().CPlusPlus11) {
2781 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2782 Info.Note(VD->getLocation(), diag::note_declared_at);
2786 return CompleteObject();
2790 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2791 return CompleteObject();
2793 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2796 if (const MaterializeTemporaryExpr *MTE =
2797 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2798 assert(MTE->getStorageDuration() == SD_Static &&
2799 "should have a frame for a non-global materialized temporary");
2801 // Per C++1y [expr.const]p2:
2802 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2803 // - a [...] glvalue of integral or enumeration type that refers to
2804 // a non-volatile const object [...]
2806 // - a [...] glvalue of literal type that refers to a non-volatile
2807 // object whose lifetime began within the evaluation of e.
2809 // C++11 misses the 'began within the evaluation of e' check and
2810 // instead allows all temporaries, including things like:
2813 // constexpr int k = r;
2814 // Therefore we use the C++1y rules in C++11 too.
2815 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2816 const ValueDecl *ED = MTE->getExtendingDecl();
2817 if (!(BaseType.isConstQualified() &&
2818 BaseType->isIntegralOrEnumerationType()) &&
2819 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2820 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2821 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2822 return CompleteObject();
2825 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2826 assert(BaseVal && "got reference to unevaluated temporary");
2829 return CompleteObject();
2832 BaseVal = Frame->getTemporary(Base);
2833 assert(BaseVal && "missing value for temporary");
2836 // Volatile temporary objects cannot be accessed in constant expressions.
2837 if (BaseType.isVolatileQualified()) {
2838 if (Info.getLangOpts().CPlusPlus) {
2839 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2841 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2845 return CompleteObject();
2849 // During the construction of an object, it is not yet 'const'.
2850 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2851 // and this doesn't do quite the right thing for const subobjects of the
2852 // object under construction.
2853 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2854 BaseType = Info.Ctx.getCanonicalType(BaseType);
2855 BaseType.removeLocalConst();
2858 // In C++1y, we can't safely access any mutable state when we might be
2859 // evaluating after an unmodeled side effect.
2861 // FIXME: Not all local state is mutable. Allow local constant subobjects
2862 // to be read here (but take care with 'mutable' fields).
2863 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2864 Info.EvalStatus.HasSideEffects) ||
2865 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
2866 return CompleteObject();
2868 return CompleteObject(BaseVal, BaseType);
2871 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2872 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2873 /// glvalue referred to by an entity of reference type.
2875 /// \param Info - Information about the ongoing evaluation.
2876 /// \param Conv - The expression for which we are performing the conversion.
2877 /// Used for diagnostics.
2878 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2879 /// case of a non-class type).
2880 /// \param LVal - The glvalue on which we are attempting to perform this action.
2881 /// \param RVal - The produced value will be placed here.
2882 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2884 const LValue &LVal, APValue &RVal) {
2885 if (LVal.Designator.Invalid)
2888 // Check for special cases where there is no existing APValue to look at.
2889 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2890 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
2891 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2892 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2893 // initializer until now for such expressions. Such an expression can't be
2894 // an ICE in C, so this only matters for fold.
2895 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2896 if (Type.isVolatileQualified()) {
2901 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2903 CompleteObject LitObj(&Lit, Base->getType());
2904 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2905 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
2906 // We represent a string literal array as an lvalue pointing at the
2907 // corresponding expression, rather than building an array of chars.
2908 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2909 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2910 CompleteObject StrObj(&Str, Base->getType());
2911 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2915 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2916 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2919 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2920 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2921 QualType LValType, APValue &Val) {
2922 if (LVal.Designator.Invalid)
2925 if (!Info.getLangOpts().CPlusPlus14) {
2930 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2931 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2934 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2935 return T->isSignedIntegerType() &&
2936 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2940 struct CompoundAssignSubobjectHandler {
2943 QualType PromotedLHSType;
2944 BinaryOperatorKind Opcode;
2947 static const AccessKinds AccessKind = AK_Assign;
2949 typedef bool result_type;
2951 bool checkConst(QualType QT) {
2952 // Assigning to a const object has undefined behavior.
2953 if (QT.isConstQualified()) {
2954 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2960 bool failed() { return false; }
2961 bool found(APValue &Subobj, QualType SubobjType) {
2962 switch (Subobj.getKind()) {
2964 return found(Subobj.getInt(), SubobjType);
2965 case APValue::Float:
2966 return found(Subobj.getFloat(), SubobjType);
2967 case APValue::ComplexInt:
2968 case APValue::ComplexFloat:
2969 // FIXME: Implement complex compound assignment.
2972 case APValue::LValue:
2973 return foundPointer(Subobj, SubobjType);
2975 // FIXME: can this happen?
2980 bool found(APSInt &Value, QualType SubobjType) {
2981 if (!checkConst(SubobjType))
2984 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2985 // We don't support compound assignment on integer-cast-to-pointer
2991 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2993 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2995 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2998 bool found(APFloat &Value, QualType SubobjType) {
2999 return checkConst(SubobjType) &&
3000 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3002 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3003 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3005 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3006 if (!checkConst(SubobjType))
3009 QualType PointeeType;
3010 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3011 PointeeType = PT->getPointeeType();
3013 if (PointeeType.isNull() || !RHS.isInt() ||
3014 (Opcode != BO_Add && Opcode != BO_Sub)) {
3019 int64_t Offset = getExtValue(RHS.getInt());
3020 if (Opcode == BO_Sub)
3024 LVal.setFrom(Info.Ctx, Subobj);
3025 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3027 LVal.moveInto(Subobj);
3030 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3031 llvm_unreachable("shouldn't encounter string elements here");
3034 } // end anonymous namespace
3036 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3038 /// Perform a compound assignment of LVal <op>= RVal.
3039 static bool handleCompoundAssignment(
3040 EvalInfo &Info, const Expr *E,
3041 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3042 BinaryOperatorKind Opcode, const APValue &RVal) {
3043 if (LVal.Designator.Invalid)
3046 if (!Info.getLangOpts().CPlusPlus14) {
3051 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3052 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3054 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3058 struct IncDecSubobjectHandler {
3061 AccessKinds AccessKind;
3064 typedef bool result_type;
3066 bool checkConst(QualType QT) {
3067 // Assigning to a const object has undefined behavior.
3068 if (QT.isConstQualified()) {
3069 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3075 bool failed() { return false; }
3076 bool found(APValue &Subobj, QualType SubobjType) {
3077 // Stash the old value. Also clear Old, so we don't clobber it later
3078 // if we're post-incrementing a complex.
3084 switch (Subobj.getKind()) {
3086 return found(Subobj.getInt(), SubobjType);
3087 case APValue::Float:
3088 return found(Subobj.getFloat(), SubobjType);
3089 case APValue::ComplexInt:
3090 return found(Subobj.getComplexIntReal(),
3091 SubobjType->castAs<ComplexType>()->getElementType()
3092 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3093 case APValue::ComplexFloat:
3094 return found(Subobj.getComplexFloatReal(),
3095 SubobjType->castAs<ComplexType>()->getElementType()
3096 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3097 case APValue::LValue:
3098 return foundPointer(Subobj, SubobjType);
3100 // FIXME: can this happen?
3105 bool found(APSInt &Value, QualType SubobjType) {
3106 if (!checkConst(SubobjType))
3109 if (!SubobjType->isIntegerType()) {
3110 // We don't support increment / decrement on integer-cast-to-pointer
3116 if (Old) *Old = APValue(Value);
3118 // bool arithmetic promotes to int, and the conversion back to bool
3119 // doesn't reduce mod 2^n, so special-case it.
3120 if (SubobjType->isBooleanType()) {
3121 if (AccessKind == AK_Increment)
3128 bool WasNegative = Value.isNegative();
3129 if (AccessKind == AK_Increment) {
3132 if (!WasNegative && Value.isNegative() &&
3133 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3134 APSInt ActualValue(Value, /*IsUnsigned*/true);
3135 return HandleOverflow(Info, E, ActualValue, SubobjType);
3140 if (WasNegative && !Value.isNegative() &&
3141 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3142 unsigned BitWidth = Value.getBitWidth();
3143 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3144 ActualValue.setBit(BitWidth);
3145 return HandleOverflow(Info, E, ActualValue, SubobjType);
3150 bool found(APFloat &Value, QualType SubobjType) {
3151 if (!checkConst(SubobjType))
3154 if (Old) *Old = APValue(Value);
3156 APFloat One(Value.getSemantics(), 1);
3157 if (AccessKind == AK_Increment)
3158 Value.add(One, APFloat::rmNearestTiesToEven);
3160 Value.subtract(One, APFloat::rmNearestTiesToEven);
3163 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3164 if (!checkConst(SubobjType))
3167 QualType PointeeType;
3168 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3169 PointeeType = PT->getPointeeType();
3176 LVal.setFrom(Info.Ctx, Subobj);
3177 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3178 AccessKind == AK_Increment ? 1 : -1))
3180 LVal.moveInto(Subobj);
3183 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3184 llvm_unreachable("shouldn't encounter string elements here");
3187 } // end anonymous namespace
3189 /// Perform an increment or decrement on LVal.
3190 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3191 QualType LValType, bool IsIncrement, APValue *Old) {
3192 if (LVal.Designator.Invalid)
3195 if (!Info.getLangOpts().CPlusPlus14) {
3200 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3201 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3202 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3203 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3206 /// Build an lvalue for the object argument of a member function call.
3207 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3209 if (Object->getType()->isPointerType())
3210 return EvaluatePointer(Object, This, Info);
3212 if (Object->isGLValue())
3213 return EvaluateLValue(Object, This, Info);
3215 if (Object->getType()->isLiteralType(Info.Ctx))
3216 return EvaluateTemporary(Object, This, Info);
3218 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3222 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3223 /// lvalue referring to the result.
3225 /// \param Info - Information about the ongoing evaluation.
3226 /// \param LV - An lvalue referring to the base of the member pointer.
3227 /// \param RHS - The member pointer expression.
3228 /// \param IncludeMember - Specifies whether the member itself is included in
3229 /// the resulting LValue subobject designator. This is not possible when
3230 /// creating a bound member function.
3231 /// \return The field or method declaration to which the member pointer refers,
3232 /// or 0 if evaluation fails.
3233 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3237 bool IncludeMember = true) {
3239 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3242 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3243 // member value, the behavior is undefined.
3244 if (!MemPtr.getDecl()) {
3245 // FIXME: Specific diagnostic.
3250 if (MemPtr.isDerivedMember()) {
3251 // This is a member of some derived class. Truncate LV appropriately.
3252 // The end of the derived-to-base path for the base object must match the
3253 // derived-to-base path for the member pointer.
3254 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3255 LV.Designator.Entries.size()) {
3259 unsigned PathLengthToMember =
3260 LV.Designator.Entries.size() - MemPtr.Path.size();
3261 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3262 const CXXRecordDecl *LVDecl = getAsBaseClass(
3263 LV.Designator.Entries[PathLengthToMember + I]);
3264 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3265 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3271 // Truncate the lvalue to the appropriate derived class.
3272 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3273 PathLengthToMember))
3275 } else if (!MemPtr.Path.empty()) {
3276 // Extend the LValue path with the member pointer's path.
3277 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3278 MemPtr.Path.size() + IncludeMember);
3280 // Walk down to the appropriate base class.
3281 if (const PointerType *PT = LVType->getAs<PointerType>())
3282 LVType = PT->getPointeeType();
3283 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3284 assert(RD && "member pointer access on non-class-type expression");
3285 // The first class in the path is that of the lvalue.
3286 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3287 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3288 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3292 // Finally cast to the class containing the member.
3293 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3294 MemPtr.getContainingRecord()))
3298 // Add the member. Note that we cannot build bound member functions here.
3299 if (IncludeMember) {
3300 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3301 if (!HandleLValueMember(Info, RHS, LV, FD))
3303 } else if (const IndirectFieldDecl *IFD =
3304 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3305 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3308 llvm_unreachable("can't construct reference to bound member function");
3312 return MemPtr.getDecl();
3315 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3316 const BinaryOperator *BO,
3318 bool IncludeMember = true) {
3319 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3321 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3322 if (Info.noteFailure()) {
3324 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3329 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3330 BO->getRHS(), IncludeMember);
3333 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3334 /// the provided lvalue, which currently refers to the base object.
3335 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3337 SubobjectDesignator &D = Result.Designator;
3338 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3341 QualType TargetQT = E->getType();
3342 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3343 TargetQT = PT->getPointeeType();
3345 // Check this cast lands within the final derived-to-base subobject path.
3346 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3347 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3348 << D.MostDerivedType << TargetQT;
3352 // Check the type of the final cast. We don't need to check the path,
3353 // since a cast can only be formed if the path is unique.
3354 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3355 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3356 const CXXRecordDecl *FinalType;
3357 if (NewEntriesSize == D.MostDerivedPathLength)
3358 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3360 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3361 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3362 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3363 << D.MostDerivedType << TargetQT;
3367 // Truncate the lvalue to the appropriate derived class.
3368 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3372 enum EvalStmtResult {
3373 /// Evaluation failed.
3375 /// Hit a 'return' statement.
3377 /// Evaluation succeeded.
3379 /// Hit a 'continue' statement.
3381 /// Hit a 'break' statement.
3383 /// Still scanning for 'case' or 'default' statement.
3388 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3389 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3390 // We don't need to evaluate the initializer for a static local.
3391 if (!VD->hasLocalStorage())
3395 Result.set(VD, Info.CurrentCall->Index);
3396 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3398 const Expr *InitE = VD->getInit();
3400 Info.FFDiag(D->getLocStart(), diag::note_constexpr_uninitialized)
3401 << false << VD->getType();
3406 if (InitE->isValueDependent())
3409 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3410 // Wipe out any partially-computed value, to allow tracking that this
3411 // evaluation failed.
3420 /// Evaluate a condition (either a variable declaration or an expression).
3421 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3422 const Expr *Cond, bool &Result) {
3423 FullExpressionRAII Scope(Info);
3424 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3426 return EvaluateAsBooleanCondition(Cond, Result, Info);
3430 /// \brief A location where the result (returned value) of evaluating a
3431 /// statement should be stored.
3433 /// The APValue that should be filled in with the returned value.
3435 /// The location containing the result, if any (used to support RVO).
3440 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3442 const SwitchCase *SC = nullptr);
3444 /// Evaluate the body of a loop, and translate the result as appropriate.
3445 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3447 const SwitchCase *Case = nullptr) {
3448 BlockScopeRAII Scope(Info);
3449 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3451 return ESR_Succeeded;
3454 return ESR_Continue;
3457 case ESR_CaseNotFound:
3460 llvm_unreachable("Invalid EvalStmtResult!");
3463 /// Evaluate a switch statement.
3464 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3465 const SwitchStmt *SS) {
3466 BlockScopeRAII Scope(Info);
3468 // Evaluate the switch condition.
3471 FullExpressionRAII Scope(Info);
3472 if (const Stmt *Init = SS->getInit()) {
3473 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3474 if (ESR != ESR_Succeeded)
3477 if (SS->getConditionVariable() &&
3478 !EvaluateDecl(Info, SS->getConditionVariable()))
3480 if (!EvaluateInteger(SS->getCond(), Value, Info))
3484 // Find the switch case corresponding to the value of the condition.
3485 // FIXME: Cache this lookup.
3486 const SwitchCase *Found = nullptr;
3487 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3488 SC = SC->getNextSwitchCase()) {
3489 if (isa<DefaultStmt>(SC)) {
3494 const CaseStmt *CS = cast<CaseStmt>(SC);
3495 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3496 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3498 if (LHS <= Value && Value <= RHS) {
3505 return ESR_Succeeded;
3507 // Search the switch body for the switch case and evaluate it from there.
3508 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3510 return ESR_Succeeded;
3516 case ESR_CaseNotFound:
3517 // This can only happen if the switch case is nested within a statement
3518 // expression. We have no intention of supporting that.
3519 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3522 llvm_unreachable("Invalid EvalStmtResult!");
3525 // Evaluate a statement.
3526 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3527 const Stmt *S, const SwitchCase *Case) {
3528 if (!Info.nextStep(S))
3531 // If we're hunting down a 'case' or 'default' label, recurse through
3532 // substatements until we hit the label.
3534 // FIXME: We don't start the lifetime of objects whose initialization we
3535 // jump over. However, such objects must be of class type with a trivial
3536 // default constructor that initialize all subobjects, so must be empty,
3537 // so this almost never matters.
3538 switch (S->getStmtClass()) {
3539 case Stmt::CompoundStmtClass:
3540 // FIXME: Precompute which substatement of a compound statement we
3541 // would jump to, and go straight there rather than performing a
3542 // linear scan each time.
3543 case Stmt::LabelStmtClass:
3544 case Stmt::AttributedStmtClass:
3545 case Stmt::DoStmtClass:
3548 case Stmt::CaseStmtClass:
3549 case Stmt::DefaultStmtClass:
3554 case Stmt::IfStmtClass: {
3555 // FIXME: Precompute which side of an 'if' we would jump to, and go
3556 // straight there rather than scanning both sides.
3557 const IfStmt *IS = cast<IfStmt>(S);
3559 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3560 // preceded by our switch label.
3561 BlockScopeRAII Scope(Info);
3563 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3564 if (ESR != ESR_CaseNotFound || !IS->getElse())
3566 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3569 case Stmt::WhileStmtClass: {
3570 EvalStmtResult ESR =
3571 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3572 if (ESR != ESR_Continue)
3577 case Stmt::ForStmtClass: {
3578 const ForStmt *FS = cast<ForStmt>(S);
3579 EvalStmtResult ESR =
3580 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3581 if (ESR != ESR_Continue)
3584 FullExpressionRAII IncScope(Info);
3585 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3591 case Stmt::DeclStmtClass:
3592 // FIXME: If the variable has initialization that can't be jumped over,
3593 // bail out of any immediately-surrounding compound-statement too.
3595 return ESR_CaseNotFound;
3599 switch (S->getStmtClass()) {
3601 if (const Expr *E = dyn_cast<Expr>(S)) {
3602 // Don't bother evaluating beyond an expression-statement which couldn't
3604 FullExpressionRAII Scope(Info);
3605 if (!EvaluateIgnoredValue(Info, E))
3607 return ESR_Succeeded;
3610 Info.FFDiag(S->getLocStart());
3613 case Stmt::NullStmtClass:
3614 return ESR_Succeeded;
3616 case Stmt::DeclStmtClass: {
3617 const DeclStmt *DS = cast<DeclStmt>(S);
3618 for (const auto *DclIt : DS->decls()) {
3619 // Each declaration initialization is its own full-expression.
3620 // FIXME: This isn't quite right; if we're performing aggregate
3621 // initialization, each braced subexpression is its own full-expression.
3622 FullExpressionRAII Scope(Info);
3623 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3626 return ESR_Succeeded;
3629 case Stmt::ReturnStmtClass: {
3630 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3631 FullExpressionRAII Scope(Info);
3634 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3635 : Evaluate(Result.Value, Info, RetExpr)))
3637 return ESR_Returned;
3640 case Stmt::CompoundStmtClass: {
3641 BlockScopeRAII Scope(Info);
3643 const CompoundStmt *CS = cast<CompoundStmt>(S);
3644 for (const auto *BI : CS->body()) {
3645 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3646 if (ESR == ESR_Succeeded)
3648 else if (ESR != ESR_CaseNotFound)
3651 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3654 case Stmt::IfStmtClass: {
3655 const IfStmt *IS = cast<IfStmt>(S);
3657 // Evaluate the condition, as either a var decl or as an expression.
3658 BlockScopeRAII Scope(Info);
3659 if (const Stmt *Init = IS->getInit()) {
3660 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3661 if (ESR != ESR_Succeeded)
3665 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3668 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3669 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3670 if (ESR != ESR_Succeeded)
3673 return ESR_Succeeded;
3676 case Stmt::WhileStmtClass: {
3677 const WhileStmt *WS = cast<WhileStmt>(S);
3679 BlockScopeRAII Scope(Info);
3681 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3687 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3688 if (ESR != ESR_Continue)
3691 return ESR_Succeeded;
3694 case Stmt::DoStmtClass: {
3695 const DoStmt *DS = cast<DoStmt>(S);
3698 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3699 if (ESR != ESR_Continue)
3703 FullExpressionRAII CondScope(Info);
3704 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3707 return ESR_Succeeded;
3710 case Stmt::ForStmtClass: {
3711 const ForStmt *FS = cast<ForStmt>(S);
3712 BlockScopeRAII Scope(Info);
3713 if (FS->getInit()) {
3714 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3715 if (ESR != ESR_Succeeded)
3719 BlockScopeRAII Scope(Info);
3720 bool Continue = true;
3721 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3722 FS->getCond(), Continue))
3727 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3728 if (ESR != ESR_Continue)
3732 FullExpressionRAII IncScope(Info);
3733 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3737 return ESR_Succeeded;
3740 case Stmt::CXXForRangeStmtClass: {
3741 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3742 BlockScopeRAII Scope(Info);
3744 // Initialize the __range variable.
3745 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3746 if (ESR != ESR_Succeeded)
3749 // Create the __begin and __end iterators.
3750 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3751 if (ESR != ESR_Succeeded)
3753 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3754 if (ESR != ESR_Succeeded)
3758 // Condition: __begin != __end.
3760 bool Continue = true;
3761 FullExpressionRAII CondExpr(Info);
3762 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3768 // User's variable declaration, initialized by *__begin.
3769 BlockScopeRAII InnerScope(Info);
3770 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3771 if (ESR != ESR_Succeeded)
3775 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3776 if (ESR != ESR_Continue)
3779 // Increment: ++__begin
3780 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3784 return ESR_Succeeded;
3787 case Stmt::SwitchStmtClass:
3788 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3790 case Stmt::ContinueStmtClass:
3791 return ESR_Continue;
3793 case Stmt::BreakStmtClass:
3796 case Stmt::LabelStmtClass:
3797 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3799 case Stmt::AttributedStmtClass:
3800 // As a general principle, C++11 attributes can be ignored without
3801 // any semantic impact.
3802 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3805 case Stmt::CaseStmtClass:
3806 case Stmt::DefaultStmtClass:
3807 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3811 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3812 /// default constructor. If so, we'll fold it whether or not it's marked as
3813 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3814 /// so we need special handling.
3815 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3816 const CXXConstructorDecl *CD,
3817 bool IsValueInitialization) {
3818 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3821 // Value-initialization does not call a trivial default constructor, so such a
3822 // call is a core constant expression whether or not the constructor is
3824 if (!CD->isConstexpr() && !IsValueInitialization) {
3825 if (Info.getLangOpts().CPlusPlus11) {
3826 // FIXME: If DiagDecl is an implicitly-declared special member function,
3827 // we should be much more explicit about why it's not constexpr.
3828 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3829 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3830 Info.Note(CD->getLocation(), diag::note_declared_at);
3832 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3838 /// CheckConstexprFunction - Check that a function can be called in a constant
3840 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3841 const FunctionDecl *Declaration,
3842 const FunctionDecl *Definition,
3844 // Potential constant expressions can contain calls to declared, but not yet
3845 // defined, constexpr functions.
3846 if (Info.checkingPotentialConstantExpression() && !Definition &&
3847 Declaration->isConstexpr())
3850 // Bail out with no diagnostic if the function declaration itself is invalid.
3851 // We will have produced a relevant diagnostic while parsing it.
3852 if (Declaration->isInvalidDecl())
3855 // Can we evaluate this function call?
3856 if (Definition && Definition->isConstexpr() &&
3857 !Definition->isInvalidDecl() && Body)
3860 if (Info.getLangOpts().CPlusPlus11) {
3861 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3863 // If this function is not constexpr because it is an inherited
3864 // non-constexpr constructor, diagnose that directly.
3865 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3866 if (CD && CD->isInheritingConstructor()) {
3867 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3868 if (!Inherited->isConstexpr())
3869 DiagDecl = CD = Inherited;
3872 // FIXME: If DiagDecl is an implicitly-declared special member function
3873 // or an inheriting constructor, we should be much more explicit about why
3874 // it's not constexpr.
3875 if (CD && CD->isInheritingConstructor())
3876 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
3877 << CD->getInheritedConstructor().getConstructor()->getParent();
3879 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
3880 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
3881 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3883 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3888 /// Determine if a class has any fields that might need to be copied by a
3889 /// trivial copy or move operation.
3890 static bool hasFields(const CXXRecordDecl *RD) {
3891 if (!RD || RD->isEmpty())
3893 for (auto *FD : RD->fields()) {
3894 if (FD->isUnnamedBitfield())
3898 for (auto &Base : RD->bases())
3899 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3905 typedef SmallVector<APValue, 8> ArgVector;
3908 /// EvaluateArgs - Evaluate the arguments to a function call.
3909 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3911 bool Success = true;
3912 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3914 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3915 // If we're checking for a potential constant expression, evaluate all
3916 // initializers even if some of them fail.
3917 if (!Info.noteFailure())
3925 /// Evaluate a function call.
3926 static bool HandleFunctionCall(SourceLocation CallLoc,
3927 const FunctionDecl *Callee, const LValue *This,
3928 ArrayRef<const Expr*> Args, const Stmt *Body,
3929 EvalInfo &Info, APValue &Result,
3930 const LValue *ResultSlot) {
3931 ArgVector ArgValues(Args.size());
3932 if (!EvaluateArgs(Args, ArgValues, Info))
3935 if (!Info.CheckCallLimit(CallLoc))
3938 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3940 // For a trivial copy or move assignment, perform an APValue copy. This is
3941 // essential for unions, where the operations performed by the assignment
3942 // operator cannot be represented as statements.
3944 // Skip this for non-union classes with no fields; in that case, the defaulted
3945 // copy/move does not actually read the object.
3946 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3947 if (MD && MD->isDefaulted() &&
3948 (MD->getParent()->isUnion() ||
3949 (MD->isTrivial() && hasFields(MD->getParent())))) {
3951 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3953 RHS.setFrom(Info.Ctx, ArgValues[0]);
3955 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3958 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3961 This->moveInto(Result);
3965 StmtResult Ret = {Result, ResultSlot};
3966 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
3967 if (ESR == ESR_Succeeded) {
3968 if (Callee->getReturnType()->isVoidType())
3970 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3972 return ESR == ESR_Returned;
3975 /// Evaluate a constructor call.
3976 static bool HandleConstructorCall(const Expr *E, const LValue &This,
3978 const CXXConstructorDecl *Definition,
3979 EvalInfo &Info, APValue &Result) {
3980 SourceLocation CallLoc = E->getExprLoc();
3981 if (!Info.CheckCallLimit(CallLoc))
3984 const CXXRecordDecl *RD = Definition->getParent();
3985 if (RD->getNumVBases()) {
3986 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3990 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
3992 // FIXME: Creating an APValue just to hold a nonexistent return value is
3995 StmtResult Ret = {RetVal, nullptr};
3997 // If it's a delegating constructor, delegate.
3998 if (Definition->isDelegatingConstructor()) {
3999 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4001 FullExpressionRAII InitScope(Info);
4002 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4005 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4008 // For a trivial copy or move constructor, perform an APValue copy. This is
4009 // essential for unions (or classes with anonymous union members), where the
4010 // operations performed by the constructor cannot be represented by
4011 // ctor-initializers.
4013 // Skip this for empty non-union classes; we should not perform an
4014 // lvalue-to-rvalue conversion on them because their copy constructor does not
4015 // actually read them.
4016 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4017 (Definition->getParent()->isUnion() ||
4018 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4020 RHS.setFrom(Info.Ctx, ArgValues[0]);
4021 return handleLValueToRValueConversion(
4022 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4026 // Reserve space for the struct members.
4027 if (!RD->isUnion() && Result.isUninit())
4028 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4029 std::distance(RD->field_begin(), RD->field_end()));
4031 if (RD->isInvalidDecl()) return false;
4032 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4034 // A scope for temporaries lifetime-extended by reference members.
4035 BlockScopeRAII LifetimeExtendedScope(Info);
4037 bool Success = true;
4038 unsigned BasesSeen = 0;
4040 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4042 for (const auto *I : Definition->inits()) {
4043 LValue Subobject = This;
4044 APValue *Value = &Result;
4046 // Determine the subobject to initialize.
4047 FieldDecl *FD = nullptr;
4048 if (I->isBaseInitializer()) {
4049 QualType BaseType(I->getBaseClass(), 0);
4051 // Non-virtual base classes are initialized in the order in the class
4052 // definition. We have already checked for virtual base classes.
4053 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4054 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4055 "base class initializers not in expected order");
4058 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4059 BaseType->getAsCXXRecordDecl(), &Layout))
4061 Value = &Result.getStructBase(BasesSeen++);
4062 } else if ((FD = I->getMember())) {
4063 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4065 if (RD->isUnion()) {
4066 Result = APValue(FD);
4067 Value = &Result.getUnionValue();
4069 Value = &Result.getStructField(FD->getFieldIndex());
4071 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4072 // Walk the indirect field decl's chain to find the object to initialize,
4073 // and make sure we've initialized every step along it.
4074 for (auto *C : IFD->chain()) {
4075 FD = cast<FieldDecl>(C);
4076 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4077 // Switch the union field if it differs. This happens if we had
4078 // preceding zero-initialization, and we're now initializing a union
4079 // subobject other than the first.
4080 // FIXME: In this case, the values of the other subobjects are
4081 // specified, since zero-initialization sets all padding bits to zero.
4082 if (Value->isUninit() ||
4083 (Value->isUnion() && Value->getUnionField() != FD)) {
4085 *Value = APValue(FD);
4087 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4088 std::distance(CD->field_begin(), CD->field_end()));
4090 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4093 Value = &Value->getUnionValue();
4095 Value = &Value->getStructField(FD->getFieldIndex());
4098 llvm_unreachable("unknown base initializer kind");
4101 FullExpressionRAII InitScope(Info);
4102 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4103 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4105 // If we're checking for a potential constant expression, evaluate all
4106 // initializers even if some of them fail.
4107 if (!Info.noteFailure())
4114 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4117 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4118 ArrayRef<const Expr*> Args,
4119 const CXXConstructorDecl *Definition,
4120 EvalInfo &Info, APValue &Result) {
4121 ArgVector ArgValues(Args.size());
4122 if (!EvaluateArgs(Args, ArgValues, Info))
4125 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4129 //===----------------------------------------------------------------------===//
4130 // Generic Evaluation
4131 //===----------------------------------------------------------------------===//
4134 template <class Derived>
4135 class ExprEvaluatorBase
4136 : public ConstStmtVisitor<Derived, bool> {
4138 Derived &getDerived() { return static_cast<Derived&>(*this); }
4139 bool DerivedSuccess(const APValue &V, const Expr *E) {
4140 return getDerived().Success(V, E);
4142 bool DerivedZeroInitialization(const Expr *E) {
4143 return getDerived().ZeroInitialization(E);
4146 // Check whether a conditional operator with a non-constant condition is a
4147 // potential constant expression. If neither arm is a potential constant
4148 // expression, then the conditional operator is not either.
4149 template<typename ConditionalOperator>
4150 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4151 assert(Info.checkingPotentialConstantExpression());
4153 // Speculatively evaluate both arms.
4154 SmallVector<PartialDiagnosticAt, 8> Diag;
4156 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4157 StmtVisitorTy::Visit(E->getFalseExpr());
4163 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4165 StmtVisitorTy::Visit(E->getTrueExpr());
4170 Error(E, diag::note_constexpr_conditional_never_const);
4174 template<typename ConditionalOperator>
4175 bool HandleConditionalOperator(const ConditionalOperator *E) {
4177 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4178 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4179 CheckPotentialConstantConditional(E);
4183 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4184 return StmtVisitorTy::Visit(EvalExpr);
4189 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4190 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4192 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4193 return Info.CCEDiag(E, D);
4196 bool ZeroInitialization(const Expr *E) { return Error(E); }
4199 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4201 EvalInfo &getEvalInfo() { return Info; }
4203 /// Report an evaluation error. This should only be called when an error is
4204 /// first discovered. When propagating an error, just return false.
4205 bool Error(const Expr *E, diag::kind D) {
4209 bool Error(const Expr *E) {
4210 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4213 bool VisitStmt(const Stmt *) {
4214 llvm_unreachable("Expression evaluator should not be called on stmts");
4216 bool VisitExpr(const Expr *E) {
4220 bool VisitParenExpr(const ParenExpr *E)
4221 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4222 bool VisitUnaryExtension(const UnaryOperator *E)
4223 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4224 bool VisitUnaryPlus(const UnaryOperator *E)
4225 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4226 bool VisitChooseExpr(const ChooseExpr *E)
4227 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4228 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4229 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4230 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4231 { return StmtVisitorTy::Visit(E->getReplacement()); }
4232 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4233 { return StmtVisitorTy::Visit(E->getExpr()); }
4234 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4235 // The initializer may not have been parsed yet, or might be erroneous.
4238 return StmtVisitorTy::Visit(E->getExpr());
4240 // We cannot create any objects for which cleanups are required, so there is
4241 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4242 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4243 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4245 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4246 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4247 return static_cast<Derived*>(this)->VisitCastExpr(E);
4249 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4250 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4251 return static_cast<Derived*>(this)->VisitCastExpr(E);
4254 bool VisitBinaryOperator(const BinaryOperator *E) {
4255 switch (E->getOpcode()) {
4260 VisitIgnoredValue(E->getLHS());
4261 return StmtVisitorTy::Visit(E->getRHS());
4266 if (!HandleMemberPointerAccess(Info, E, Obj))
4269 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4271 return DerivedSuccess(Result, E);
4276 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4277 // Evaluate and cache the common expression. We treat it as a temporary,
4278 // even though it's not quite the same thing.
4279 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4280 Info, E->getCommon()))
4283 return HandleConditionalOperator(E);
4286 bool VisitConditionalOperator(const ConditionalOperator *E) {
4287 bool IsBcpCall = false;
4288 // If the condition (ignoring parens) is a __builtin_constant_p call,
4289 // the result is a constant expression if it can be folded without
4290 // side-effects. This is an important GNU extension. See GCC PR38377
4292 if (const CallExpr *CallCE =
4293 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4294 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4297 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4298 // constant expression; we can't check whether it's potentially foldable.
4299 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4302 FoldConstant Fold(Info, IsBcpCall);
4303 if (!HandleConditionalOperator(E)) {
4304 Fold.keepDiagnostics();
4311 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4312 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4313 return DerivedSuccess(*Value, E);
4315 const Expr *Source = E->getSourceExpr();
4318 if (Source == E) { // sanity checking.
4319 assert(0 && "OpaqueValueExpr recursively refers to itself");
4322 return StmtVisitorTy::Visit(Source);
4325 bool VisitCallExpr(const CallExpr *E) {
4327 if (!handleCallExpr(E, Result, nullptr))
4329 return DerivedSuccess(Result, E);
4332 bool handleCallExpr(const CallExpr *E, APValue &Result,
4333 const LValue *ResultSlot) {
4334 const Expr *Callee = E->getCallee()->IgnoreParens();
4335 QualType CalleeType = Callee->getType();
4337 const FunctionDecl *FD = nullptr;
4338 LValue *This = nullptr, ThisVal;
4339 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4340 bool HasQualifier = false;
4342 // Extract function decl and 'this' pointer from the callee.
4343 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4344 const ValueDecl *Member = nullptr;
4345 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4346 // Explicit bound member calls, such as x.f() or p->g();
4347 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4349 Member = ME->getMemberDecl();
4351 HasQualifier = ME->hasQualifier();
4352 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4353 // Indirect bound member calls ('.*' or '->*').
4354 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4355 if (!Member) return false;
4358 return Error(Callee);
4360 FD = dyn_cast<FunctionDecl>(Member);
4362 return Error(Callee);
4363 } else if (CalleeType->isFunctionPointerType()) {
4365 if (!EvaluatePointer(Callee, Call, Info))
4368 if (!Call.getLValueOffset().isZero())
4369 return Error(Callee);
4370 FD = dyn_cast_or_null<FunctionDecl>(
4371 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4373 return Error(Callee);
4375 // Overloaded operator calls to member functions are represented as normal
4376 // calls with '*this' as the first argument.
4377 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4378 if (MD && !MD->isStatic()) {
4379 // FIXME: When selecting an implicit conversion for an overloaded
4380 // operator delete, we sometimes try to evaluate calls to conversion
4381 // operators without a 'this' parameter!
4385 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4388 Args = Args.slice(1);
4391 // Don't call function pointers which have been cast to some other type.
4392 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
4397 if (This && !This->checkSubobject(Info, E, CSK_This))
4400 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4401 // calls to such functions in constant expressions.
4402 if (This && !HasQualifier &&
4403 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4404 return Error(E, diag::note_constexpr_virtual_call);
4406 const FunctionDecl *Definition = nullptr;
4407 Stmt *Body = FD->getBody(Definition);
4409 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4410 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4411 Result, ResultSlot))
4417 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4418 return StmtVisitorTy::Visit(E->getInitializer());
4420 bool VisitInitListExpr(const InitListExpr *E) {
4421 if (E->getNumInits() == 0)
4422 return DerivedZeroInitialization(E);
4423 if (E->getNumInits() == 1)
4424 return StmtVisitorTy::Visit(E->getInit(0));
4427 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4428 return DerivedZeroInitialization(E);
4430 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4431 return DerivedZeroInitialization(E);
4433 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4434 return DerivedZeroInitialization(E);
4437 /// A member expression where the object is a prvalue is itself a prvalue.
4438 bool VisitMemberExpr(const MemberExpr *E) {
4439 assert(!E->isArrow() && "missing call to bound member function?");
4442 if (!Evaluate(Val, Info, E->getBase()))
4445 QualType BaseTy = E->getBase()->getType();
4447 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4448 if (!FD) return Error(E);
4449 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4450 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4451 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4453 CompleteObject Obj(&Val, BaseTy);
4454 SubobjectDesignator Designator(BaseTy);
4455 Designator.addDeclUnchecked(FD);
4458 return extractSubobject(Info, E, Obj, Designator, Result) &&
4459 DerivedSuccess(Result, E);
4462 bool VisitCastExpr(const CastExpr *E) {
4463 switch (E->getCastKind()) {
4467 case CK_AtomicToNonAtomic: {
4469 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4471 return DerivedSuccess(AtomicVal, E);
4475 case CK_UserDefinedConversion:
4476 return StmtVisitorTy::Visit(E->getSubExpr());
4478 case CK_LValueToRValue: {
4480 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4483 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4484 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4487 return DerivedSuccess(RVal, E);
4494 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4495 return VisitUnaryPostIncDec(UO);
4497 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4498 return VisitUnaryPostIncDec(UO);
4500 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4501 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4505 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4508 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4509 UO->isIncrementOp(), &RVal))
4511 return DerivedSuccess(RVal, UO);
4514 bool VisitStmtExpr(const StmtExpr *E) {
4515 // We will have checked the full-expressions inside the statement expression
4516 // when they were completed, and don't need to check them again now.
4517 if (Info.checkingForOverflow())
4520 BlockScopeRAII Scope(Info);
4521 const CompoundStmt *CS = E->getSubStmt();
4522 if (CS->body_empty())
4525 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4526 BE = CS->body_end();
4529 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4531 Info.FFDiag((*BI)->getLocStart(),
4532 diag::note_constexpr_stmt_expr_unsupported);
4535 return this->Visit(FinalExpr);
4538 APValue ReturnValue;
4539 StmtResult Result = { ReturnValue, nullptr };
4540 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4541 if (ESR != ESR_Succeeded) {
4542 // FIXME: If the statement-expression terminated due to 'return',
4543 // 'break', or 'continue', it would be nice to propagate that to
4544 // the outer statement evaluation rather than bailing out.
4545 if (ESR != ESR_Failed)
4546 Info.FFDiag((*BI)->getLocStart(),
4547 diag::note_constexpr_stmt_expr_unsupported);
4552 llvm_unreachable("Return from function from the loop above.");
4555 /// Visit a value which is evaluated, but whose value is ignored.
4556 void VisitIgnoredValue(const Expr *E) {
4557 EvaluateIgnoredValue(Info, E);
4560 /// Potentially visit a MemberExpr's base expression.
4561 void VisitIgnoredBaseExpression(const Expr *E) {
4562 // While MSVC doesn't evaluate the base expression, it does diagnose the
4563 // presence of side-effecting behavior.
4564 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4566 VisitIgnoredValue(E);
4572 //===----------------------------------------------------------------------===//
4573 // Common base class for lvalue and temporary evaluation.
4574 //===----------------------------------------------------------------------===//
4576 template<class Derived>
4577 class LValueExprEvaluatorBase
4578 : public ExprEvaluatorBase<Derived> {
4581 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4582 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4584 bool Success(APValue::LValueBase B) {
4590 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4591 ExprEvaluatorBaseTy(Info), Result(Result) {}
4593 bool Success(const APValue &V, const Expr *E) {
4594 Result.setFrom(this->Info.Ctx, V);
4598 bool VisitMemberExpr(const MemberExpr *E) {
4599 // Handle non-static data members.
4603 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
4604 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4605 } else if (E->getBase()->isRValue()) {
4606 assert(E->getBase()->getType()->isRecordType());
4607 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4608 BaseTy = E->getBase()->getType();
4610 EvalOK = this->Visit(E->getBase());
4611 BaseTy = E->getBase()->getType();
4614 if (!this->Info.allowInvalidBaseExpr())
4616 Result.setInvalid(E);
4620 const ValueDecl *MD = E->getMemberDecl();
4621 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4622 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4623 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4625 if (!HandleLValueMember(this->Info, E, Result, FD))
4627 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4628 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4631 return this->Error(E);
4633 if (MD->getType()->isReferenceType()) {
4635 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4638 return Success(RefValue, E);
4643 bool VisitBinaryOperator(const BinaryOperator *E) {
4644 switch (E->getOpcode()) {
4646 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4650 return HandleMemberPointerAccess(this->Info, E, Result);
4654 bool VisitCastExpr(const CastExpr *E) {
4655 switch (E->getCastKind()) {
4657 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4659 case CK_DerivedToBase:
4660 case CK_UncheckedDerivedToBase:
4661 if (!this->Visit(E->getSubExpr()))
4664 // Now figure out the necessary offset to add to the base LV to get from
4665 // the derived class to the base class.
4666 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4673 //===----------------------------------------------------------------------===//
4674 // LValue Evaluation
4676 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4677 // function designators (in C), decl references to void objects (in C), and
4678 // temporaries (if building with -Wno-address-of-temporary).
4680 // LValue evaluation produces values comprising a base expression of one of the
4686 // * CompoundLiteralExpr in C
4690 // * ObjCStringLiteralExpr
4694 // * CallExpr for a MakeStringConstant builtin
4695 // - Locals and temporaries
4696 // * MaterializeTemporaryExpr
4697 // * Any Expr, with a CallIndex indicating the function in which the temporary
4698 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4699 // from the AST (FIXME).
4700 // * A MaterializeTemporaryExpr that has static storage duration, with no
4701 // CallIndex, for a lifetime-extended temporary.
4702 // plus an offset in bytes.
4703 //===----------------------------------------------------------------------===//
4705 class LValueExprEvaluator
4706 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4708 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4709 LValueExprEvaluatorBaseTy(Info, Result) {}
4711 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4712 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4714 bool VisitDeclRefExpr(const DeclRefExpr *E);
4715 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4716 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4717 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4718 bool VisitMemberExpr(const MemberExpr *E);
4719 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4720 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4721 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4722 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4723 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4724 bool VisitUnaryDeref(const UnaryOperator *E);
4725 bool VisitUnaryReal(const UnaryOperator *E);
4726 bool VisitUnaryImag(const UnaryOperator *E);
4727 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4728 return VisitUnaryPreIncDec(UO);
4730 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4731 return VisitUnaryPreIncDec(UO);
4733 bool VisitBinAssign(const BinaryOperator *BO);
4734 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4736 bool VisitCastExpr(const CastExpr *E) {
4737 switch (E->getCastKind()) {
4739 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4741 case CK_LValueBitCast:
4742 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4743 if (!Visit(E->getSubExpr()))
4745 Result.Designator.setInvalid();
4748 case CK_BaseToDerived:
4749 if (!Visit(E->getSubExpr()))
4751 return HandleBaseToDerivedCast(Info, E, Result);
4755 } // end anonymous namespace
4757 /// Evaluate an expression as an lvalue. This can be legitimately called on
4758 /// expressions which are not glvalues, in three cases:
4759 /// * function designators in C, and
4760 /// * "extern void" objects
4761 /// * @selector() expressions in Objective-C
4762 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4763 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4764 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4765 return LValueExprEvaluator(Info, Result).Visit(E);
4768 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4769 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4771 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4772 return VisitVarDecl(E, VD);
4776 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4777 CallStackFrame *Frame = nullptr;
4778 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4779 Frame = Info.CurrentCall;
4781 if (!VD->getType()->isReferenceType()) {
4783 Result.set(VD, Frame->Index);
4790 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4792 if (V->isUninit()) {
4793 if (!Info.checkingPotentialConstantExpression())
4794 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
4797 return Success(*V, E);
4800 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4801 const MaterializeTemporaryExpr *E) {
4802 // Walk through the expression to find the materialized temporary itself.
4803 SmallVector<const Expr *, 2> CommaLHSs;
4804 SmallVector<SubobjectAdjustment, 2> Adjustments;
4805 const Expr *Inner = E->GetTemporaryExpr()->
4806 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4808 // If we passed any comma operators, evaluate their LHSs.
4809 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4810 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4813 // A materialized temporary with static storage duration can appear within the
4814 // result of a constant expression evaluation, so we need to preserve its
4815 // value for use outside this evaluation.
4817 if (E->getStorageDuration() == SD_Static) {
4818 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4822 Value = &Info.CurrentCall->
4823 createTemporary(E, E->getStorageDuration() == SD_Automatic);
4824 Result.set(E, Info.CurrentCall->Index);
4827 QualType Type = Inner->getType();
4829 // Materialize the temporary itself.
4830 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4831 (E->getStorageDuration() == SD_Static &&
4832 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4837 // Adjust our lvalue to refer to the desired subobject.
4838 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4840 switch (Adjustments[I].Kind) {
4841 case SubobjectAdjustment::DerivedToBaseAdjustment:
4842 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4845 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4848 case SubobjectAdjustment::FieldAdjustment:
4849 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4851 Type = Adjustments[I].Field->getType();
4854 case SubobjectAdjustment::MemberPointerAdjustment:
4855 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4856 Adjustments[I].Ptr.RHS))
4858 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4867 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4868 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4869 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4870 // only see this when folding in C, so there's no standard to follow here.
4874 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4875 if (!E->isPotentiallyEvaluated())
4878 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
4879 << E->getExprOperand()->getType()
4880 << E->getExprOperand()->getSourceRange();
4884 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4888 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4889 // Handle static data members.
4890 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4891 VisitIgnoredBaseExpression(E->getBase());
4892 return VisitVarDecl(E, VD);
4895 // Handle static member functions.
4896 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4897 if (MD->isStatic()) {
4898 VisitIgnoredBaseExpression(E->getBase());
4903 // Handle non-static data members.
4904 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4907 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4908 // FIXME: Deal with vectors as array subscript bases.
4909 if (E->getBase()->getType()->isVectorType())
4912 if (!EvaluatePointer(E->getBase(), Result, Info))
4916 if (!EvaluateInteger(E->getIdx(), Index, Info))
4919 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4920 getExtValue(Index));
4923 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4924 return EvaluatePointer(E->getSubExpr(), Result, Info);
4927 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4928 if (!Visit(E->getSubExpr()))
4930 // __real is a no-op on scalar lvalues.
4931 if (E->getSubExpr()->getType()->isAnyComplexType())
4932 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4936 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4937 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4938 "lvalue __imag__ on scalar?");
4939 if (!Visit(E->getSubExpr()))
4941 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4945 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4946 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4949 if (!this->Visit(UO->getSubExpr()))
4952 return handleIncDec(
4953 this->Info, UO, Result, UO->getSubExpr()->getType(),
4954 UO->isIncrementOp(), nullptr);
4957 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4958 const CompoundAssignOperator *CAO) {
4959 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4964 // The overall lvalue result is the result of evaluating the LHS.
4965 if (!this->Visit(CAO->getLHS())) {
4966 if (Info.noteFailure())
4967 Evaluate(RHS, this->Info, CAO->getRHS());
4971 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4974 return handleCompoundAssignment(
4976 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4977 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4980 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4981 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4986 if (!this->Visit(E->getLHS())) {
4987 if (Info.noteFailure())
4988 Evaluate(NewVal, this->Info, E->getRHS());
4992 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4995 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4999 //===----------------------------------------------------------------------===//
5000 // Pointer Evaluation
5001 //===----------------------------------------------------------------------===//
5004 class PointerExprEvaluator
5005 : public ExprEvaluatorBase<PointerExprEvaluator> {
5008 bool Success(const Expr *E) {
5014 PointerExprEvaluator(EvalInfo &info, LValue &Result)
5015 : ExprEvaluatorBaseTy(info), Result(Result) {}
5017 bool Success(const APValue &V, const Expr *E) {
5018 Result.setFrom(Info.Ctx, V);
5021 bool ZeroInitialization(const Expr *E) {
5022 return Success((Expr*)nullptr);
5025 bool VisitBinaryOperator(const BinaryOperator *E);
5026 bool VisitCastExpr(const CastExpr* E);
5027 bool VisitUnaryAddrOf(const UnaryOperator *E);
5028 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5029 { return Success(E); }
5030 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5031 { return Success(E); }
5032 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5033 { return Success(E); }
5034 bool VisitCallExpr(const CallExpr *E);
5035 bool VisitBlockExpr(const BlockExpr *E) {
5036 if (!E->getBlockDecl()->hasCaptures())
5040 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5041 // Can't look at 'this' when checking a potential constant expression.
5042 if (Info.checkingPotentialConstantExpression())
5044 if (!Info.CurrentCall->This) {
5045 if (Info.getLangOpts().CPlusPlus11)
5046 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5051 Result = *Info.CurrentCall->This;
5055 // FIXME: Missing: @protocol, @selector
5057 } // end anonymous namespace
5059 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
5060 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5061 return PointerExprEvaluator(Info, Result).Visit(E);
5064 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5065 if (E->getOpcode() != BO_Add &&
5066 E->getOpcode() != BO_Sub)
5067 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5069 const Expr *PExp = E->getLHS();
5070 const Expr *IExp = E->getRHS();
5071 if (IExp->getType()->isPointerType())
5072 std::swap(PExp, IExp);
5074 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
5075 if (!EvalPtrOK && !Info.noteFailure())
5078 llvm::APSInt Offset;
5079 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5082 int64_t AdditionalOffset = getExtValue(Offset);
5083 if (E->getOpcode() == BO_Sub)
5084 AdditionalOffset = -AdditionalOffset;
5086 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5087 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5091 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5092 return EvaluateLValue(E->getSubExpr(), Result, Info);
5095 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5096 const Expr* SubExpr = E->getSubExpr();
5098 switch (E->getCastKind()) {
5103 case CK_CPointerToObjCPointerCast:
5104 case CK_BlockPointerToObjCPointerCast:
5105 case CK_AnyPointerToBlockPointerCast:
5106 case CK_AddressSpaceConversion:
5107 if (!Visit(SubExpr))
5109 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5110 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5111 // also static_casts, but we disallow them as a resolution to DR1312.
5112 if (!E->getType()->isVoidPointerType()) {
5113 Result.Designator.setInvalid();
5114 if (SubExpr->getType()->isVoidPointerType())
5115 CCEDiag(E, diag::note_constexpr_invalid_cast)
5116 << 3 << SubExpr->getType();
5118 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5122 case CK_DerivedToBase:
5123 case CK_UncheckedDerivedToBase:
5124 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
5126 if (!Result.Base && Result.Offset.isZero())
5129 // Now figure out the necessary offset to add to the base LV to get from
5130 // the derived class to the base class.
5131 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5132 castAs<PointerType>()->getPointeeType(),
5135 case CK_BaseToDerived:
5136 if (!Visit(E->getSubExpr()))
5138 if (!Result.Base && Result.Offset.isZero())
5140 return HandleBaseToDerivedCast(Info, E, Result);
5142 case CK_NullToPointer:
5143 VisitIgnoredValue(E->getSubExpr());
5144 return ZeroInitialization(E);
5146 case CK_IntegralToPointer: {
5147 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5150 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5153 if (Value.isInt()) {
5154 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5155 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5156 Result.Base = (Expr*)nullptr;
5157 Result.InvalidBase = false;
5158 Result.Offset = CharUnits::fromQuantity(N);
5159 Result.CallIndex = 0;
5160 Result.Designator.setInvalid();
5163 // Cast is of an lvalue, no need to change value.
5164 Result.setFrom(Info.Ctx, Value);
5168 case CK_ArrayToPointerDecay:
5169 if (SubExpr->isGLValue()) {
5170 if (!EvaluateLValue(SubExpr, Result, Info))
5173 Result.set(SubExpr, Info.CurrentCall->Index);
5174 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5175 Info, Result, SubExpr))
5178 // The result is a pointer to the first element of the array.
5179 if (const ConstantArrayType *CAT
5180 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5181 Result.addArray(Info, E, CAT);
5183 Result.Designator.setInvalid();
5186 case CK_FunctionToPointerDecay:
5187 return EvaluateLValue(SubExpr, Result, Info);
5190 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5193 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5194 // C++ [expr.alignof]p3:
5195 // When alignof is applied to a reference type, the result is the
5196 // alignment of the referenced type.
5197 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5198 T = Ref->getPointeeType();
5200 // __alignof is defined to return the preferred alignment.
5201 return Info.Ctx.toCharUnitsFromBits(
5202 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5205 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5206 E = E->IgnoreParens();
5208 // The kinds of expressions that we have special-case logic here for
5209 // should be kept up to date with the special checks for those
5210 // expressions in Sema.
5212 // alignof decl is always accepted, even if it doesn't make sense: we default
5213 // to 1 in those cases.
5214 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5215 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5216 /*RefAsPointee*/true);
5218 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5219 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5220 /*RefAsPointee*/true);
5222 return GetAlignOfType(Info, E->getType());
5225 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5226 if (IsStringLiteralCall(E))
5229 switch (E->getBuiltinCallee()) {
5230 case Builtin::BI__builtin_addressof:
5231 return EvaluateLValue(E->getArg(0), Result, Info);
5232 case Builtin::BI__builtin_assume_aligned: {
5233 // We need to be very careful here because: if the pointer does not have the
5234 // asserted alignment, then the behavior is undefined, and undefined
5235 // behavior is non-constant.
5236 if (!EvaluatePointer(E->getArg(0), Result, Info))
5239 LValue OffsetResult(Result);
5241 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5243 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5245 if (E->getNumArgs() > 2) {
5247 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5250 int64_t AdditionalOffset = -getExtValue(Offset);
5251 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5254 // If there is a base object, then it must have the correct alignment.
5255 if (OffsetResult.Base) {
5256 CharUnits BaseAlignment;
5257 if (const ValueDecl *VD =
5258 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5259 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5262 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5265 if (BaseAlignment < Align) {
5266 Result.Designator.setInvalid();
5267 // FIXME: Quantities here cast to integers because the plural modifier
5268 // does not work on APSInts yet.
5269 CCEDiag(E->getArg(0),
5270 diag::note_constexpr_baa_insufficient_alignment) << 0
5271 << (int) BaseAlignment.getQuantity()
5272 << (unsigned) getExtValue(Alignment);
5277 // The offset must also have the correct alignment.
5278 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5279 Result.Designator.setInvalid();
5280 APSInt Offset(64, false);
5281 Offset = OffsetResult.Offset.getQuantity();
5283 if (OffsetResult.Base)
5284 CCEDiag(E->getArg(0),
5285 diag::note_constexpr_baa_insufficient_alignment) << 1
5286 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5288 CCEDiag(E->getArg(0),
5289 diag::note_constexpr_baa_value_insufficient_alignment)
5290 << Offset << (unsigned) getExtValue(Alignment);
5298 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5302 //===----------------------------------------------------------------------===//
5303 // Member Pointer Evaluation
5304 //===----------------------------------------------------------------------===//
5307 class MemberPointerExprEvaluator
5308 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5311 bool Success(const ValueDecl *D) {
5312 Result = MemberPtr(D);
5317 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5318 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5320 bool Success(const APValue &V, const Expr *E) {
5324 bool ZeroInitialization(const Expr *E) {
5325 return Success((const ValueDecl*)nullptr);
5328 bool VisitCastExpr(const CastExpr *E);
5329 bool VisitUnaryAddrOf(const UnaryOperator *E);
5331 } // end anonymous namespace
5333 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5335 assert(E->isRValue() && E->getType()->isMemberPointerType());
5336 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5339 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5340 switch (E->getCastKind()) {
5342 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5344 case CK_NullToMemberPointer:
5345 VisitIgnoredValue(E->getSubExpr());
5346 return ZeroInitialization(E);
5348 case CK_BaseToDerivedMemberPointer: {
5349 if (!Visit(E->getSubExpr()))
5351 if (E->path_empty())
5353 // Base-to-derived member pointer casts store the path in derived-to-base
5354 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5355 // the wrong end of the derived->base arc, so stagger the path by one class.
5356 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5357 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5358 PathI != PathE; ++PathI) {
5359 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5360 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5361 if (!Result.castToDerived(Derived))
5364 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5365 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5370 case CK_DerivedToBaseMemberPointer:
5371 if (!Visit(E->getSubExpr()))
5373 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5374 PathE = E->path_end(); PathI != PathE; ++PathI) {
5375 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5376 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5377 if (!Result.castToBase(Base))
5384 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5385 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5386 // member can be formed.
5387 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5390 //===----------------------------------------------------------------------===//
5391 // Record Evaluation
5392 //===----------------------------------------------------------------------===//
5395 class RecordExprEvaluator
5396 : public ExprEvaluatorBase<RecordExprEvaluator> {
5401 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5402 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5404 bool Success(const APValue &V, const Expr *E) {
5408 bool ZeroInitialization(const Expr *E) {
5409 return ZeroInitialization(E, E->getType());
5411 bool ZeroInitialization(const Expr *E, QualType T);
5413 bool VisitCallExpr(const CallExpr *E) {
5414 return handleCallExpr(E, Result, &This);
5416 bool VisitCastExpr(const CastExpr *E);
5417 bool VisitInitListExpr(const InitListExpr *E);
5418 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5419 return VisitCXXConstructExpr(E, E->getType());
5421 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
5422 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
5423 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5427 /// Perform zero-initialization on an object of non-union class type.
5428 /// C++11 [dcl.init]p5:
5429 /// To zero-initialize an object or reference of type T means:
5431 /// -- if T is a (possibly cv-qualified) non-union class type,
5432 /// each non-static data member and each base-class subobject is
5433 /// zero-initialized
5434 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5435 const RecordDecl *RD,
5436 const LValue &This, APValue &Result) {
5437 assert(!RD->isUnion() && "Expected non-union class type");
5438 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5439 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5440 std::distance(RD->field_begin(), RD->field_end()));
5442 if (RD->isInvalidDecl()) return false;
5443 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5447 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5448 End = CD->bases_end(); I != End; ++I, ++Index) {
5449 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5450 LValue Subobject = This;
5451 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5453 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5454 Result.getStructBase(Index)))
5459 for (const auto *I : RD->fields()) {
5460 // -- if T is a reference type, no initialization is performed.
5461 if (I->getType()->isReferenceType())
5464 LValue Subobject = This;
5465 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5468 ImplicitValueInitExpr VIE(I->getType());
5469 if (!EvaluateInPlace(
5470 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5477 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5478 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5479 if (RD->isInvalidDecl()) return false;
5480 if (RD->isUnion()) {
5481 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5482 // object's first non-static named data member is zero-initialized
5483 RecordDecl::field_iterator I = RD->field_begin();
5484 if (I == RD->field_end()) {
5485 Result = APValue((const FieldDecl*)nullptr);
5489 LValue Subobject = This;
5490 if (!HandleLValueMember(Info, E, Subobject, *I))
5492 Result = APValue(*I);
5493 ImplicitValueInitExpr VIE(I->getType());
5494 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5497 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5498 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
5502 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5505 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5506 switch (E->getCastKind()) {
5508 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5510 case CK_ConstructorConversion:
5511 return Visit(E->getSubExpr());
5513 case CK_DerivedToBase:
5514 case CK_UncheckedDerivedToBase: {
5515 APValue DerivedObject;
5516 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5518 if (!DerivedObject.isStruct())
5519 return Error(E->getSubExpr());
5521 // Derived-to-base rvalue conversion: just slice off the derived part.
5522 APValue *Value = &DerivedObject;
5523 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5524 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5525 PathE = E->path_end(); PathI != PathE; ++PathI) {
5526 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5527 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5528 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5537 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5538 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5539 if (RD->isInvalidDecl()) return false;
5540 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5542 if (RD->isUnion()) {
5543 const FieldDecl *Field = E->getInitializedFieldInUnion();
5544 Result = APValue(Field);
5548 // If the initializer list for a union does not contain any elements, the
5549 // first element of the union is value-initialized.
5550 // FIXME: The element should be initialized from an initializer list.
5551 // Is this difference ever observable for initializer lists which
5553 ImplicitValueInitExpr VIE(Field->getType());
5554 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5556 LValue Subobject = This;
5557 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5560 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5561 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5562 isa<CXXDefaultInitExpr>(InitExpr));
5564 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5567 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
5568 if (Result.isUninit())
5569 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5570 std::distance(RD->field_begin(), RD->field_end()));
5571 unsigned ElementNo = 0;
5572 bool Success = true;
5574 // Initialize base classes.
5576 for (const auto &Base : CXXRD->bases()) {
5577 assert(ElementNo < E->getNumInits() && "missing init for base class");
5578 const Expr *Init = E->getInit(ElementNo);
5580 LValue Subobject = This;
5581 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5584 APValue &FieldVal = Result.getStructBase(ElementNo);
5585 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
5586 if (!Info.noteFailure())
5594 // Initialize members.
5595 for (const auto *Field : RD->fields()) {
5596 // Anonymous bit-fields are not considered members of the class for
5597 // purposes of aggregate initialization.
5598 if (Field->isUnnamedBitfield())
5601 LValue Subobject = This;
5603 bool HaveInit = ElementNo < E->getNumInits();
5605 // FIXME: Diagnostics here should point to the end of the initializer
5606 // list, not the start.
5607 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5608 Subobject, Field, &Layout))
5611 // Perform an implicit value-initialization for members beyond the end of
5612 // the initializer list.
5613 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5614 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5616 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5617 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5618 isa<CXXDefaultInitExpr>(Init));
5620 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5621 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5622 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5623 FieldVal, Field))) {
5624 if (!Info.noteFailure())
5633 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5635 // Note that E's type is not necessarily the type of our class here; we might
5636 // be initializing an array element instead.
5637 const CXXConstructorDecl *FD = E->getConstructor();
5638 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5640 bool ZeroInit = E->requiresZeroInitialization();
5641 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5642 // If we've already performed zero-initialization, we're already done.
5643 if (!Result.isUninit())
5646 // We can get here in two different ways:
5647 // 1) We're performing value-initialization, and should zero-initialize
5649 // 2) We're performing default-initialization of an object with a trivial
5650 // constexpr default constructor, in which case we should start the
5651 // lifetimes of all the base subobjects (there can be no data member
5652 // subobjects in this case) per [basic.life]p1.
5653 // Either way, ZeroInitialization is appropriate.
5654 return ZeroInitialization(E, T);
5657 const FunctionDecl *Definition = nullptr;
5658 auto Body = FD->getBody(Definition);
5660 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5663 // Avoid materializing a temporary for an elidable copy/move constructor.
5664 if (E->isElidable() && !ZeroInit)
5665 if (const MaterializeTemporaryExpr *ME
5666 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5667 return Visit(ME->GetTemporaryExpr());
5669 if (ZeroInit && !ZeroInitialization(E, T))
5672 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5673 return HandleConstructorCall(E, This, Args,
5674 cast<CXXConstructorDecl>(Definition), Info,
5678 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5679 const CXXInheritedCtorInitExpr *E) {
5680 if (!Info.CurrentCall) {
5681 assert(Info.checkingPotentialConstantExpression());
5685 const CXXConstructorDecl *FD = E->getConstructor();
5686 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5689 const FunctionDecl *Definition = nullptr;
5690 auto Body = FD->getBody(Definition);
5692 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5695 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
5696 cast<CXXConstructorDecl>(Definition), Info,
5700 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5701 const CXXStdInitializerListExpr *E) {
5702 const ConstantArrayType *ArrayType =
5703 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5706 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5709 // Get a pointer to the first element of the array.
5710 Array.addArray(Info, E, ArrayType);
5712 // FIXME: Perform the checks on the field types in SemaInit.
5713 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5714 RecordDecl::field_iterator Field = Record->field_begin();
5715 if (Field == Record->field_end())
5719 if (!Field->getType()->isPointerType() ||
5720 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5721 ArrayType->getElementType()))
5724 // FIXME: What if the initializer_list type has base classes, etc?
5725 Result = APValue(APValue::UninitStruct(), 0, 2);
5726 Array.moveInto(Result.getStructField(0));
5728 if (++Field == Record->field_end())
5731 if (Field->getType()->isPointerType() &&
5732 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5733 ArrayType->getElementType())) {
5735 if (!HandleLValueArrayAdjustment(Info, E, Array,
5736 ArrayType->getElementType(),
5737 ArrayType->getSize().getZExtValue()))
5739 Array.moveInto(Result.getStructField(1));
5740 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5742 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5746 if (++Field != Record->field_end())
5752 static bool EvaluateRecord(const Expr *E, const LValue &This,
5753 APValue &Result, EvalInfo &Info) {
5754 assert(E->isRValue() && E->getType()->isRecordType() &&
5755 "can't evaluate expression as a record rvalue");
5756 return RecordExprEvaluator(Info, This, Result).Visit(E);
5759 //===----------------------------------------------------------------------===//
5760 // Temporary Evaluation
5762 // Temporaries are represented in the AST as rvalues, but generally behave like
5763 // lvalues. The full-object of which the temporary is a subobject is implicitly
5764 // materialized so that a reference can bind to it.
5765 //===----------------------------------------------------------------------===//
5767 class TemporaryExprEvaluator
5768 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5770 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5771 LValueExprEvaluatorBaseTy(Info, Result) {}
5773 /// Visit an expression which constructs the value of this temporary.
5774 bool VisitConstructExpr(const Expr *E) {
5775 Result.set(E, Info.CurrentCall->Index);
5776 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5780 bool VisitCastExpr(const CastExpr *E) {
5781 switch (E->getCastKind()) {
5783 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5785 case CK_ConstructorConversion:
5786 return VisitConstructExpr(E->getSubExpr());
5789 bool VisitInitListExpr(const InitListExpr *E) {
5790 return VisitConstructExpr(E);
5792 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5793 return VisitConstructExpr(E);
5795 bool VisitCallExpr(const CallExpr *E) {
5796 return VisitConstructExpr(E);
5798 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5799 return VisitConstructExpr(E);
5802 } // end anonymous namespace
5804 /// Evaluate an expression of record type as a temporary.
5805 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5806 assert(E->isRValue() && E->getType()->isRecordType());
5807 return TemporaryExprEvaluator(Info, Result).Visit(E);
5810 //===----------------------------------------------------------------------===//
5811 // Vector Evaluation
5812 //===----------------------------------------------------------------------===//
5815 class VectorExprEvaluator
5816 : public ExprEvaluatorBase<VectorExprEvaluator> {
5820 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5821 : ExprEvaluatorBaseTy(info), Result(Result) {}
5823 bool Success(ArrayRef<APValue> V, const Expr *E) {
5824 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5825 // FIXME: remove this APValue copy.
5826 Result = APValue(V.data(), V.size());
5829 bool Success(const APValue &V, const Expr *E) {
5830 assert(V.isVector());
5834 bool ZeroInitialization(const Expr *E);
5836 bool VisitUnaryReal(const UnaryOperator *E)
5837 { return Visit(E->getSubExpr()); }
5838 bool VisitCastExpr(const CastExpr* E);
5839 bool VisitInitListExpr(const InitListExpr *E);
5840 bool VisitUnaryImag(const UnaryOperator *E);
5841 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5842 // binary comparisons, binary and/or/xor,
5843 // shufflevector, ExtVectorElementExpr
5845 } // end anonymous namespace
5847 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5848 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5849 return VectorExprEvaluator(Info, Result).Visit(E);
5852 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
5853 const VectorType *VTy = E->getType()->castAs<VectorType>();
5854 unsigned NElts = VTy->getNumElements();
5856 const Expr *SE = E->getSubExpr();
5857 QualType SETy = SE->getType();
5859 switch (E->getCastKind()) {
5860 case CK_VectorSplat: {
5861 APValue Val = APValue();
5862 if (SETy->isIntegerType()) {
5864 if (!EvaluateInteger(SE, IntResult, Info))
5866 Val = APValue(std::move(IntResult));
5867 } else if (SETy->isRealFloatingType()) {
5868 APFloat FloatResult(0.0);
5869 if (!EvaluateFloat(SE, FloatResult, Info))
5871 Val = APValue(std::move(FloatResult));
5876 // Splat and create vector APValue.
5877 SmallVector<APValue, 4> Elts(NElts, Val);
5878 return Success(Elts, E);
5881 // Evaluate the operand into an APInt we can extract from.
5882 llvm::APInt SValInt;
5883 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5885 // Extract the elements
5886 QualType EltTy = VTy->getElementType();
5887 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5888 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5889 SmallVector<APValue, 4> Elts;
5890 if (EltTy->isRealFloatingType()) {
5891 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5892 unsigned FloatEltSize = EltSize;
5893 if (&Sem == &APFloat::x87DoubleExtended)
5895 for (unsigned i = 0; i < NElts; i++) {
5898 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5900 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5901 Elts.push_back(APValue(APFloat(Sem, Elt)));
5903 } else if (EltTy->isIntegerType()) {
5904 for (unsigned i = 0; i < NElts; i++) {
5907 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5909 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5910 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5915 return Success(Elts, E);
5918 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5923 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5924 const VectorType *VT = E->getType()->castAs<VectorType>();
5925 unsigned NumInits = E->getNumInits();
5926 unsigned NumElements = VT->getNumElements();
5928 QualType EltTy = VT->getElementType();
5929 SmallVector<APValue, 4> Elements;
5931 // The number of initializers can be less than the number of
5932 // vector elements. For OpenCL, this can be due to nested vector
5933 // initialization. For GCC compatibility, missing trailing elements
5934 // should be initialized with zeroes.
5935 unsigned CountInits = 0, CountElts = 0;
5936 while (CountElts < NumElements) {
5937 // Handle nested vector initialization.
5938 if (CountInits < NumInits
5939 && E->getInit(CountInits)->getType()->isVectorType()) {
5941 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5943 unsigned vlen = v.getVectorLength();
5944 for (unsigned j = 0; j < vlen; j++)
5945 Elements.push_back(v.getVectorElt(j));
5947 } else if (EltTy->isIntegerType()) {
5948 llvm::APSInt sInt(32);
5949 if (CountInits < NumInits) {
5950 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5952 } else // trailing integer zero.
5953 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5954 Elements.push_back(APValue(sInt));
5957 llvm::APFloat f(0.0);
5958 if (CountInits < NumInits) {
5959 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5961 } else // trailing float zero.
5962 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5963 Elements.push_back(APValue(f));
5968 return Success(Elements, E);
5972 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5973 const VectorType *VT = E->getType()->getAs<VectorType>();
5974 QualType EltTy = VT->getElementType();
5975 APValue ZeroElement;
5976 if (EltTy->isIntegerType())
5977 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5980 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5982 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5983 return Success(Elements, E);
5986 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5987 VisitIgnoredValue(E->getSubExpr());
5988 return ZeroInitialization(E);
5991 //===----------------------------------------------------------------------===//
5993 //===----------------------------------------------------------------------===//
5996 class ArrayExprEvaluator
5997 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6002 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6003 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6005 bool Success(const APValue &V, const Expr *E) {
6006 assert((V.isArray() || V.isLValue()) &&
6007 "expected array or string literal");
6012 bool ZeroInitialization(const Expr *E) {
6013 const ConstantArrayType *CAT =
6014 Info.Ctx.getAsConstantArrayType(E->getType());
6018 Result = APValue(APValue::UninitArray(), 0,
6019 CAT->getSize().getZExtValue());
6020 if (!Result.hasArrayFiller()) return true;
6022 // Zero-initialize all elements.
6023 LValue Subobject = This;
6024 Subobject.addArray(Info, E, CAT);
6025 ImplicitValueInitExpr VIE(CAT->getElementType());
6026 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6029 bool VisitCallExpr(const CallExpr *E) {
6030 return handleCallExpr(E, Result, &This);
6032 bool VisitInitListExpr(const InitListExpr *E);
6033 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6034 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6035 const LValue &Subobject,
6036 APValue *Value, QualType Type);
6038 } // end anonymous namespace
6040 static bool EvaluateArray(const Expr *E, const LValue &This,
6041 APValue &Result, EvalInfo &Info) {
6042 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6043 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6046 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6047 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6051 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6052 // an appropriately-typed string literal enclosed in braces.
6053 if (E->isStringLiteralInit()) {
6055 if (!EvaluateLValue(E->getInit(0), LV, Info))
6059 return Success(Val, E);
6062 bool Success = true;
6064 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6065 "zero-initialized array shouldn't have any initialized elts");
6067 if (Result.isArray() && Result.hasArrayFiller())
6068 Filler = Result.getArrayFiller();
6070 unsigned NumEltsToInit = E->getNumInits();
6071 unsigned NumElts = CAT->getSize().getZExtValue();
6072 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6074 // If the initializer might depend on the array index, run it for each
6075 // array element. For now, just whitelist non-class value-initialization.
6076 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6077 NumEltsToInit = NumElts;
6079 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6081 // If the array was previously zero-initialized, preserve the
6082 // zero-initialized values.
6083 if (!Filler.isUninit()) {
6084 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6085 Result.getArrayInitializedElt(I) = Filler;
6086 if (Result.hasArrayFiller())
6087 Result.getArrayFiller() = Filler;
6090 LValue Subobject = This;
6091 Subobject.addArray(Info, E, CAT);
6092 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6094 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6095 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6096 Info, Subobject, Init) ||
6097 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6098 CAT->getElementType(), 1)) {
6099 if (!Info.noteFailure())
6105 if (!Result.hasArrayFiller())
6108 // If we get here, we have a trivial filler, which we can just evaluate
6109 // once and splat over the rest of the array elements.
6110 assert(FillerExpr && "no array filler for incomplete init list");
6111 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6112 FillerExpr) && Success;
6115 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6116 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6119 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6120 const LValue &Subobject,
6123 bool HadZeroInit = !Value->isUninit();
6125 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6126 unsigned N = CAT->getSize().getZExtValue();
6128 // Preserve the array filler if we had prior zero-initialization.
6130 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6133 *Value = APValue(APValue::UninitArray(), N, N);
6136 for (unsigned I = 0; I != N; ++I)
6137 Value->getArrayInitializedElt(I) = Filler;
6139 // Initialize the elements.
6140 LValue ArrayElt = Subobject;
6141 ArrayElt.addArray(Info, E, CAT);
6142 for (unsigned I = 0; I != N; ++I)
6143 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6144 CAT->getElementType()) ||
6145 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6146 CAT->getElementType(), 1))
6152 if (!Type->isRecordType())
6155 return RecordExprEvaluator(Info, Subobject, *Value)
6156 .VisitCXXConstructExpr(E, Type);
6159 //===----------------------------------------------------------------------===//
6160 // Integer Evaluation
6162 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6163 // types and back in constant folding. Integer values are thus represented
6164 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6165 //===----------------------------------------------------------------------===//
6168 class IntExprEvaluator
6169 : public ExprEvaluatorBase<IntExprEvaluator> {
6172 IntExprEvaluator(EvalInfo &info, APValue &result)
6173 : ExprEvaluatorBaseTy(info), Result(result) {}
6175 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6176 assert(E->getType()->isIntegralOrEnumerationType() &&
6177 "Invalid evaluation result.");
6178 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6179 "Invalid evaluation result.");
6180 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6181 "Invalid evaluation result.");
6182 Result = APValue(SI);
6185 bool Success(const llvm::APSInt &SI, const Expr *E) {
6186 return Success(SI, E, Result);
6189 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6190 assert(E->getType()->isIntegralOrEnumerationType() &&
6191 "Invalid evaluation result.");
6192 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6193 "Invalid evaluation result.");
6194 Result = APValue(APSInt(I));
6195 Result.getInt().setIsUnsigned(
6196 E->getType()->isUnsignedIntegerOrEnumerationType());
6199 bool Success(const llvm::APInt &I, const Expr *E) {
6200 return Success(I, E, Result);
6203 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6204 assert(E->getType()->isIntegralOrEnumerationType() &&
6205 "Invalid evaluation result.");
6206 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6209 bool Success(uint64_t Value, const Expr *E) {
6210 return Success(Value, E, Result);
6213 bool Success(CharUnits Size, const Expr *E) {
6214 return Success(Size.getQuantity(), E);
6217 bool Success(const APValue &V, const Expr *E) {
6218 if (V.isLValue() || V.isAddrLabelDiff()) {
6222 return Success(V.getInt(), E);
6225 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6227 //===--------------------------------------------------------------------===//
6229 //===--------------------------------------------------------------------===//
6231 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6232 return Success(E->getValue(), E);
6234 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6235 return Success(E->getValue(), E);
6238 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6239 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6240 if (CheckReferencedDecl(E, E->getDecl()))
6243 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6245 bool VisitMemberExpr(const MemberExpr *E) {
6246 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6247 VisitIgnoredBaseExpression(E->getBase());
6251 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6254 bool VisitCallExpr(const CallExpr *E);
6255 bool VisitBinaryOperator(const BinaryOperator *E);
6256 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6257 bool VisitUnaryOperator(const UnaryOperator *E);
6259 bool VisitCastExpr(const CastExpr* E);
6260 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6262 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6263 return Success(E->getValue(), E);
6266 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6267 return Success(E->getValue(), E);
6270 // Note, GNU defines __null as an integer, not a pointer.
6271 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6272 return ZeroInitialization(E);
6275 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6276 return Success(E->getValue(), E);
6279 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6280 return Success(E->getValue(), E);
6283 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6284 return Success(E->getValue(), E);
6287 bool VisitUnaryReal(const UnaryOperator *E);
6288 bool VisitUnaryImag(const UnaryOperator *E);
6290 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6291 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6294 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
6295 // FIXME: Missing: array subscript of vector, member of vector
6297 } // end anonymous namespace
6299 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6300 /// produce either the integer value or a pointer.
6302 /// GCC has a heinous extension which folds casts between pointer types and
6303 /// pointer-sized integral types. We support this by allowing the evaluation of
6304 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6305 /// Some simple arithmetic on such values is supported (they are treated much
6307 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6309 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6310 return IntExprEvaluator(Info, Result).Visit(E);
6313 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6315 if (!EvaluateIntegerOrLValue(E, Val, Info))
6318 // FIXME: It would be better to produce the diagnostic for casting
6319 // a pointer to an integer.
6320 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6323 Result = Val.getInt();
6327 /// Check whether the given declaration can be directly converted to an integral
6328 /// rvalue. If not, no diagnostic is produced; there are other things we can
6330 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6331 // Enums are integer constant exprs.
6332 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6333 // Check for signedness/width mismatches between E type and ECD value.
6334 bool SameSign = (ECD->getInitVal().isSigned()
6335 == E->getType()->isSignedIntegerOrEnumerationType());
6336 bool SameWidth = (ECD->getInitVal().getBitWidth()
6337 == Info.Ctx.getIntWidth(E->getType()));
6338 if (SameSign && SameWidth)
6339 return Success(ECD->getInitVal(), E);
6341 // Get rid of mismatch (otherwise Success assertions will fail)
6342 // by computing a new value matching the type of E.
6343 llvm::APSInt Val = ECD->getInitVal();
6345 Val.setIsSigned(!ECD->getInitVal().isSigned());
6347 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6348 return Success(Val, E);
6354 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6356 static int EvaluateBuiltinClassifyType(const CallExpr *E,
6357 const LangOptions &LangOpts) {
6358 // The following enum mimics the values returned by GCC.
6359 // FIXME: Does GCC differ between lvalue and rvalue references here?
6360 enum gcc_type_class {
6362 void_type_class, integer_type_class, char_type_class,
6363 enumeral_type_class, boolean_type_class,
6364 pointer_type_class, reference_type_class, offset_type_class,
6365 real_type_class, complex_type_class,
6366 function_type_class, method_type_class,
6367 record_type_class, union_type_class,
6368 array_type_class, string_type_class,
6372 // If no argument was supplied, default to "no_type_class". This isn't
6373 // ideal, however it is what gcc does.
6374 if (E->getNumArgs() == 0)
6375 return no_type_class;
6377 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6378 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6380 switch (CanTy->getTypeClass()) {
6381 #define TYPE(ID, BASE)
6382 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6383 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6384 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6385 #include "clang/AST/TypeNodes.def"
6386 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6389 switch (BT->getKind()) {
6390 #define BUILTIN_TYPE(ID, SINGLETON_ID)
6391 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6392 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6393 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6394 #include "clang/AST/BuiltinTypes.def"
6395 case BuiltinType::Void:
6396 return void_type_class;
6398 case BuiltinType::Bool:
6399 return boolean_type_class;
6401 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6402 case BuiltinType::UChar:
6403 case BuiltinType::UShort:
6404 case BuiltinType::UInt:
6405 case BuiltinType::ULong:
6406 case BuiltinType::ULongLong:
6407 case BuiltinType::UInt128:
6408 return integer_type_class;
6410 case BuiltinType::NullPtr:
6411 return pointer_type_class;
6413 case BuiltinType::WChar_U:
6414 case BuiltinType::Char16:
6415 case BuiltinType::Char32:
6416 case BuiltinType::ObjCId:
6417 case BuiltinType::ObjCClass:
6418 case BuiltinType::ObjCSel:
6419 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6420 case BuiltinType::Id:
6421 #include "clang/Basic/OpenCLImageTypes.def"
6422 case BuiltinType::OCLSampler:
6423 case BuiltinType::OCLEvent:
6424 case BuiltinType::OCLClkEvent:
6425 case BuiltinType::OCLQueue:
6426 case BuiltinType::OCLNDRange:
6427 case BuiltinType::OCLReserveID:
6428 case BuiltinType::Dependent:
6429 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6433 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6437 return pointer_type_class;
6440 case Type::MemberPointer:
6441 if (CanTy->isMemberDataPointerType())
6442 return offset_type_class;
6444 // We expect member pointers to be either data or function pointers,
6446 assert(CanTy->isMemberFunctionPointerType());
6447 return method_type_class;
6451 return complex_type_class;
6453 case Type::FunctionNoProto:
6454 case Type::FunctionProto:
6455 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6458 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6459 switch (RT->getDecl()->getTagKind()) {
6460 case TagTypeKind::TTK_Struct:
6461 case TagTypeKind::TTK_Class:
6462 case TagTypeKind::TTK_Interface:
6463 return record_type_class;
6465 case TagTypeKind::TTK_Enum:
6466 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6468 case TagTypeKind::TTK_Union:
6469 return union_type_class;
6472 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6474 case Type::ConstantArray:
6475 case Type::VariableArray:
6476 case Type::IncompleteArray:
6477 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6479 case Type::BlockPointer:
6480 case Type::LValueReference:
6481 case Type::RValueReference:
6483 case Type::ExtVector:
6485 case Type::ObjCObject:
6486 case Type::ObjCInterface:
6487 case Type::ObjCObjectPointer:
6490 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6493 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6496 /// EvaluateBuiltinConstantPForLValue - Determine the result of
6497 /// __builtin_constant_p when applied to the given lvalue.
6499 /// An lvalue is only "constant" if it is a pointer or reference to the first
6500 /// character of a string literal.
6501 template<typename LValue>
6502 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
6503 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
6504 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6507 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6508 /// GCC as we can manage.
6509 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6510 QualType ArgType = Arg->getType();
6512 // __builtin_constant_p always has one operand. The rules which gcc follows
6513 // are not precisely documented, but are as follows:
6515 // - If the operand is of integral, floating, complex or enumeration type,
6516 // and can be folded to a known value of that type, it returns 1.
6517 // - If the operand and can be folded to a pointer to the first character
6518 // of a string literal (or such a pointer cast to an integral type), it
6521 // Otherwise, it returns 0.
6523 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6524 // its support for this does not currently work.
6525 if (ArgType->isIntegralOrEnumerationType()) {
6526 Expr::EvalResult Result;
6527 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6530 APValue &V = Result.Val;
6531 if (V.getKind() == APValue::Int)
6533 if (V.getKind() == APValue::LValue)
6534 return EvaluateBuiltinConstantPForLValue(V);
6535 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6536 return Arg->isEvaluatable(Ctx);
6537 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6539 Expr::EvalStatus Status;
6540 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
6541 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6542 : EvaluatePointer(Arg, LV, Info)) &&
6543 !Status.HasSideEffects)
6544 return EvaluateBuiltinConstantPForLValue(LV);
6547 // Anything else isn't considered to be sufficiently constant.
6551 /// Retrieves the "underlying object type" of the given expression,
6552 /// as used by __builtin_object_size.
6553 static QualType getObjectType(APValue::LValueBase B) {
6554 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6555 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
6556 return VD->getType();
6557 } else if (const Expr *E = B.get<const Expr*>()) {
6558 if (isa<CompoundLiteralExpr>(E))
6559 return E->getType();
6565 /// A more selective version of E->IgnoreParenCasts for
6566 /// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6567 /// to change the type of E.
6568 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6570 /// Always returns an RValue with a pointer representation.
6571 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6572 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6574 auto *NoParens = E->IgnoreParens();
6575 auto *Cast = dyn_cast<CastExpr>(NoParens);
6576 if (Cast == nullptr)
6579 // We only conservatively allow a few kinds of casts, because this code is
6580 // inherently a simple solution that seeks to support the common case.
6581 auto CastKind = Cast->getCastKind();
6582 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6583 CastKind != CK_AddressSpaceConversion)
6586 auto *SubExpr = Cast->getSubExpr();
6587 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6589 return ignorePointerCastsAndParens(SubExpr);
6592 /// Checks to see if the given LValue's Designator is at the end of the LValue's
6593 /// record layout. e.g.
6594 /// struct { struct { int a, b; } fst, snd; } obj;
6600 /// obj.snd.b // yes
6602 /// Please note: this function is specialized for how __builtin_object_size
6603 /// views "objects".
6605 /// If this encounters an invalid RecordDecl, it will always return true.
6606 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6607 assert(!LVal.Designator.Invalid);
6609 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6610 const RecordDecl *Parent = FD->getParent();
6611 Invalid = Parent->isInvalidDecl();
6612 if (Invalid || Parent->isUnion())
6614 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
6615 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6618 auto &Base = LVal.getLValueBase();
6619 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6620 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
6622 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6624 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
6625 for (auto *FD : IFD->chain()) {
6627 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6633 QualType BaseType = getType(Base);
6634 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6635 if (BaseType->isArrayType()) {
6636 // Because __builtin_object_size treats arrays as objects, we can ignore
6637 // the index iff this is the last array in the Designator.
6640 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6641 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6642 if (Index + 1 != CAT->getSize())
6644 BaseType = CAT->getElementType();
6645 } else if (BaseType->isAnyComplexType()) {
6646 auto *CT = BaseType->castAs<ComplexType>();
6647 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6650 BaseType = CT->getElementType();
6651 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
6653 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6655 BaseType = FD->getType();
6657 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6658 "Expecting cast to a base class");
6665 /// Tests to see if the LValue has a designator (that isn't necessarily valid).
6666 static bool refersToCompleteObject(const LValue &LVal) {
6667 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6670 if (!LVal.InvalidBase)
6673 auto *E = LVal.Base.dyn_cast<const Expr *>();
6675 assert(E != nullptr && isa<MemberExpr>(E));
6679 /// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6680 /// true and stores the result in @p Size.
6682 /// If @p WasError is non-null, this will report whether the failure to evaluate
6683 /// is to be treated as an Error in IntExprEvaluator.
6684 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6685 EvalInfo &Info, uint64_t &Size,
6686 bool *WasError = nullptr) {
6687 if (WasError != nullptr)
6690 auto Error = [&](const Expr *E) {
6691 if (WasError != nullptr)
6696 auto Success = [&](uint64_t S, const Expr *E) {
6701 // Determine the denoted object.
6704 // The operand of __builtin_object_size is never evaluated for side-effects.
6705 // If there are any, but we can determine the pointed-to object anyway, then
6706 // ignore the side-effects.
6707 SpeculativeEvaluationRAII SpeculativeEval(Info);
6708 FoldOffsetRAII Fold(Info, Type & 1);
6710 if (E->isGLValue()) {
6711 // It's possible for us to be given GLValues if we're called via
6712 // Expr::tryEvaluateObjectSize.
6714 if (!EvaluateAsRValue(Info, E, RVal))
6716 Base.setFrom(Info.Ctx, RVal);
6717 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
6721 CharUnits BaseOffset = Base.getLValueOffset();
6722 // If we point to before the start of the object, there are no accessible
6724 if (BaseOffset.isNegative())
6725 return Success(0, E);
6727 // In the case where we're not dealing with a subobject, we discard the
6729 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
6731 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6732 // exist. If we can't verify the base, then we can't do that.
6734 // As a special case, we produce a valid object size for an unknown object
6735 // with a known designator if Type & 1 is 1. For instance:
6737 // extern struct X { char buff[32]; int a, b, c; } *p;
6738 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6739 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6741 // This matches GCC's behavior.
6742 if (Base.InvalidBase && !SubobjectOnly)
6745 // If we're not examining only the subobject, then we reset to a complete
6746 // object designator
6748 // If Type is 1 and we've lost track of the subobject, just find the complete
6749 // object instead. (If Type is 3, that's not correct behavior and we should
6750 // return 0 instead.)
6752 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
6753 QualType T = getObjectType(End.getLValueBase());
6755 End.Designator.setInvalid();
6757 End.Designator = SubobjectDesignator(T);
6758 End.Offset = CharUnits::Zero();
6762 // If it is not possible to determine which objects ptr points to at compile
6763 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6764 // and (size_t) 0 for type 2 or 3.
6765 if (End.Designator.Invalid)
6768 // According to the GCC documentation, we want the size of the subobject
6769 // denoted by the pointer. But that's not quite right -- what we actually
6770 // want is the size of the immediately-enclosing array, if there is one.
6771 int64_t AmountToAdd = 1;
6772 if (End.Designator.MostDerivedIsArrayElement &&
6773 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6774 // We got a pointer to an array. Step to its end.
6775 AmountToAdd = End.Designator.MostDerivedArraySize -
6776 End.Designator.Entries.back().ArrayIndex;
6777 } else if (End.Designator.isOnePastTheEnd()) {
6778 // We're already pointing at the end of the object.
6782 QualType PointeeType = End.Designator.MostDerivedType;
6783 assert(!PointeeType.isNull());
6784 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
6787 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6791 auto EndOffset = End.getLValueOffset();
6793 // The following is a moderately common idiom in C:
6795 // struct Foo { int a; char c[1]; };
6796 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6797 // strcpy(&F->c[0], Bar);
6799 // So, if we see that we're examining a 1-length (or 0-length) array at the
6800 // end of a struct with an unknown base, we give up instead of breaking code
6801 // that behaves this way. Note that we only do this when Type=1, because
6802 // Type=3 is a lower bound, so answering conservatively is fine.
6803 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6804 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6805 End.Designator.MostDerivedIsArrayElement &&
6806 End.Designator.MostDerivedArraySize < 2 &&
6807 isDesignatorAtObjectEnd(Info.Ctx, End))
6810 if (BaseOffset > EndOffset)
6811 return Success(0, E);
6813 return Success((EndOffset - BaseOffset).getQuantity(), E);
6816 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6820 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6821 return Success(Size, E);
6827 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
6828 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
6830 return ExprEvaluatorBaseTy::VisitCallExpr(E);
6832 case Builtin::BI__builtin_object_size: {
6833 // The type was checked when we built the expression.
6835 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6836 assert(Type <= 3 && "unexpected type");
6838 if (TryEvaluateBuiltinObjectSize(E, Type))
6841 if (E->getArg(0)->HasSideEffects(Info.Ctx))
6842 return Success((Type & 2) ? 0 : -1, E);
6844 // Expression had no side effects, but we couldn't statically determine the
6845 // size of the referenced object.
6846 switch (Info.EvalMode) {
6847 case EvalInfo::EM_ConstantExpression:
6848 case EvalInfo::EM_PotentialConstantExpression:
6849 case EvalInfo::EM_ConstantFold:
6850 case EvalInfo::EM_EvaluateForOverflow:
6851 case EvalInfo::EM_IgnoreSideEffects:
6852 case EvalInfo::EM_DesignatorFold:
6853 // Leave it to IR generation.
6855 case EvalInfo::EM_ConstantExpressionUnevaluated:
6856 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6857 // Reduce it to a constant now.
6858 return Success((Type & 2) ? 0 : -1, E);
6862 case Builtin::BI__builtin_bswap16:
6863 case Builtin::BI__builtin_bswap32:
6864 case Builtin::BI__builtin_bswap64: {
6866 if (!EvaluateInteger(E->getArg(0), Val, Info))
6869 return Success(Val.byteSwap(), E);
6872 case Builtin::BI__builtin_classify_type:
6873 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
6875 // FIXME: BI__builtin_clrsb
6876 // FIXME: BI__builtin_clrsbl
6877 // FIXME: BI__builtin_clrsbll
6879 case Builtin::BI__builtin_clz:
6880 case Builtin::BI__builtin_clzl:
6881 case Builtin::BI__builtin_clzll:
6882 case Builtin::BI__builtin_clzs: {
6884 if (!EvaluateInteger(E->getArg(0), Val, Info))
6889 return Success(Val.countLeadingZeros(), E);
6892 case Builtin::BI__builtin_constant_p:
6893 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6895 case Builtin::BI__builtin_ctz:
6896 case Builtin::BI__builtin_ctzl:
6897 case Builtin::BI__builtin_ctzll:
6898 case Builtin::BI__builtin_ctzs: {
6900 if (!EvaluateInteger(E->getArg(0), Val, Info))
6905 return Success(Val.countTrailingZeros(), E);
6908 case Builtin::BI__builtin_eh_return_data_regno: {
6909 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6910 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6911 return Success(Operand, E);
6914 case Builtin::BI__builtin_expect:
6915 return Visit(E->getArg(0));
6917 case Builtin::BI__builtin_ffs:
6918 case Builtin::BI__builtin_ffsl:
6919 case Builtin::BI__builtin_ffsll: {
6921 if (!EvaluateInteger(E->getArg(0), Val, Info))
6924 unsigned N = Val.countTrailingZeros();
6925 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6928 case Builtin::BI__builtin_fpclassify: {
6930 if (!EvaluateFloat(E->getArg(5), Val, Info))
6933 switch (Val.getCategory()) {
6934 case APFloat::fcNaN: Arg = 0; break;
6935 case APFloat::fcInfinity: Arg = 1; break;
6936 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6937 case APFloat::fcZero: Arg = 4; break;
6939 return Visit(E->getArg(Arg));
6942 case Builtin::BI__builtin_isinf_sign: {
6944 return EvaluateFloat(E->getArg(0), Val, Info) &&
6945 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6948 case Builtin::BI__builtin_isinf: {
6950 return EvaluateFloat(E->getArg(0), Val, Info) &&
6951 Success(Val.isInfinity() ? 1 : 0, E);
6954 case Builtin::BI__builtin_isfinite: {
6956 return EvaluateFloat(E->getArg(0), Val, Info) &&
6957 Success(Val.isFinite() ? 1 : 0, E);
6960 case Builtin::BI__builtin_isnan: {
6962 return EvaluateFloat(E->getArg(0), Val, Info) &&
6963 Success(Val.isNaN() ? 1 : 0, E);
6966 case Builtin::BI__builtin_isnormal: {
6968 return EvaluateFloat(E->getArg(0), Val, Info) &&
6969 Success(Val.isNormal() ? 1 : 0, E);
6972 case Builtin::BI__builtin_parity:
6973 case Builtin::BI__builtin_parityl:
6974 case Builtin::BI__builtin_parityll: {
6976 if (!EvaluateInteger(E->getArg(0), Val, Info))
6979 return Success(Val.countPopulation() % 2, E);
6982 case Builtin::BI__builtin_popcount:
6983 case Builtin::BI__builtin_popcountl:
6984 case Builtin::BI__builtin_popcountll: {
6986 if (!EvaluateInteger(E->getArg(0), Val, Info))
6989 return Success(Val.countPopulation(), E);
6992 case Builtin::BIstrlen:
6993 // A call to strlen is not a constant expression.
6994 if (Info.getLangOpts().CPlusPlus11)
6995 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6996 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6998 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7000 case Builtin::BI__builtin_strlen: {
7001 // As an extension, we support __builtin_strlen() as a constant expression,
7002 // and support folding strlen() to a constant.
7004 if (!EvaluatePointer(E->getArg(0), String, Info))
7007 // Fast path: if it's a string literal, search the string value.
7008 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7009 String.getLValueBase().dyn_cast<const Expr *>())) {
7010 // The string literal may have embedded null characters. Find the first
7011 // one and truncate there.
7012 StringRef Str = S->getBytes();
7013 int64_t Off = String.Offset.getQuantity();
7014 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7015 S->getCharByteWidth() == 1) {
7016 Str = Str.substr(Off);
7018 StringRef::size_type Pos = Str.find(0);
7019 if (Pos != StringRef::npos)
7020 Str = Str.substr(0, Pos);
7022 return Success(Str.size(), E);
7025 // Fall through to slow path to issue appropriate diagnostic.
7028 // Slow path: scan the bytes of the string looking for the terminating 0.
7029 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7030 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7032 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7036 return Success(Strlen, E);
7037 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7042 case Builtin::BI__atomic_always_lock_free:
7043 case Builtin::BI__atomic_is_lock_free:
7044 case Builtin::BI__c11_atomic_is_lock_free: {
7046 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7049 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7050 // of two less than the maximum inline atomic width, we know it is
7051 // lock-free. If the size isn't a power of two, or greater than the
7052 // maximum alignment where we promote atomics, we know it is not lock-free
7053 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7054 // the answer can only be determined at runtime; for example, 16-byte
7055 // atomics have lock-free implementations on some, but not all,
7056 // x86-64 processors.
7058 // Check power-of-two.
7059 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7060 if (Size.isPowerOfTwo()) {
7061 // Check against inlining width.
7062 unsigned InlineWidthBits =
7063 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7064 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7065 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7066 Size == CharUnits::One() ||
7067 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7068 Expr::NPC_NeverValueDependent))
7069 // OK, we will inline appropriately-aligned operations of this size,
7070 // and _Atomic(T) is appropriately-aligned.
7071 return Success(1, E);
7073 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7074 castAs<PointerType>()->getPointeeType();
7075 if (!PointeeType->isIncompleteType() &&
7076 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7077 // OK, we will inline operations on this object.
7078 return Success(1, E);
7083 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7084 Success(0, E) : Error(E);
7089 static bool HasSameBase(const LValue &A, const LValue &B) {
7090 if (!A.getLValueBase())
7091 return !B.getLValueBase();
7092 if (!B.getLValueBase())
7095 if (A.getLValueBase().getOpaqueValue() !=
7096 B.getLValueBase().getOpaqueValue()) {
7097 const Decl *ADecl = GetLValueBaseDecl(A);
7100 const Decl *BDecl = GetLValueBaseDecl(B);
7101 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7105 return IsGlobalLValue(A.getLValueBase()) ||
7106 A.getLValueCallIndex() == B.getLValueCallIndex();
7109 /// \brief Determine whether this is a pointer past the end of the complete
7110 /// object referred to by the lvalue.
7111 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7113 // A null pointer can be viewed as being "past the end" but we don't
7114 // choose to look at it that way here.
7115 if (!LV.getLValueBase())
7118 // If the designator is valid and refers to a subobject, we're not pointing
7120 if (!LV.getLValueDesignator().Invalid &&
7121 !LV.getLValueDesignator().isOnePastTheEnd())
7124 // A pointer to an incomplete type might be past-the-end if the type's size is
7125 // zero. We cannot tell because the type is incomplete.
7126 QualType Ty = getType(LV.getLValueBase());
7127 if (Ty->isIncompleteType())
7130 // We're a past-the-end pointer if we point to the byte after the object,
7131 // no matter what our type or path is.
7132 auto Size = Ctx.getTypeSizeInChars(Ty);
7133 return LV.getLValueOffset() == Size;
7138 /// \brief Data recursive integer evaluator of certain binary operators.
7140 /// We use a data recursive algorithm for binary operators so that we are able
7141 /// to handle extreme cases of chained binary operators without causing stack
7143 class DataRecursiveIntBinOpEvaluator {
7148 EvalResult() : Failed(false) { }
7150 void swap(EvalResult &RHS) {
7152 Failed = RHS.Failed;
7159 EvalResult LHSResult; // meaningful only for binary operator expression.
7160 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7164 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
7165 SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
7167 void startSpeculativeEval(EvalInfo &Info) {
7168 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7172 SpeculativeEvaluationRAII SpecEvalRAII;
7175 SmallVector<Job, 16> Queue;
7177 IntExprEvaluator &IntEval;
7179 APValue &FinalResult;
7182 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7183 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7185 /// \brief True if \param E is a binary operator that we are going to handle
7186 /// data recursively.
7187 /// We handle binary operators that are comma, logical, or that have operands
7188 /// with integral or enumeration type.
7189 static bool shouldEnqueue(const BinaryOperator *E) {
7190 return E->getOpcode() == BO_Comma ||
7193 E->getType()->isIntegralOrEnumerationType() &&
7194 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7195 E->getRHS()->getType()->isIntegralOrEnumerationType());
7198 bool Traverse(const BinaryOperator *E) {
7200 EvalResult PrevResult;
7201 while (!Queue.empty())
7202 process(PrevResult);
7204 if (PrevResult.Failed) return false;
7206 FinalResult.swap(PrevResult.Val);
7211 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7212 return IntEval.Success(Value, E, Result);
7214 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7215 return IntEval.Success(Value, E, Result);
7217 bool Error(const Expr *E) {
7218 return IntEval.Error(E);
7220 bool Error(const Expr *E, diag::kind D) {
7221 return IntEval.Error(E, D);
7224 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7225 return Info.CCEDiag(E, D);
7228 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7229 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7230 bool &SuppressRHSDiags);
7232 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7233 const BinaryOperator *E, APValue &Result);
7235 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7236 Result.Failed = !Evaluate(Result.Val, Info, E);
7238 Result.Val = APValue();
7241 void process(EvalResult &Result);
7243 void enqueue(const Expr *E) {
7244 E = E->IgnoreParens();
7245 Queue.resize(Queue.size()+1);
7247 Queue.back().Kind = Job::AnyExprKind;
7253 bool DataRecursiveIntBinOpEvaluator::
7254 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7255 bool &SuppressRHSDiags) {
7256 if (E->getOpcode() == BO_Comma) {
7257 // Ignore LHS but note if we could not evaluate it.
7258 if (LHSResult.Failed)
7259 return Info.noteSideEffect();
7263 if (E->isLogicalOp()) {
7265 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7266 // We were able to evaluate the LHS, see if we can get away with not
7267 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7268 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7269 Success(LHSAsBool, E, LHSResult.Val);
7270 return false; // Ignore RHS
7273 LHSResult.Failed = true;
7275 // Since we weren't able to evaluate the left hand side, it
7276 // might have had side effects.
7277 if (!Info.noteSideEffect())
7280 // We can't evaluate the LHS; however, sometimes the result
7281 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7282 // Don't ignore RHS and suppress diagnostics from this arm.
7283 SuppressRHSDiags = true;
7289 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7290 E->getRHS()->getType()->isIntegralOrEnumerationType());
7292 if (LHSResult.Failed && !Info.noteFailure())
7293 return false; // Ignore RHS;
7298 bool DataRecursiveIntBinOpEvaluator::
7299 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7300 const BinaryOperator *E, APValue &Result) {
7301 if (E->getOpcode() == BO_Comma) {
7302 if (RHSResult.Failed)
7304 Result = RHSResult.Val;
7308 if (E->isLogicalOp()) {
7309 bool lhsResult, rhsResult;
7310 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7311 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7315 if (E->getOpcode() == BO_LOr)
7316 return Success(lhsResult || rhsResult, E, Result);
7318 return Success(lhsResult && rhsResult, E, Result);
7322 // We can't evaluate the LHS; however, sometimes the result
7323 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7324 if (rhsResult == (E->getOpcode() == BO_LOr))
7325 return Success(rhsResult, E, Result);
7332 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7333 E->getRHS()->getType()->isIntegralOrEnumerationType());
7335 if (LHSResult.Failed || RHSResult.Failed)
7338 const APValue &LHSVal = LHSResult.Val;
7339 const APValue &RHSVal = RHSResult.Val;
7341 // Handle cases like (unsigned long)&a + 4.
7342 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7344 CharUnits AdditionalOffset =
7345 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7346 if (E->getOpcode() == BO_Add)
7347 Result.getLValueOffset() += AdditionalOffset;
7349 Result.getLValueOffset() -= AdditionalOffset;
7353 // Handle cases like 4 + (unsigned long)&a
7354 if (E->getOpcode() == BO_Add &&
7355 RHSVal.isLValue() && LHSVal.isInt()) {
7357 Result.getLValueOffset() +=
7358 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
7362 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7363 // Handle (intptr_t)&&A - (intptr_t)&&B.
7364 if (!LHSVal.getLValueOffset().isZero() ||
7365 !RHSVal.getLValueOffset().isZero())
7367 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7368 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7369 if (!LHSExpr || !RHSExpr)
7371 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7372 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7373 if (!LHSAddrExpr || !RHSAddrExpr)
7375 // Make sure both labels come from the same function.
7376 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7377 RHSAddrExpr->getLabel()->getDeclContext())
7379 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7383 // All the remaining cases expect both operands to be an integer
7384 if (!LHSVal.isInt() || !RHSVal.isInt())
7387 // Set up the width and signedness manually, in case it can't be deduced
7388 // from the operation we're performing.
7389 // FIXME: Don't do this in the cases where we can deduce it.
7390 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7391 E->getType()->isUnsignedIntegerOrEnumerationType());
7392 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7393 RHSVal.getInt(), Value))
7395 return Success(Value, E, Result);
7398 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
7399 Job &job = Queue.back();
7402 case Job::AnyExprKind: {
7403 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7404 if (shouldEnqueue(Bop)) {
7405 job.Kind = Job::BinOpKind;
7406 enqueue(Bop->getLHS());
7411 EvaluateExpr(job.E, Result);
7416 case Job::BinOpKind: {
7417 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7418 bool SuppressRHSDiags = false;
7419 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
7423 if (SuppressRHSDiags)
7424 job.startSpeculativeEval(Info);
7425 job.LHSResult.swap(Result);
7426 job.Kind = Job::BinOpVisitedLHSKind;
7427 enqueue(Bop->getRHS());
7431 case Job::BinOpVisitedLHSKind: {
7432 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7435 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
7441 llvm_unreachable("Invalid Job::Kind!");
7445 /// Used when we determine that we should fail, but can keep evaluating prior to
7446 /// noting that we had a failure.
7447 class DelayedNoteFailureRAII {
7452 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7453 : Info(Info), NoteFailure(NoteFailure) {}
7454 ~DelayedNoteFailureRAII() {
7456 bool ContinueAfterFailure = Info.noteFailure();
7457 (void)ContinueAfterFailure;
7458 assert(ContinueAfterFailure &&
7459 "Shouldn't have kept evaluating on failure.");
7465 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7466 // We don't call noteFailure immediately because the assignment happens after
7467 // we evaluate LHS and RHS.
7468 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
7471 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
7472 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7473 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
7475 QualType LHSTy = E->getLHS()->getType();
7476 QualType RHSTy = E->getRHS()->getType();
7478 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
7479 ComplexValue LHS, RHS;
7481 if (E->isAssignmentOp()) {
7483 EvaluateLValue(E->getLHS(), LV, Info);
7485 } else if (LHSTy->isRealFloatingType()) {
7486 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7488 LHS.makeComplexFloat();
7489 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7492 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7494 if (!LHSOK && !Info.noteFailure())
7497 if (E->getRHS()->getType()->isRealFloatingType()) {
7498 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7500 RHS.makeComplexFloat();
7501 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7502 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7505 if (LHS.isComplexFloat()) {
7506 APFloat::cmpResult CR_r =
7507 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
7508 APFloat::cmpResult CR_i =
7509 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7511 if (E->getOpcode() == BO_EQ)
7512 return Success((CR_r == APFloat::cmpEqual &&
7513 CR_i == APFloat::cmpEqual), E);
7515 assert(E->getOpcode() == BO_NE &&
7516 "Invalid complex comparison.");
7517 return Success(((CR_r == APFloat::cmpGreaterThan ||
7518 CR_r == APFloat::cmpLessThan ||
7519 CR_r == APFloat::cmpUnordered) ||
7520 (CR_i == APFloat::cmpGreaterThan ||
7521 CR_i == APFloat::cmpLessThan ||
7522 CR_i == APFloat::cmpUnordered)), E);
7525 if (E->getOpcode() == BO_EQ)
7526 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7527 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7529 assert(E->getOpcode() == BO_NE &&
7530 "Invalid compex comparison.");
7531 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7532 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7537 if (LHSTy->isRealFloatingType() &&
7538 RHSTy->isRealFloatingType()) {
7539 APFloat RHS(0.0), LHS(0.0);
7541 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7542 if (!LHSOK && !Info.noteFailure())
7545 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
7548 APFloat::cmpResult CR = LHS.compare(RHS);
7550 switch (E->getOpcode()) {
7552 llvm_unreachable("Invalid binary operator!");
7554 return Success(CR == APFloat::cmpLessThan, E);
7556 return Success(CR == APFloat::cmpGreaterThan, E);
7558 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
7560 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
7563 return Success(CR == APFloat::cmpEqual, E);
7565 return Success(CR == APFloat::cmpGreaterThan
7566 || CR == APFloat::cmpLessThan
7567 || CR == APFloat::cmpUnordered, E);
7571 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
7572 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
7573 LValue LHSValue, RHSValue;
7575 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7576 if (!LHSOK && !Info.noteFailure())
7579 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7582 // Reject differing bases from the normal codepath; we special-case
7583 // comparisons to null.
7584 if (!HasSameBase(LHSValue, RHSValue)) {
7585 if (E->getOpcode() == BO_Sub) {
7586 // Handle &&A - &&B.
7587 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7589 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
7590 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
7591 if (!LHSExpr || !RHSExpr)
7593 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7594 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7595 if (!LHSAddrExpr || !RHSAddrExpr)
7597 // Make sure both labels come from the same function.
7598 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7599 RHSAddrExpr->getLabel()->getDeclContext())
7601 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
7603 // Inequalities and subtractions between unrelated pointers have
7604 // unspecified or undefined behavior.
7605 if (!E->isEqualityOp())
7607 // A constant address may compare equal to the address of a symbol.
7608 // The one exception is that address of an object cannot compare equal
7609 // to a null pointer constant.
7610 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7611 (!RHSValue.Base && !RHSValue.Offset.isZero()))
7613 // It's implementation-defined whether distinct literals will have
7614 // distinct addresses. In clang, the result of such a comparison is
7615 // unspecified, so it is not a constant expression. However, we do know
7616 // that the address of a literal will be non-null.
7617 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7618 LHSValue.Base && RHSValue.Base)
7620 // We can't tell whether weak symbols will end up pointing to the same
7622 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
7624 // We can't compare the address of the start of one object with the
7625 // past-the-end address of another object, per C++ DR1652.
7626 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7627 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7628 (RHSValue.Base && RHSValue.Offset.isZero() &&
7629 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7631 // We can't tell whether an object is at the same address as another
7632 // zero sized object.
7633 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7634 (LHSValue.Base && isZeroSized(RHSValue)))
7636 // Pointers with different bases cannot represent the same object.
7637 // (Note that clang defaults to -fmerge-all-constants, which can
7638 // lead to inconsistent results for comparisons involving the address
7639 // of a constant; this generally doesn't matter in practice.)
7640 return Success(E->getOpcode() == BO_NE, E);
7643 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7644 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7646 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7647 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7649 if (E->getOpcode() == BO_Sub) {
7650 // C++11 [expr.add]p6:
7651 // Unless both pointers point to elements of the same array object, or
7652 // one past the last element of the array object, the behavior is
7654 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7655 !AreElementsOfSameArray(getType(LHSValue.Base),
7656 LHSDesignator, RHSDesignator))
7657 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7659 QualType Type = E->getLHS()->getType();
7660 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
7662 CharUnits ElementSize;
7663 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
7666 // As an extension, a type may have zero size (empty struct or union in
7667 // C, array of zero length). Pointer subtraction in such cases has
7668 // undefined behavior, so is not constant.
7669 if (ElementSize.isZero()) {
7670 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7675 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7676 // and produce incorrect results when it overflows. Such behavior
7677 // appears to be non-conforming, but is common, so perhaps we should
7678 // assume the standard intended for such cases to be undefined behavior
7679 // and check for them.
7681 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7682 // overflow in the final conversion to ptrdiff_t.
7684 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7686 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7688 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7689 APSInt TrueResult = (LHS - RHS) / ElemSize;
7690 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7692 if (Result.extend(65) != TrueResult &&
7693 !HandleOverflow(Info, E, TrueResult, E->getType()))
7695 return Success(Result, E);
7698 // C++11 [expr.rel]p3:
7699 // Pointers to void (after pointer conversions) can be compared, with a
7700 // result defined as follows: If both pointers represent the same
7701 // address or are both the null pointer value, the result is true if the
7702 // operator is <= or >= and false otherwise; otherwise the result is
7704 // We interpret this as applying to pointers to *cv* void.
7705 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
7706 E->isRelationalOp())
7707 CCEDiag(E, diag::note_constexpr_void_comparison);
7709 // C++11 [expr.rel]p2:
7710 // - If two pointers point to non-static data members of the same object,
7711 // or to subobjects or array elements fo such members, recursively, the
7712 // pointer to the later declared member compares greater provided the
7713 // two members have the same access control and provided their class is
7716 // - Otherwise pointer comparisons are unspecified.
7717 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7718 E->isRelationalOp()) {
7721 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7722 RHSDesignator, WasArrayIndex);
7723 // At the point where the designators diverge, the comparison has a
7724 // specified value if:
7725 // - we are comparing array indices
7726 // - we are comparing fields of a union, or fields with the same access
7727 // Otherwise, the result is unspecified and thus the comparison is not a
7728 // constant expression.
7729 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7730 Mismatch < RHSDesignator.Entries.size()) {
7731 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7732 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7734 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7736 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7737 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7738 << RF->getParent() << RF;
7740 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7741 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7742 << LF->getParent() << LF;
7743 else if (!LF->getParent()->isUnion() &&
7744 LF->getAccess() != RF->getAccess())
7745 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7746 << LF << LF->getAccess() << RF << RF->getAccess()
7751 // The comparison here must be unsigned, and performed with the same
7752 // width as the pointer.
7753 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7754 uint64_t CompareLHS = LHSOffset.getQuantity();
7755 uint64_t CompareRHS = RHSOffset.getQuantity();
7756 assert(PtrSize <= 64 && "Unexpected pointer width");
7757 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7761 // If there is a base and this is a relational operator, we can only
7762 // compare pointers within the object in question; otherwise, the result
7763 // depends on where the object is located in memory.
7764 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7765 QualType BaseTy = getType(LHSValue.Base);
7766 if (BaseTy->isIncompleteType())
7768 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7769 uint64_t OffsetLimit = Size.getQuantity();
7770 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7774 switch (E->getOpcode()) {
7775 default: llvm_unreachable("missing comparison operator");
7776 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7777 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7778 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7779 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7780 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7781 case BO_NE: return Success(CompareLHS != CompareRHS, E);
7786 if (LHSTy->isMemberPointerType()) {
7787 assert(E->isEqualityOp() && "unexpected member pointer operation");
7788 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7790 MemberPtr LHSValue, RHSValue;
7792 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7793 if (!LHSOK && !Info.noteFailure())
7796 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7799 // C++11 [expr.eq]p2:
7800 // If both operands are null, they compare equal. Otherwise if only one is
7801 // null, they compare unequal.
7802 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7803 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7804 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7807 // Otherwise if either is a pointer to a virtual member function, the
7808 // result is unspecified.
7809 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7810 if (MD->isVirtual())
7811 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7812 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7813 if (MD->isVirtual())
7814 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7816 // Otherwise they compare equal if and only if they would refer to the
7817 // same member of the same most derived object or the same subobject if
7818 // they were dereferenced with a hypothetical object of the associated
7820 bool Equal = LHSValue == RHSValue;
7821 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7824 if (LHSTy->isNullPtrType()) {
7825 assert(E->isComparisonOp() && "unexpected nullptr operation");
7826 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7827 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7828 // are compared, the result is true of the operator is <=, >= or ==, and
7830 BinaryOperator::Opcode Opcode = E->getOpcode();
7831 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7834 assert((!LHSTy->isIntegralOrEnumerationType() ||
7835 !RHSTy->isIntegralOrEnumerationType()) &&
7836 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7837 // We can't continue from here for non-integral types.
7838 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7841 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7842 /// a result as the expression's type.
7843 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7844 const UnaryExprOrTypeTraitExpr *E) {
7845 switch(E->getKind()) {
7846 case UETT_AlignOf: {
7847 if (E->isArgumentType())
7848 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
7850 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
7853 case UETT_VecStep: {
7854 QualType Ty = E->getTypeOfArgument();
7856 if (Ty->isVectorType()) {
7857 unsigned n = Ty->castAs<VectorType>()->getNumElements();
7859 // The vec_step built-in functions that take a 3-component
7860 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7864 return Success(n, E);
7866 return Success(1, E);
7870 QualType SrcTy = E->getTypeOfArgument();
7871 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7872 // the result is the size of the referenced type."
7873 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7874 SrcTy = Ref->getPointeeType();
7877 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
7879 return Success(Sizeof, E);
7881 case UETT_OpenMPRequiredSimdAlign:
7882 assert(E->isArgumentType());
7884 Info.Ctx.toCharUnitsFromBits(
7885 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7890 llvm_unreachable("unknown expr/type trait");
7893 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
7895 unsigned n = OOE->getNumComponents();
7898 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
7899 for (unsigned i = 0; i != n; ++i) {
7900 OffsetOfNode ON = OOE->getComponent(i);
7901 switch (ON.getKind()) {
7902 case OffsetOfNode::Array: {
7903 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
7905 if (!EvaluateInteger(Idx, IdxResult, Info))
7907 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7910 CurrentType = AT->getElementType();
7911 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7912 Result += IdxResult.getSExtValue() * ElementSize;
7916 case OffsetOfNode::Field: {
7917 FieldDecl *MemberDecl = ON.getField();
7918 const RecordType *RT = CurrentType->getAs<RecordType>();
7921 RecordDecl *RD = RT->getDecl();
7922 if (RD->isInvalidDecl()) return false;
7923 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7924 unsigned i = MemberDecl->getFieldIndex();
7925 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
7926 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
7927 CurrentType = MemberDecl->getType().getNonReferenceType();
7931 case OffsetOfNode::Identifier:
7932 llvm_unreachable("dependent __builtin_offsetof");
7934 case OffsetOfNode::Base: {
7935 CXXBaseSpecifier *BaseSpec = ON.getBase();
7936 if (BaseSpec->isVirtual())
7939 // Find the layout of the class whose base we are looking into.
7940 const RecordType *RT = CurrentType->getAs<RecordType>();
7943 RecordDecl *RD = RT->getDecl();
7944 if (RD->isInvalidDecl()) return false;
7945 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7947 // Find the base class itself.
7948 CurrentType = BaseSpec->getType();
7949 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7953 // Add the offset to the base.
7954 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7959 return Success(Result, OOE);
7962 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7963 switch (E->getOpcode()) {
7965 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7969 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7970 // If so, we could clear the diagnostic ID.
7971 return Visit(E->getSubExpr());
7973 // The result is just the value.
7974 return Visit(E->getSubExpr());
7976 if (!Visit(E->getSubExpr()))
7978 if (!Result.isInt()) return Error(E);
7979 const APSInt &Value = Result.getInt();
7980 if (Value.isSigned() && Value.isMinSignedValue() &&
7981 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7984 return Success(-Value, E);
7987 if (!Visit(E->getSubExpr()))
7989 if (!Result.isInt()) return Error(E);
7990 return Success(~Result.getInt(), E);
7994 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7996 return Success(!bres, E);
8001 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8002 /// result type is integer.
8003 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8004 const Expr *SubExpr = E->getSubExpr();
8005 QualType DestType = E->getType();
8006 QualType SrcType = SubExpr->getType();
8008 switch (E->getCastKind()) {
8009 case CK_BaseToDerived:
8010 case CK_DerivedToBase:
8011 case CK_UncheckedDerivedToBase:
8014 case CK_ArrayToPointerDecay:
8015 case CK_FunctionToPointerDecay:
8016 case CK_NullToPointer:
8017 case CK_NullToMemberPointer:
8018 case CK_BaseToDerivedMemberPointer:
8019 case CK_DerivedToBaseMemberPointer:
8020 case CK_ReinterpretMemberPointer:
8021 case CK_ConstructorConversion:
8022 case CK_IntegralToPointer:
8024 case CK_VectorSplat:
8025 case CK_IntegralToFloating:
8026 case CK_FloatingCast:
8027 case CK_CPointerToObjCPointerCast:
8028 case CK_BlockPointerToObjCPointerCast:
8029 case CK_AnyPointerToBlockPointerCast:
8030 case CK_ObjCObjectLValueCast:
8031 case CK_FloatingRealToComplex:
8032 case CK_FloatingComplexToReal:
8033 case CK_FloatingComplexCast:
8034 case CK_FloatingComplexToIntegralComplex:
8035 case CK_IntegralRealToComplex:
8036 case CK_IntegralComplexCast:
8037 case CK_IntegralComplexToFloatingComplex:
8038 case CK_BuiltinFnToFnPtr:
8039 case CK_ZeroToOCLEvent:
8040 case CK_NonAtomicToAtomic:
8041 case CK_AddressSpaceConversion:
8042 llvm_unreachable("invalid cast kind for integral value");
8046 case CK_LValueBitCast:
8047 case CK_ARCProduceObject:
8048 case CK_ARCConsumeObject:
8049 case CK_ARCReclaimReturnedObject:
8050 case CK_ARCExtendBlockObject:
8051 case CK_CopyAndAutoreleaseBlockObject:
8054 case CK_UserDefinedConversion:
8055 case CK_LValueToRValue:
8056 case CK_AtomicToNonAtomic:
8058 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8060 case CK_MemberPointerToBoolean:
8061 case CK_PointerToBoolean:
8062 case CK_IntegralToBoolean:
8063 case CK_FloatingToBoolean:
8064 case CK_BooleanToSignedIntegral:
8065 case CK_FloatingComplexToBoolean:
8066 case CK_IntegralComplexToBoolean: {
8068 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8070 uint64_t IntResult = BoolResult;
8071 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8072 IntResult = (uint64_t)-1;
8073 return Success(IntResult, E);
8076 case CK_IntegralCast: {
8077 if (!Visit(SubExpr))
8080 if (!Result.isInt()) {
8081 // Allow casts of address-of-label differences if they are no-ops
8082 // or narrowing. (The narrowing case isn't actually guaranteed to
8083 // be constant-evaluatable except in some narrow cases which are hard
8084 // to detect here. We let it through on the assumption the user knows
8085 // what they are doing.)
8086 if (Result.isAddrLabelDiff())
8087 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8088 // Only allow casts of lvalues if they are lossless.
8089 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8092 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8093 Result.getInt()), E);
8096 case CK_PointerToIntegral: {
8097 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8100 if (!EvaluatePointer(SubExpr, LV, Info))
8103 if (LV.getLValueBase()) {
8104 // Only allow based lvalue casts if they are lossless.
8105 // FIXME: Allow a larger integer size than the pointer size, and allow
8106 // narrowing back down to pointer width in subsequent integral casts.
8107 // FIXME: Check integer type's active bits, not its type size.
8108 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8111 LV.Designator.setInvalid();
8112 LV.moveInto(Result);
8116 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8118 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8121 case CK_IntegralComplexToReal: {
8123 if (!EvaluateComplex(SubExpr, C, Info))
8125 return Success(C.getComplexIntReal(), E);
8128 case CK_FloatingToIntegral: {
8130 if (!EvaluateFloat(SubExpr, F, Info))
8134 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8136 return Success(Value, E);
8140 llvm_unreachable("unknown cast resulting in integral value");
8143 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8144 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8146 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8148 if (!LV.isComplexInt())
8150 return Success(LV.getComplexIntReal(), E);
8153 return Visit(E->getSubExpr());
8156 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8157 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8159 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8161 if (!LV.isComplexInt())
8163 return Success(LV.getComplexIntImag(), E);
8166 VisitIgnoredValue(E->getSubExpr());
8167 return Success(0, E);
8170 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8171 return Success(E->getPackLength(), E);
8174 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8175 return Success(E->getValue(), E);
8178 //===----------------------------------------------------------------------===//
8180 //===----------------------------------------------------------------------===//
8183 class FloatExprEvaluator
8184 : public ExprEvaluatorBase<FloatExprEvaluator> {
8187 FloatExprEvaluator(EvalInfo &info, APFloat &result)
8188 : ExprEvaluatorBaseTy(info), Result(result) {}
8190 bool Success(const APValue &V, const Expr *e) {
8191 Result = V.getFloat();
8195 bool ZeroInitialization(const Expr *E) {
8196 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8200 bool VisitCallExpr(const CallExpr *E);
8202 bool VisitUnaryOperator(const UnaryOperator *E);
8203 bool VisitBinaryOperator(const BinaryOperator *E);
8204 bool VisitFloatingLiteral(const FloatingLiteral *E);
8205 bool VisitCastExpr(const CastExpr *E);
8207 bool VisitUnaryReal(const UnaryOperator *E);
8208 bool VisitUnaryImag(const UnaryOperator *E);
8210 // FIXME: Missing: array subscript of vector, member of vector
8212 } // end anonymous namespace
8214 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
8215 assert(E->isRValue() && E->getType()->isRealFloatingType());
8216 return FloatExprEvaluator(Info, Result).Visit(E);
8219 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
8223 llvm::APFloat &Result) {
8224 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8225 if (!S) return false;
8227 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8231 // Treat empty strings as if they were zero.
8232 if (S->getString().empty())
8233 fill = llvm::APInt(32, 0);
8234 else if (S->getString().getAsInteger(0, fill))
8237 if (Context.getTargetInfo().isNan2008()) {
8239 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8241 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8243 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8244 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8245 // a different encoding to what became a standard in 2008, and for pre-
8246 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8247 // sNaN. This is now known as "legacy NaN" encoding.
8249 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8251 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8257 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
8258 switch (E->getBuiltinCallee()) {
8260 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8262 case Builtin::BI__builtin_huge_val:
8263 case Builtin::BI__builtin_huge_valf:
8264 case Builtin::BI__builtin_huge_vall:
8265 case Builtin::BI__builtin_inf:
8266 case Builtin::BI__builtin_inff:
8267 case Builtin::BI__builtin_infl: {
8268 const llvm::fltSemantics &Sem =
8269 Info.Ctx.getFloatTypeSemantics(E->getType());
8270 Result = llvm::APFloat::getInf(Sem);
8274 case Builtin::BI__builtin_nans:
8275 case Builtin::BI__builtin_nansf:
8276 case Builtin::BI__builtin_nansl:
8277 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8282 case Builtin::BI__builtin_nan:
8283 case Builtin::BI__builtin_nanf:
8284 case Builtin::BI__builtin_nanl:
8285 // If this is __builtin_nan() turn this into a nan, otherwise we
8286 // can't constant fold it.
8287 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8292 case Builtin::BI__builtin_fabs:
8293 case Builtin::BI__builtin_fabsf:
8294 case Builtin::BI__builtin_fabsl:
8295 if (!EvaluateFloat(E->getArg(0), Result, Info))
8298 if (Result.isNegative())
8299 Result.changeSign();
8302 // FIXME: Builtin::BI__builtin_powi
8303 // FIXME: Builtin::BI__builtin_powif
8304 // FIXME: Builtin::BI__builtin_powil
8306 case Builtin::BI__builtin_copysign:
8307 case Builtin::BI__builtin_copysignf:
8308 case Builtin::BI__builtin_copysignl: {
8310 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8311 !EvaluateFloat(E->getArg(1), RHS, Info))
8313 Result.copySign(RHS);
8319 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8320 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8322 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8324 Result = CV.FloatReal;
8328 return Visit(E->getSubExpr());
8331 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8332 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8334 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8336 Result = CV.FloatImag;
8340 VisitIgnoredValue(E->getSubExpr());
8341 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8342 Result = llvm::APFloat::getZero(Sem);
8346 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8347 switch (E->getOpcode()) {
8348 default: return Error(E);
8350 return EvaluateFloat(E->getSubExpr(), Result, Info);
8352 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8354 Result.changeSign();
8359 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8360 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8361 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8364 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8365 if (!LHSOK && !Info.noteFailure())
8367 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8368 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
8371 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8372 Result = E->getValue();
8376 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8377 const Expr* SubExpr = E->getSubExpr();
8379 switch (E->getCastKind()) {
8381 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8383 case CK_IntegralToFloating: {
8385 return EvaluateInteger(SubExpr, IntResult, Info) &&
8386 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8387 E->getType(), Result);
8390 case CK_FloatingCast: {
8391 if (!Visit(SubExpr))
8393 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8397 case CK_FloatingComplexToReal: {
8399 if (!EvaluateComplex(SubExpr, V, Info))
8401 Result = V.getComplexFloatReal();
8407 //===----------------------------------------------------------------------===//
8408 // Complex Evaluation (for float and integer)
8409 //===----------------------------------------------------------------------===//
8412 class ComplexExprEvaluator
8413 : public ExprEvaluatorBase<ComplexExprEvaluator> {
8414 ComplexValue &Result;
8417 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
8418 : ExprEvaluatorBaseTy(info), Result(Result) {}
8420 bool Success(const APValue &V, const Expr *e) {
8425 bool ZeroInitialization(const Expr *E);
8427 //===--------------------------------------------------------------------===//
8429 //===--------------------------------------------------------------------===//
8431 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
8432 bool VisitCastExpr(const CastExpr *E);
8433 bool VisitBinaryOperator(const BinaryOperator *E);
8434 bool VisitUnaryOperator(const UnaryOperator *E);
8435 bool VisitInitListExpr(const InitListExpr *E);
8437 } // end anonymous namespace
8439 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8441 assert(E->isRValue() && E->getType()->isAnyComplexType());
8442 return ComplexExprEvaluator(Info, Result).Visit(E);
8445 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
8446 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
8447 if (ElemTy->isRealFloatingType()) {
8448 Result.makeComplexFloat();
8449 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8450 Result.FloatReal = Zero;
8451 Result.FloatImag = Zero;
8453 Result.makeComplexInt();
8454 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8455 Result.IntReal = Zero;
8456 Result.IntImag = Zero;
8461 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8462 const Expr* SubExpr = E->getSubExpr();
8464 if (SubExpr->getType()->isRealFloatingType()) {
8465 Result.makeComplexFloat();
8466 APFloat &Imag = Result.FloatImag;
8467 if (!EvaluateFloat(SubExpr, Imag, Info))
8470 Result.FloatReal = APFloat(Imag.getSemantics());
8473 assert(SubExpr->getType()->isIntegerType() &&
8474 "Unexpected imaginary literal.");
8476 Result.makeComplexInt();
8477 APSInt &Imag = Result.IntImag;
8478 if (!EvaluateInteger(SubExpr, Imag, Info))
8481 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8486 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
8488 switch (E->getCastKind()) {
8490 case CK_BaseToDerived:
8491 case CK_DerivedToBase:
8492 case CK_UncheckedDerivedToBase:
8495 case CK_ArrayToPointerDecay:
8496 case CK_FunctionToPointerDecay:
8497 case CK_NullToPointer:
8498 case CK_NullToMemberPointer:
8499 case CK_BaseToDerivedMemberPointer:
8500 case CK_DerivedToBaseMemberPointer:
8501 case CK_MemberPointerToBoolean:
8502 case CK_ReinterpretMemberPointer:
8503 case CK_ConstructorConversion:
8504 case CK_IntegralToPointer:
8505 case CK_PointerToIntegral:
8506 case CK_PointerToBoolean:
8508 case CK_VectorSplat:
8509 case CK_IntegralCast:
8510 case CK_BooleanToSignedIntegral:
8511 case CK_IntegralToBoolean:
8512 case CK_IntegralToFloating:
8513 case CK_FloatingToIntegral:
8514 case CK_FloatingToBoolean:
8515 case CK_FloatingCast:
8516 case CK_CPointerToObjCPointerCast:
8517 case CK_BlockPointerToObjCPointerCast:
8518 case CK_AnyPointerToBlockPointerCast:
8519 case CK_ObjCObjectLValueCast:
8520 case CK_FloatingComplexToReal:
8521 case CK_FloatingComplexToBoolean:
8522 case CK_IntegralComplexToReal:
8523 case CK_IntegralComplexToBoolean:
8524 case CK_ARCProduceObject:
8525 case CK_ARCConsumeObject:
8526 case CK_ARCReclaimReturnedObject:
8527 case CK_ARCExtendBlockObject:
8528 case CK_CopyAndAutoreleaseBlockObject:
8529 case CK_BuiltinFnToFnPtr:
8530 case CK_ZeroToOCLEvent:
8531 case CK_NonAtomicToAtomic:
8532 case CK_AddressSpaceConversion:
8533 llvm_unreachable("invalid cast kind for complex value");
8535 case CK_LValueToRValue:
8536 case CK_AtomicToNonAtomic:
8538 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8541 case CK_LValueBitCast:
8542 case CK_UserDefinedConversion:
8545 case CK_FloatingRealToComplex: {
8546 APFloat &Real = Result.FloatReal;
8547 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
8550 Result.makeComplexFloat();
8551 Result.FloatImag = APFloat(Real.getSemantics());
8555 case CK_FloatingComplexCast: {
8556 if (!Visit(E->getSubExpr()))
8559 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8561 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8563 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8564 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
8567 case CK_FloatingComplexToIntegralComplex: {
8568 if (!Visit(E->getSubExpr()))
8571 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8573 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8574 Result.makeComplexInt();
8575 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8576 To, Result.IntReal) &&
8577 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8578 To, Result.IntImag);
8581 case CK_IntegralRealToComplex: {
8582 APSInt &Real = Result.IntReal;
8583 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8586 Result.makeComplexInt();
8587 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8591 case CK_IntegralComplexCast: {
8592 if (!Visit(E->getSubExpr()))
8595 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8597 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8599 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8600 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
8604 case CK_IntegralComplexToFloatingComplex: {
8605 if (!Visit(E->getSubExpr()))
8608 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
8610 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
8611 Result.makeComplexFloat();
8612 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8613 To, Result.FloatReal) &&
8614 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8615 To, Result.FloatImag);
8619 llvm_unreachable("unknown cast resulting in complex value");
8622 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8623 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8624 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8626 // Track whether the LHS or RHS is real at the type system level. When this is
8627 // the case we can simplify our evaluation strategy.
8628 bool LHSReal = false, RHSReal = false;
8631 if (E->getLHS()->getType()->isRealFloatingType()) {
8633 APFloat &Real = Result.FloatReal;
8634 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8636 Result.makeComplexFloat();
8637 Result.FloatImag = APFloat(Real.getSemantics());
8640 LHSOK = Visit(E->getLHS());
8642 if (!LHSOK && !Info.noteFailure())
8646 if (E->getRHS()->getType()->isRealFloatingType()) {
8648 APFloat &Real = RHS.FloatReal;
8649 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8651 RHS.makeComplexFloat();
8652 RHS.FloatImag = APFloat(Real.getSemantics());
8653 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8656 assert(!(LHSReal && RHSReal) &&
8657 "Cannot have both operands of a complex operation be real.");
8658 switch (E->getOpcode()) {
8659 default: return Error(E);
8661 if (Result.isComplexFloat()) {
8662 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8663 APFloat::rmNearestTiesToEven);
8665 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8667 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8668 APFloat::rmNearestTiesToEven);
8670 Result.getComplexIntReal() += RHS.getComplexIntReal();
8671 Result.getComplexIntImag() += RHS.getComplexIntImag();
8675 if (Result.isComplexFloat()) {
8676 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8677 APFloat::rmNearestTiesToEven);
8679 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8680 Result.getComplexFloatImag().changeSign();
8681 } else if (!RHSReal) {
8682 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8683 APFloat::rmNearestTiesToEven);
8686 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8687 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8691 if (Result.isComplexFloat()) {
8692 // This is an implementation of complex multiplication according to the
8693 // constraints laid out in C11 Annex G. The implemantion uses the
8694 // following naming scheme:
8695 // (a + ib) * (c + id)
8696 ComplexValue LHS = Result;
8697 APFloat &A = LHS.getComplexFloatReal();
8698 APFloat &B = LHS.getComplexFloatImag();
8699 APFloat &C = RHS.getComplexFloatReal();
8700 APFloat &D = RHS.getComplexFloatImag();
8701 APFloat &ResR = Result.getComplexFloatReal();
8702 APFloat &ResI = Result.getComplexFloatImag();
8704 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8707 } else if (RHSReal) {
8711 // In the fully general case, we need to handle NaNs and infinities
8719 if (ResR.isNaN() && ResI.isNaN()) {
8720 bool Recalc = false;
8721 if (A.isInfinity() || B.isInfinity()) {
8722 A = APFloat::copySign(
8723 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8724 B = APFloat::copySign(
8725 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8727 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8729 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8732 if (C.isInfinity() || D.isInfinity()) {
8733 C = APFloat::copySign(
8734 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8735 D = APFloat::copySign(
8736 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8738 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8740 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8743 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8744 AD.isInfinity() || BC.isInfinity())) {
8746 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8748 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8750 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8752 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8756 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8757 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8762 ComplexValue LHS = Result;
8763 Result.getComplexIntReal() =
8764 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8765 LHS.getComplexIntImag() * RHS.getComplexIntImag());
8766 Result.getComplexIntImag() =
8767 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8768 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8772 if (Result.isComplexFloat()) {
8773 // This is an implementation of complex division according to the
8774 // constraints laid out in C11 Annex G. The implemantion uses the
8775 // following naming scheme:
8776 // (a + ib) / (c + id)
8777 ComplexValue LHS = Result;
8778 APFloat &A = LHS.getComplexFloatReal();
8779 APFloat &B = LHS.getComplexFloatImag();
8780 APFloat &C = RHS.getComplexFloatReal();
8781 APFloat &D = RHS.getComplexFloatImag();
8782 APFloat &ResR = Result.getComplexFloatReal();
8783 APFloat &ResI = Result.getComplexFloatImag();
8789 // No real optimizations we can do here, stub out with zero.
8790 B = APFloat::getZero(A.getSemantics());
8793 APFloat MaxCD = maxnum(abs(C), abs(D));
8794 if (MaxCD.isFinite()) {
8795 DenomLogB = ilogb(MaxCD);
8796 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8797 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
8799 APFloat Denom = C * C + D * D;
8800 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8801 APFloat::rmNearestTiesToEven);
8802 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8803 APFloat::rmNearestTiesToEven);
8804 if (ResR.isNaN() && ResI.isNaN()) {
8805 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8806 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8807 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8808 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8810 A = APFloat::copySign(
8811 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8812 B = APFloat::copySign(
8813 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8814 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8815 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8816 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8817 C = APFloat::copySign(
8818 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8819 D = APFloat::copySign(
8820 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8821 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8822 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8827 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8828 return Error(E, diag::note_expr_divide_by_zero);
8830 ComplexValue LHS = Result;
8831 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8832 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8833 Result.getComplexIntReal() =
8834 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8835 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8836 Result.getComplexIntImag() =
8837 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8838 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8846 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8847 // Get the operand value into 'Result'.
8848 if (!Visit(E->getSubExpr()))
8851 switch (E->getOpcode()) {
8857 // The result is always just the subexpr.
8860 if (Result.isComplexFloat()) {
8861 Result.getComplexFloatReal().changeSign();
8862 Result.getComplexFloatImag().changeSign();
8865 Result.getComplexIntReal() = -Result.getComplexIntReal();
8866 Result.getComplexIntImag() = -Result.getComplexIntImag();
8870 if (Result.isComplexFloat())
8871 Result.getComplexFloatImag().changeSign();
8873 Result.getComplexIntImag() = -Result.getComplexIntImag();
8878 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8879 if (E->getNumInits() == 2) {
8880 if (E->getType()->isComplexType()) {
8881 Result.makeComplexFloat();
8882 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8884 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8887 Result.makeComplexInt();
8888 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8890 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8895 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8898 //===----------------------------------------------------------------------===//
8899 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8900 // implicit conversion.
8901 //===----------------------------------------------------------------------===//
8904 class AtomicExprEvaluator :
8905 public ExprEvaluatorBase<AtomicExprEvaluator> {
8908 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8909 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8911 bool Success(const APValue &V, const Expr *E) {
8916 bool ZeroInitialization(const Expr *E) {
8917 ImplicitValueInitExpr VIE(
8918 E->getType()->castAs<AtomicType>()->getValueType());
8919 return Evaluate(Result, Info, &VIE);
8922 bool VisitCastExpr(const CastExpr *E) {
8923 switch (E->getCastKind()) {
8925 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8926 case CK_NonAtomicToAtomic:
8927 return Evaluate(Result, Info, E->getSubExpr());
8931 } // end anonymous namespace
8933 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8934 assert(E->isRValue() && E->getType()->isAtomicType());
8935 return AtomicExprEvaluator(Info, Result).Visit(E);
8938 //===----------------------------------------------------------------------===//
8939 // Void expression evaluation, primarily for a cast to void on the LHS of a
8941 //===----------------------------------------------------------------------===//
8944 class VoidExprEvaluator
8945 : public ExprEvaluatorBase<VoidExprEvaluator> {
8947 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8949 bool Success(const APValue &V, const Expr *e) { return true; }
8951 bool VisitCastExpr(const CastExpr *E) {
8952 switch (E->getCastKind()) {
8954 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8956 VisitIgnoredValue(E->getSubExpr());
8961 bool VisitCallExpr(const CallExpr *E) {
8962 switch (E->getBuiltinCallee()) {
8964 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8965 case Builtin::BI__assume:
8966 case Builtin::BI__builtin_assume:
8967 // The argument is not evaluated!
8972 } // end anonymous namespace
8974 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8975 assert(E->isRValue() && E->getType()->isVoidType());
8976 return VoidExprEvaluator(Info).Visit(E);
8979 //===----------------------------------------------------------------------===//
8980 // Top level Expr::EvaluateAsRValue method.
8981 //===----------------------------------------------------------------------===//
8983 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
8984 // In C, function designators are not lvalues, but we evaluate them as if they
8986 QualType T = E->getType();
8987 if (E->isGLValue() || T->isFunctionType()) {
8989 if (!EvaluateLValue(E, LV, Info))
8991 LV.moveInto(Result);
8992 } else if (T->isVectorType()) {
8993 if (!EvaluateVector(E, Result, Info))
8995 } else if (T->isIntegralOrEnumerationType()) {
8996 if (!IntExprEvaluator(Info, Result).Visit(E))
8998 } else if (T->hasPointerRepresentation()) {
9000 if (!EvaluatePointer(E, LV, Info))
9002 LV.moveInto(Result);
9003 } else if (T->isRealFloatingType()) {
9004 llvm::APFloat F(0.0);
9005 if (!EvaluateFloat(E, F, Info))
9007 Result = APValue(F);
9008 } else if (T->isAnyComplexType()) {
9010 if (!EvaluateComplex(E, C, Info))
9013 } else if (T->isMemberPointerType()) {
9015 if (!EvaluateMemberPointer(E, P, Info))
9019 } else if (T->isArrayType()) {
9021 LV.set(E, Info.CurrentCall->Index);
9022 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9023 if (!EvaluateArray(E, LV, Value, Info))
9026 } else if (T->isRecordType()) {
9028 LV.set(E, Info.CurrentCall->Index);
9029 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9030 if (!EvaluateRecord(E, LV, Value, Info))
9033 } else if (T->isVoidType()) {
9034 if (!Info.getLangOpts().CPlusPlus11)
9035 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9037 if (!EvaluateVoid(E, Info))
9039 } else if (T->isAtomicType()) {
9040 if (!EvaluateAtomic(E, Result, Info))
9042 } else if (Info.getLangOpts().CPlusPlus11) {
9043 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9046 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9053 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9054 /// cases, the in-place evaluation is essential, since later initializers for
9055 /// an object can indirectly refer to subobjects which were initialized earlier.
9056 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9057 const Expr *E, bool AllowNonLiteralTypes) {
9058 assert(!E->isValueDependent());
9060 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9063 if (E->isRValue()) {
9064 // Evaluate arrays and record types in-place, so that later initializers can
9065 // refer to earlier-initialized members of the object.
9066 if (E->getType()->isArrayType())
9067 return EvaluateArray(E, This, Result, Info);
9068 else if (E->getType()->isRecordType())
9069 return EvaluateRecord(E, This, Result, Info);
9072 // For any other type, in-place evaluation is unimportant.
9073 return Evaluate(Result, Info, E);
9076 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9077 /// lvalue-to-rvalue cast if it is an lvalue.
9078 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9079 if (E->getType().isNull())
9082 if (!CheckLiteralType(Info, E))
9085 if (!::Evaluate(Result, Info, E))
9088 if (E->isGLValue()) {
9090 LV.setFrom(Info.Ctx, Result);
9091 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9095 // Check this core constant expression is a constant expression.
9096 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9099 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9100 const ASTContext &Ctx, bool &IsConst) {
9101 // Fast-path evaluations of integer literals, since we sometimes see files
9102 // containing vast quantities of these.
9103 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9104 Result.Val = APValue(APSInt(L->getValue(),
9105 L->getType()->isUnsignedIntegerType()));
9110 // This case should be rare, but we need to check it before we check on
9112 if (Exp->getType().isNull()) {
9117 // FIXME: Evaluating values of large array and record types can cause
9118 // performance problems. Only do so in C++11 for now.
9119 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9120 Exp->getType()->isRecordType()) &&
9121 !Ctx.getLangOpts().CPlusPlus11) {
9129 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9130 /// any crazy technique (that has nothing to do with language standards) that
9131 /// we want to. If this function returns true, it returns the folded constant
9132 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9133 /// will be applied to the result.
9134 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9136 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9139 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9140 return ::EvaluateAsRValue(Info, this, Result.Val);
9143 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9144 const ASTContext &Ctx) const {
9146 return EvaluateAsRValue(Scratch, Ctx) &&
9147 HandleConversionToBool(Scratch.Val, Result);
9150 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9151 Expr::SideEffectsKind SEK) {
9152 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9153 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9156 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9157 SideEffectsKind AllowSideEffects) const {
9158 if (!getType()->isIntegralOrEnumerationType())
9161 EvalResult ExprResult;
9162 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9163 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9166 Result = ExprResult.Val.getInt();
9170 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9171 SideEffectsKind AllowSideEffects) const {
9172 if (!getType()->isRealFloatingType())
9175 EvalResult ExprResult;
9176 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9177 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9180 Result = ExprResult.Val.getFloat();
9184 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
9185 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
9188 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9189 !CheckLValueConstantExpression(Info, getExprLoc(),
9190 Ctx.getLValueReferenceType(getType()), LV))
9193 LV.moveInto(Result.Val);
9197 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9199 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
9200 // FIXME: Evaluating initializers for large array and record types can cause
9201 // performance problems. Only do so in C++11 for now.
9202 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
9203 !Ctx.getLangOpts().CPlusPlus11)
9206 Expr::EvalStatus EStatus;
9207 EStatus.Diag = &Notes;
9209 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9210 ? EvalInfo::EM_ConstantExpression
9211 : EvalInfo::EM_ConstantFold);
9212 InitInfo.setEvaluatingDecl(VD, Value);
9217 // C++11 [basic.start.init]p2:
9218 // Variables with static storage duration or thread storage duration shall be
9219 // zero-initialized before any other initialization takes place.
9220 // This behavior is not present in C.
9221 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
9222 !VD->getType()->isReferenceType()) {
9223 ImplicitValueInitExpr VIE(VD->getType());
9224 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
9225 /*AllowNonLiteralTypes=*/true))
9229 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9230 /*AllowNonLiteralTypes=*/true) ||
9231 EStatus.HasSideEffects)
9234 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9238 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9239 /// constant folded, but discard the result.
9240 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
9242 return EvaluateAsRValue(Result, Ctx) &&
9243 !hasUnacceptableSideEffect(Result, SEK);
9246 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
9247 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
9248 EvalResult EvalResult;
9249 EvalResult.Diag = Diag;
9250 bool Result = EvaluateAsRValue(EvalResult, Ctx);
9252 assert(Result && "Could not evaluate expression");
9253 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
9255 return EvalResult.Val.getInt();
9258 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
9260 EvalResult EvalResult;
9261 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
9262 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
9263 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9267 bool Expr::EvalResult::isGlobalLValue() const {
9268 assert(Val.isLValue());
9269 return IsGlobalLValue(Val.getLValueBase());
9273 /// isIntegerConstantExpr - this recursive routine will test if an expression is
9274 /// an integer constant expression.
9276 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9279 // CheckICE - This function does the fundamental ICE checking: the returned
9280 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9281 // and a (possibly null) SourceLocation indicating the location of the problem.
9283 // Note that to reduce code duplication, this helper does no evaluation
9284 // itself; the caller checks whether the expression is evaluatable, and
9285 // in the rare cases where CheckICE actually cares about the evaluated
9286 // value, it calls into Evalute.
9291 /// This expression is an ICE.
9293 /// This expression is not an ICE, but if it isn't evaluated, it's
9294 /// a legal subexpression for an ICE. This return value is used to handle
9295 /// the comma operator in C99 mode, and non-constant subexpressions.
9296 IK_ICEIfUnevaluated,
9297 /// This expression is not an ICE, and is not a legal subexpression for one.
9305 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9310 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9312 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9314 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9315 Expr::EvalResult EVResult;
9316 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9317 !EVResult.Val.isInt())
9318 return ICEDiag(IK_NotICE, E->getLocStart());
9323 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9324 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9325 if (!E->getType()->isIntegralOrEnumerationType())
9326 return ICEDiag(IK_NotICE, E->getLocStart());
9328 switch (E->getStmtClass()) {
9329 #define ABSTRACT_STMT(Node)
9330 #define STMT(Node, Base) case Expr::Node##Class:
9331 #define EXPR(Node, Base)
9332 #include "clang/AST/StmtNodes.inc"
9333 case Expr::PredefinedExprClass:
9334 case Expr::FloatingLiteralClass:
9335 case Expr::ImaginaryLiteralClass:
9336 case Expr::StringLiteralClass:
9337 case Expr::ArraySubscriptExprClass:
9338 case Expr::OMPArraySectionExprClass:
9339 case Expr::MemberExprClass:
9340 case Expr::CompoundAssignOperatorClass:
9341 case Expr::CompoundLiteralExprClass:
9342 case Expr::ExtVectorElementExprClass:
9343 case Expr::DesignatedInitExprClass:
9344 case Expr::NoInitExprClass:
9345 case Expr::DesignatedInitUpdateExprClass:
9346 case Expr::ImplicitValueInitExprClass:
9347 case Expr::ParenListExprClass:
9348 case Expr::VAArgExprClass:
9349 case Expr::AddrLabelExprClass:
9350 case Expr::StmtExprClass:
9351 case Expr::CXXMemberCallExprClass:
9352 case Expr::CUDAKernelCallExprClass:
9353 case Expr::CXXDynamicCastExprClass:
9354 case Expr::CXXTypeidExprClass:
9355 case Expr::CXXUuidofExprClass:
9356 case Expr::MSPropertyRefExprClass:
9357 case Expr::MSPropertySubscriptExprClass:
9358 case Expr::CXXNullPtrLiteralExprClass:
9359 case Expr::UserDefinedLiteralClass:
9360 case Expr::CXXThisExprClass:
9361 case Expr::CXXThrowExprClass:
9362 case Expr::CXXNewExprClass:
9363 case Expr::CXXDeleteExprClass:
9364 case Expr::CXXPseudoDestructorExprClass:
9365 case Expr::UnresolvedLookupExprClass:
9366 case Expr::TypoExprClass:
9367 case Expr::DependentScopeDeclRefExprClass:
9368 case Expr::CXXConstructExprClass:
9369 case Expr::CXXInheritedCtorInitExprClass:
9370 case Expr::CXXStdInitializerListExprClass:
9371 case Expr::CXXBindTemporaryExprClass:
9372 case Expr::ExprWithCleanupsClass:
9373 case Expr::CXXTemporaryObjectExprClass:
9374 case Expr::CXXUnresolvedConstructExprClass:
9375 case Expr::CXXDependentScopeMemberExprClass:
9376 case Expr::UnresolvedMemberExprClass:
9377 case Expr::ObjCStringLiteralClass:
9378 case Expr::ObjCBoxedExprClass:
9379 case Expr::ObjCArrayLiteralClass:
9380 case Expr::ObjCDictionaryLiteralClass:
9381 case Expr::ObjCEncodeExprClass:
9382 case Expr::ObjCMessageExprClass:
9383 case Expr::ObjCSelectorExprClass:
9384 case Expr::ObjCProtocolExprClass:
9385 case Expr::ObjCIvarRefExprClass:
9386 case Expr::ObjCPropertyRefExprClass:
9387 case Expr::ObjCSubscriptRefExprClass:
9388 case Expr::ObjCIsaExprClass:
9389 case Expr::ObjCAvailabilityCheckExprClass:
9390 case Expr::ShuffleVectorExprClass:
9391 case Expr::ConvertVectorExprClass:
9392 case Expr::BlockExprClass:
9393 case Expr::NoStmtClass:
9394 case Expr::OpaqueValueExprClass:
9395 case Expr::PackExpansionExprClass:
9396 case Expr::SubstNonTypeTemplateParmPackExprClass:
9397 case Expr::FunctionParmPackExprClass:
9398 case Expr::AsTypeExprClass:
9399 case Expr::ObjCIndirectCopyRestoreExprClass:
9400 case Expr::MaterializeTemporaryExprClass:
9401 case Expr::PseudoObjectExprClass:
9402 case Expr::AtomicExprClass:
9403 case Expr::LambdaExprClass:
9404 case Expr::CXXFoldExprClass:
9405 case Expr::CoawaitExprClass:
9406 case Expr::CoyieldExprClass:
9407 return ICEDiag(IK_NotICE, E->getLocStart());
9409 case Expr::InitListExprClass: {
9410 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9411 // form "T x = { a };" is equivalent to "T x = a;".
9412 // Unless we're initializing a reference, T is a scalar as it is known to be
9413 // of integral or enumeration type.
9415 if (cast<InitListExpr>(E)->getNumInits() == 1)
9416 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9417 return ICEDiag(IK_NotICE, E->getLocStart());
9420 case Expr::SizeOfPackExprClass:
9421 case Expr::GNUNullExprClass:
9422 // GCC considers the GNU __null value to be an integral constant expression.
9425 case Expr::SubstNonTypeTemplateParmExprClass:
9427 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9429 case Expr::ParenExprClass:
9430 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
9431 case Expr::GenericSelectionExprClass:
9432 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
9433 case Expr::IntegerLiteralClass:
9434 case Expr::CharacterLiteralClass:
9435 case Expr::ObjCBoolLiteralExprClass:
9436 case Expr::CXXBoolLiteralExprClass:
9437 case Expr::CXXScalarValueInitExprClass:
9438 case Expr::TypeTraitExprClass:
9439 case Expr::ArrayTypeTraitExprClass:
9440 case Expr::ExpressionTraitExprClass:
9441 case Expr::CXXNoexceptExprClass:
9443 case Expr::CallExprClass:
9444 case Expr::CXXOperatorCallExprClass: {
9445 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9446 // constant expressions, but they can never be ICEs because an ICE cannot
9447 // contain an operand of (pointer to) function type.
9448 const CallExpr *CE = cast<CallExpr>(E);
9449 if (CE->getBuiltinCallee())
9450 return CheckEvalInICE(E, Ctx);
9451 return ICEDiag(IK_NotICE, E->getLocStart());
9453 case Expr::DeclRefExprClass: {
9454 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9456 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
9457 if (Ctx.getLangOpts().CPlusPlus &&
9458 D && IsConstNonVolatile(D->getType())) {
9459 // Parameter variables are never constants. Without this check,
9460 // getAnyInitializer() can find a default argument, which leads
9462 if (isa<ParmVarDecl>(D))
9463 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9466 // A variable of non-volatile const-qualified integral or enumeration
9467 // type initialized by an ICE can be used in ICEs.
9468 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
9469 if (!Dcl->getType()->isIntegralOrEnumerationType())
9470 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9473 // Look for a declaration of this variable that has an initializer, and
9474 // check whether it is an ICE.
9475 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9478 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
9481 return ICEDiag(IK_NotICE, E->getLocStart());
9483 case Expr::UnaryOperatorClass: {
9484 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9485 switch (Exp->getOpcode()) {
9493 // C99 6.6/3 allows increment and decrement within unevaluated
9494 // subexpressions of constant expressions, but they can never be ICEs
9495 // because an ICE cannot contain an lvalue operand.
9496 return ICEDiag(IK_NotICE, E->getLocStart());
9504 return CheckICE(Exp->getSubExpr(), Ctx);
9507 // OffsetOf falls through here.
9509 case Expr::OffsetOfExprClass: {
9510 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9511 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9512 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9513 // compliance: we should warn earlier for offsetof expressions with
9514 // array subscripts that aren't ICEs, and if the array subscripts
9515 // are ICEs, the value of the offsetof must be an integer constant.
9516 return CheckEvalInICE(E, Ctx);
9518 case Expr::UnaryExprOrTypeTraitExprClass: {
9519 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9520 if ((Exp->getKind() == UETT_SizeOf) &&
9521 Exp->getTypeOfArgument()->isVariableArrayType())
9522 return ICEDiag(IK_NotICE, E->getLocStart());
9525 case Expr::BinaryOperatorClass: {
9526 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9527 switch (Exp->getOpcode()) {
9541 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9542 // constant expressions, but they can never be ICEs because an ICE cannot
9543 // contain an lvalue operand.
9544 return ICEDiag(IK_NotICE, E->getLocStart());
9563 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9564 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
9565 if (Exp->getOpcode() == BO_Div ||
9566 Exp->getOpcode() == BO_Rem) {
9567 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
9568 // we don't evaluate one.
9569 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
9570 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
9572 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9573 if (REval.isSigned() && REval.isAllOnesValue()) {
9574 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
9575 if (LEval.isMinSignedValue())
9576 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9580 if (Exp->getOpcode() == BO_Comma) {
9581 if (Ctx.getLangOpts().C99) {
9582 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9583 // if it isn't evaluated.
9584 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9585 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
9587 // In both C89 and C++, commas in ICEs are illegal.
9588 return ICEDiag(IK_NotICE, E->getLocStart());
9591 return Worst(LHSResult, RHSResult);
9595 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9596 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
9597 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
9598 // Rare case where the RHS has a comma "side-effect"; we need
9599 // to actually check the condition to see whether the side
9600 // with the comma is evaluated.
9601 if ((Exp->getOpcode() == BO_LAnd) !=
9602 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
9607 return Worst(LHSResult, RHSResult);
9611 case Expr::ImplicitCastExprClass:
9612 case Expr::CStyleCastExprClass:
9613 case Expr::CXXFunctionalCastExprClass:
9614 case Expr::CXXStaticCastExprClass:
9615 case Expr::CXXReinterpretCastExprClass:
9616 case Expr::CXXConstCastExprClass:
9617 case Expr::ObjCBridgedCastExprClass: {
9618 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
9619 if (isa<ExplicitCastExpr>(E)) {
9620 if (const FloatingLiteral *FL
9621 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9622 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9623 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9624 APSInt IgnoredVal(DestWidth, !DestSigned);
9626 // If the value does not fit in the destination type, the behavior is
9627 // undefined, so we are not required to treat it as a constant
9629 if (FL->getValue().convertToInteger(IgnoredVal,
9630 llvm::APFloat::rmTowardZero,
9631 &Ignored) & APFloat::opInvalidOp)
9632 return ICEDiag(IK_NotICE, E->getLocStart());
9636 switch (cast<CastExpr>(E)->getCastKind()) {
9637 case CK_LValueToRValue:
9638 case CK_AtomicToNonAtomic:
9639 case CK_NonAtomicToAtomic:
9641 case CK_IntegralToBoolean:
9642 case CK_IntegralCast:
9643 return CheckICE(SubExpr, Ctx);
9645 return ICEDiag(IK_NotICE, E->getLocStart());
9648 case Expr::BinaryConditionalOperatorClass: {
9649 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9650 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
9651 if (CommonResult.Kind == IK_NotICE) return CommonResult;
9652 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9653 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9654 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9655 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
9656 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
9659 case Expr::ConditionalOperatorClass: {
9660 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9661 // If the condition (ignoring parens) is a __builtin_constant_p call,
9662 // then only the true side is actually considered in an integer constant
9663 // expression, and it is fully evaluated. This is an important GNU
9664 // extension. See GCC PR38377 for discussion.
9665 if (const CallExpr *CallCE
9666 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
9667 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
9668 return CheckEvalInICE(E, Ctx);
9669 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
9670 if (CondResult.Kind == IK_NotICE)
9673 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9674 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
9676 if (TrueResult.Kind == IK_NotICE)
9678 if (FalseResult.Kind == IK_NotICE)
9680 if (CondResult.Kind == IK_ICEIfUnevaluated)
9682 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
9684 // Rare case where the diagnostics depend on which side is evaluated
9685 // Note that if we get here, CondResult is 0, and at least one of
9686 // TrueResult and FalseResult is non-zero.
9687 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
9691 case Expr::CXXDefaultArgExprClass:
9692 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
9693 case Expr::CXXDefaultInitExprClass:
9694 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
9695 case Expr::ChooseExprClass: {
9696 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
9700 llvm_unreachable("Invalid StmtClass!");
9703 /// Evaluate an expression as a C++11 integral constant expression.
9704 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
9706 llvm::APSInt *Value,
9707 SourceLocation *Loc) {
9708 if (!E->getType()->isIntegralOrEnumerationType()) {
9709 if (Loc) *Loc = E->getExprLoc();
9714 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
9717 if (!Result.isInt()) {
9718 if (Loc) *Loc = E->getExprLoc();
9722 if (Value) *Value = Result.getInt();
9726 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9727 SourceLocation *Loc) const {
9728 if (Ctx.getLangOpts().CPlusPlus11)
9729 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
9731 ICEDiag D = CheckICE(this, Ctx);
9732 if (D.Kind != IK_ICE) {
9733 if (Loc) *Loc = D.Loc;
9739 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
9740 SourceLocation *Loc, bool isEvaluated) const {
9741 if (Ctx.getLangOpts().CPlusPlus11)
9742 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9744 if (!isIntegerConstantExpr(Ctx, Loc))
9746 // The only possible side-effects here are due to UB discovered in the
9747 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9748 // required to treat the expression as an ICE, so we produce the folded
9750 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
9751 llvm_unreachable("ICE cannot be evaluated!");
9755 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
9756 return CheckICE(this, Ctx).Kind == IK_ICE;
9759 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
9760 SourceLocation *Loc) const {
9761 // We support this checking in C++98 mode in order to diagnose compatibility
9763 assert(Ctx.getLangOpts().CPlusPlus);
9765 // Build evaluation settings.
9766 Expr::EvalStatus Status;
9767 SmallVector<PartialDiagnosticAt, 8> Diags;
9768 Status.Diag = &Diags;
9769 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
9772 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9774 if (!Diags.empty()) {
9775 IsConstExpr = false;
9776 if (Loc) *Loc = Diags[0].first;
9777 } else if (!IsConstExpr) {
9778 // FIXME: This shouldn't happen.
9779 if (Loc) *Loc = getExprLoc();
9785 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9786 const FunctionDecl *Callee,
9787 ArrayRef<const Expr*> Args) const {
9788 Expr::EvalStatus Status;
9789 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9791 ArgVector ArgValues(Args.size());
9792 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9794 if ((*I)->isValueDependent() ||
9795 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
9796 // If evaluation fails, throw away the argument entirely.
9797 ArgValues[I - Args.begin()] = APValue();
9798 if (Info.EvalStatus.HasSideEffects)
9802 // Build fake call to Callee.
9803 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
9805 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9808 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
9810 PartialDiagnosticAt> &Diags) {
9811 // FIXME: It would be useful to check constexpr function templates, but at the
9812 // moment the constant expression evaluator cannot cope with the non-rigorous
9813 // ASTs which we build for dependent expressions.
9814 if (FD->isDependentContext())
9817 Expr::EvalStatus Status;
9818 Status.Diag = &Diags;
9820 EvalInfo Info(FD->getASTContext(), Status,
9821 EvalInfo::EM_PotentialConstantExpression);
9823 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9824 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
9826 // Fabricate an arbitrary expression on the stack and pretend that it
9827 // is a temporary being used as the 'this' pointer.
9829 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
9830 This.set(&VIE, Info.CurrentCall->Index);
9832 ArrayRef<const Expr*> Args;
9835 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9836 // Evaluate the call as a constant initializer, to allow the construction
9837 // of objects of non-literal types.
9838 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
9839 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
9841 SourceLocation Loc = FD->getLocation();
9842 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
9843 Args, FD->getBody(), Info, Scratch, nullptr);
9846 return Diags.empty();
9849 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9850 const FunctionDecl *FD,
9852 PartialDiagnosticAt> &Diags) {
9853 Expr::EvalStatus Status;
9854 Status.Diag = &Diags;
9856 EvalInfo Info(FD->getASTContext(), Status,
9857 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9859 // Fabricate a call stack frame to give the arguments a plausible cover story.
9860 ArrayRef<const Expr*> Args;
9861 ArgVector ArgValues(0);
9862 bool Success = EvaluateArgs(Args, ArgValues, Info);
9865 "Failed to set up arguments for potential constant evaluation");
9866 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
9868 APValue ResultScratch;
9869 Evaluate(ResultScratch, Info, E);
9870 return Diags.empty();
9873 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9874 unsigned Type) const {
9875 if (!getType()->isPointerType())
9878 Expr::EvalStatus Status;
9879 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9880 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);