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/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.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
79 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
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 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&
155 "Unsized arrays shouldn't appear here");
156 unsigned MostDerivedLength = 0;
157 Type = getType(Base);
159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 MostDerivedLength = I + 1;
167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
171 MostDerivedLength = I + 1;
173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
176 MostDerivedLength = I + 1;
179 // Path[I] describes a base class.
184 return MostDerivedLength;
187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
190 CSK_This, CSK_Real, CSK_Imag
193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
198 unsigned Invalid : 1;
200 /// Is this a pointer one past the end of an object?
201 unsigned IsOnePastTheEnd : 1;
203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
206 /// Indicator of whether the most-derived object is an array element.
207 unsigned MostDerivedIsArrayElement : 1;
209 /// The length of the path to the most-derived object of which this is a
211 unsigned MostDerivedPathLength : 28;
213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
218 /// If the current array is an unsized array, the value of this is
220 uint64_t MostDerivedArraySize;
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
225 typedef APValue::LValuePathEntry PathEntry;
227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
230 SubobjectDesignator() : Invalid(true) {}
232 explicit SubobjectDesignator(QualType T)
233 : Invalid(false), IsOnePastTheEnd(false),
234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
247 if (V.getLValueBase()) {
248 bool IsArray = false;
249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
252 MostDerivedIsArrayElement = IsArray;
262 /// Determine whether the most derived subobject is an array without a
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators");
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273 return MostDerivedArraySize;
276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
291 return !isOnePastTheEnd();
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
300 Entry.ArrayIndex = 0;
301 Entries.push_back(Entry);
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
305 MostDerivedIsArrayElement = true;
306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 MostDerivedPathLength = Entries.size();
324 /// Update this designator to refer to the given base or member of this
326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
330 Entries.push_back(Entry);
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
335 MostDerivedIsArrayElement = false;
336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
349 MostDerivedIsArrayElement = true;
350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
354 /// Add N to the address of this subobject.
355 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
357 if (isMostDerivedAnUnsizedArray()) {
358 // Can't verify -- trust that the user is doing the right thing (or if
359 // not, trust that the caller will catch the bad behavior).
360 Entries.back().ArrayIndex += N;
363 if (MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement) {
365 Entries.back().ArrayIndex += N;
366 if (Entries.back().ArrayIndex > getMostDerivedArraySize()) {
367 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
372 // [expr.add]p4: For the purposes of these operators, a pointer to a
373 // nonarray object behaves the same as a pointer to the first element of
374 // an array of length one with the type of the object as its element type.
375 if (IsOnePastTheEnd && N == (uint64_t)-1)
376 IsOnePastTheEnd = false;
377 else if (!IsOnePastTheEnd && N == 1)
378 IsOnePastTheEnd = true;
380 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
386 /// A stack frame in the constexpr call stack.
387 struct CallStackFrame {
390 /// Parent - The caller of this stack frame.
391 CallStackFrame *Caller;
393 /// Callee - The function which was called.
394 const FunctionDecl *Callee;
396 /// This - The binding for the this pointer in this call, if any.
399 /// Arguments - Parameter bindings for this function call, indexed by
400 /// parameters' function scope indices.
403 // Note that we intentionally use std::map here so that references to
404 // values are stable.
405 typedef std::map<const void*, APValue> MapTy;
406 typedef MapTy::const_iterator temp_iterator;
407 /// Temporaries - Temporary lvalues materialized within this stack frame.
410 /// CallLoc - The location of the call expression for this call.
411 SourceLocation CallLoc;
413 /// Index - The call index of this call.
416 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
417 const FunctionDecl *Callee, const LValue *This,
421 APValue *getTemporary(const void *Key) {
422 MapTy::iterator I = Temporaries.find(Key);
423 return I == Temporaries.end() ? nullptr : &I->second;
425 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
428 /// Temporarily override 'this'.
429 class ThisOverrideRAII {
431 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
432 : Frame(Frame), OldThis(Frame.This) {
434 Frame.This = NewThis;
436 ~ThisOverrideRAII() {
437 Frame.This = OldThis;
440 CallStackFrame &Frame;
441 const LValue *OldThis;
444 /// A partial diagnostic which we might know in advance that we are not going
446 class OptionalDiagnostic {
447 PartialDiagnostic *Diag;
450 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
454 OptionalDiagnostic &operator<<(const T &v) {
460 OptionalDiagnostic &operator<<(const APSInt &I) {
462 SmallVector<char, 32> Buffer;
464 *Diag << StringRef(Buffer.data(), Buffer.size());
469 OptionalDiagnostic &operator<<(const APFloat &F) {
471 // FIXME: Force the precision of the source value down so we don't
472 // print digits which are usually useless (we don't really care here if
473 // we truncate a digit by accident in edge cases). Ideally,
474 // APFloat::toString would automatically print the shortest
475 // representation which rounds to the correct value, but it's a bit
476 // tricky to implement.
478 llvm::APFloat::semanticsPrecision(F.getSemantics());
479 precision = (precision * 59 + 195) / 196;
480 SmallVector<char, 32> Buffer;
481 F.toString(Buffer, precision);
482 *Diag << StringRef(Buffer.data(), Buffer.size());
488 /// A cleanup, and a flag indicating whether it is lifetime-extended.
490 llvm::PointerIntPair<APValue*, 1, bool> Value;
493 Cleanup(APValue *Val, bool IsLifetimeExtended)
494 : Value(Val, IsLifetimeExtended) {}
496 bool isLifetimeExtended() const { return Value.getInt(); }
498 *Value.getPointer() = APValue();
502 /// EvalInfo - This is a private struct used by the evaluator to capture
503 /// information about a subexpression as it is folded. It retains information
504 /// about the AST context, but also maintains information about the folded
507 /// If an expression could be evaluated, it is still possible it is not a C
508 /// "integer constant expression" or constant expression. If not, this struct
509 /// captures information about how and why not.
511 /// One bit of information passed *into* the request for constant folding
512 /// indicates whether the subexpression is "evaluated" or not according to C
513 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
514 /// evaluate the expression regardless of what the RHS is, but C only allows
515 /// certain things in certain situations.
516 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
519 /// EvalStatus - Contains information about the evaluation.
520 Expr::EvalStatus &EvalStatus;
522 /// CurrentCall - The top of the constexpr call stack.
523 CallStackFrame *CurrentCall;
525 /// CallStackDepth - The number of calls in the call stack right now.
526 unsigned CallStackDepth;
528 /// NextCallIndex - The next call index to assign.
529 unsigned NextCallIndex;
531 /// StepsLeft - The remaining number of evaluation steps we're permitted
532 /// to perform. This is essentially a limit for the number of statements
533 /// we will evaluate.
536 /// BottomFrame - The frame in which evaluation started. This must be
537 /// initialized after CurrentCall and CallStackDepth.
538 CallStackFrame BottomFrame;
540 /// A stack of values whose lifetimes end at the end of some surrounding
541 /// evaluation frame.
542 llvm::SmallVector<Cleanup, 16> CleanupStack;
544 /// EvaluatingDecl - This is the declaration whose initializer is being
545 /// evaluated, if any.
546 APValue::LValueBase EvaluatingDecl;
548 /// EvaluatingDeclValue - This is the value being constructed for the
549 /// declaration whose initializer is being evaluated, if any.
550 APValue *EvaluatingDeclValue;
552 /// The current array initialization index, if we're performing array
554 uint64_t ArrayInitIndex = -1;
556 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
557 /// notes attached to it will also be stored, otherwise they will not be.
558 bool HasActiveDiagnostic;
560 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
561 /// fold (not just why it's not strictly a constant expression)?
562 bool HasFoldFailureDiagnostic;
564 /// \brief Whether or not we're currently speculatively evaluating.
565 bool IsSpeculativelyEvaluating;
567 enum EvaluationMode {
568 /// Evaluate as a constant expression. Stop if we find that the expression
569 /// is not a constant expression.
570 EM_ConstantExpression,
572 /// Evaluate as a potential constant expression. Keep going if we hit a
573 /// construct that we can't evaluate yet (because we don't yet know the
574 /// value of something) but stop if we hit something that could never be
575 /// a constant expression.
576 EM_PotentialConstantExpression,
578 /// Fold the expression to a constant. Stop if we hit a side-effect that
582 /// Evaluate the expression looking for integer overflow and similar
583 /// issues. Don't worry about side-effects, and try to visit all
585 EM_EvaluateForOverflow,
587 /// Evaluate in any way we know how. Don't worry about side-effects that
588 /// can't be modeled.
589 EM_IgnoreSideEffects,
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression. Some expressions can be retried in the
593 /// optimizer if we don't constant fold them here, but in an unevaluated
594 /// context we try to fold them immediately since the optimizer never
595 /// gets a chance to look at it.
596 EM_ConstantExpressionUnevaluated,
598 /// Evaluate as a potential constant expression. Keep going if we hit a
599 /// construct that we can't evaluate yet (because we don't yet know the
600 /// value of something) but stop if we hit something that could never be
601 /// a constant expression. Some expressions can be retried in the
602 /// optimizer if we don't constant fold them here, but in an unevaluated
603 /// context we try to fold them immediately since the optimizer never
604 /// gets a chance to look at it.
605 EM_PotentialConstantExpressionUnevaluated,
607 /// Evaluate as a constant expression. Continue evaluating if either:
608 /// - We find a MemberExpr with a base that can't be evaluated.
609 /// - We find a variable initialized with a call to a function that has
610 /// the alloc_size attribute on it.
611 /// In either case, the LValue returned shall have an invalid base; in the
612 /// former, the base will be the invalid MemberExpr, in the latter, the
613 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
618 /// Are we checking whether the expression is a potential constant
620 bool checkingPotentialConstantExpression() const {
621 return EvalMode == EM_PotentialConstantExpression ||
622 EvalMode == EM_PotentialConstantExpressionUnevaluated;
625 /// Are we checking an expression for overflow?
626 // FIXME: We should check for any kind of undefined or suspicious behavior
627 // in such constructs, not just overflow.
628 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
630 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
631 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
632 CallStackDepth(0), NextCallIndex(1),
633 StepsLeft(getLangOpts().ConstexprStepLimit),
634 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
635 EvaluatingDecl((const ValueDecl *)nullptr),
636 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
637 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
640 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
641 EvaluatingDecl = Base;
642 EvaluatingDeclValue = &Value;
645 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
647 bool CheckCallLimit(SourceLocation Loc) {
648 // Don't perform any constexpr calls (other than the call we're checking)
649 // when checking a potential constant expression.
650 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
652 if (NextCallIndex == 0) {
653 // NextCallIndex has wrapped around.
654 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
657 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
659 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
660 << getLangOpts().ConstexprCallDepth;
664 CallStackFrame *getCallFrame(unsigned CallIndex) {
665 assert(CallIndex && "no call index in getCallFrame");
666 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
667 // be null in this loop.
668 CallStackFrame *Frame = CurrentCall;
669 while (Frame->Index > CallIndex)
670 Frame = Frame->Caller;
671 return (Frame->Index == CallIndex) ? Frame : nullptr;
674 bool nextStep(const Stmt *S) {
676 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
684 /// Add a diagnostic to the diagnostics list.
685 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
686 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
687 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
688 return EvalStatus.Diag->back().second;
691 /// Add notes containing a call stack to the current point of evaluation.
692 void addCallStack(unsigned Limit);
695 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
696 unsigned ExtraNotes, bool IsCCEDiag) {
698 if (EvalStatus.Diag) {
699 // If we have a prior diagnostic, it will be noting that the expression
700 // isn't a constant expression. This diagnostic is more important,
701 // unless we require this evaluation to produce a constant expression.
703 // FIXME: We might want to show both diagnostics to the user in
704 // EM_ConstantFold mode.
705 if (!EvalStatus.Diag->empty()) {
707 case EM_ConstantFold:
708 case EM_IgnoreSideEffects:
709 case EM_EvaluateForOverflow:
710 if (!HasFoldFailureDiagnostic)
712 // We've already failed to fold something. Keep that diagnostic.
713 case EM_ConstantExpression:
714 case EM_PotentialConstantExpression:
715 case EM_ConstantExpressionUnevaluated:
716 case EM_PotentialConstantExpressionUnevaluated:
718 HasActiveDiagnostic = false;
719 return OptionalDiagnostic();
723 unsigned CallStackNotes = CallStackDepth - 1;
724 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
726 CallStackNotes = std::min(CallStackNotes, Limit + 1);
727 if (checkingPotentialConstantExpression())
730 HasActiveDiagnostic = true;
731 HasFoldFailureDiagnostic = !IsCCEDiag;
732 EvalStatus.Diag->clear();
733 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
734 addDiag(Loc, DiagId);
735 if (!checkingPotentialConstantExpression())
737 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
739 HasActiveDiagnostic = false;
740 return OptionalDiagnostic();
743 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
745 FFDiag(SourceLocation Loc,
746 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
747 unsigned ExtraNotes = 0) {
748 return Diag(Loc, DiagId, ExtraNotes, false);
751 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
752 = diag::note_invalid_subexpr_in_const_expr,
753 unsigned ExtraNotes = 0) {
755 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
756 HasActiveDiagnostic = false;
757 return OptionalDiagnostic();
760 /// Diagnose that the evaluation does not produce a C++11 core constant
763 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
764 /// EM_PotentialConstantExpression mode and we produce one of these.
765 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
766 = diag::note_invalid_subexpr_in_const_expr,
767 unsigned ExtraNotes = 0) {
768 // Don't override a previous diagnostic. Don't bother collecting
769 // diagnostics if we're evaluating for overflow.
770 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
771 HasActiveDiagnostic = false;
772 return OptionalDiagnostic();
774 return Diag(Loc, DiagId, ExtraNotes, true);
776 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
777 = diag::note_invalid_subexpr_in_const_expr,
778 unsigned ExtraNotes = 0) {
779 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
781 /// Add a note to a prior diagnostic.
782 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
783 if (!HasActiveDiagnostic)
784 return OptionalDiagnostic();
785 return OptionalDiagnostic(&addDiag(Loc, DiagId));
788 /// Add a stack of notes to a prior diagnostic.
789 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
790 if (HasActiveDiagnostic) {
791 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
792 Diags.begin(), Diags.end());
796 /// Should we continue evaluation after encountering a side-effect that we
798 bool keepEvaluatingAfterSideEffect() {
800 case EM_PotentialConstantExpression:
801 case EM_PotentialConstantExpressionUnevaluated:
802 case EM_EvaluateForOverflow:
803 case EM_IgnoreSideEffects:
806 case EM_ConstantExpression:
807 case EM_ConstantExpressionUnevaluated:
808 case EM_ConstantFold:
812 llvm_unreachable("Missed EvalMode case");
815 /// Note that we have had a side-effect, and determine whether we should
817 bool noteSideEffect() {
818 EvalStatus.HasSideEffects = true;
819 return keepEvaluatingAfterSideEffect();
822 /// Should we continue evaluation after encountering undefined behavior?
823 bool keepEvaluatingAfterUndefinedBehavior() {
825 case EM_EvaluateForOverflow:
826 case EM_IgnoreSideEffects:
827 case EM_ConstantFold:
831 case EM_PotentialConstantExpression:
832 case EM_PotentialConstantExpressionUnevaluated:
833 case EM_ConstantExpression:
834 case EM_ConstantExpressionUnevaluated:
837 llvm_unreachable("Missed EvalMode case");
840 /// Note that we hit something that was technically undefined behavior, but
841 /// that we can evaluate past it (such as signed overflow or floating-point
842 /// division by zero.)
843 bool noteUndefinedBehavior() {
844 EvalStatus.HasUndefinedBehavior = true;
845 return keepEvaluatingAfterUndefinedBehavior();
848 /// Should we continue evaluation as much as possible after encountering a
849 /// construct which can't be reduced to a value?
850 bool keepEvaluatingAfterFailure() {
855 case EM_PotentialConstantExpression:
856 case EM_PotentialConstantExpressionUnevaluated:
857 case EM_EvaluateForOverflow:
860 case EM_ConstantExpression:
861 case EM_ConstantExpressionUnevaluated:
862 case EM_ConstantFold:
863 case EM_IgnoreSideEffects:
867 llvm_unreachable("Missed EvalMode case");
870 /// Notes that we failed to evaluate an expression that other expressions
871 /// directly depend on, and determine if we should keep evaluating. This
872 /// should only be called if we actually intend to keep evaluating.
874 /// Call noteSideEffect() instead if we may be able to ignore the value that
875 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
877 /// (Foo(), 1) // use noteSideEffect
878 /// (Foo() || true) // use noteSideEffect
879 /// Foo() + 1 // use noteFailure
880 LLVM_NODISCARD bool noteFailure() {
881 // Failure when evaluating some expression often means there is some
882 // subexpression whose evaluation was skipped. Therefore, (because we
883 // don't track whether we skipped an expression when unwinding after an
884 // evaluation failure) every evaluation failure that bubbles up from a
885 // subexpression implies that a side-effect has potentially happened. We
886 // skip setting the HasSideEffects flag to true until we decide to
887 // continue evaluating after that point, which happens here.
888 bool KeepGoing = keepEvaluatingAfterFailure();
889 EvalStatus.HasSideEffects |= KeepGoing;
893 bool allowInvalidBaseExpr() const {
894 return EvalMode == EM_OffsetFold;
897 class ArrayInitLoopIndex {
902 ArrayInitLoopIndex(EvalInfo &Info)
903 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
904 Info.ArrayInitIndex = 0;
906 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
908 operator uint64_t&() { return Info.ArrayInitIndex; }
912 /// Object used to treat all foldable expressions as constant expressions.
913 struct FoldConstant {
916 bool HadNoPriorDiags;
917 EvalInfo::EvaluationMode OldMode;
919 explicit FoldConstant(EvalInfo &Info, bool Enabled)
922 HadNoPriorDiags(Info.EvalStatus.Diag &&
923 Info.EvalStatus.Diag->empty() &&
924 !Info.EvalStatus.HasSideEffects),
925 OldMode(Info.EvalMode) {
927 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
928 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
929 Info.EvalMode = EvalInfo::EM_ConstantFold;
931 void keepDiagnostics() { Enabled = false; }
933 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
934 !Info.EvalStatus.HasSideEffects)
935 Info.EvalStatus.Diag->clear();
936 Info.EvalMode = OldMode;
940 /// RAII object used to treat the current evaluation as the correct pointer
941 /// offset fold for the current EvalMode
942 struct FoldOffsetRAII {
944 EvalInfo::EvaluationMode OldMode;
945 explicit FoldOffsetRAII(EvalInfo &Info)
946 : Info(Info), OldMode(Info.EvalMode) {
947 if (!Info.checkingPotentialConstantExpression())
948 Info.EvalMode = EvalInfo::EM_OffsetFold;
951 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
954 /// RAII object used to optionally suppress diagnostics and side-effects from
955 /// a speculative evaluation.
956 class SpeculativeEvaluationRAII {
957 /// Pair of EvalInfo, and a bit that stores whether or not we were
958 /// speculatively evaluating when we created this RAII.
959 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
960 Expr::EvalStatus Old;
962 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
963 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
965 Other.InfoAndOldSpecEval.setPointer(nullptr);
968 void maybeRestoreState() {
969 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
973 Info->EvalStatus = Old;
974 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
978 SpeculativeEvaluationRAII() = default;
980 SpeculativeEvaluationRAII(
981 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
982 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
983 Old(Info.EvalStatus) {
984 Info.EvalStatus.Diag = NewDiag;
985 Info.IsSpeculativelyEvaluating = true;
988 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
989 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
990 moveFromAndCancel(std::move(Other));
993 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
995 moveFromAndCancel(std::move(Other));
999 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1002 /// RAII object wrapping a full-expression or block scope, and handling
1003 /// the ending of the lifetime of temporaries created within it.
1004 template<bool IsFullExpression>
1007 unsigned OldStackSize;
1009 ScopeRAII(EvalInfo &Info)
1010 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1012 // Body moved to a static method to encourage the compiler to inline away
1013 // instances of this class.
1014 cleanup(Info, OldStackSize);
1017 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1018 unsigned NewEnd = OldStackSize;
1019 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1021 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1022 // Full-expression cleanup of a lifetime-extended temporary: nothing
1023 // to do, just move this cleanup to the right place in the stack.
1024 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1027 // End the lifetime of the object.
1028 Info.CleanupStack[I].endLifetime();
1031 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1032 Info.CleanupStack.end());
1035 typedef ScopeRAII<false> BlockScopeRAII;
1036 typedef ScopeRAII<true> FullExpressionRAII;
1039 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1040 CheckSubobjectKind CSK) {
1043 if (isOnePastTheEnd()) {
1044 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1052 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1053 const Expr *E, uint64_t N) {
1054 // If we're complaining, we must be able to statically determine the size of
1055 // the most derived array.
1056 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1057 Info.CCEDiag(E, diag::note_constexpr_array_index)
1058 << static_cast<int>(N) << /*array*/ 0
1059 << static_cast<unsigned>(getMostDerivedArraySize());
1061 Info.CCEDiag(E, diag::note_constexpr_array_index)
1062 << static_cast<int>(N) << /*non-array*/ 1;
1066 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1067 const FunctionDecl *Callee, const LValue *This,
1069 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1070 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1071 Info.CurrentCall = this;
1072 ++Info.CallStackDepth;
1075 CallStackFrame::~CallStackFrame() {
1076 assert(Info.CurrentCall == this && "calls retired out of order");
1077 --Info.CallStackDepth;
1078 Info.CurrentCall = Caller;
1081 APValue &CallStackFrame::createTemporary(const void *Key,
1082 bool IsLifetimeExtended) {
1083 APValue &Result = Temporaries[Key];
1084 assert(Result.isUninit() && "temporary created multiple times");
1085 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1089 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1091 void EvalInfo::addCallStack(unsigned Limit) {
1092 // Determine which calls to skip, if any.
1093 unsigned ActiveCalls = CallStackDepth - 1;
1094 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1095 if (Limit && Limit < ActiveCalls) {
1096 SkipStart = Limit / 2 + Limit % 2;
1097 SkipEnd = ActiveCalls - Limit / 2;
1100 // Walk the call stack and add the diagnostics.
1101 unsigned CallIdx = 0;
1102 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1103 Frame = Frame->Caller, ++CallIdx) {
1105 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1106 if (CallIdx == SkipStart) {
1107 // Note that we're skipping calls.
1108 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1109 << unsigned(ActiveCalls - Limit);
1114 // Use a different note for an inheriting constructor, because from the
1115 // user's perspective it's not really a function at all.
1116 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1117 if (CD->isInheritingConstructor()) {
1118 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1124 SmallVector<char, 128> Buffer;
1125 llvm::raw_svector_ostream Out(Buffer);
1126 describeCall(Frame, Out);
1127 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1132 struct ComplexValue {
1137 APSInt IntReal, IntImag;
1138 APFloat FloatReal, FloatImag;
1140 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1142 void makeComplexFloat() { IsInt = false; }
1143 bool isComplexFloat() const { return !IsInt; }
1144 APFloat &getComplexFloatReal() { return FloatReal; }
1145 APFloat &getComplexFloatImag() { return FloatImag; }
1147 void makeComplexInt() { IsInt = true; }
1148 bool isComplexInt() const { return IsInt; }
1149 APSInt &getComplexIntReal() { return IntReal; }
1150 APSInt &getComplexIntImag() { return IntImag; }
1152 void moveInto(APValue &v) const {
1153 if (isComplexFloat())
1154 v = APValue(FloatReal, FloatImag);
1156 v = APValue(IntReal, IntImag);
1158 void setFrom(const APValue &v) {
1159 assert(v.isComplexFloat() || v.isComplexInt());
1160 if (v.isComplexFloat()) {
1162 FloatReal = v.getComplexFloatReal();
1163 FloatImag = v.getComplexFloatImag();
1166 IntReal = v.getComplexIntReal();
1167 IntImag = v.getComplexIntImag();
1173 APValue::LValueBase Base;
1175 unsigned InvalidBase : 1;
1176 unsigned CallIndex : 31;
1177 SubobjectDesignator Designator;
1180 const APValue::LValueBase getLValueBase() const { return Base; }
1181 CharUnits &getLValueOffset() { return Offset; }
1182 const CharUnits &getLValueOffset() const { return Offset; }
1183 unsigned getLValueCallIndex() const { return CallIndex; }
1184 SubobjectDesignator &getLValueDesignator() { return Designator; }
1185 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1186 bool isNullPointer() const { return IsNullPtr;}
1188 void moveInto(APValue &V) const {
1189 if (Designator.Invalid)
1190 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1193 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1194 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1195 "Unsized array with a valid base?");
1196 V = APValue(Base, Offset, Designator.Entries,
1197 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1200 void setFrom(ASTContext &Ctx, const APValue &V) {
1201 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1202 Base = V.getLValueBase();
1203 Offset = V.getLValueOffset();
1204 InvalidBase = false;
1205 CallIndex = V.getLValueCallIndex();
1206 Designator = SubobjectDesignator(Ctx, V);
1207 IsNullPtr = V.isNullPointer();
1210 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1211 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
1213 // We only allow a few types of invalid bases. Enforce that here.
1215 const auto *E = B.get<const Expr *>();
1216 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1217 "Unexpected type of invalid base");
1222 Offset = CharUnits::fromQuantity(Offset_);
1223 InvalidBase = BInvalid;
1225 Designator = SubobjectDesignator(getType(B));
1226 IsNullPtr = IsNullPtr_;
1229 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1233 // Check that this LValue is not based on a null pointer. If it is, produce
1234 // a diagnostic and mark the designator as invalid.
1235 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1236 CheckSubobjectKind CSK) {
1237 if (Designator.Invalid)
1240 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1242 Designator.setInvalid();
1248 // Check this LValue refers to an object. If not, set the designator to be
1249 // invalid and emit a diagnostic.
1250 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1251 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1252 Designator.checkSubobject(Info, E, CSK);
1255 void addDecl(EvalInfo &Info, const Expr *E,
1256 const Decl *D, bool Virtual = false) {
1257 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1258 Designator.addDeclUnchecked(D, Virtual);
1260 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1261 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1262 assert(isBaseAnAllocSizeCall(Base) &&
1263 "Only alloc_size bases can have unsized arrays");
1264 Designator.FirstEntryIsAnUnsizedArray = true;
1265 Designator.addUnsizedArrayUnchecked(ElemTy);
1267 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1268 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1269 Designator.addArrayUnchecked(CAT);
1271 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1272 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1273 Designator.addComplexUnchecked(EltTy, Imag);
1275 void clearIsNullPointer() {
1278 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1279 CharUnits ElementSize) {
1280 // Compute the new offset in the appropriate width.
1281 Offset += Index * ElementSize;
1282 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1283 Designator.adjustIndex(Info, E, Index);
1285 clearIsNullPointer();
1287 void adjustOffset(CharUnits N) {
1289 if (N.getQuantity())
1290 clearIsNullPointer();
1296 explicit MemberPtr(const ValueDecl *Decl) :
1297 DeclAndIsDerivedMember(Decl, false), Path() {}
1299 /// The member or (direct or indirect) field referred to by this member
1300 /// pointer, or 0 if this is a null member pointer.
1301 const ValueDecl *getDecl() const {
1302 return DeclAndIsDerivedMember.getPointer();
1304 /// Is this actually a member of some type derived from the relevant class?
1305 bool isDerivedMember() const {
1306 return DeclAndIsDerivedMember.getInt();
1308 /// Get the class which the declaration actually lives in.
1309 const CXXRecordDecl *getContainingRecord() const {
1310 return cast<CXXRecordDecl>(
1311 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1314 void moveInto(APValue &V) const {
1315 V = APValue(getDecl(), isDerivedMember(), Path);
1317 void setFrom(const APValue &V) {
1318 assert(V.isMemberPointer());
1319 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1320 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1322 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1323 Path.insert(Path.end(), P.begin(), P.end());
1326 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1327 /// whether the member is a member of some class derived from the class type
1328 /// of the member pointer.
1329 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1330 /// Path - The path of base/derived classes from the member declaration's
1331 /// class (exclusive) to the class type of the member pointer (inclusive).
1332 SmallVector<const CXXRecordDecl*, 4> Path;
1334 /// Perform a cast towards the class of the Decl (either up or down the
1336 bool castBack(const CXXRecordDecl *Class) {
1337 assert(!Path.empty());
1338 const CXXRecordDecl *Expected;
1339 if (Path.size() >= 2)
1340 Expected = Path[Path.size() - 2];
1342 Expected = getContainingRecord();
1343 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1344 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1345 // if B does not contain the original member and is not a base or
1346 // derived class of the class containing the original member, the result
1347 // of the cast is undefined.
1348 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1349 // (D::*). We consider that to be a language defect.
1355 /// Perform a base-to-derived member pointer cast.
1356 bool castToDerived(const CXXRecordDecl *Derived) {
1359 if (!isDerivedMember()) {
1360 Path.push_back(Derived);
1363 if (!castBack(Derived))
1366 DeclAndIsDerivedMember.setInt(false);
1369 /// Perform a derived-to-base member pointer cast.
1370 bool castToBase(const CXXRecordDecl *Base) {
1374 DeclAndIsDerivedMember.setInt(true);
1375 if (isDerivedMember()) {
1376 Path.push_back(Base);
1379 return castBack(Base);
1383 /// Compare two member pointers, which are assumed to be of the same type.
1384 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1385 if (!LHS.getDecl() || !RHS.getDecl())
1386 return !LHS.getDecl() && !RHS.getDecl();
1387 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1389 return LHS.Path == RHS.Path;
1393 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1394 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1395 const LValue &This, const Expr *E,
1396 bool AllowNonLiteralTypes = false);
1397 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1398 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1399 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1401 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1402 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1403 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1405 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1406 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1407 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1408 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1410 //===----------------------------------------------------------------------===//
1412 //===----------------------------------------------------------------------===//
1414 /// Produce a string describing the given constexpr call.
1415 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1416 unsigned ArgIndex = 0;
1417 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1418 !isa<CXXConstructorDecl>(Frame->Callee) &&
1419 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1422 Out << *Frame->Callee << '(';
1424 if (Frame->This && IsMemberCall) {
1426 Frame->This->moveInto(Val);
1427 Val.printPretty(Out, Frame->Info.Ctx,
1428 Frame->This->Designator.MostDerivedType);
1429 // FIXME: Add parens around Val if needed.
1430 Out << "->" << *Frame->Callee << '(';
1431 IsMemberCall = false;
1434 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1435 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1436 if (ArgIndex > (unsigned)IsMemberCall)
1439 const ParmVarDecl *Param = *I;
1440 const APValue &Arg = Frame->Arguments[ArgIndex];
1441 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1443 if (ArgIndex == 0 && IsMemberCall)
1444 Out << "->" << *Frame->Callee << '(';
1450 /// Evaluate an expression to see if it had side-effects, and discard its
1452 /// \return \c true if the caller should keep evaluating.
1453 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1455 if (!Evaluate(Scratch, Info, E))
1456 // We don't need the value, but we might have skipped a side effect here.
1457 return Info.noteSideEffect();
1461 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1462 /// return its existing value.
1463 static int64_t getExtValue(const APSInt &Value) {
1464 return Value.isSigned() ? Value.getSExtValue()
1465 : static_cast<int64_t>(Value.getZExtValue());
1468 /// Should this call expression be treated as a string literal?
1469 static bool IsStringLiteralCall(const CallExpr *E) {
1470 unsigned Builtin = E->getBuiltinCallee();
1471 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1472 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1475 static bool IsGlobalLValue(APValue::LValueBase B) {
1476 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1477 // constant expression of pointer type that evaluates to...
1479 // ... a null pointer value, or a prvalue core constant expression of type
1481 if (!B) return true;
1483 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1484 // ... the address of an object with static storage duration,
1485 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1486 return VD->hasGlobalStorage();
1487 // ... the address of a function,
1488 return isa<FunctionDecl>(D);
1491 const Expr *E = B.get<const Expr*>();
1492 switch (E->getStmtClass()) {
1495 case Expr::CompoundLiteralExprClass: {
1496 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1497 return CLE->isFileScope() && CLE->isLValue();
1499 case Expr::MaterializeTemporaryExprClass:
1500 // A materialized temporary might have been lifetime-extended to static
1501 // storage duration.
1502 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1503 // A string literal has static storage duration.
1504 case Expr::StringLiteralClass:
1505 case Expr::PredefinedExprClass:
1506 case Expr::ObjCStringLiteralClass:
1507 case Expr::ObjCEncodeExprClass:
1508 case Expr::CXXTypeidExprClass:
1509 case Expr::CXXUuidofExprClass:
1511 case Expr::CallExprClass:
1512 return IsStringLiteralCall(cast<CallExpr>(E));
1513 // For GCC compatibility, &&label has static storage duration.
1514 case Expr::AddrLabelExprClass:
1516 // A Block literal expression may be used as the initialization value for
1517 // Block variables at global or local static scope.
1518 case Expr::BlockExprClass:
1519 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1520 case Expr::ImplicitValueInitExprClass:
1522 // We can never form an lvalue with an implicit value initialization as its
1523 // base through expression evaluation, so these only appear in one case: the
1524 // implicit variable declaration we invent when checking whether a constexpr
1525 // constructor can produce a constant expression. We must assume that such
1526 // an expression might be a global lvalue.
1531 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1532 assert(Base && "no location for a null lvalue");
1533 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1535 Info.Note(VD->getLocation(), diag::note_declared_at);
1537 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1538 diag::note_constexpr_temporary_here);
1541 /// Check that this reference or pointer core constant expression is a valid
1542 /// value for an address or reference constant expression. Return true if we
1543 /// can fold this expression, whether or not it's a constant expression.
1544 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1545 QualType Type, const LValue &LVal) {
1546 bool IsReferenceType = Type->isReferenceType();
1548 APValue::LValueBase Base = LVal.getLValueBase();
1549 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1551 // Check that the object is a global. Note that the fake 'this' object we
1552 // manufacture when checking potential constant expressions is conservatively
1553 // assumed to be global here.
1554 if (!IsGlobalLValue(Base)) {
1555 if (Info.getLangOpts().CPlusPlus11) {
1556 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1557 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1558 << IsReferenceType << !Designator.Entries.empty()
1560 NoteLValueLocation(Info, Base);
1564 // Don't allow references to temporaries to escape.
1567 assert((Info.checkingPotentialConstantExpression() ||
1568 LVal.getLValueCallIndex() == 0) &&
1569 "have call index for global lvalue");
1571 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1572 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1573 // Check if this is a thread-local variable.
1574 if (Var->getTLSKind())
1577 // A dllimport variable never acts like a constant.
1578 if (Var->hasAttr<DLLImportAttr>())
1581 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1582 // __declspec(dllimport) must be handled very carefully:
1583 // We must never initialize an expression with the thunk in C++.
1584 // Doing otherwise would allow the same id-expression to yield
1585 // different addresses for the same function in different translation
1586 // units. However, this means that we must dynamically initialize the
1587 // expression with the contents of the import address table at runtime.
1589 // The C language has no notion of ODR; furthermore, it has no notion of
1590 // dynamic initialization. This means that we are permitted to
1591 // perform initialization with the address of the thunk.
1592 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1597 // Allow address constant expressions to be past-the-end pointers. This is
1598 // an extension: the standard requires them to point to an object.
1599 if (!IsReferenceType)
1602 // A reference constant expression must refer to an object.
1604 // FIXME: diagnostic
1609 // Does this refer one past the end of some object?
1610 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1611 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1612 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1613 << !Designator.Entries.empty() << !!VD << VD;
1614 NoteLValueLocation(Info, Base);
1620 /// Check that this core constant expression is of literal type, and if not,
1621 /// produce an appropriate diagnostic.
1622 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1623 const LValue *This = nullptr) {
1624 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1627 // C++1y: A constant initializer for an object o [...] may also invoke
1628 // constexpr constructors for o and its subobjects even if those objects
1629 // are of non-literal class types.
1630 if (Info.getLangOpts().CPlusPlus14 && This &&
1631 Info.EvaluatingDecl == This->getLValueBase())
1634 // Prvalue constant expressions must be of literal types.
1635 if (Info.getLangOpts().CPlusPlus11)
1636 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1639 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1643 /// Check that this core constant expression value is a valid value for a
1644 /// constant expression. If not, report an appropriate diagnostic. Does not
1645 /// check that the expression is of literal type.
1646 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1647 QualType Type, const APValue &Value) {
1648 if (Value.isUninit()) {
1649 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1654 // We allow _Atomic(T) to be initialized from anything that T can be
1655 // initialized from.
1656 if (const AtomicType *AT = Type->getAs<AtomicType>())
1657 Type = AT->getValueType();
1659 // Core issue 1454: For a literal constant expression of array or class type,
1660 // each subobject of its value shall have been initialized by a constant
1662 if (Value.isArray()) {
1663 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1664 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1665 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1666 Value.getArrayInitializedElt(I)))
1669 if (!Value.hasArrayFiller())
1671 return CheckConstantExpression(Info, DiagLoc, EltTy,
1672 Value.getArrayFiller());
1674 if (Value.isUnion() && Value.getUnionField()) {
1675 return CheckConstantExpression(Info, DiagLoc,
1676 Value.getUnionField()->getType(),
1677 Value.getUnionValue());
1679 if (Value.isStruct()) {
1680 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1681 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1682 unsigned BaseIndex = 0;
1683 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1684 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1685 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1686 Value.getStructBase(BaseIndex)))
1690 for (const auto *I : RD->fields()) {
1691 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1692 Value.getStructField(I->getFieldIndex())))
1697 if (Value.isLValue()) {
1699 LVal.setFrom(Info.Ctx, Value);
1700 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1703 // Everything else is fine.
1707 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1708 return LVal.Base.dyn_cast<const ValueDecl*>();
1711 static bool IsLiteralLValue(const LValue &Value) {
1712 if (Value.CallIndex)
1714 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1715 return E && !isa<MaterializeTemporaryExpr>(E);
1718 static bool IsWeakLValue(const LValue &Value) {
1719 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1720 return Decl && Decl->isWeak();
1723 static bool isZeroSized(const LValue &Value) {
1724 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1725 if (Decl && isa<VarDecl>(Decl)) {
1726 QualType Ty = Decl->getType();
1727 if (Ty->isArrayType())
1728 return Ty->isIncompleteType() ||
1729 Decl->getASTContext().getTypeSize(Ty) == 0;
1734 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1735 // A null base expression indicates a null pointer. These are always
1736 // evaluatable, and they are false unless the offset is zero.
1737 if (!Value.getLValueBase()) {
1738 Result = !Value.getLValueOffset().isZero();
1742 // We have a non-null base. These are generally known to be true, but if it's
1743 // a weak declaration it can be null at runtime.
1745 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1746 return !Decl || !Decl->isWeak();
1749 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1750 switch (Val.getKind()) {
1751 case APValue::Uninitialized:
1754 Result = Val.getInt().getBoolValue();
1756 case APValue::Float:
1757 Result = !Val.getFloat().isZero();
1759 case APValue::ComplexInt:
1760 Result = Val.getComplexIntReal().getBoolValue() ||
1761 Val.getComplexIntImag().getBoolValue();
1763 case APValue::ComplexFloat:
1764 Result = !Val.getComplexFloatReal().isZero() ||
1765 !Val.getComplexFloatImag().isZero();
1767 case APValue::LValue:
1768 return EvalPointerValueAsBool(Val, Result);
1769 case APValue::MemberPointer:
1770 Result = Val.getMemberPointerDecl();
1772 case APValue::Vector:
1773 case APValue::Array:
1774 case APValue::Struct:
1775 case APValue::Union:
1776 case APValue::AddrLabelDiff:
1780 llvm_unreachable("unknown APValue kind");
1783 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1785 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1787 if (!Evaluate(Val, Info, E))
1789 return HandleConversionToBool(Val, Result);
1792 template<typename T>
1793 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1794 const T &SrcValue, QualType DestType) {
1795 Info.CCEDiag(E, diag::note_constexpr_overflow)
1796 << SrcValue << DestType;
1797 return Info.noteUndefinedBehavior();
1800 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1801 QualType SrcType, const APFloat &Value,
1802 QualType DestType, APSInt &Result) {
1803 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1804 // Determine whether we are converting to unsigned or signed.
1805 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1807 Result = APSInt(DestWidth, !DestSigned);
1809 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1810 & APFloat::opInvalidOp)
1811 return HandleOverflow(Info, E, Value, DestType);
1815 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1816 QualType SrcType, QualType DestType,
1818 APFloat Value = Result;
1820 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1821 APFloat::rmNearestTiesToEven, &ignored)
1822 & APFloat::opOverflow)
1823 return HandleOverflow(Info, E, Value, DestType);
1827 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1828 QualType DestType, QualType SrcType,
1829 const APSInt &Value) {
1830 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1831 APSInt Result = Value;
1832 // Figure out if this is a truncate, extend or noop cast.
1833 // If the input is signed, do a sign extend, noop, or truncate.
1834 Result = Result.extOrTrunc(DestWidth);
1835 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1839 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1840 QualType SrcType, const APSInt &Value,
1841 QualType DestType, APFloat &Result) {
1842 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1843 if (Result.convertFromAPInt(Value, Value.isSigned(),
1844 APFloat::rmNearestTiesToEven)
1845 & APFloat::opOverflow)
1846 return HandleOverflow(Info, E, Value, DestType);
1850 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1851 APValue &Value, const FieldDecl *FD) {
1852 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1854 if (!Value.isInt()) {
1855 // Trying to store a pointer-cast-to-integer into a bitfield.
1856 // FIXME: In this case, we should provide the diagnostic for casting
1857 // a pointer to an integer.
1858 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1863 APSInt &Int = Value.getInt();
1864 unsigned OldBitWidth = Int.getBitWidth();
1865 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1866 if (NewBitWidth < OldBitWidth)
1867 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1871 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1874 if (!Evaluate(SVal, Info, E))
1877 Res = SVal.getInt();
1880 if (SVal.isFloat()) {
1881 Res = SVal.getFloat().bitcastToAPInt();
1884 if (SVal.isVector()) {
1885 QualType VecTy = E->getType();
1886 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1887 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1888 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1889 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1890 Res = llvm::APInt::getNullValue(VecSize);
1891 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1892 APValue &Elt = SVal.getVectorElt(i);
1893 llvm::APInt EltAsInt;
1895 EltAsInt = Elt.getInt();
1896 } else if (Elt.isFloat()) {
1897 EltAsInt = Elt.getFloat().bitcastToAPInt();
1899 // Don't try to handle vectors of anything other than int or float
1900 // (not sure if it's possible to hit this case).
1901 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1904 unsigned BaseEltSize = EltAsInt.getBitWidth();
1906 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1908 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1912 // Give up if the input isn't an int, float, or vector. For example, we
1913 // reject "(v4i16)(intptr_t)&a".
1914 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1918 /// Perform the given integer operation, which is known to need at most BitWidth
1919 /// bits, and check for overflow in the original type (if that type was not an
1921 template<typename Operation>
1922 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1923 const APSInt &LHS, const APSInt &RHS,
1924 unsigned BitWidth, Operation Op,
1926 if (LHS.isUnsigned()) {
1927 Result = Op(LHS, RHS);
1931 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1932 Result = Value.trunc(LHS.getBitWidth());
1933 if (Result.extend(BitWidth) != Value) {
1934 if (Info.checkingForOverflow())
1935 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1936 diag::warn_integer_constant_overflow)
1937 << Result.toString(10) << E->getType();
1939 return HandleOverflow(Info, E, Value, E->getType());
1944 /// Perform the given binary integer operation.
1945 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1946 BinaryOperatorKind Opcode, APSInt RHS,
1953 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1954 std::multiplies<APSInt>(), Result);
1956 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1957 std::plus<APSInt>(), Result);
1959 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1960 std::minus<APSInt>(), Result);
1961 case BO_And: Result = LHS & RHS; return true;
1962 case BO_Xor: Result = LHS ^ RHS; return true;
1963 case BO_Or: Result = LHS | RHS; return true;
1967 Info.FFDiag(E, diag::note_expr_divide_by_zero);
1970 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1971 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1972 // this operation and gives the two's complement result.
1973 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1974 LHS.isSigned() && LHS.isMinSignedValue())
1975 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1979 if (Info.getLangOpts().OpenCL)
1980 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1981 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1982 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1984 else if (RHS.isSigned() && RHS.isNegative()) {
1985 // During constant-folding, a negative shift is an opposite shift. Such
1986 // a shift is not a constant expression.
1987 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1992 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1993 // the shifted type.
1994 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1996 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1997 << RHS << E->getType() << LHS.getBitWidth();
1998 } else if (LHS.isSigned()) {
1999 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2000 // operand, and must not overflow the corresponding unsigned type.
2001 if (LHS.isNegative())
2002 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2003 else if (LHS.countLeadingZeros() < SA)
2004 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2010 if (Info.getLangOpts().OpenCL)
2011 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2012 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2013 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2015 else if (RHS.isSigned() && RHS.isNegative()) {
2016 // During constant-folding, a negative shift is an opposite shift. Such a
2017 // shift is not a constant expression.
2018 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2023 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2025 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2027 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2028 << RHS << E->getType() << LHS.getBitWidth();
2033 case BO_LT: Result = LHS < RHS; return true;
2034 case BO_GT: Result = LHS > RHS; return true;
2035 case BO_LE: Result = LHS <= RHS; return true;
2036 case BO_GE: Result = LHS >= RHS; return true;
2037 case BO_EQ: Result = LHS == RHS; return true;
2038 case BO_NE: Result = LHS != RHS; return true;
2042 /// Perform the given binary floating-point operation, in-place, on LHS.
2043 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2044 APFloat &LHS, BinaryOperatorKind Opcode,
2045 const APFloat &RHS) {
2051 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2054 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2057 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2060 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2064 if (LHS.isInfinity() || LHS.isNaN()) {
2065 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2066 return Info.noteUndefinedBehavior();
2071 /// Cast an lvalue referring to a base subobject to a derived class, by
2072 /// truncating the lvalue's path to the given length.
2073 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2074 const RecordDecl *TruncatedType,
2075 unsigned TruncatedElements) {
2076 SubobjectDesignator &D = Result.Designator;
2078 // Check we actually point to a derived class object.
2079 if (TruncatedElements == D.Entries.size())
2081 assert(TruncatedElements >= D.MostDerivedPathLength &&
2082 "not casting to a derived class");
2083 if (!Result.checkSubobject(Info, E, CSK_Derived))
2086 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2087 const RecordDecl *RD = TruncatedType;
2088 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2089 if (RD->isInvalidDecl()) return false;
2090 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2091 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2092 if (isVirtualBaseClass(D.Entries[I]))
2093 Result.Offset -= Layout.getVBaseClassOffset(Base);
2095 Result.Offset -= Layout.getBaseClassOffset(Base);
2098 D.Entries.resize(TruncatedElements);
2102 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2103 const CXXRecordDecl *Derived,
2104 const CXXRecordDecl *Base,
2105 const ASTRecordLayout *RL = nullptr) {
2107 if (Derived->isInvalidDecl()) return false;
2108 RL = &Info.Ctx.getASTRecordLayout(Derived);
2111 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2112 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2116 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2117 const CXXRecordDecl *DerivedDecl,
2118 const CXXBaseSpecifier *Base) {
2119 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2121 if (!Base->isVirtual())
2122 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2124 SubobjectDesignator &D = Obj.Designator;
2128 // Extract most-derived object and corresponding type.
2129 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2130 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2133 // Find the virtual base class.
2134 if (DerivedDecl->isInvalidDecl()) return false;
2135 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2136 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2137 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2141 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2142 QualType Type, LValue &Result) {
2143 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2144 PathE = E->path_end();
2145 PathI != PathE; ++PathI) {
2146 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2149 Type = (*PathI)->getType();
2154 /// Update LVal to refer to the given field, which must be a member of the type
2155 /// currently described by LVal.
2156 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2157 const FieldDecl *FD,
2158 const ASTRecordLayout *RL = nullptr) {
2160 if (FD->getParent()->isInvalidDecl()) return false;
2161 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2164 unsigned I = FD->getFieldIndex();
2165 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2166 LVal.addDecl(Info, E, FD);
2170 /// Update LVal to refer to the given indirect field.
2171 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2173 const IndirectFieldDecl *IFD) {
2174 for (const auto *C : IFD->chain())
2175 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2180 /// Get the size of the given type in char units.
2181 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2182 QualType Type, CharUnits &Size) {
2183 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2185 if (Type->isVoidType() || Type->isFunctionType()) {
2186 Size = CharUnits::One();
2190 if (Type->isDependentType()) {
2195 if (!Type->isConstantSizeType()) {
2196 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2197 // FIXME: Better diagnostic.
2202 Size = Info.Ctx.getTypeSizeInChars(Type);
2206 /// Update a pointer value to model pointer arithmetic.
2207 /// \param Info - Information about the ongoing evaluation.
2208 /// \param E - The expression being evaluated, for diagnostic purposes.
2209 /// \param LVal - The pointer value to be updated.
2210 /// \param EltTy - The pointee type represented by LVal.
2211 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2212 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2213 LValue &LVal, QualType EltTy,
2214 int64_t Adjustment) {
2215 CharUnits SizeOfPointee;
2216 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2219 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2223 /// Update an lvalue to refer to a component of a complex number.
2224 /// \param Info - Information about the ongoing evaluation.
2225 /// \param LVal - The lvalue to be updated.
2226 /// \param EltTy - The complex number's component type.
2227 /// \param Imag - False for the real component, true for the imaginary.
2228 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2229 LValue &LVal, QualType EltTy,
2232 CharUnits SizeOfComponent;
2233 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2235 LVal.Offset += SizeOfComponent;
2237 LVal.addComplex(Info, E, EltTy, Imag);
2241 /// Try to evaluate the initializer for a variable declaration.
2243 /// \param Info Information about the ongoing evaluation.
2244 /// \param E An expression to be used when printing diagnostics.
2245 /// \param VD The variable whose initializer should be obtained.
2246 /// \param Frame The frame in which the variable was created. Must be null
2247 /// if this variable is not local to the evaluation.
2248 /// \param Result Filled in with a pointer to the value of the variable.
2249 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2250 const VarDecl *VD, CallStackFrame *Frame,
2252 // If this is a parameter to an active constexpr function call, perform
2253 // argument substitution.
2254 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2255 // Assume arguments of a potential constant expression are unknown
2256 // constant expressions.
2257 if (Info.checkingPotentialConstantExpression())
2259 if (!Frame || !Frame->Arguments) {
2260 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2263 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2267 // If this is a local variable, dig out its value.
2269 Result = Frame->getTemporary(VD);
2271 // Assume variables referenced within a lambda's call operator that were
2272 // not declared within the call operator are captures and during checking
2273 // of a potential constant expression, assume they are unknown constant
2275 assert(isLambdaCallOperator(Frame->Callee) &&
2276 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2277 "missing value for local variable");
2278 if (Info.checkingPotentialConstantExpression())
2280 // FIXME: implement capture evaluation during constant expr evaluation.
2281 Info.FFDiag(E->getLocStart(),
2282 diag::note_unimplemented_constexpr_lambda_feature_ast)
2283 << "captures not currently allowed";
2289 // Dig out the initializer, and use the declaration which it's attached to.
2290 const Expr *Init = VD->getAnyInitializer(VD);
2291 if (!Init || Init->isValueDependent()) {
2292 // If we're checking a potential constant expression, the variable could be
2293 // initialized later.
2294 if (!Info.checkingPotentialConstantExpression())
2295 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2299 // If we're currently evaluating the initializer of this declaration, use that
2301 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2302 Result = Info.EvaluatingDeclValue;
2306 // Never evaluate the initializer of a weak variable. We can't be sure that
2307 // this is the definition which will be used.
2309 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2313 // Check that we can fold the initializer. In C++, we will have already done
2314 // this in the cases where it matters for conformance.
2315 SmallVector<PartialDiagnosticAt, 8> Notes;
2316 if (!VD->evaluateValue(Notes)) {
2317 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2318 Notes.size() + 1) << VD;
2319 Info.Note(VD->getLocation(), diag::note_declared_at);
2320 Info.addNotes(Notes);
2322 } else if (!VD->checkInitIsICE()) {
2323 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2324 Notes.size() + 1) << VD;
2325 Info.Note(VD->getLocation(), diag::note_declared_at);
2326 Info.addNotes(Notes);
2329 Result = VD->getEvaluatedValue();
2333 static bool IsConstNonVolatile(QualType T) {
2334 Qualifiers Quals = T.getQualifiers();
2335 return Quals.hasConst() && !Quals.hasVolatile();
2338 /// Get the base index of the given base class within an APValue representing
2339 /// the given derived class.
2340 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2341 const CXXRecordDecl *Base) {
2342 Base = Base->getCanonicalDecl();
2344 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2345 E = Derived->bases_end(); I != E; ++I, ++Index) {
2346 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2350 llvm_unreachable("base class missing from derived class's bases list");
2353 /// Extract the value of a character from a string literal.
2354 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2356 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2357 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2358 Lit = PE->getFunctionName();
2359 const StringLiteral *S = cast<StringLiteral>(Lit);
2360 const ConstantArrayType *CAT =
2361 Info.Ctx.getAsConstantArrayType(S->getType());
2362 assert(CAT && "string literal isn't an array");
2363 QualType CharType = CAT->getElementType();
2364 assert(CharType->isIntegerType() && "unexpected character type");
2366 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2367 CharType->isUnsignedIntegerType());
2368 if (Index < S->getLength())
2369 Value = S->getCodeUnit(Index);
2373 // Expand a string literal into an array of characters.
2374 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2376 const StringLiteral *S = cast<StringLiteral>(Lit);
2377 const ConstantArrayType *CAT =
2378 Info.Ctx.getAsConstantArrayType(S->getType());
2379 assert(CAT && "string literal isn't an array");
2380 QualType CharType = CAT->getElementType();
2381 assert(CharType->isIntegerType() && "unexpected character type");
2383 unsigned Elts = CAT->getSize().getZExtValue();
2384 Result = APValue(APValue::UninitArray(),
2385 std::min(S->getLength(), Elts), Elts);
2386 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2387 CharType->isUnsignedIntegerType());
2388 if (Result.hasArrayFiller())
2389 Result.getArrayFiller() = APValue(Value);
2390 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2391 Value = S->getCodeUnit(I);
2392 Result.getArrayInitializedElt(I) = APValue(Value);
2396 // Expand an array so that it has more than Index filled elements.
2397 static void expandArray(APValue &Array, unsigned Index) {
2398 unsigned Size = Array.getArraySize();
2399 assert(Index < Size);
2401 // Always at least double the number of elements for which we store a value.
2402 unsigned OldElts = Array.getArrayInitializedElts();
2403 unsigned NewElts = std::max(Index+1, OldElts * 2);
2404 NewElts = std::min(Size, std::max(NewElts, 8u));
2406 // Copy the data across.
2407 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2408 for (unsigned I = 0; I != OldElts; ++I)
2409 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2410 for (unsigned I = OldElts; I != NewElts; ++I)
2411 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2412 if (NewValue.hasArrayFiller())
2413 NewValue.getArrayFiller() = Array.getArrayFiller();
2414 Array.swap(NewValue);
2417 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2418 /// conversion. If it's of class type, we may assume that the copy operation
2419 /// is trivial. Note that this is never true for a union type with fields
2420 /// (because the copy always "reads" the active member) and always true for
2421 /// a non-class type.
2422 static bool isReadByLvalueToRvalueConversion(QualType T) {
2423 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2424 if (!RD || (RD->isUnion() && !RD->field_empty()))
2429 for (auto *Field : RD->fields())
2430 if (isReadByLvalueToRvalueConversion(Field->getType()))
2433 for (auto &BaseSpec : RD->bases())
2434 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2440 /// Diagnose an attempt to read from any unreadable field within the specified
2441 /// type, which might be a class type.
2442 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2444 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2448 if (!RD->hasMutableFields())
2451 for (auto *Field : RD->fields()) {
2452 // If we're actually going to read this field in some way, then it can't
2453 // be mutable. If we're in a union, then assigning to a mutable field
2454 // (even an empty one) can change the active member, so that's not OK.
2455 // FIXME: Add core issue number for the union case.
2456 if (Field->isMutable() &&
2457 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2458 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2459 Info.Note(Field->getLocation(), diag::note_declared_at);
2463 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2467 for (auto &BaseSpec : RD->bases())
2468 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2471 // All mutable fields were empty, and thus not actually read.
2475 /// Kinds of access we can perform on an object, for diagnostics.
2484 /// A handle to a complete object (an object that is not a subobject of
2485 /// another object).
2486 struct CompleteObject {
2487 /// The value of the complete object.
2489 /// The type of the complete object.
2492 CompleteObject() : Value(nullptr) {}
2493 CompleteObject(APValue *Value, QualType Type)
2494 : Value(Value), Type(Type) {
2495 assert(Value && "missing value for complete object");
2498 explicit operator bool() const { return Value; }
2500 } // end anonymous namespace
2502 /// Find the designated sub-object of an rvalue.
2503 template<typename SubobjectHandler>
2504 typename SubobjectHandler::result_type
2505 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2506 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2508 // A diagnostic will have already been produced.
2509 return handler.failed();
2510 if (Sub.isOnePastTheEnd()) {
2511 if (Info.getLangOpts().CPlusPlus11)
2512 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2513 << handler.AccessKind;
2516 return handler.failed();
2519 APValue *O = Obj.Value;
2520 QualType ObjType = Obj.Type;
2521 const FieldDecl *LastField = nullptr;
2523 // Walk the designator's path to find the subobject.
2524 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2525 if (O->isUninit()) {
2526 if (!Info.checkingPotentialConstantExpression())
2527 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2528 return handler.failed();
2532 // If we are reading an object of class type, there may still be more
2533 // things we need to check: if there are any mutable subobjects, we
2534 // cannot perform this read. (This only happens when performing a trivial
2535 // copy or assignment.)
2536 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2537 diagnoseUnreadableFields(Info, E, ObjType))
2538 return handler.failed();
2540 if (!handler.found(*O, ObjType))
2543 // If we modified a bit-field, truncate it to the right width.
2544 if (handler.AccessKind != AK_Read &&
2545 LastField && LastField->isBitField() &&
2546 !truncateBitfieldValue(Info, E, *O, LastField))
2552 LastField = nullptr;
2553 if (ObjType->isArrayType()) {
2554 // Next subobject is an array element.
2555 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2556 assert(CAT && "vla in literal type?");
2557 uint64_t Index = Sub.Entries[I].ArrayIndex;
2558 if (CAT->getSize().ule(Index)) {
2559 // Note, it should not be possible to form a pointer with a valid
2560 // designator which points more than one past the end of the array.
2561 if (Info.getLangOpts().CPlusPlus11)
2562 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2563 << handler.AccessKind;
2566 return handler.failed();
2569 ObjType = CAT->getElementType();
2571 // An array object is represented as either an Array APValue or as an
2572 // LValue which refers to a string literal.
2573 if (O->isLValue()) {
2574 assert(I == N - 1 && "extracting subobject of character?");
2575 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2576 if (handler.AccessKind != AK_Read)
2577 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2580 return handler.foundString(*O, ObjType, Index);
2583 if (O->getArrayInitializedElts() > Index)
2584 O = &O->getArrayInitializedElt(Index);
2585 else if (handler.AccessKind != AK_Read) {
2586 expandArray(*O, Index);
2587 O = &O->getArrayInitializedElt(Index);
2589 O = &O->getArrayFiller();
2590 } else if (ObjType->isAnyComplexType()) {
2591 // Next subobject is a complex number.
2592 uint64_t Index = Sub.Entries[I].ArrayIndex;
2594 if (Info.getLangOpts().CPlusPlus11)
2595 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2596 << handler.AccessKind;
2599 return handler.failed();
2602 bool WasConstQualified = ObjType.isConstQualified();
2603 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2604 if (WasConstQualified)
2607 assert(I == N - 1 && "extracting subobject of scalar?");
2608 if (O->isComplexInt()) {
2609 return handler.found(Index ? O->getComplexIntImag()
2610 : O->getComplexIntReal(), ObjType);
2612 assert(O->isComplexFloat());
2613 return handler.found(Index ? O->getComplexFloatImag()
2614 : O->getComplexFloatReal(), ObjType);
2616 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2617 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2618 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2620 Info.Note(Field->getLocation(), diag::note_declared_at);
2621 return handler.failed();
2624 // Next subobject is a class, struct or union field.
2625 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2626 if (RD->isUnion()) {
2627 const FieldDecl *UnionField = O->getUnionField();
2629 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2630 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2631 << handler.AccessKind << Field << !UnionField << UnionField;
2632 return handler.failed();
2634 O = &O->getUnionValue();
2636 O = &O->getStructField(Field->getFieldIndex());
2638 bool WasConstQualified = ObjType.isConstQualified();
2639 ObjType = Field->getType();
2640 if (WasConstQualified && !Field->isMutable())
2643 if (ObjType.isVolatileQualified()) {
2644 if (Info.getLangOpts().CPlusPlus) {
2645 // FIXME: Include a description of the path to the volatile subobject.
2646 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2647 << handler.AccessKind << 2 << Field;
2648 Info.Note(Field->getLocation(), diag::note_declared_at);
2650 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2652 return handler.failed();
2657 // Next subobject is a base class.
2658 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2659 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2660 O = &O->getStructBase(getBaseIndex(Derived, Base));
2662 bool WasConstQualified = ObjType.isConstQualified();
2663 ObjType = Info.Ctx.getRecordType(Base);
2664 if (WasConstQualified)
2671 struct ExtractSubobjectHandler {
2675 static const AccessKinds AccessKind = AK_Read;
2677 typedef bool result_type;
2678 bool failed() { return false; }
2679 bool found(APValue &Subobj, QualType SubobjType) {
2683 bool found(APSInt &Value, QualType SubobjType) {
2684 Result = APValue(Value);
2687 bool found(APFloat &Value, QualType SubobjType) {
2688 Result = APValue(Value);
2691 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2692 Result = APValue(extractStringLiteralCharacter(
2693 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2697 } // end anonymous namespace
2699 const AccessKinds ExtractSubobjectHandler::AccessKind;
2701 /// Extract the designated sub-object of an rvalue.
2702 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2703 const CompleteObject &Obj,
2704 const SubobjectDesignator &Sub,
2706 ExtractSubobjectHandler Handler = { Info, Result };
2707 return findSubobject(Info, E, Obj, Sub, Handler);
2711 struct ModifySubobjectHandler {
2716 typedef bool result_type;
2717 static const AccessKinds AccessKind = AK_Assign;
2719 bool checkConst(QualType QT) {
2720 // Assigning to a const object has undefined behavior.
2721 if (QT.isConstQualified()) {
2722 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2728 bool failed() { return false; }
2729 bool found(APValue &Subobj, QualType SubobjType) {
2730 if (!checkConst(SubobjType))
2732 // We've been given ownership of NewVal, so just swap it in.
2733 Subobj.swap(NewVal);
2736 bool found(APSInt &Value, QualType SubobjType) {
2737 if (!checkConst(SubobjType))
2739 if (!NewVal.isInt()) {
2740 // Maybe trying to write a cast pointer value into a complex?
2744 Value = NewVal.getInt();
2747 bool found(APFloat &Value, QualType SubobjType) {
2748 if (!checkConst(SubobjType))
2750 Value = NewVal.getFloat();
2753 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2754 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2757 } // end anonymous namespace
2759 const AccessKinds ModifySubobjectHandler::AccessKind;
2761 /// Update the designated sub-object of an rvalue to the given value.
2762 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2763 const CompleteObject &Obj,
2764 const SubobjectDesignator &Sub,
2766 ModifySubobjectHandler Handler = { Info, NewVal, E };
2767 return findSubobject(Info, E, Obj, Sub, Handler);
2770 /// Find the position where two subobject designators diverge, or equivalently
2771 /// the length of the common initial subsequence.
2772 static unsigned FindDesignatorMismatch(QualType ObjType,
2773 const SubobjectDesignator &A,
2774 const SubobjectDesignator &B,
2775 bool &WasArrayIndex) {
2776 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2777 for (/**/; I != N; ++I) {
2778 if (!ObjType.isNull() &&
2779 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2780 // Next subobject is an array element.
2781 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2782 WasArrayIndex = true;
2785 if (ObjType->isAnyComplexType())
2786 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2788 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2790 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2791 WasArrayIndex = false;
2794 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2795 // Next subobject is a field.
2796 ObjType = FD->getType();
2798 // Next subobject is a base class.
2799 ObjType = QualType();
2802 WasArrayIndex = false;
2806 /// Determine whether the given subobject designators refer to elements of the
2807 /// same array object.
2808 static bool AreElementsOfSameArray(QualType ObjType,
2809 const SubobjectDesignator &A,
2810 const SubobjectDesignator &B) {
2811 if (A.Entries.size() != B.Entries.size())
2814 bool IsArray = A.MostDerivedIsArrayElement;
2815 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2816 // A is a subobject of the array element.
2819 // If A (and B) designates an array element, the last entry will be the array
2820 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2821 // of length 1' case, and the entire path must match.
2823 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2824 return CommonLength >= A.Entries.size() - IsArray;
2827 /// Find the complete object to which an LValue refers.
2828 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2829 AccessKinds AK, const LValue &LVal,
2830 QualType LValType) {
2832 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2833 return CompleteObject();
2836 CallStackFrame *Frame = nullptr;
2837 if (LVal.CallIndex) {
2838 Frame = Info.getCallFrame(LVal.CallIndex);
2840 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2841 << AK << LVal.Base.is<const ValueDecl*>();
2842 NoteLValueLocation(Info, LVal.Base);
2843 return CompleteObject();
2847 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2848 // is not a constant expression (even if the object is non-volatile). We also
2849 // apply this rule to C++98, in order to conform to the expected 'volatile'
2851 if (LValType.isVolatileQualified()) {
2852 if (Info.getLangOpts().CPlusPlus)
2853 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2857 return CompleteObject();
2860 // Compute value storage location and type of base object.
2861 APValue *BaseVal = nullptr;
2862 QualType BaseType = getType(LVal.Base);
2864 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2865 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2866 // In C++11, constexpr, non-volatile variables initialized with constant
2867 // expressions are constant expressions too. Inside constexpr functions,
2868 // parameters are constant expressions even if they're non-const.
2869 // In C++1y, objects local to a constant expression (those with a Frame) are
2870 // both readable and writable inside constant expressions.
2871 // In C, such things can also be folded, although they are not ICEs.
2872 const VarDecl *VD = dyn_cast<VarDecl>(D);
2874 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2877 if (!VD || VD->isInvalidDecl()) {
2879 return CompleteObject();
2882 // Accesses of volatile-qualified objects are not allowed.
2883 if (BaseType.isVolatileQualified()) {
2884 if (Info.getLangOpts().CPlusPlus) {
2885 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2887 Info.Note(VD->getLocation(), diag::note_declared_at);
2891 return CompleteObject();
2894 // Unless we're looking at a local variable or argument in a constexpr call,
2895 // the variable we're reading must be const.
2897 if (Info.getLangOpts().CPlusPlus14 &&
2898 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2899 // OK, we can read and modify an object if we're in the process of
2900 // evaluating its initializer, because its lifetime began in this
2902 } else if (AK != AK_Read) {
2903 // All the remaining cases only permit reading.
2904 Info.FFDiag(E, diag::note_constexpr_modify_global);
2905 return CompleteObject();
2906 } else if (VD->isConstexpr()) {
2907 // OK, we can read this variable.
2908 } else if (BaseType->isIntegralOrEnumerationType()) {
2909 // In OpenCL if a variable is in constant address space it is a const value.
2910 if (!(BaseType.isConstQualified() ||
2911 (Info.getLangOpts().OpenCL &&
2912 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
2913 if (Info.getLangOpts().CPlusPlus) {
2914 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2915 Info.Note(VD->getLocation(), diag::note_declared_at);
2919 return CompleteObject();
2921 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2922 // We support folding of const floating-point types, in order to make
2923 // static const data members of such types (supported as an extension)
2925 if (Info.getLangOpts().CPlusPlus11) {
2926 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2927 Info.Note(VD->getLocation(), diag::note_declared_at);
2931 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2932 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2933 // Keep evaluating to see what we can do.
2935 // FIXME: Allow folding of values of any literal type in all languages.
2936 if (Info.checkingPotentialConstantExpression() &&
2937 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2938 // The definition of this variable could be constexpr. We can't
2939 // access it right now, but may be able to in future.
2940 } else if (Info.getLangOpts().CPlusPlus11) {
2941 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2942 Info.Note(VD->getLocation(), diag::note_declared_at);
2946 return CompleteObject();
2950 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2951 return CompleteObject();
2953 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2956 if (const MaterializeTemporaryExpr *MTE =
2957 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2958 assert(MTE->getStorageDuration() == SD_Static &&
2959 "should have a frame for a non-global materialized temporary");
2961 // Per C++1y [expr.const]p2:
2962 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2963 // - a [...] glvalue of integral or enumeration type that refers to
2964 // a non-volatile const object [...]
2966 // - a [...] glvalue of literal type that refers to a non-volatile
2967 // object whose lifetime began within the evaluation of e.
2969 // C++11 misses the 'began within the evaluation of e' check and
2970 // instead allows all temporaries, including things like:
2973 // constexpr int k = r;
2974 // Therefore we use the C++1y rules in C++11 too.
2975 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2976 const ValueDecl *ED = MTE->getExtendingDecl();
2977 if (!(BaseType.isConstQualified() &&
2978 BaseType->isIntegralOrEnumerationType()) &&
2979 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2980 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2981 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2982 return CompleteObject();
2985 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2986 assert(BaseVal && "got reference to unevaluated temporary");
2989 return CompleteObject();
2992 BaseVal = Frame->getTemporary(Base);
2993 assert(BaseVal && "missing value for temporary");
2996 // Volatile temporary objects cannot be accessed in constant expressions.
2997 if (BaseType.isVolatileQualified()) {
2998 if (Info.getLangOpts().CPlusPlus) {
2999 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3001 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3005 return CompleteObject();
3009 // During the construction of an object, it is not yet 'const'.
3010 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3011 // and this doesn't do quite the right thing for const subobjects of the
3012 // object under construction.
3013 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3014 BaseType = Info.Ctx.getCanonicalType(BaseType);
3015 BaseType.removeLocalConst();
3018 // In C++1y, we can't safely access any mutable state when we might be
3019 // evaluating after an unmodeled side effect.
3021 // FIXME: Not all local state is mutable. Allow local constant subobjects
3022 // to be read here (but take care with 'mutable' fields).
3023 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3024 Info.EvalStatus.HasSideEffects) ||
3025 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3026 return CompleteObject();
3028 return CompleteObject(BaseVal, BaseType);
3031 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3032 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3033 /// glvalue referred to by an entity of reference type.
3035 /// \param Info - Information about the ongoing evaluation.
3036 /// \param Conv - The expression for which we are performing the conversion.
3037 /// Used for diagnostics.
3038 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3039 /// case of a non-class type).
3040 /// \param LVal - The glvalue on which we are attempting to perform this action.
3041 /// \param RVal - The produced value will be placed here.
3042 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3044 const LValue &LVal, APValue &RVal) {
3045 if (LVal.Designator.Invalid)
3048 // Check for special cases where there is no existing APValue to look at.
3049 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3050 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3051 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3052 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3053 // initializer until now for such expressions. Such an expression can't be
3054 // an ICE in C, so this only matters for fold.
3055 if (Type.isVolatileQualified()) {
3060 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3062 CompleteObject LitObj(&Lit, Base->getType());
3063 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3064 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3065 // We represent a string literal array as an lvalue pointing at the
3066 // corresponding expression, rather than building an array of chars.
3067 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3068 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3069 CompleteObject StrObj(&Str, Base->getType());
3070 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3074 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3075 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3078 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3079 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3080 QualType LValType, APValue &Val) {
3081 if (LVal.Designator.Invalid)
3084 if (!Info.getLangOpts().CPlusPlus14) {
3089 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3090 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3093 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3094 return T->isSignedIntegerType() &&
3095 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3099 struct CompoundAssignSubobjectHandler {
3102 QualType PromotedLHSType;
3103 BinaryOperatorKind Opcode;
3106 static const AccessKinds AccessKind = AK_Assign;
3108 typedef bool result_type;
3110 bool checkConst(QualType QT) {
3111 // Assigning to a const object has undefined behavior.
3112 if (QT.isConstQualified()) {
3113 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3119 bool failed() { return false; }
3120 bool found(APValue &Subobj, QualType SubobjType) {
3121 switch (Subobj.getKind()) {
3123 return found(Subobj.getInt(), SubobjType);
3124 case APValue::Float:
3125 return found(Subobj.getFloat(), SubobjType);
3126 case APValue::ComplexInt:
3127 case APValue::ComplexFloat:
3128 // FIXME: Implement complex compound assignment.
3131 case APValue::LValue:
3132 return foundPointer(Subobj, SubobjType);
3134 // FIXME: can this happen?
3139 bool found(APSInt &Value, QualType SubobjType) {
3140 if (!checkConst(SubobjType))
3143 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3144 // We don't support compound assignment on integer-cast-to-pointer
3150 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3152 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3154 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3157 bool found(APFloat &Value, QualType SubobjType) {
3158 return checkConst(SubobjType) &&
3159 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3161 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3162 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3164 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3165 if (!checkConst(SubobjType))
3168 QualType PointeeType;
3169 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3170 PointeeType = PT->getPointeeType();
3172 if (PointeeType.isNull() || !RHS.isInt() ||
3173 (Opcode != BO_Add && Opcode != BO_Sub)) {
3178 int64_t Offset = getExtValue(RHS.getInt());
3179 if (Opcode == BO_Sub)
3183 LVal.setFrom(Info.Ctx, Subobj);
3184 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3186 LVal.moveInto(Subobj);
3189 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3190 llvm_unreachable("shouldn't encounter string elements here");
3193 } // end anonymous namespace
3195 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3197 /// Perform a compound assignment of LVal <op>= RVal.
3198 static bool handleCompoundAssignment(
3199 EvalInfo &Info, const Expr *E,
3200 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3201 BinaryOperatorKind Opcode, const APValue &RVal) {
3202 if (LVal.Designator.Invalid)
3205 if (!Info.getLangOpts().CPlusPlus14) {
3210 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3211 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3213 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3217 struct IncDecSubobjectHandler {
3220 AccessKinds AccessKind;
3223 typedef bool result_type;
3225 bool checkConst(QualType QT) {
3226 // Assigning to a const object has undefined behavior.
3227 if (QT.isConstQualified()) {
3228 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3234 bool failed() { return false; }
3235 bool found(APValue &Subobj, QualType SubobjType) {
3236 // Stash the old value. Also clear Old, so we don't clobber it later
3237 // if we're post-incrementing a complex.
3243 switch (Subobj.getKind()) {
3245 return found(Subobj.getInt(), SubobjType);
3246 case APValue::Float:
3247 return found(Subobj.getFloat(), SubobjType);
3248 case APValue::ComplexInt:
3249 return found(Subobj.getComplexIntReal(),
3250 SubobjType->castAs<ComplexType>()->getElementType()
3251 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3252 case APValue::ComplexFloat:
3253 return found(Subobj.getComplexFloatReal(),
3254 SubobjType->castAs<ComplexType>()->getElementType()
3255 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3256 case APValue::LValue:
3257 return foundPointer(Subobj, SubobjType);
3259 // FIXME: can this happen?
3264 bool found(APSInt &Value, QualType SubobjType) {
3265 if (!checkConst(SubobjType))
3268 if (!SubobjType->isIntegerType()) {
3269 // We don't support increment / decrement on integer-cast-to-pointer
3275 if (Old) *Old = APValue(Value);
3277 // bool arithmetic promotes to int, and the conversion back to bool
3278 // doesn't reduce mod 2^n, so special-case it.
3279 if (SubobjType->isBooleanType()) {
3280 if (AccessKind == AK_Increment)
3287 bool WasNegative = Value.isNegative();
3288 if (AccessKind == AK_Increment) {
3291 if (!WasNegative && Value.isNegative() &&
3292 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3293 APSInt ActualValue(Value, /*IsUnsigned*/true);
3294 return HandleOverflow(Info, E, ActualValue, SubobjType);
3299 if (WasNegative && !Value.isNegative() &&
3300 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3301 unsigned BitWidth = Value.getBitWidth();
3302 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3303 ActualValue.setBit(BitWidth);
3304 return HandleOverflow(Info, E, ActualValue, SubobjType);
3309 bool found(APFloat &Value, QualType SubobjType) {
3310 if (!checkConst(SubobjType))
3313 if (Old) *Old = APValue(Value);
3315 APFloat One(Value.getSemantics(), 1);
3316 if (AccessKind == AK_Increment)
3317 Value.add(One, APFloat::rmNearestTiesToEven);
3319 Value.subtract(One, APFloat::rmNearestTiesToEven);
3322 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3323 if (!checkConst(SubobjType))
3326 QualType PointeeType;
3327 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3328 PointeeType = PT->getPointeeType();
3335 LVal.setFrom(Info.Ctx, Subobj);
3336 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3337 AccessKind == AK_Increment ? 1 : -1))
3339 LVal.moveInto(Subobj);
3342 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3343 llvm_unreachable("shouldn't encounter string elements here");
3346 } // end anonymous namespace
3348 /// Perform an increment or decrement on LVal.
3349 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3350 QualType LValType, bool IsIncrement, APValue *Old) {
3351 if (LVal.Designator.Invalid)
3354 if (!Info.getLangOpts().CPlusPlus14) {
3359 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3360 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3361 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3362 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3365 /// Build an lvalue for the object argument of a member function call.
3366 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3368 if (Object->getType()->isPointerType())
3369 return EvaluatePointer(Object, This, Info);
3371 if (Object->isGLValue())
3372 return EvaluateLValue(Object, This, Info);
3374 if (Object->getType()->isLiteralType(Info.Ctx))
3375 return EvaluateTemporary(Object, This, Info);
3377 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3381 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3382 /// lvalue referring to the result.
3384 /// \param Info - Information about the ongoing evaluation.
3385 /// \param LV - An lvalue referring to the base of the member pointer.
3386 /// \param RHS - The member pointer expression.
3387 /// \param IncludeMember - Specifies whether the member itself is included in
3388 /// the resulting LValue subobject designator. This is not possible when
3389 /// creating a bound member function.
3390 /// \return The field or method declaration to which the member pointer refers,
3391 /// or 0 if evaluation fails.
3392 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3396 bool IncludeMember = true) {
3398 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3401 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3402 // member value, the behavior is undefined.
3403 if (!MemPtr.getDecl()) {
3404 // FIXME: Specific diagnostic.
3409 if (MemPtr.isDerivedMember()) {
3410 // This is a member of some derived class. Truncate LV appropriately.
3411 // The end of the derived-to-base path for the base object must match the
3412 // derived-to-base path for the member pointer.
3413 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3414 LV.Designator.Entries.size()) {
3418 unsigned PathLengthToMember =
3419 LV.Designator.Entries.size() - MemPtr.Path.size();
3420 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3421 const CXXRecordDecl *LVDecl = getAsBaseClass(
3422 LV.Designator.Entries[PathLengthToMember + I]);
3423 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3424 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3430 // Truncate the lvalue to the appropriate derived class.
3431 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3432 PathLengthToMember))
3434 } else if (!MemPtr.Path.empty()) {
3435 // Extend the LValue path with the member pointer's path.
3436 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3437 MemPtr.Path.size() + IncludeMember);
3439 // Walk down to the appropriate base class.
3440 if (const PointerType *PT = LVType->getAs<PointerType>())
3441 LVType = PT->getPointeeType();
3442 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3443 assert(RD && "member pointer access on non-class-type expression");
3444 // The first class in the path is that of the lvalue.
3445 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3446 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3447 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3451 // Finally cast to the class containing the member.
3452 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3453 MemPtr.getContainingRecord()))
3457 // Add the member. Note that we cannot build bound member functions here.
3458 if (IncludeMember) {
3459 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3460 if (!HandleLValueMember(Info, RHS, LV, FD))
3462 } else if (const IndirectFieldDecl *IFD =
3463 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3464 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3467 llvm_unreachable("can't construct reference to bound member function");
3471 return MemPtr.getDecl();
3474 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3475 const BinaryOperator *BO,
3477 bool IncludeMember = true) {
3478 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3480 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3481 if (Info.noteFailure()) {
3483 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3488 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3489 BO->getRHS(), IncludeMember);
3492 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3493 /// the provided lvalue, which currently refers to the base object.
3494 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3496 SubobjectDesignator &D = Result.Designator;
3497 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3500 QualType TargetQT = E->getType();
3501 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3502 TargetQT = PT->getPointeeType();
3504 // Check this cast lands within the final derived-to-base subobject path.
3505 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3506 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3507 << D.MostDerivedType << TargetQT;
3511 // Check the type of the final cast. We don't need to check the path,
3512 // since a cast can only be formed if the path is unique.
3513 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3514 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3515 const CXXRecordDecl *FinalType;
3516 if (NewEntriesSize == D.MostDerivedPathLength)
3517 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3519 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3520 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3521 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3522 << D.MostDerivedType << TargetQT;
3526 // Truncate the lvalue to the appropriate derived class.
3527 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3531 enum EvalStmtResult {
3532 /// Evaluation failed.
3534 /// Hit a 'return' statement.
3536 /// Evaluation succeeded.
3538 /// Hit a 'continue' statement.
3540 /// Hit a 'break' statement.
3542 /// Still scanning for 'case' or 'default' statement.
3547 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3548 // We don't need to evaluate the initializer for a static local.
3549 if (!VD->hasLocalStorage())
3553 Result.set(VD, Info.CurrentCall->Index);
3554 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3556 const Expr *InitE = VD->getInit();
3558 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3559 << false << VD->getType();
3564 if (InitE->isValueDependent())
3567 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3568 // Wipe out any partially-computed value, to allow tracking that this
3569 // evaluation failed.
3577 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3580 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3581 OK &= EvaluateVarDecl(Info, VD);
3583 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3584 for (auto *BD : DD->bindings())
3585 if (auto *VD = BD->getHoldingVar())
3586 OK &= EvaluateDecl(Info, VD);
3592 /// Evaluate a condition (either a variable declaration or an expression).
3593 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3594 const Expr *Cond, bool &Result) {
3595 FullExpressionRAII Scope(Info);
3596 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3598 return EvaluateAsBooleanCondition(Cond, Result, Info);
3602 /// \brief A location where the result (returned value) of evaluating a
3603 /// statement should be stored.
3605 /// The APValue that should be filled in with the returned value.
3607 /// The location containing the result, if any (used to support RVO).
3612 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3614 const SwitchCase *SC = nullptr);
3616 /// Evaluate the body of a loop, and translate the result as appropriate.
3617 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3619 const SwitchCase *Case = nullptr) {
3620 BlockScopeRAII Scope(Info);
3621 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3623 return ESR_Succeeded;
3626 return ESR_Continue;
3629 case ESR_CaseNotFound:
3632 llvm_unreachable("Invalid EvalStmtResult!");
3635 /// Evaluate a switch statement.
3636 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3637 const SwitchStmt *SS) {
3638 BlockScopeRAII Scope(Info);
3640 // Evaluate the switch condition.
3643 FullExpressionRAII Scope(Info);
3644 if (const Stmt *Init = SS->getInit()) {
3645 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3646 if (ESR != ESR_Succeeded)
3649 if (SS->getConditionVariable() &&
3650 !EvaluateDecl(Info, SS->getConditionVariable()))
3652 if (!EvaluateInteger(SS->getCond(), Value, Info))
3656 // Find the switch case corresponding to the value of the condition.
3657 // FIXME: Cache this lookup.
3658 const SwitchCase *Found = nullptr;
3659 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3660 SC = SC->getNextSwitchCase()) {
3661 if (isa<DefaultStmt>(SC)) {
3666 const CaseStmt *CS = cast<CaseStmt>(SC);
3667 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3668 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3670 if (LHS <= Value && Value <= RHS) {
3677 return ESR_Succeeded;
3679 // Search the switch body for the switch case and evaluate it from there.
3680 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3682 return ESR_Succeeded;
3688 case ESR_CaseNotFound:
3689 // This can only happen if the switch case is nested within a statement
3690 // expression. We have no intention of supporting that.
3691 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3694 llvm_unreachable("Invalid EvalStmtResult!");
3697 // Evaluate a statement.
3698 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3699 const Stmt *S, const SwitchCase *Case) {
3700 if (!Info.nextStep(S))
3703 // If we're hunting down a 'case' or 'default' label, recurse through
3704 // substatements until we hit the label.
3706 // FIXME: We don't start the lifetime of objects whose initialization we
3707 // jump over. However, such objects must be of class type with a trivial
3708 // default constructor that initialize all subobjects, so must be empty,
3709 // so this almost never matters.
3710 switch (S->getStmtClass()) {
3711 case Stmt::CompoundStmtClass:
3712 // FIXME: Precompute which substatement of a compound statement we
3713 // would jump to, and go straight there rather than performing a
3714 // linear scan each time.
3715 case Stmt::LabelStmtClass:
3716 case Stmt::AttributedStmtClass:
3717 case Stmt::DoStmtClass:
3720 case Stmt::CaseStmtClass:
3721 case Stmt::DefaultStmtClass:
3726 case Stmt::IfStmtClass: {
3727 // FIXME: Precompute which side of an 'if' we would jump to, and go
3728 // straight there rather than scanning both sides.
3729 const IfStmt *IS = cast<IfStmt>(S);
3731 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3732 // preceded by our switch label.
3733 BlockScopeRAII Scope(Info);
3735 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3736 if (ESR != ESR_CaseNotFound || !IS->getElse())
3738 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3741 case Stmt::WhileStmtClass: {
3742 EvalStmtResult ESR =
3743 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3744 if (ESR != ESR_Continue)
3749 case Stmt::ForStmtClass: {
3750 const ForStmt *FS = cast<ForStmt>(S);
3751 EvalStmtResult ESR =
3752 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3753 if (ESR != ESR_Continue)
3756 FullExpressionRAII IncScope(Info);
3757 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3763 case Stmt::DeclStmtClass:
3764 // FIXME: If the variable has initialization that can't be jumped over,
3765 // bail out of any immediately-surrounding compound-statement too.
3767 return ESR_CaseNotFound;
3771 switch (S->getStmtClass()) {
3773 if (const Expr *E = dyn_cast<Expr>(S)) {
3774 // Don't bother evaluating beyond an expression-statement which couldn't
3776 FullExpressionRAII Scope(Info);
3777 if (!EvaluateIgnoredValue(Info, E))
3779 return ESR_Succeeded;
3782 Info.FFDiag(S->getLocStart());
3785 case Stmt::NullStmtClass:
3786 return ESR_Succeeded;
3788 case Stmt::DeclStmtClass: {
3789 const DeclStmt *DS = cast<DeclStmt>(S);
3790 for (const auto *DclIt : DS->decls()) {
3791 // Each declaration initialization is its own full-expression.
3792 // FIXME: This isn't quite right; if we're performing aggregate
3793 // initialization, each braced subexpression is its own full-expression.
3794 FullExpressionRAII Scope(Info);
3795 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3798 return ESR_Succeeded;
3801 case Stmt::ReturnStmtClass: {
3802 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3803 FullExpressionRAII Scope(Info);
3806 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3807 : Evaluate(Result.Value, Info, RetExpr)))
3809 return ESR_Returned;
3812 case Stmt::CompoundStmtClass: {
3813 BlockScopeRAII Scope(Info);
3815 const CompoundStmt *CS = cast<CompoundStmt>(S);
3816 for (const auto *BI : CS->body()) {
3817 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3818 if (ESR == ESR_Succeeded)
3820 else if (ESR != ESR_CaseNotFound)
3823 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3826 case Stmt::IfStmtClass: {
3827 const IfStmt *IS = cast<IfStmt>(S);
3829 // Evaluate the condition, as either a var decl or as an expression.
3830 BlockScopeRAII Scope(Info);
3831 if (const Stmt *Init = IS->getInit()) {
3832 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3833 if (ESR != ESR_Succeeded)
3837 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3840 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3841 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3842 if (ESR != ESR_Succeeded)
3845 return ESR_Succeeded;
3848 case Stmt::WhileStmtClass: {
3849 const WhileStmt *WS = cast<WhileStmt>(S);
3851 BlockScopeRAII Scope(Info);
3853 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3859 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3860 if (ESR != ESR_Continue)
3863 return ESR_Succeeded;
3866 case Stmt::DoStmtClass: {
3867 const DoStmt *DS = cast<DoStmt>(S);
3870 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3871 if (ESR != ESR_Continue)
3875 FullExpressionRAII CondScope(Info);
3876 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3879 return ESR_Succeeded;
3882 case Stmt::ForStmtClass: {
3883 const ForStmt *FS = cast<ForStmt>(S);
3884 BlockScopeRAII Scope(Info);
3885 if (FS->getInit()) {
3886 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3887 if (ESR != ESR_Succeeded)
3891 BlockScopeRAII Scope(Info);
3892 bool Continue = true;
3893 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3894 FS->getCond(), Continue))
3899 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3900 if (ESR != ESR_Continue)
3904 FullExpressionRAII IncScope(Info);
3905 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3909 return ESR_Succeeded;
3912 case Stmt::CXXForRangeStmtClass: {
3913 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3914 BlockScopeRAII Scope(Info);
3916 // Initialize the __range variable.
3917 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3918 if (ESR != ESR_Succeeded)
3921 // Create the __begin and __end iterators.
3922 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3923 if (ESR != ESR_Succeeded)
3925 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3926 if (ESR != ESR_Succeeded)
3930 // Condition: __begin != __end.
3932 bool Continue = true;
3933 FullExpressionRAII CondExpr(Info);
3934 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3940 // User's variable declaration, initialized by *__begin.
3941 BlockScopeRAII InnerScope(Info);
3942 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3943 if (ESR != ESR_Succeeded)
3947 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3948 if (ESR != ESR_Continue)
3951 // Increment: ++__begin
3952 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3956 return ESR_Succeeded;
3959 case Stmt::SwitchStmtClass:
3960 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3962 case Stmt::ContinueStmtClass:
3963 return ESR_Continue;
3965 case Stmt::BreakStmtClass:
3968 case Stmt::LabelStmtClass:
3969 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3971 case Stmt::AttributedStmtClass:
3972 // As a general principle, C++11 attributes can be ignored without
3973 // any semantic impact.
3974 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3977 case Stmt::CaseStmtClass:
3978 case Stmt::DefaultStmtClass:
3979 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3983 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3984 /// default constructor. If so, we'll fold it whether or not it's marked as
3985 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3986 /// so we need special handling.
3987 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3988 const CXXConstructorDecl *CD,
3989 bool IsValueInitialization) {
3990 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3993 // Value-initialization does not call a trivial default constructor, so such a
3994 // call is a core constant expression whether or not the constructor is
3996 if (!CD->isConstexpr() && !IsValueInitialization) {
3997 if (Info.getLangOpts().CPlusPlus11) {
3998 // FIXME: If DiagDecl is an implicitly-declared special member function,
3999 // we should be much more explicit about why it's not constexpr.
4000 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4001 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4002 Info.Note(CD->getLocation(), diag::note_declared_at);
4004 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4010 /// CheckConstexprFunction - Check that a function can be called in a constant
4012 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4013 const FunctionDecl *Declaration,
4014 const FunctionDecl *Definition,
4016 // Potential constant expressions can contain calls to declared, but not yet
4017 // defined, constexpr functions.
4018 if (Info.checkingPotentialConstantExpression() && !Definition &&
4019 Declaration->isConstexpr())
4022 // Bail out with no diagnostic if the function declaration itself is invalid.
4023 // We will have produced a relevant diagnostic while parsing it.
4024 if (Declaration->isInvalidDecl())
4027 // Can we evaluate this function call?
4028 if (Definition && Definition->isConstexpr() &&
4029 !Definition->isInvalidDecl() && Body)
4032 if (Info.getLangOpts().CPlusPlus11) {
4033 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4035 // If this function is not constexpr because it is an inherited
4036 // non-constexpr constructor, diagnose that directly.
4037 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4038 if (CD && CD->isInheritingConstructor()) {
4039 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4040 if (!Inherited->isConstexpr())
4041 DiagDecl = CD = Inherited;
4044 // FIXME: If DiagDecl is an implicitly-declared special member function
4045 // or an inheriting constructor, we should be much more explicit about why
4046 // it's not constexpr.
4047 if (CD && CD->isInheritingConstructor())
4048 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4049 << CD->getInheritedConstructor().getConstructor()->getParent();
4051 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4052 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4053 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4055 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4060 /// Determine if a class has any fields that might need to be copied by a
4061 /// trivial copy or move operation.
4062 static bool hasFields(const CXXRecordDecl *RD) {
4063 if (!RD || RD->isEmpty())
4065 for (auto *FD : RD->fields()) {
4066 if (FD->isUnnamedBitfield())
4070 for (auto &Base : RD->bases())
4071 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4077 typedef SmallVector<APValue, 8> ArgVector;
4080 /// EvaluateArgs - Evaluate the arguments to a function call.
4081 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4083 bool Success = true;
4084 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4086 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4087 // If we're checking for a potential constant expression, evaluate all
4088 // initializers even if some of them fail.
4089 if (!Info.noteFailure())
4097 /// Evaluate a function call.
4098 static bool HandleFunctionCall(SourceLocation CallLoc,
4099 const FunctionDecl *Callee, const LValue *This,
4100 ArrayRef<const Expr*> Args, const Stmt *Body,
4101 EvalInfo &Info, APValue &Result,
4102 const LValue *ResultSlot) {
4103 ArgVector ArgValues(Args.size());
4104 if (!EvaluateArgs(Args, ArgValues, Info))
4107 if (!Info.CheckCallLimit(CallLoc))
4110 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4112 // For a trivial copy or move assignment, perform an APValue copy. This is
4113 // essential for unions, where the operations performed by the assignment
4114 // operator cannot be represented as statements.
4116 // Skip this for non-union classes with no fields; in that case, the defaulted
4117 // copy/move does not actually read the object.
4118 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4119 if (MD && MD->isDefaulted() &&
4120 (MD->getParent()->isUnion() ||
4121 (MD->isTrivial() && hasFields(MD->getParent())))) {
4123 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4125 RHS.setFrom(Info.Ctx, ArgValues[0]);
4127 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4130 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4133 This->moveInto(Result);
4137 StmtResult Ret = {Result, ResultSlot};
4138 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4139 if (ESR == ESR_Succeeded) {
4140 if (Callee->getReturnType()->isVoidType())
4142 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4144 return ESR == ESR_Returned;
4147 /// Evaluate a constructor call.
4148 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4150 const CXXConstructorDecl *Definition,
4151 EvalInfo &Info, APValue &Result) {
4152 SourceLocation CallLoc = E->getExprLoc();
4153 if (!Info.CheckCallLimit(CallLoc))
4156 const CXXRecordDecl *RD = Definition->getParent();
4157 if (RD->getNumVBases()) {
4158 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4162 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4164 // FIXME: Creating an APValue just to hold a nonexistent return value is
4167 StmtResult Ret = {RetVal, nullptr};
4169 // If it's a delegating constructor, delegate.
4170 if (Definition->isDelegatingConstructor()) {
4171 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4173 FullExpressionRAII InitScope(Info);
4174 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4177 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4180 // For a trivial copy or move constructor, perform an APValue copy. This is
4181 // essential for unions (or classes with anonymous union members), where the
4182 // operations performed by the constructor cannot be represented by
4183 // ctor-initializers.
4185 // Skip this for empty non-union classes; we should not perform an
4186 // lvalue-to-rvalue conversion on them because their copy constructor does not
4187 // actually read them.
4188 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4189 (Definition->getParent()->isUnion() ||
4190 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4192 RHS.setFrom(Info.Ctx, ArgValues[0]);
4193 return handleLValueToRValueConversion(
4194 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4198 // Reserve space for the struct members.
4199 if (!RD->isUnion() && Result.isUninit())
4200 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4201 std::distance(RD->field_begin(), RD->field_end()));
4203 if (RD->isInvalidDecl()) return false;
4204 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4206 // A scope for temporaries lifetime-extended by reference members.
4207 BlockScopeRAII LifetimeExtendedScope(Info);
4209 bool Success = true;
4210 unsigned BasesSeen = 0;
4212 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4214 for (const auto *I : Definition->inits()) {
4215 LValue Subobject = This;
4216 APValue *Value = &Result;
4218 // Determine the subobject to initialize.
4219 FieldDecl *FD = nullptr;
4220 if (I->isBaseInitializer()) {
4221 QualType BaseType(I->getBaseClass(), 0);
4223 // Non-virtual base classes are initialized in the order in the class
4224 // definition. We have already checked for virtual base classes.
4225 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4226 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4227 "base class initializers not in expected order");
4230 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4231 BaseType->getAsCXXRecordDecl(), &Layout))
4233 Value = &Result.getStructBase(BasesSeen++);
4234 } else if ((FD = I->getMember())) {
4235 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4237 if (RD->isUnion()) {
4238 Result = APValue(FD);
4239 Value = &Result.getUnionValue();
4241 Value = &Result.getStructField(FD->getFieldIndex());
4243 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4244 // Walk the indirect field decl's chain to find the object to initialize,
4245 // and make sure we've initialized every step along it.
4246 for (auto *C : IFD->chain()) {
4247 FD = cast<FieldDecl>(C);
4248 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4249 // Switch the union field if it differs. This happens if we had
4250 // preceding zero-initialization, and we're now initializing a union
4251 // subobject other than the first.
4252 // FIXME: In this case, the values of the other subobjects are
4253 // specified, since zero-initialization sets all padding bits to zero.
4254 if (Value->isUninit() ||
4255 (Value->isUnion() && Value->getUnionField() != FD)) {
4257 *Value = APValue(FD);
4259 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4260 std::distance(CD->field_begin(), CD->field_end()));
4262 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4265 Value = &Value->getUnionValue();
4267 Value = &Value->getStructField(FD->getFieldIndex());
4270 llvm_unreachable("unknown base initializer kind");
4273 FullExpressionRAII InitScope(Info);
4274 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4275 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4277 // If we're checking for a potential constant expression, evaluate all
4278 // initializers even if some of them fail.
4279 if (!Info.noteFailure())
4286 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4289 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4290 ArrayRef<const Expr*> Args,
4291 const CXXConstructorDecl *Definition,
4292 EvalInfo &Info, APValue &Result) {
4293 ArgVector ArgValues(Args.size());
4294 if (!EvaluateArgs(Args, ArgValues, Info))
4297 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4301 //===----------------------------------------------------------------------===//
4302 // Generic Evaluation
4303 //===----------------------------------------------------------------------===//
4306 template <class Derived>
4307 class ExprEvaluatorBase
4308 : public ConstStmtVisitor<Derived, bool> {
4310 Derived &getDerived() { return static_cast<Derived&>(*this); }
4311 bool DerivedSuccess(const APValue &V, const Expr *E) {
4312 return getDerived().Success(V, E);
4314 bool DerivedZeroInitialization(const Expr *E) {
4315 return getDerived().ZeroInitialization(E);
4318 // Check whether a conditional operator with a non-constant condition is a
4319 // potential constant expression. If neither arm is a potential constant
4320 // expression, then the conditional operator is not either.
4321 template<typename ConditionalOperator>
4322 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4323 assert(Info.checkingPotentialConstantExpression());
4325 // Speculatively evaluate both arms.
4326 SmallVector<PartialDiagnosticAt, 8> Diag;
4328 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4329 StmtVisitorTy::Visit(E->getFalseExpr());
4335 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4337 StmtVisitorTy::Visit(E->getTrueExpr());
4342 Error(E, diag::note_constexpr_conditional_never_const);
4346 template<typename ConditionalOperator>
4347 bool HandleConditionalOperator(const ConditionalOperator *E) {
4349 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4350 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4351 CheckPotentialConstantConditional(E);
4355 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4356 return StmtVisitorTy::Visit(EvalExpr);
4361 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4362 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4364 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4365 return Info.CCEDiag(E, D);
4368 bool ZeroInitialization(const Expr *E) { return Error(E); }
4371 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4373 EvalInfo &getEvalInfo() { return Info; }
4375 /// Report an evaluation error. This should only be called when an error is
4376 /// first discovered. When propagating an error, just return false.
4377 bool Error(const Expr *E, diag::kind D) {
4381 bool Error(const Expr *E) {
4382 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4385 bool VisitStmt(const Stmt *) {
4386 llvm_unreachable("Expression evaluator should not be called on stmts");
4388 bool VisitExpr(const Expr *E) {
4392 bool VisitParenExpr(const ParenExpr *E)
4393 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4394 bool VisitUnaryExtension(const UnaryOperator *E)
4395 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4396 bool VisitUnaryPlus(const UnaryOperator *E)
4397 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4398 bool VisitChooseExpr(const ChooseExpr *E)
4399 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4400 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4401 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4402 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4403 { return StmtVisitorTy::Visit(E->getReplacement()); }
4404 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4405 { return StmtVisitorTy::Visit(E->getExpr()); }
4406 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4407 // The initializer may not have been parsed yet, or might be erroneous.
4410 return StmtVisitorTy::Visit(E->getExpr());
4412 // We cannot create any objects for which cleanups are required, so there is
4413 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4414 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4415 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4417 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4418 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4419 return static_cast<Derived*>(this)->VisitCastExpr(E);
4421 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4422 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4423 return static_cast<Derived*>(this)->VisitCastExpr(E);
4426 bool VisitBinaryOperator(const BinaryOperator *E) {
4427 switch (E->getOpcode()) {
4432 VisitIgnoredValue(E->getLHS());
4433 return StmtVisitorTy::Visit(E->getRHS());
4438 if (!HandleMemberPointerAccess(Info, E, Obj))
4441 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4443 return DerivedSuccess(Result, E);
4448 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4449 // Evaluate and cache the common expression. We treat it as a temporary,
4450 // even though it's not quite the same thing.
4451 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4452 Info, E->getCommon()))
4455 return HandleConditionalOperator(E);
4458 bool VisitConditionalOperator(const ConditionalOperator *E) {
4459 bool IsBcpCall = false;
4460 // If the condition (ignoring parens) is a __builtin_constant_p call,
4461 // the result is a constant expression if it can be folded without
4462 // side-effects. This is an important GNU extension. See GCC PR38377
4464 if (const CallExpr *CallCE =
4465 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4466 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4469 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4470 // constant expression; we can't check whether it's potentially foldable.
4471 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4474 FoldConstant Fold(Info, IsBcpCall);
4475 if (!HandleConditionalOperator(E)) {
4476 Fold.keepDiagnostics();
4483 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4484 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4485 return DerivedSuccess(*Value, E);
4487 const Expr *Source = E->getSourceExpr();
4490 if (Source == E) { // sanity checking.
4491 assert(0 && "OpaqueValueExpr recursively refers to itself");
4494 return StmtVisitorTy::Visit(Source);
4497 bool VisitCallExpr(const CallExpr *E) {
4499 if (!handleCallExpr(E, Result, nullptr))
4501 return DerivedSuccess(Result, E);
4504 bool handleCallExpr(const CallExpr *E, APValue &Result,
4505 const LValue *ResultSlot) {
4506 const Expr *Callee = E->getCallee()->IgnoreParens();
4507 QualType CalleeType = Callee->getType();
4509 const FunctionDecl *FD = nullptr;
4510 LValue *This = nullptr, ThisVal;
4511 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4512 bool HasQualifier = false;
4514 // Extract function decl and 'this' pointer from the callee.
4515 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4516 const ValueDecl *Member = nullptr;
4517 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4518 // Explicit bound member calls, such as x.f() or p->g();
4519 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4521 Member = ME->getMemberDecl();
4523 HasQualifier = ME->hasQualifier();
4524 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4525 // Indirect bound member calls ('.*' or '->*').
4526 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4527 if (!Member) return false;
4530 return Error(Callee);
4532 FD = dyn_cast<FunctionDecl>(Member);
4534 return Error(Callee);
4535 } else if (CalleeType->isFunctionPointerType()) {
4537 if (!EvaluatePointer(Callee, Call, Info))
4540 if (!Call.getLValueOffset().isZero())
4541 return Error(Callee);
4542 FD = dyn_cast_or_null<FunctionDecl>(
4543 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4545 return Error(Callee);
4546 // Don't call function pointers which have been cast to some other type.
4547 // Per DR (no number yet), the caller and callee can differ in noexcept.
4548 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4549 CalleeType->getPointeeType(), FD->getType())) {
4553 // Overloaded operator calls to member functions are represented as normal
4554 // calls with '*this' as the first argument.
4555 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4556 if (MD && !MD->isStatic()) {
4557 // FIXME: When selecting an implicit conversion for an overloaded
4558 // operator delete, we sometimes try to evaluate calls to conversion
4559 // operators without a 'this' parameter!
4563 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4566 Args = Args.slice(1);
4567 } else if (MD && MD->isLambdaStaticInvoker()) {
4568 // Map the static invoker for the lambda back to the call operator.
4569 // Conveniently, we don't have to slice out the 'this' argument (as is
4570 // being done for the non-static case), since a static member function
4571 // doesn't have an implicit argument passed in.
4572 const CXXRecordDecl *ClosureClass = MD->getParent();
4574 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4575 "Number of captures must be zero for conversion to function-ptr");
4577 const CXXMethodDecl *LambdaCallOp =
4578 ClosureClass->getLambdaCallOperator();
4580 // Set 'FD', the function that will be called below, to the call
4581 // operator. If the closure object represents a generic lambda, find
4582 // the corresponding specialization of the call operator.
4584 if (ClosureClass->isGenericLambda()) {
4585 assert(MD->isFunctionTemplateSpecialization() &&
4586 "A generic lambda's static-invoker function must be a "
4587 "template specialization");
4588 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4589 FunctionTemplateDecl *CallOpTemplate =
4590 LambdaCallOp->getDescribedFunctionTemplate();
4591 void *InsertPos = nullptr;
4592 FunctionDecl *CorrespondingCallOpSpecialization =
4593 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4594 assert(CorrespondingCallOpSpecialization &&
4595 "We must always have a function call operator specialization "
4596 "that corresponds to our static invoker specialization");
4597 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4606 if (This && !This->checkSubobject(Info, E, CSK_This))
4609 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4610 // calls to such functions in constant expressions.
4611 if (This && !HasQualifier &&
4612 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4613 return Error(E, diag::note_constexpr_virtual_call);
4615 const FunctionDecl *Definition = nullptr;
4616 Stmt *Body = FD->getBody(Definition);
4618 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4619 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4620 Result, ResultSlot))
4626 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4627 return StmtVisitorTy::Visit(E->getInitializer());
4629 bool VisitInitListExpr(const InitListExpr *E) {
4630 if (E->getNumInits() == 0)
4631 return DerivedZeroInitialization(E);
4632 if (E->getNumInits() == 1)
4633 return StmtVisitorTy::Visit(E->getInit(0));
4636 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4637 return DerivedZeroInitialization(E);
4639 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4640 return DerivedZeroInitialization(E);
4642 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4643 return DerivedZeroInitialization(E);
4646 /// A member expression where the object is a prvalue is itself a prvalue.
4647 bool VisitMemberExpr(const MemberExpr *E) {
4648 assert(!E->isArrow() && "missing call to bound member function?");
4651 if (!Evaluate(Val, Info, E->getBase()))
4654 QualType BaseTy = E->getBase()->getType();
4656 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4657 if (!FD) return Error(E);
4658 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4659 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4660 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4662 CompleteObject Obj(&Val, BaseTy);
4663 SubobjectDesignator Designator(BaseTy);
4664 Designator.addDeclUnchecked(FD);
4667 return extractSubobject(Info, E, Obj, Designator, Result) &&
4668 DerivedSuccess(Result, E);
4671 bool VisitCastExpr(const CastExpr *E) {
4672 switch (E->getCastKind()) {
4676 case CK_AtomicToNonAtomic: {
4678 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4680 return DerivedSuccess(AtomicVal, E);
4684 case CK_UserDefinedConversion:
4685 return StmtVisitorTy::Visit(E->getSubExpr());
4687 case CK_LValueToRValue: {
4689 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4692 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4693 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4696 return DerivedSuccess(RVal, E);
4703 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4704 return VisitUnaryPostIncDec(UO);
4706 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4707 return VisitUnaryPostIncDec(UO);
4709 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4710 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4714 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4717 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4718 UO->isIncrementOp(), &RVal))
4720 return DerivedSuccess(RVal, UO);
4723 bool VisitStmtExpr(const StmtExpr *E) {
4724 // We will have checked the full-expressions inside the statement expression
4725 // when they were completed, and don't need to check them again now.
4726 if (Info.checkingForOverflow())
4729 BlockScopeRAII Scope(Info);
4730 const CompoundStmt *CS = E->getSubStmt();
4731 if (CS->body_empty())
4734 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4735 BE = CS->body_end();
4738 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4740 Info.FFDiag((*BI)->getLocStart(),
4741 diag::note_constexpr_stmt_expr_unsupported);
4744 return this->Visit(FinalExpr);
4747 APValue ReturnValue;
4748 StmtResult Result = { ReturnValue, nullptr };
4749 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4750 if (ESR != ESR_Succeeded) {
4751 // FIXME: If the statement-expression terminated due to 'return',
4752 // 'break', or 'continue', it would be nice to propagate that to
4753 // the outer statement evaluation rather than bailing out.
4754 if (ESR != ESR_Failed)
4755 Info.FFDiag((*BI)->getLocStart(),
4756 diag::note_constexpr_stmt_expr_unsupported);
4761 llvm_unreachable("Return from function from the loop above.");
4764 /// Visit a value which is evaluated, but whose value is ignored.
4765 void VisitIgnoredValue(const Expr *E) {
4766 EvaluateIgnoredValue(Info, E);
4769 /// Potentially visit a MemberExpr's base expression.
4770 void VisitIgnoredBaseExpression(const Expr *E) {
4771 // While MSVC doesn't evaluate the base expression, it does diagnose the
4772 // presence of side-effecting behavior.
4773 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4775 VisitIgnoredValue(E);
4781 //===----------------------------------------------------------------------===//
4782 // Common base class for lvalue and temporary evaluation.
4783 //===----------------------------------------------------------------------===//
4785 template<class Derived>
4786 class LValueExprEvaluatorBase
4787 : public ExprEvaluatorBase<Derived> {
4790 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4791 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4793 bool Success(APValue::LValueBase B) {
4799 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4800 ExprEvaluatorBaseTy(Info), Result(Result) {}
4802 bool Success(const APValue &V, const Expr *E) {
4803 Result.setFrom(this->Info.Ctx, V);
4807 bool VisitMemberExpr(const MemberExpr *E) {
4808 // Handle non-static data members.
4812 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
4813 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4814 } else if (E->getBase()->isRValue()) {
4815 assert(E->getBase()->getType()->isRecordType());
4816 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4817 BaseTy = E->getBase()->getType();
4819 EvalOK = this->Visit(E->getBase());
4820 BaseTy = E->getBase()->getType();
4823 if (!this->Info.allowInvalidBaseExpr())
4825 Result.setInvalid(E);
4829 const ValueDecl *MD = E->getMemberDecl();
4830 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4831 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4832 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4834 if (!HandleLValueMember(this->Info, E, Result, FD))
4836 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4837 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4840 return this->Error(E);
4842 if (MD->getType()->isReferenceType()) {
4844 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4847 return Success(RefValue, E);
4852 bool VisitBinaryOperator(const BinaryOperator *E) {
4853 switch (E->getOpcode()) {
4855 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4859 return HandleMemberPointerAccess(this->Info, E, Result);
4863 bool VisitCastExpr(const CastExpr *E) {
4864 switch (E->getCastKind()) {
4866 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4868 case CK_DerivedToBase:
4869 case CK_UncheckedDerivedToBase:
4870 if (!this->Visit(E->getSubExpr()))
4873 // Now figure out the necessary offset to add to the base LV to get from
4874 // the derived class to the base class.
4875 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4882 //===----------------------------------------------------------------------===//
4883 // LValue Evaluation
4885 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4886 // function designators (in C), decl references to void objects (in C), and
4887 // temporaries (if building with -Wno-address-of-temporary).
4889 // LValue evaluation produces values comprising a base expression of one of the
4895 // * CompoundLiteralExpr in C (and in global scope in C++)
4899 // * ObjCStringLiteralExpr
4903 // * CallExpr for a MakeStringConstant builtin
4904 // - Locals and temporaries
4905 // * MaterializeTemporaryExpr
4906 // * Any Expr, with a CallIndex indicating the function in which the temporary
4907 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4908 // from the AST (FIXME).
4909 // * A MaterializeTemporaryExpr that has static storage duration, with no
4910 // CallIndex, for a lifetime-extended temporary.
4911 // plus an offset in bytes.
4912 //===----------------------------------------------------------------------===//
4914 class LValueExprEvaluator
4915 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4917 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4918 LValueExprEvaluatorBaseTy(Info, Result) {}
4920 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4921 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4923 bool VisitDeclRefExpr(const DeclRefExpr *E);
4924 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4925 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4926 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4927 bool VisitMemberExpr(const MemberExpr *E);
4928 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4929 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4930 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4931 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4932 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4933 bool VisitUnaryDeref(const UnaryOperator *E);
4934 bool VisitUnaryReal(const UnaryOperator *E);
4935 bool VisitUnaryImag(const UnaryOperator *E);
4936 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4937 return VisitUnaryPreIncDec(UO);
4939 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4940 return VisitUnaryPreIncDec(UO);
4942 bool VisitBinAssign(const BinaryOperator *BO);
4943 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4945 bool VisitCastExpr(const CastExpr *E) {
4946 switch (E->getCastKind()) {
4948 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4950 case CK_LValueBitCast:
4951 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4952 if (!Visit(E->getSubExpr()))
4954 Result.Designator.setInvalid();
4957 case CK_BaseToDerived:
4958 if (!Visit(E->getSubExpr()))
4960 return HandleBaseToDerivedCast(Info, E, Result);
4964 } // end anonymous namespace
4966 /// Evaluate an expression as an lvalue. This can be legitimately called on
4967 /// expressions which are not glvalues, in three cases:
4968 /// * function designators in C, and
4969 /// * "extern void" objects
4970 /// * @selector() expressions in Objective-C
4971 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4972 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4973 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4974 return LValueExprEvaluator(Info, Result).Visit(E);
4977 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4978 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4980 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4981 return VisitVarDecl(E, VD);
4982 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
4983 return Visit(BD->getBinding());
4988 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4989 CallStackFrame *Frame = nullptr;
4990 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
4991 // Only if a local variable was declared in the function currently being
4992 // evaluated, do we expect to be able to find its value in the current
4993 // frame. (Otherwise it was likely declared in an enclosing context and
4994 // could either have a valid evaluatable value (for e.g. a constexpr
4995 // variable) or be ill-formed (and trigger an appropriate evaluation
4997 if (Info.CurrentCall->Callee &&
4998 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
4999 Frame = Info.CurrentCall;
5003 if (!VD->getType()->isReferenceType()) {
5005 Result.set(VD, Frame->Index);
5012 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5014 if (V->isUninit()) {
5015 if (!Info.checkingPotentialConstantExpression())
5016 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5019 return Success(*V, E);
5022 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5023 const MaterializeTemporaryExpr *E) {
5024 // Walk through the expression to find the materialized temporary itself.
5025 SmallVector<const Expr *, 2> CommaLHSs;
5026 SmallVector<SubobjectAdjustment, 2> Adjustments;
5027 const Expr *Inner = E->GetTemporaryExpr()->
5028 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5030 // If we passed any comma operators, evaluate their LHSs.
5031 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5032 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5035 // A materialized temporary with static storage duration can appear within the
5036 // result of a constant expression evaluation, so we need to preserve its
5037 // value for use outside this evaluation.
5039 if (E->getStorageDuration() == SD_Static) {
5040 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5044 Value = &Info.CurrentCall->
5045 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5046 Result.set(E, Info.CurrentCall->Index);
5049 QualType Type = Inner->getType();
5051 // Materialize the temporary itself.
5052 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5053 (E->getStorageDuration() == SD_Static &&
5054 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5059 // Adjust our lvalue to refer to the desired subobject.
5060 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5062 switch (Adjustments[I].Kind) {
5063 case SubobjectAdjustment::DerivedToBaseAdjustment:
5064 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5067 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5070 case SubobjectAdjustment::FieldAdjustment:
5071 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5073 Type = Adjustments[I].Field->getType();
5076 case SubobjectAdjustment::MemberPointerAdjustment:
5077 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5078 Adjustments[I].Ptr.RHS))
5080 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5089 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5090 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5091 "lvalue compound literal in c++?");
5092 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5093 // only see this when folding in C, so there's no standard to follow here.
5097 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5098 if (!E->isPotentiallyEvaluated())
5101 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5102 << E->getExprOperand()->getType()
5103 << E->getExprOperand()->getSourceRange();
5107 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5111 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5112 // Handle static data members.
5113 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5114 VisitIgnoredBaseExpression(E->getBase());
5115 return VisitVarDecl(E, VD);
5118 // Handle static member functions.
5119 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5120 if (MD->isStatic()) {
5121 VisitIgnoredBaseExpression(E->getBase());
5126 // Handle non-static data members.
5127 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5130 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5131 // FIXME: Deal with vectors as array subscript bases.
5132 if (E->getBase()->getType()->isVectorType())
5135 if (!EvaluatePointer(E->getBase(), Result, Info))
5139 if (!EvaluateInteger(E->getIdx(), Index, Info))
5142 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5143 getExtValue(Index));
5146 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5147 return EvaluatePointer(E->getSubExpr(), Result, Info);
5150 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5151 if (!Visit(E->getSubExpr()))
5153 // __real is a no-op on scalar lvalues.
5154 if (E->getSubExpr()->getType()->isAnyComplexType())
5155 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5159 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5160 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5161 "lvalue __imag__ on scalar?");
5162 if (!Visit(E->getSubExpr()))
5164 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5168 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5169 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5172 if (!this->Visit(UO->getSubExpr()))
5175 return handleIncDec(
5176 this->Info, UO, Result, UO->getSubExpr()->getType(),
5177 UO->isIncrementOp(), nullptr);
5180 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5181 const CompoundAssignOperator *CAO) {
5182 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5187 // The overall lvalue result is the result of evaluating the LHS.
5188 if (!this->Visit(CAO->getLHS())) {
5189 if (Info.noteFailure())
5190 Evaluate(RHS, this->Info, CAO->getRHS());
5194 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5197 return handleCompoundAssignment(
5199 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5200 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5203 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5204 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5209 if (!this->Visit(E->getLHS())) {
5210 if (Info.noteFailure())
5211 Evaluate(NewVal, this->Info, E->getRHS());
5215 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5218 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5222 //===----------------------------------------------------------------------===//
5223 // Pointer Evaluation
5224 //===----------------------------------------------------------------------===//
5226 /// \brief Attempts to compute the number of bytes available at the pointer
5227 /// returned by a function with the alloc_size attribute. Returns true if we
5228 /// were successful. Places an unsigned number into `Result`.
5230 /// This expects the given CallExpr to be a call to a function with an
5231 /// alloc_size attribute.
5232 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5233 const CallExpr *Call,
5234 llvm::APInt &Result) {
5235 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5237 // alloc_size args are 1-indexed, 0 means not present.
5238 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5239 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5240 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5241 if (Call->getNumArgs() <= SizeArgNo)
5244 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5245 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5247 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5249 Into = Into.zextOrSelf(BitsInSizeT);
5254 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5257 if (!AllocSize->getNumElemsParam()) {
5258 Result = std::move(SizeOfElem);
5262 APSInt NumberOfElems;
5263 // Argument numbers start at 1
5264 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5265 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5269 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5273 Result = std::move(BytesAvailable);
5277 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5279 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5281 llvm::APInt &Result) {
5282 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5283 "Can't get the size of a non alloc_size function");
5284 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5285 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5286 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5289 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5290 /// a function with the alloc_size attribute. If it was possible to do so, this
5291 /// function will return true, make Result's Base point to said function call,
5292 /// and mark Result's Base as invalid.
5293 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5295 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5298 // Because we do no form of static analysis, we only support const variables.
5300 // Additionally, we can't support parameters, nor can we support static
5301 // variables (in the latter case, use-before-assign isn't UB; in the former,
5302 // we have no clue what they'll be assigned to).
5304 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5305 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5308 const Expr *Init = VD->getAnyInitializer();
5312 const Expr *E = Init->IgnoreParens();
5313 if (!tryUnwrapAllocSizeCall(E))
5316 // Store E instead of E unwrapped so that the type of the LValue's base is
5317 // what the user wanted.
5318 Result.setInvalid(E);
5320 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5321 Result.addUnsizedArray(Info, Pointee);
5326 class PointerExprEvaluator
5327 : public ExprEvaluatorBase<PointerExprEvaluator> {
5330 bool Success(const Expr *E) {
5335 bool visitNonBuiltinCallExpr(const CallExpr *E);
5338 PointerExprEvaluator(EvalInfo &info, LValue &Result)
5339 : ExprEvaluatorBaseTy(info), Result(Result) {}
5341 bool Success(const APValue &V, const Expr *E) {
5342 Result.setFrom(Info.Ctx, V);
5345 bool ZeroInitialization(const Expr *E) {
5346 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5347 Result.set((Expr*)nullptr, 0, false, true, Offset);
5351 bool VisitBinaryOperator(const BinaryOperator *E);
5352 bool VisitCastExpr(const CastExpr* E);
5353 bool VisitUnaryAddrOf(const UnaryOperator *E);
5354 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5355 { return Success(E); }
5356 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5357 { return Success(E); }
5358 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5359 { return Success(E); }
5360 bool VisitCallExpr(const CallExpr *E);
5361 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5362 bool VisitBlockExpr(const BlockExpr *E) {
5363 if (!E->getBlockDecl()->hasCaptures())
5367 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5368 // Can't look at 'this' when checking a potential constant expression.
5369 if (Info.checkingPotentialConstantExpression())
5371 if (!Info.CurrentCall->This) {
5372 if (Info.getLangOpts().CPlusPlus11)
5373 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5378 Result = *Info.CurrentCall->This;
5382 // FIXME: Missing: @protocol, @selector
5384 } // end anonymous namespace
5386 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
5387 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5388 return PointerExprEvaluator(Info, Result).Visit(E);
5391 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5392 if (E->getOpcode() != BO_Add &&
5393 E->getOpcode() != BO_Sub)
5394 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5396 const Expr *PExp = E->getLHS();
5397 const Expr *IExp = E->getRHS();
5398 if (IExp->getType()->isPointerType())
5399 std::swap(PExp, IExp);
5401 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
5402 if (!EvalPtrOK && !Info.noteFailure())
5405 llvm::APSInt Offset;
5406 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5409 int64_t AdditionalOffset = getExtValue(Offset);
5410 if (E->getOpcode() == BO_Sub)
5411 AdditionalOffset = -AdditionalOffset;
5413 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5414 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5418 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5419 return EvaluateLValue(E->getSubExpr(), Result, Info);
5422 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5423 const Expr* SubExpr = E->getSubExpr();
5425 switch (E->getCastKind()) {
5430 case CK_CPointerToObjCPointerCast:
5431 case CK_BlockPointerToObjCPointerCast:
5432 case CK_AnyPointerToBlockPointerCast:
5433 case CK_AddressSpaceConversion:
5434 if (!Visit(SubExpr))
5436 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5437 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5438 // also static_casts, but we disallow them as a resolution to DR1312.
5439 if (!E->getType()->isVoidPointerType()) {
5440 Result.Designator.setInvalid();
5441 if (SubExpr->getType()->isVoidPointerType())
5442 CCEDiag(E, diag::note_constexpr_invalid_cast)
5443 << 3 << SubExpr->getType();
5445 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5447 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5448 ZeroInitialization(E);
5451 case CK_DerivedToBase:
5452 case CK_UncheckedDerivedToBase:
5453 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
5455 if (!Result.Base && Result.Offset.isZero())
5458 // Now figure out the necessary offset to add to the base LV to get from
5459 // the derived class to the base class.
5460 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5461 castAs<PointerType>()->getPointeeType(),
5464 case CK_BaseToDerived:
5465 if (!Visit(E->getSubExpr()))
5467 if (!Result.Base && Result.Offset.isZero())
5469 return HandleBaseToDerivedCast(Info, E, Result);
5471 case CK_NullToPointer:
5472 VisitIgnoredValue(E->getSubExpr());
5473 return ZeroInitialization(E);
5475 case CK_IntegralToPointer: {
5476 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5479 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5482 if (Value.isInt()) {
5483 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5484 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5485 Result.Base = (Expr*)nullptr;
5486 Result.InvalidBase = false;
5487 Result.Offset = CharUnits::fromQuantity(N);
5488 Result.CallIndex = 0;
5489 Result.Designator.setInvalid();
5490 Result.IsNullPtr = false;
5493 // Cast is of an lvalue, no need to change value.
5494 Result.setFrom(Info.Ctx, Value);
5498 case CK_ArrayToPointerDecay:
5499 if (SubExpr->isGLValue()) {
5500 if (!EvaluateLValue(SubExpr, Result, Info))
5503 Result.set(SubExpr, Info.CurrentCall->Index);
5504 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5505 Info, Result, SubExpr))
5508 // The result is a pointer to the first element of the array.
5509 if (const ConstantArrayType *CAT
5510 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5511 Result.addArray(Info, E, CAT);
5513 Result.Designator.setInvalid();
5516 case CK_FunctionToPointerDecay:
5517 return EvaluateLValue(SubExpr, Result, Info);
5519 case CK_LValueToRValue: {
5521 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5525 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5526 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5528 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5529 return Success(RVal, E);
5533 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5536 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5537 // C++ [expr.alignof]p3:
5538 // When alignof is applied to a reference type, the result is the
5539 // alignment of the referenced type.
5540 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5541 T = Ref->getPointeeType();
5543 // __alignof is defined to return the preferred alignment.
5544 return Info.Ctx.toCharUnitsFromBits(
5545 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5548 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5549 E = E->IgnoreParens();
5551 // The kinds of expressions that we have special-case logic here for
5552 // should be kept up to date with the special checks for those
5553 // expressions in Sema.
5555 // alignof decl is always accepted, even if it doesn't make sense: we default
5556 // to 1 in those cases.
5557 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5558 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5559 /*RefAsPointee*/true);
5561 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5562 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5563 /*RefAsPointee*/true);
5565 return GetAlignOfType(Info, E->getType());
5568 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5569 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5570 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5573 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5576 Result.setInvalid(E);
5577 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5578 Result.addUnsizedArray(Info, PointeeTy);
5582 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5583 if (IsStringLiteralCall(E))
5586 if (unsigned BuiltinOp = E->getBuiltinCallee())
5587 return VisitBuiltinCallExpr(E, BuiltinOp);
5589 return visitNonBuiltinCallExpr(E);
5592 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5593 unsigned BuiltinOp) {
5594 switch (BuiltinOp) {
5595 case Builtin::BI__builtin_addressof:
5596 return EvaluateLValue(E->getArg(0), Result, Info);
5597 case Builtin::BI__builtin_assume_aligned: {
5598 // We need to be very careful here because: if the pointer does not have the
5599 // asserted alignment, then the behavior is undefined, and undefined
5600 // behavior is non-constant.
5601 if (!EvaluatePointer(E->getArg(0), Result, Info))
5604 LValue OffsetResult(Result);
5606 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5608 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5610 if (E->getNumArgs() > 2) {
5612 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5615 int64_t AdditionalOffset = -getExtValue(Offset);
5616 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5619 // If there is a base object, then it must have the correct alignment.
5620 if (OffsetResult.Base) {
5621 CharUnits BaseAlignment;
5622 if (const ValueDecl *VD =
5623 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5624 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5627 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5630 if (BaseAlignment < Align) {
5631 Result.Designator.setInvalid();
5632 // FIXME: Quantities here cast to integers because the plural modifier
5633 // does not work on APSInts yet.
5634 CCEDiag(E->getArg(0),
5635 diag::note_constexpr_baa_insufficient_alignment) << 0
5636 << (int) BaseAlignment.getQuantity()
5637 << (unsigned) getExtValue(Alignment);
5642 // The offset must also have the correct alignment.
5643 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5644 Result.Designator.setInvalid();
5645 APSInt Offset(64, false);
5646 Offset = OffsetResult.Offset.getQuantity();
5648 if (OffsetResult.Base)
5649 CCEDiag(E->getArg(0),
5650 diag::note_constexpr_baa_insufficient_alignment) << 1
5651 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5653 CCEDiag(E->getArg(0),
5654 diag::note_constexpr_baa_value_insufficient_alignment)
5655 << Offset << (unsigned) getExtValue(Alignment);
5663 case Builtin::BIstrchr:
5664 case Builtin::BIwcschr:
5665 case Builtin::BImemchr:
5666 case Builtin::BIwmemchr:
5667 if (Info.getLangOpts().CPlusPlus11)
5668 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5669 << /*isConstexpr*/0 << /*isConstructor*/0
5670 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5672 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5674 case Builtin::BI__builtin_strchr:
5675 case Builtin::BI__builtin_wcschr:
5676 case Builtin::BI__builtin_memchr:
5677 case Builtin::BI__builtin_wmemchr: {
5678 if (!Visit(E->getArg(0)))
5681 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5683 uint64_t MaxLength = uint64_t(-1);
5684 if (BuiltinOp != Builtin::BIstrchr &&
5685 BuiltinOp != Builtin::BIwcschr &&
5686 BuiltinOp != Builtin::BI__builtin_strchr &&
5687 BuiltinOp != Builtin::BI__builtin_wcschr) {
5689 if (!EvaluateInteger(E->getArg(2), N, Info))
5691 MaxLength = N.getExtValue();
5694 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5696 // Figure out what value we're actually looking for (after converting to
5697 // the corresponding unsigned type if necessary).
5698 uint64_t DesiredVal;
5699 bool StopAtNull = false;
5700 switch (BuiltinOp) {
5701 case Builtin::BIstrchr:
5702 case Builtin::BI__builtin_strchr:
5703 // strchr compares directly to the passed integer, and therefore
5704 // always fails if given an int that is not a char.
5705 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5706 E->getArg(1)->getType(),
5709 return ZeroInitialization(E);
5712 case Builtin::BImemchr:
5713 case Builtin::BI__builtin_memchr:
5714 // memchr compares by converting both sides to unsigned char. That's also
5715 // correct for strchr if we get this far (to cope with plain char being
5716 // unsigned in the strchr case).
5717 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5720 case Builtin::BIwcschr:
5721 case Builtin::BI__builtin_wcschr:
5724 case Builtin::BIwmemchr:
5725 case Builtin::BI__builtin_wmemchr:
5726 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5727 DesiredVal = Desired.getZExtValue();
5731 for (; MaxLength; --MaxLength) {
5733 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5736 if (Char.getInt().getZExtValue() == DesiredVal)
5738 if (StopAtNull && !Char.getInt())
5740 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5743 // Not found: return nullptr.
5744 return ZeroInitialization(E);
5748 return visitNonBuiltinCallExpr(E);
5752 //===----------------------------------------------------------------------===//
5753 // Member Pointer Evaluation
5754 //===----------------------------------------------------------------------===//
5757 class MemberPointerExprEvaluator
5758 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5761 bool Success(const ValueDecl *D) {
5762 Result = MemberPtr(D);
5767 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5768 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5770 bool Success(const APValue &V, const Expr *E) {
5774 bool ZeroInitialization(const Expr *E) {
5775 return Success((const ValueDecl*)nullptr);
5778 bool VisitCastExpr(const CastExpr *E);
5779 bool VisitUnaryAddrOf(const UnaryOperator *E);
5781 } // end anonymous namespace
5783 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5785 assert(E->isRValue() && E->getType()->isMemberPointerType());
5786 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5789 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5790 switch (E->getCastKind()) {
5792 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5794 case CK_NullToMemberPointer:
5795 VisitIgnoredValue(E->getSubExpr());
5796 return ZeroInitialization(E);
5798 case CK_BaseToDerivedMemberPointer: {
5799 if (!Visit(E->getSubExpr()))
5801 if (E->path_empty())
5803 // Base-to-derived member pointer casts store the path in derived-to-base
5804 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5805 // the wrong end of the derived->base arc, so stagger the path by one class.
5806 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5807 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5808 PathI != PathE; ++PathI) {
5809 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5810 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5811 if (!Result.castToDerived(Derived))
5814 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5815 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5820 case CK_DerivedToBaseMemberPointer:
5821 if (!Visit(E->getSubExpr()))
5823 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5824 PathE = E->path_end(); PathI != PathE; ++PathI) {
5825 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5826 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5827 if (!Result.castToBase(Base))
5834 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5835 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5836 // member can be formed.
5837 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5840 //===----------------------------------------------------------------------===//
5841 // Record Evaluation
5842 //===----------------------------------------------------------------------===//
5845 class RecordExprEvaluator
5846 : public ExprEvaluatorBase<RecordExprEvaluator> {
5851 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5852 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5854 bool Success(const APValue &V, const Expr *E) {
5858 bool ZeroInitialization(const Expr *E) {
5859 return ZeroInitialization(E, E->getType());
5861 bool ZeroInitialization(const Expr *E, QualType T);
5863 bool VisitCallExpr(const CallExpr *E) {
5864 return handleCallExpr(E, Result, &This);
5866 bool VisitCastExpr(const CastExpr *E);
5867 bool VisitInitListExpr(const InitListExpr *E);
5868 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5869 return VisitCXXConstructExpr(E, E->getType());
5871 bool VisitLambdaExpr(const LambdaExpr *E);
5872 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
5873 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
5874 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5878 /// Perform zero-initialization on an object of non-union class type.
5879 /// C++11 [dcl.init]p5:
5880 /// To zero-initialize an object or reference of type T means:
5882 /// -- if T is a (possibly cv-qualified) non-union class type,
5883 /// each non-static data member and each base-class subobject is
5884 /// zero-initialized
5885 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5886 const RecordDecl *RD,
5887 const LValue &This, APValue &Result) {
5888 assert(!RD->isUnion() && "Expected non-union class type");
5889 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5890 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5891 std::distance(RD->field_begin(), RD->field_end()));
5893 if (RD->isInvalidDecl()) return false;
5894 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5898 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5899 End = CD->bases_end(); I != End; ++I, ++Index) {
5900 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5901 LValue Subobject = This;
5902 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5904 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5905 Result.getStructBase(Index)))
5910 for (const auto *I : RD->fields()) {
5911 // -- if T is a reference type, no initialization is performed.
5912 if (I->getType()->isReferenceType())
5915 LValue Subobject = This;
5916 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5919 ImplicitValueInitExpr VIE(I->getType());
5920 if (!EvaluateInPlace(
5921 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5928 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5929 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5930 if (RD->isInvalidDecl()) return false;
5931 if (RD->isUnion()) {
5932 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5933 // object's first non-static named data member is zero-initialized
5934 RecordDecl::field_iterator I = RD->field_begin();
5935 if (I == RD->field_end()) {
5936 Result = APValue((const FieldDecl*)nullptr);
5940 LValue Subobject = This;
5941 if (!HandleLValueMember(Info, E, Subobject, *I))
5943 Result = APValue(*I);
5944 ImplicitValueInitExpr VIE(I->getType());
5945 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5948 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5949 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
5953 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5956 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5957 switch (E->getCastKind()) {
5959 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5961 case CK_ConstructorConversion:
5962 return Visit(E->getSubExpr());
5964 case CK_DerivedToBase:
5965 case CK_UncheckedDerivedToBase: {
5966 APValue DerivedObject;
5967 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5969 if (!DerivedObject.isStruct())
5970 return Error(E->getSubExpr());
5972 // Derived-to-base rvalue conversion: just slice off the derived part.
5973 APValue *Value = &DerivedObject;
5974 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5975 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5976 PathE = E->path_end(); PathI != PathE; ++PathI) {
5977 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5978 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5979 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5988 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5989 if (E->isTransparent())
5990 return Visit(E->getInit(0));
5992 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5993 if (RD->isInvalidDecl()) return false;
5994 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5996 if (RD->isUnion()) {
5997 const FieldDecl *Field = E->getInitializedFieldInUnion();
5998 Result = APValue(Field);
6002 // If the initializer list for a union does not contain any elements, the
6003 // first element of the union is value-initialized.
6004 // FIXME: The element should be initialized from an initializer list.
6005 // Is this difference ever observable for initializer lists which
6007 ImplicitValueInitExpr VIE(Field->getType());
6008 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6010 LValue Subobject = This;
6011 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6014 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6015 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6016 isa<CXXDefaultInitExpr>(InitExpr));
6018 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6021 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6022 if (Result.isUninit())
6023 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6024 std::distance(RD->field_begin(), RD->field_end()));
6025 unsigned ElementNo = 0;
6026 bool Success = true;
6028 // Initialize base classes.
6030 for (const auto &Base : CXXRD->bases()) {
6031 assert(ElementNo < E->getNumInits() && "missing init for base class");
6032 const Expr *Init = E->getInit(ElementNo);
6034 LValue Subobject = This;
6035 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6038 APValue &FieldVal = Result.getStructBase(ElementNo);
6039 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6040 if (!Info.noteFailure())
6048 // Initialize members.
6049 for (const auto *Field : RD->fields()) {
6050 // Anonymous bit-fields are not considered members of the class for
6051 // purposes of aggregate initialization.
6052 if (Field->isUnnamedBitfield())
6055 LValue Subobject = This;
6057 bool HaveInit = ElementNo < E->getNumInits();
6059 // FIXME: Diagnostics here should point to the end of the initializer
6060 // list, not the start.
6061 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6062 Subobject, Field, &Layout))
6065 // Perform an implicit value-initialization for members beyond the end of
6066 // the initializer list.
6067 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6068 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6070 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6071 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6072 isa<CXXDefaultInitExpr>(Init));
6074 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6075 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6076 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6077 FieldVal, Field))) {
6078 if (!Info.noteFailure())
6087 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6089 // Note that E's type is not necessarily the type of our class here; we might
6090 // be initializing an array element instead.
6091 const CXXConstructorDecl *FD = E->getConstructor();
6092 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6094 bool ZeroInit = E->requiresZeroInitialization();
6095 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6096 // If we've already performed zero-initialization, we're already done.
6097 if (!Result.isUninit())
6100 // We can get here in two different ways:
6101 // 1) We're performing value-initialization, and should zero-initialize
6103 // 2) We're performing default-initialization of an object with a trivial
6104 // constexpr default constructor, in which case we should start the
6105 // lifetimes of all the base subobjects (there can be no data member
6106 // subobjects in this case) per [basic.life]p1.
6107 // Either way, ZeroInitialization is appropriate.
6108 return ZeroInitialization(E, T);
6111 const FunctionDecl *Definition = nullptr;
6112 auto Body = FD->getBody(Definition);
6114 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6117 // Avoid materializing a temporary for an elidable copy/move constructor.
6118 if (E->isElidable() && !ZeroInit)
6119 if (const MaterializeTemporaryExpr *ME
6120 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6121 return Visit(ME->GetTemporaryExpr());
6123 if (ZeroInit && !ZeroInitialization(E, T))
6126 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6127 return HandleConstructorCall(E, This, Args,
6128 cast<CXXConstructorDecl>(Definition), Info,
6132 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6133 const CXXInheritedCtorInitExpr *E) {
6134 if (!Info.CurrentCall) {
6135 assert(Info.checkingPotentialConstantExpression());
6139 const CXXConstructorDecl *FD = E->getConstructor();
6140 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6143 const FunctionDecl *Definition = nullptr;
6144 auto Body = FD->getBody(Definition);
6146 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6149 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6150 cast<CXXConstructorDecl>(Definition), Info,
6154 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6155 const CXXStdInitializerListExpr *E) {
6156 const ConstantArrayType *ArrayType =
6157 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6160 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6163 // Get a pointer to the first element of the array.
6164 Array.addArray(Info, E, ArrayType);
6166 // FIXME: Perform the checks on the field types in SemaInit.
6167 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6168 RecordDecl::field_iterator Field = Record->field_begin();
6169 if (Field == Record->field_end())
6173 if (!Field->getType()->isPointerType() ||
6174 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6175 ArrayType->getElementType()))
6178 // FIXME: What if the initializer_list type has base classes, etc?
6179 Result = APValue(APValue::UninitStruct(), 0, 2);
6180 Array.moveInto(Result.getStructField(0));
6182 if (++Field == Record->field_end())
6185 if (Field->getType()->isPointerType() &&
6186 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6187 ArrayType->getElementType())) {
6189 if (!HandleLValueArrayAdjustment(Info, E, Array,
6190 ArrayType->getElementType(),
6191 ArrayType->getSize().getZExtValue()))
6193 Array.moveInto(Result.getStructField(1));
6194 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6196 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6200 if (++Field != Record->field_end())
6206 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6207 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6208 if (ClosureClass->isInvalidDecl()) return false;
6210 if (Info.checkingPotentialConstantExpression()) return true;
6211 if (E->capture_size()) {
6212 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6213 << "can not evaluate lambda expressions with captures";
6216 // FIXME: Implement captures.
6217 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6221 static bool EvaluateRecord(const Expr *E, const LValue &This,
6222 APValue &Result, EvalInfo &Info) {
6223 assert(E->isRValue() && E->getType()->isRecordType() &&
6224 "can't evaluate expression as a record rvalue");
6225 return RecordExprEvaluator(Info, This, Result).Visit(E);
6228 //===----------------------------------------------------------------------===//
6229 // Temporary Evaluation
6231 // Temporaries are represented in the AST as rvalues, but generally behave like
6232 // lvalues. The full-object of which the temporary is a subobject is implicitly
6233 // materialized so that a reference can bind to it.
6234 //===----------------------------------------------------------------------===//
6236 class TemporaryExprEvaluator
6237 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6239 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6240 LValueExprEvaluatorBaseTy(Info, Result) {}
6242 /// Visit an expression which constructs the value of this temporary.
6243 bool VisitConstructExpr(const Expr *E) {
6244 Result.set(E, Info.CurrentCall->Index);
6245 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6249 bool VisitCastExpr(const CastExpr *E) {
6250 switch (E->getCastKind()) {
6252 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6254 case CK_ConstructorConversion:
6255 return VisitConstructExpr(E->getSubExpr());
6258 bool VisitInitListExpr(const InitListExpr *E) {
6259 return VisitConstructExpr(E);
6261 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6262 return VisitConstructExpr(E);
6264 bool VisitCallExpr(const CallExpr *E) {
6265 return VisitConstructExpr(E);
6267 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6268 return VisitConstructExpr(E);
6270 bool VisitLambdaExpr(const LambdaExpr *E) {
6271 return VisitConstructExpr(E);
6274 } // end anonymous namespace
6276 /// Evaluate an expression of record type as a temporary.
6277 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6278 assert(E->isRValue() && E->getType()->isRecordType());
6279 return TemporaryExprEvaluator(Info, Result).Visit(E);
6282 //===----------------------------------------------------------------------===//
6283 // Vector Evaluation
6284 //===----------------------------------------------------------------------===//
6287 class VectorExprEvaluator
6288 : public ExprEvaluatorBase<VectorExprEvaluator> {
6292 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6293 : ExprEvaluatorBaseTy(info), Result(Result) {}
6295 bool Success(ArrayRef<APValue> V, const Expr *E) {
6296 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6297 // FIXME: remove this APValue copy.
6298 Result = APValue(V.data(), V.size());
6301 bool Success(const APValue &V, const Expr *E) {
6302 assert(V.isVector());
6306 bool ZeroInitialization(const Expr *E);
6308 bool VisitUnaryReal(const UnaryOperator *E)
6309 { return Visit(E->getSubExpr()); }
6310 bool VisitCastExpr(const CastExpr* E);
6311 bool VisitInitListExpr(const InitListExpr *E);
6312 bool VisitUnaryImag(const UnaryOperator *E);
6313 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6314 // binary comparisons, binary and/or/xor,
6315 // shufflevector, ExtVectorElementExpr
6317 } // end anonymous namespace
6319 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6320 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6321 return VectorExprEvaluator(Info, Result).Visit(E);
6324 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6325 const VectorType *VTy = E->getType()->castAs<VectorType>();
6326 unsigned NElts = VTy->getNumElements();
6328 const Expr *SE = E->getSubExpr();
6329 QualType SETy = SE->getType();
6331 switch (E->getCastKind()) {
6332 case CK_VectorSplat: {
6333 APValue Val = APValue();
6334 if (SETy->isIntegerType()) {
6336 if (!EvaluateInteger(SE, IntResult, Info))
6338 Val = APValue(std::move(IntResult));
6339 } else if (SETy->isRealFloatingType()) {
6340 APFloat FloatResult(0.0);
6341 if (!EvaluateFloat(SE, FloatResult, Info))
6343 Val = APValue(std::move(FloatResult));
6348 // Splat and create vector APValue.
6349 SmallVector<APValue, 4> Elts(NElts, Val);
6350 return Success(Elts, E);
6353 // Evaluate the operand into an APInt we can extract from.
6354 llvm::APInt SValInt;
6355 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6357 // Extract the elements
6358 QualType EltTy = VTy->getElementType();
6359 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6360 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6361 SmallVector<APValue, 4> Elts;
6362 if (EltTy->isRealFloatingType()) {
6363 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6364 unsigned FloatEltSize = EltSize;
6365 if (&Sem == &APFloat::x87DoubleExtended())
6367 for (unsigned i = 0; i < NElts; i++) {
6370 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6372 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6373 Elts.push_back(APValue(APFloat(Sem, Elt)));
6375 } else if (EltTy->isIntegerType()) {
6376 for (unsigned i = 0; i < NElts; i++) {
6379 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6381 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6382 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6387 return Success(Elts, E);
6390 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6395 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6396 const VectorType *VT = E->getType()->castAs<VectorType>();
6397 unsigned NumInits = E->getNumInits();
6398 unsigned NumElements = VT->getNumElements();
6400 QualType EltTy = VT->getElementType();
6401 SmallVector<APValue, 4> Elements;
6403 // The number of initializers can be less than the number of
6404 // vector elements. For OpenCL, this can be due to nested vector
6405 // initialization. For GCC compatibility, missing trailing elements
6406 // should be initialized with zeroes.
6407 unsigned CountInits = 0, CountElts = 0;
6408 while (CountElts < NumElements) {
6409 // Handle nested vector initialization.
6410 if (CountInits < NumInits
6411 && E->getInit(CountInits)->getType()->isVectorType()) {
6413 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6415 unsigned vlen = v.getVectorLength();
6416 for (unsigned j = 0; j < vlen; j++)
6417 Elements.push_back(v.getVectorElt(j));
6419 } else if (EltTy->isIntegerType()) {
6420 llvm::APSInt sInt(32);
6421 if (CountInits < NumInits) {
6422 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6424 } else // trailing integer zero.
6425 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6426 Elements.push_back(APValue(sInt));
6429 llvm::APFloat f(0.0);
6430 if (CountInits < NumInits) {
6431 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6433 } else // trailing float zero.
6434 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6435 Elements.push_back(APValue(f));
6440 return Success(Elements, E);
6444 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6445 const VectorType *VT = E->getType()->getAs<VectorType>();
6446 QualType EltTy = VT->getElementType();
6447 APValue ZeroElement;
6448 if (EltTy->isIntegerType())
6449 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6452 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6454 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6455 return Success(Elements, E);
6458 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6459 VisitIgnoredValue(E->getSubExpr());
6460 return ZeroInitialization(E);
6463 //===----------------------------------------------------------------------===//
6465 //===----------------------------------------------------------------------===//
6468 class ArrayExprEvaluator
6469 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6474 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6475 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6477 bool Success(const APValue &V, const Expr *E) {
6478 assert((V.isArray() || V.isLValue()) &&
6479 "expected array or string literal");
6484 bool ZeroInitialization(const Expr *E) {
6485 const ConstantArrayType *CAT =
6486 Info.Ctx.getAsConstantArrayType(E->getType());
6490 Result = APValue(APValue::UninitArray(), 0,
6491 CAT->getSize().getZExtValue());
6492 if (!Result.hasArrayFiller()) return true;
6494 // Zero-initialize all elements.
6495 LValue Subobject = This;
6496 Subobject.addArray(Info, E, CAT);
6497 ImplicitValueInitExpr VIE(CAT->getElementType());
6498 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6501 bool VisitCallExpr(const CallExpr *E) {
6502 return handleCallExpr(E, Result, &This);
6504 bool VisitInitListExpr(const InitListExpr *E);
6505 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6506 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6507 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6508 const LValue &Subobject,
6509 APValue *Value, QualType Type);
6511 } // end anonymous namespace
6513 static bool EvaluateArray(const Expr *E, const LValue &This,
6514 APValue &Result, EvalInfo &Info) {
6515 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6516 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6519 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6520 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6524 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6525 // an appropriately-typed string literal enclosed in braces.
6526 if (E->isStringLiteralInit()) {
6528 if (!EvaluateLValue(E->getInit(0), LV, Info))
6532 return Success(Val, E);
6535 bool Success = true;
6537 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6538 "zero-initialized array shouldn't have any initialized elts");
6540 if (Result.isArray() && Result.hasArrayFiller())
6541 Filler = Result.getArrayFiller();
6543 unsigned NumEltsToInit = E->getNumInits();
6544 unsigned NumElts = CAT->getSize().getZExtValue();
6545 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6547 // If the initializer might depend on the array index, run it for each
6548 // array element. For now, just whitelist non-class value-initialization.
6549 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6550 NumEltsToInit = NumElts;
6552 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6554 // If the array was previously zero-initialized, preserve the
6555 // zero-initialized values.
6556 if (!Filler.isUninit()) {
6557 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6558 Result.getArrayInitializedElt(I) = Filler;
6559 if (Result.hasArrayFiller())
6560 Result.getArrayFiller() = Filler;
6563 LValue Subobject = This;
6564 Subobject.addArray(Info, E, CAT);
6565 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6567 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6568 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6569 Info, Subobject, Init) ||
6570 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6571 CAT->getElementType(), 1)) {
6572 if (!Info.noteFailure())
6578 if (!Result.hasArrayFiller())
6581 // If we get here, we have a trivial filler, which we can just evaluate
6582 // once and splat over the rest of the array elements.
6583 assert(FillerExpr && "no array filler for incomplete init list");
6584 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6585 FillerExpr) && Success;
6588 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6589 if (E->getCommonExpr() &&
6590 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6591 Info, E->getCommonExpr()->getSourceExpr()))
6594 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6596 uint64_t Elements = CAT->getSize().getZExtValue();
6597 Result = APValue(APValue::UninitArray(), Elements, Elements);
6599 LValue Subobject = This;
6600 Subobject.addArray(Info, E, CAT);
6602 bool Success = true;
6603 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6604 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6605 Info, Subobject, E->getSubExpr()) ||
6606 !HandleLValueArrayAdjustment(Info, E, Subobject,
6607 CAT->getElementType(), 1)) {
6608 if (!Info.noteFailure())
6617 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6618 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6621 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6622 const LValue &Subobject,
6625 bool HadZeroInit = !Value->isUninit();
6627 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6628 unsigned N = CAT->getSize().getZExtValue();
6630 // Preserve the array filler if we had prior zero-initialization.
6632 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6635 *Value = APValue(APValue::UninitArray(), N, N);
6638 for (unsigned I = 0; I != N; ++I)
6639 Value->getArrayInitializedElt(I) = Filler;
6641 // Initialize the elements.
6642 LValue ArrayElt = Subobject;
6643 ArrayElt.addArray(Info, E, CAT);
6644 for (unsigned I = 0; I != N; ++I)
6645 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6646 CAT->getElementType()) ||
6647 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6648 CAT->getElementType(), 1))
6654 if (!Type->isRecordType())
6657 return RecordExprEvaluator(Info, Subobject, *Value)
6658 .VisitCXXConstructExpr(E, Type);
6661 //===----------------------------------------------------------------------===//
6662 // Integer Evaluation
6664 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6665 // types and back in constant folding. Integer values are thus represented
6666 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6667 //===----------------------------------------------------------------------===//
6670 class IntExprEvaluator
6671 : public ExprEvaluatorBase<IntExprEvaluator> {
6674 IntExprEvaluator(EvalInfo &info, APValue &result)
6675 : ExprEvaluatorBaseTy(info), Result(result) {}
6677 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6678 assert(E->getType()->isIntegralOrEnumerationType() &&
6679 "Invalid evaluation result.");
6680 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6681 "Invalid evaluation result.");
6682 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6683 "Invalid evaluation result.");
6684 Result = APValue(SI);
6687 bool Success(const llvm::APSInt &SI, const Expr *E) {
6688 return Success(SI, E, Result);
6691 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6692 assert(E->getType()->isIntegralOrEnumerationType() &&
6693 "Invalid evaluation result.");
6694 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6695 "Invalid evaluation result.");
6696 Result = APValue(APSInt(I));
6697 Result.getInt().setIsUnsigned(
6698 E->getType()->isUnsignedIntegerOrEnumerationType());
6701 bool Success(const llvm::APInt &I, const Expr *E) {
6702 return Success(I, E, Result);
6705 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6706 assert(E->getType()->isIntegralOrEnumerationType() &&
6707 "Invalid evaluation result.");
6708 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6711 bool Success(uint64_t Value, const Expr *E) {
6712 return Success(Value, E, Result);
6715 bool Success(CharUnits Size, const Expr *E) {
6716 return Success(Size.getQuantity(), E);
6719 bool Success(const APValue &V, const Expr *E) {
6720 if (V.isLValue() || V.isAddrLabelDiff()) {
6724 return Success(V.getInt(), E);
6727 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6729 //===--------------------------------------------------------------------===//
6731 //===--------------------------------------------------------------------===//
6733 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6734 return Success(E->getValue(), E);
6736 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6737 return Success(E->getValue(), E);
6740 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6741 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6742 if (CheckReferencedDecl(E, E->getDecl()))
6745 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6747 bool VisitMemberExpr(const MemberExpr *E) {
6748 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6749 VisitIgnoredBaseExpression(E->getBase());
6753 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6756 bool VisitCallExpr(const CallExpr *E);
6757 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6758 bool VisitBinaryOperator(const BinaryOperator *E);
6759 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6760 bool VisitUnaryOperator(const UnaryOperator *E);
6762 bool VisitCastExpr(const CastExpr* E);
6763 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6765 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6766 return Success(E->getValue(), E);
6769 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6770 return Success(E->getValue(), E);
6773 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6774 if (Info.ArrayInitIndex == uint64_t(-1)) {
6775 // We were asked to evaluate this subexpression independent of the
6776 // enclosing ArrayInitLoopExpr. We can't do that.
6780 return Success(Info.ArrayInitIndex, E);
6783 // Note, GNU defines __null as an integer, not a pointer.
6784 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6785 return ZeroInitialization(E);
6788 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6789 return Success(E->getValue(), E);
6792 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6793 return Success(E->getValue(), E);
6796 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6797 return Success(E->getValue(), E);
6800 bool VisitUnaryReal(const UnaryOperator *E);
6801 bool VisitUnaryImag(const UnaryOperator *E);
6803 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6804 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6806 // FIXME: Missing: array subscript of vector, member of vector
6808 } // end anonymous namespace
6810 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6811 /// produce either the integer value or a pointer.
6813 /// GCC has a heinous extension which folds casts between pointer types and
6814 /// pointer-sized integral types. We support this by allowing the evaluation of
6815 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6816 /// Some simple arithmetic on such values is supported (they are treated much
6818 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6820 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6821 return IntExprEvaluator(Info, Result).Visit(E);
6824 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6826 if (!EvaluateIntegerOrLValue(E, Val, Info))
6829 // FIXME: It would be better to produce the diagnostic for casting
6830 // a pointer to an integer.
6831 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6834 Result = Val.getInt();
6838 /// Check whether the given declaration can be directly converted to an integral
6839 /// rvalue. If not, no diagnostic is produced; there are other things we can
6841 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6842 // Enums are integer constant exprs.
6843 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6844 // Check for signedness/width mismatches between E type and ECD value.
6845 bool SameSign = (ECD->getInitVal().isSigned()
6846 == E->getType()->isSignedIntegerOrEnumerationType());
6847 bool SameWidth = (ECD->getInitVal().getBitWidth()
6848 == Info.Ctx.getIntWidth(E->getType()));
6849 if (SameSign && SameWidth)
6850 return Success(ECD->getInitVal(), E);
6852 // Get rid of mismatch (otherwise Success assertions will fail)
6853 // by computing a new value matching the type of E.
6854 llvm::APSInt Val = ECD->getInitVal();
6856 Val.setIsSigned(!ECD->getInitVal().isSigned());
6858 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6859 return Success(Val, E);
6865 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6867 static int EvaluateBuiltinClassifyType(const CallExpr *E,
6868 const LangOptions &LangOpts) {
6869 // The following enum mimics the values returned by GCC.
6870 // FIXME: Does GCC differ between lvalue and rvalue references here?
6871 enum gcc_type_class {
6873 void_type_class, integer_type_class, char_type_class,
6874 enumeral_type_class, boolean_type_class,
6875 pointer_type_class, reference_type_class, offset_type_class,
6876 real_type_class, complex_type_class,
6877 function_type_class, method_type_class,
6878 record_type_class, union_type_class,
6879 array_type_class, string_type_class,
6883 // If no argument was supplied, default to "no_type_class". This isn't
6884 // ideal, however it is what gcc does.
6885 if (E->getNumArgs() == 0)
6886 return no_type_class;
6888 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6889 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6891 switch (CanTy->getTypeClass()) {
6892 #define TYPE(ID, BASE)
6893 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6894 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6895 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6896 #include "clang/AST/TypeNodes.def"
6897 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6900 switch (BT->getKind()) {
6901 #define BUILTIN_TYPE(ID, SINGLETON_ID)
6902 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6903 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6904 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6905 #include "clang/AST/BuiltinTypes.def"
6906 case BuiltinType::Void:
6907 return void_type_class;
6909 case BuiltinType::Bool:
6910 return boolean_type_class;
6912 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6913 case BuiltinType::UChar:
6914 case BuiltinType::UShort:
6915 case BuiltinType::UInt:
6916 case BuiltinType::ULong:
6917 case BuiltinType::ULongLong:
6918 case BuiltinType::UInt128:
6919 return integer_type_class;
6921 case BuiltinType::NullPtr:
6922 return pointer_type_class;
6924 case BuiltinType::WChar_U:
6925 case BuiltinType::Char16:
6926 case BuiltinType::Char32:
6927 case BuiltinType::ObjCId:
6928 case BuiltinType::ObjCClass:
6929 case BuiltinType::ObjCSel:
6930 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6931 case BuiltinType::Id:
6932 #include "clang/Basic/OpenCLImageTypes.def"
6933 case BuiltinType::OCLSampler:
6934 case BuiltinType::OCLEvent:
6935 case BuiltinType::OCLClkEvent:
6936 case BuiltinType::OCLQueue:
6937 case BuiltinType::OCLNDRange:
6938 case BuiltinType::OCLReserveID:
6939 case BuiltinType::Dependent:
6940 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6944 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6948 return pointer_type_class;
6951 case Type::MemberPointer:
6952 if (CanTy->isMemberDataPointerType())
6953 return offset_type_class;
6955 // We expect member pointers to be either data or function pointers,
6957 assert(CanTy->isMemberFunctionPointerType());
6958 return method_type_class;
6962 return complex_type_class;
6964 case Type::FunctionNoProto:
6965 case Type::FunctionProto:
6966 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6969 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6970 switch (RT->getDecl()->getTagKind()) {
6971 case TagTypeKind::TTK_Struct:
6972 case TagTypeKind::TTK_Class:
6973 case TagTypeKind::TTK_Interface:
6974 return record_type_class;
6976 case TagTypeKind::TTK_Enum:
6977 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6979 case TagTypeKind::TTK_Union:
6980 return union_type_class;
6983 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6985 case Type::ConstantArray:
6986 case Type::VariableArray:
6987 case Type::IncompleteArray:
6988 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6990 case Type::BlockPointer:
6991 case Type::LValueReference:
6992 case Type::RValueReference:
6994 case Type::ExtVector:
6996 case Type::ObjCObject:
6997 case Type::ObjCInterface:
6998 case Type::ObjCObjectPointer:
7001 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7004 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7007 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7008 /// __builtin_constant_p when applied to the given lvalue.
7010 /// An lvalue is only "constant" if it is a pointer or reference to the first
7011 /// character of a string literal.
7012 template<typename LValue>
7013 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7014 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7015 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7018 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7019 /// GCC as we can manage.
7020 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7021 QualType ArgType = Arg->getType();
7023 // __builtin_constant_p always has one operand. The rules which gcc follows
7024 // are not precisely documented, but are as follows:
7026 // - If the operand is of integral, floating, complex or enumeration type,
7027 // and can be folded to a known value of that type, it returns 1.
7028 // - If the operand and can be folded to a pointer to the first character
7029 // of a string literal (or such a pointer cast to an integral type), it
7032 // Otherwise, it returns 0.
7034 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7035 // its support for this does not currently work.
7036 if (ArgType->isIntegralOrEnumerationType()) {
7037 Expr::EvalResult Result;
7038 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7041 APValue &V = Result.Val;
7042 if (V.getKind() == APValue::Int)
7044 if (V.getKind() == APValue::LValue)
7045 return EvaluateBuiltinConstantPForLValue(V);
7046 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7047 return Arg->isEvaluatable(Ctx);
7048 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7050 Expr::EvalStatus Status;
7051 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7052 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7053 : EvaluatePointer(Arg, LV, Info)) &&
7054 !Status.HasSideEffects)
7055 return EvaluateBuiltinConstantPForLValue(LV);
7058 // Anything else isn't considered to be sufficiently constant.
7062 /// Retrieves the "underlying object type" of the given expression,
7063 /// as used by __builtin_object_size.
7064 static QualType getObjectType(APValue::LValueBase B) {
7065 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7066 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7067 return VD->getType();
7068 } else if (const Expr *E = B.get<const Expr*>()) {
7069 if (isa<CompoundLiteralExpr>(E))
7070 return E->getType();
7076 /// A more selective version of E->IgnoreParenCasts for
7077 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7078 /// to change the type of E.
7079 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7081 /// Always returns an RValue with a pointer representation.
7082 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7083 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7085 auto *NoParens = E->IgnoreParens();
7086 auto *Cast = dyn_cast<CastExpr>(NoParens);
7087 if (Cast == nullptr)
7090 // We only conservatively allow a few kinds of casts, because this code is
7091 // inherently a simple solution that seeks to support the common case.
7092 auto CastKind = Cast->getCastKind();
7093 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7094 CastKind != CK_AddressSpaceConversion)
7097 auto *SubExpr = Cast->getSubExpr();
7098 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7100 return ignorePointerCastsAndParens(SubExpr);
7103 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7104 /// record layout. e.g.
7105 /// struct { struct { int a, b; } fst, snd; } obj;
7111 /// obj.snd.b // yes
7113 /// Please note: this function is specialized for how __builtin_object_size
7114 /// views "objects".
7116 /// If this encounters an invalid RecordDecl, it will always return true.
7117 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7118 assert(!LVal.Designator.Invalid);
7120 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7121 const RecordDecl *Parent = FD->getParent();
7122 Invalid = Parent->isInvalidDecl();
7123 if (Invalid || Parent->isUnion())
7125 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7126 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7129 auto &Base = LVal.getLValueBase();
7130 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7131 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7133 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7135 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7136 for (auto *FD : IFD->chain()) {
7138 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7145 QualType BaseType = getType(Base);
7146 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7147 assert(isBaseAnAllocSizeCall(Base) &&
7148 "Unsized array in non-alloc_size call?");
7149 // If this is an alloc_size base, we should ignore the initial array index
7151 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7154 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7155 const auto &Entry = LVal.Designator.Entries[I];
7156 if (BaseType->isArrayType()) {
7157 // Because __builtin_object_size treats arrays as objects, we can ignore
7158 // the index iff this is the last array in the Designator.
7161 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7162 uint64_t Index = Entry.ArrayIndex;
7163 if (Index + 1 != CAT->getSize())
7165 BaseType = CAT->getElementType();
7166 } else if (BaseType->isAnyComplexType()) {
7167 const auto *CT = BaseType->castAs<ComplexType>();
7168 uint64_t Index = Entry.ArrayIndex;
7171 BaseType = CT->getElementType();
7172 } else if (auto *FD = getAsField(Entry)) {
7174 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7176 BaseType = FD->getType();
7178 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7185 /// Tests to see if the LValue has a user-specified designator (that isn't
7186 /// necessarily valid). Note that this always returns 'true' if the LValue has
7187 /// an unsized array as its first designator entry, because there's currently no
7188 /// way to tell if the user typed *foo or foo[0].
7189 static bool refersToCompleteObject(const LValue &LVal) {
7190 if (LVal.Designator.Invalid)
7193 if (!LVal.Designator.Entries.empty())
7194 return LVal.Designator.isMostDerivedAnUnsizedArray();
7196 if (!LVal.InvalidBase)
7199 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7201 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7202 return !E || !isa<MemberExpr>(E);
7205 /// Attempts to detect a user writing into a piece of memory that's impossible
7206 /// to figure out the size of by just using types.
7207 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7208 const SubobjectDesignator &Designator = LVal.Designator;
7210 // - Users can only write off of the end when we have an invalid base. Invalid
7211 // bases imply we don't know where the memory came from.
7212 // - We used to be a bit more aggressive here; we'd only be conservative if
7213 // the array at the end was flexible, or if it had 0 or 1 elements. This
7214 // broke some common standard library extensions (PR30346), but was
7215 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7216 // with some sort of whitelist. OTOH, it seems that GCC is always
7217 // conservative with the last element in structs (if it's an array), so our
7218 // current behavior is more compatible than a whitelisting approach would
7220 return LVal.InvalidBase &&
7221 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7222 Designator.MostDerivedIsArrayElement &&
7223 isDesignatorAtObjectEnd(Ctx, LVal);
7226 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7227 /// Fails if the conversion would cause loss of precision.
7228 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7229 CharUnits &Result) {
7230 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7231 if (Int.ugt(CharUnitsMax))
7233 Result = CharUnits::fromQuantity(Int.getZExtValue());
7237 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7238 /// determine how many bytes exist from the beginning of the object to either
7239 /// the end of the current subobject, or the end of the object itself, depending
7240 /// on what the LValue looks like + the value of Type.
7242 /// If this returns false, the value of Result is undefined.
7243 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7244 unsigned Type, const LValue &LVal,
7245 CharUnits &EndOffset) {
7246 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7248 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7249 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7251 return HandleSizeof(Info, ExprLoc, Ty, Result);
7254 // We want to evaluate the size of the entire object. This is a valid fallback
7255 // for when Type=1 and the designator is invalid, because we're asked for an
7257 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7258 // Type=3 wants a lower bound, so we can't fall back to this.
7259 if (Type == 3 && !DetermineForCompleteObject)
7262 llvm::APInt APEndOffset;
7263 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7264 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7265 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7267 if (LVal.InvalidBase)
7270 QualType BaseTy = getObjectType(LVal.getLValueBase());
7271 return CheckedHandleSizeof(BaseTy, EndOffset);
7274 // We want to evaluate the size of a subobject.
7275 const SubobjectDesignator &Designator = LVal.Designator;
7277 // The following is a moderately common idiom in C:
7279 // struct Foo { int a; char c[1]; };
7280 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7281 // strcpy(&F->c[0], Bar);
7283 // In order to not break too much legacy code, we need to support it.
7284 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7285 // If we can resolve this to an alloc_size call, we can hand that back,
7286 // because we know for certain how many bytes there are to write to.
7287 llvm::APInt APEndOffset;
7288 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7289 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7290 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7292 // If we cannot determine the size of the initial allocation, then we can't
7293 // given an accurate upper-bound. However, we are still able to give
7294 // conservative lower-bounds for Type=3.
7299 CharUnits BytesPerElem;
7300 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7303 // According to the GCC documentation, we want the size of the subobject
7304 // denoted by the pointer. But that's not quite right -- what we actually
7305 // want is the size of the immediately-enclosing array, if there is one.
7306 int64_t ElemsRemaining;
7307 if (Designator.MostDerivedIsArrayElement &&
7308 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7309 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7310 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7311 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7313 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7316 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7320 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7321 /// returns true and stores the result in @p Size.
7323 /// If @p WasError is non-null, this will report whether the failure to evaluate
7324 /// is to be treated as an Error in IntExprEvaluator.
7325 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7326 EvalInfo &Info, uint64_t &Size) {
7327 // Determine the denoted object.
7330 // The operand of __builtin_object_size is never evaluated for side-effects.
7331 // If there are any, but we can determine the pointed-to object anyway, then
7332 // ignore the side-effects.
7333 SpeculativeEvaluationRAII SpeculativeEval(Info);
7334 FoldOffsetRAII Fold(Info);
7336 if (E->isGLValue()) {
7337 // It's possible for us to be given GLValues if we're called via
7338 // Expr::tryEvaluateObjectSize.
7340 if (!EvaluateAsRValue(Info, E, RVal))
7342 LVal.setFrom(Info.Ctx, RVal);
7343 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7347 // If we point to before the start of the object, there are no accessible
7349 if (LVal.getLValueOffset().isNegative()) {
7354 CharUnits EndOffset;
7355 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7358 // If we've fallen outside of the end offset, just pretend there's nothing to
7359 // write to/read from.
7360 if (EndOffset <= LVal.getLValueOffset())
7363 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7367 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7368 if (unsigned BuiltinOp = E->getBuiltinCallee())
7369 return VisitBuiltinCallExpr(E, BuiltinOp);
7371 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7374 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7375 unsigned BuiltinOp) {
7376 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7378 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7380 case Builtin::BI__builtin_object_size: {
7381 // The type was checked when we built the expression.
7383 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7384 assert(Type <= 3 && "unexpected type");
7387 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7388 return Success(Size, E);
7390 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7391 return Success((Type & 2) ? 0 : -1, E);
7393 // Expression had no side effects, but we couldn't statically determine the
7394 // size of the referenced object.
7395 switch (Info.EvalMode) {
7396 case EvalInfo::EM_ConstantExpression:
7397 case EvalInfo::EM_PotentialConstantExpression:
7398 case EvalInfo::EM_ConstantFold:
7399 case EvalInfo::EM_EvaluateForOverflow:
7400 case EvalInfo::EM_IgnoreSideEffects:
7401 case EvalInfo::EM_OffsetFold:
7402 // Leave it to IR generation.
7404 case EvalInfo::EM_ConstantExpressionUnevaluated:
7405 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7406 // Reduce it to a constant now.
7407 return Success((Type & 2) ? 0 : -1, E);
7410 llvm_unreachable("unexpected EvalMode");
7413 case Builtin::BI__builtin_bswap16:
7414 case Builtin::BI__builtin_bswap32:
7415 case Builtin::BI__builtin_bswap64: {
7417 if (!EvaluateInteger(E->getArg(0), Val, Info))
7420 return Success(Val.byteSwap(), E);
7423 case Builtin::BI__builtin_classify_type:
7424 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7426 // FIXME: BI__builtin_clrsb
7427 // FIXME: BI__builtin_clrsbl
7428 // FIXME: BI__builtin_clrsbll
7430 case Builtin::BI__builtin_clz:
7431 case Builtin::BI__builtin_clzl:
7432 case Builtin::BI__builtin_clzll:
7433 case Builtin::BI__builtin_clzs: {
7435 if (!EvaluateInteger(E->getArg(0), Val, Info))
7440 return Success(Val.countLeadingZeros(), E);
7443 case Builtin::BI__builtin_constant_p:
7444 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7446 case Builtin::BI__builtin_ctz:
7447 case Builtin::BI__builtin_ctzl:
7448 case Builtin::BI__builtin_ctzll:
7449 case Builtin::BI__builtin_ctzs: {
7451 if (!EvaluateInteger(E->getArg(0), Val, Info))
7456 return Success(Val.countTrailingZeros(), E);
7459 case Builtin::BI__builtin_eh_return_data_regno: {
7460 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7461 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7462 return Success(Operand, E);
7465 case Builtin::BI__builtin_expect:
7466 return Visit(E->getArg(0));
7468 case Builtin::BI__builtin_ffs:
7469 case Builtin::BI__builtin_ffsl:
7470 case Builtin::BI__builtin_ffsll: {
7472 if (!EvaluateInteger(E->getArg(0), Val, Info))
7475 unsigned N = Val.countTrailingZeros();
7476 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7479 case Builtin::BI__builtin_fpclassify: {
7481 if (!EvaluateFloat(E->getArg(5), Val, Info))
7484 switch (Val.getCategory()) {
7485 case APFloat::fcNaN: Arg = 0; break;
7486 case APFloat::fcInfinity: Arg = 1; break;
7487 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7488 case APFloat::fcZero: Arg = 4; break;
7490 return Visit(E->getArg(Arg));
7493 case Builtin::BI__builtin_isinf_sign: {
7495 return EvaluateFloat(E->getArg(0), Val, Info) &&
7496 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7499 case Builtin::BI__builtin_isinf: {
7501 return EvaluateFloat(E->getArg(0), Val, Info) &&
7502 Success(Val.isInfinity() ? 1 : 0, E);
7505 case Builtin::BI__builtin_isfinite: {
7507 return EvaluateFloat(E->getArg(0), Val, Info) &&
7508 Success(Val.isFinite() ? 1 : 0, E);
7511 case Builtin::BI__builtin_isnan: {
7513 return EvaluateFloat(E->getArg(0), Val, Info) &&
7514 Success(Val.isNaN() ? 1 : 0, E);
7517 case Builtin::BI__builtin_isnormal: {
7519 return EvaluateFloat(E->getArg(0), Val, Info) &&
7520 Success(Val.isNormal() ? 1 : 0, E);
7523 case Builtin::BI__builtin_parity:
7524 case Builtin::BI__builtin_parityl:
7525 case Builtin::BI__builtin_parityll: {
7527 if (!EvaluateInteger(E->getArg(0), Val, Info))
7530 return Success(Val.countPopulation() % 2, E);
7533 case Builtin::BI__builtin_popcount:
7534 case Builtin::BI__builtin_popcountl:
7535 case Builtin::BI__builtin_popcountll: {
7537 if (!EvaluateInteger(E->getArg(0), Val, Info))
7540 return Success(Val.countPopulation(), E);
7543 case Builtin::BIstrlen:
7544 case Builtin::BIwcslen:
7545 // A call to strlen is not a constant expression.
7546 if (Info.getLangOpts().CPlusPlus11)
7547 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7548 << /*isConstexpr*/0 << /*isConstructor*/0
7549 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7551 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7553 case Builtin::BI__builtin_strlen:
7554 case Builtin::BI__builtin_wcslen: {
7555 // As an extension, we support __builtin_strlen() as a constant expression,
7556 // and support folding strlen() to a constant.
7558 if (!EvaluatePointer(E->getArg(0), String, Info))
7561 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7563 // Fast path: if it's a string literal, search the string value.
7564 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7565 String.getLValueBase().dyn_cast<const Expr *>())) {
7566 // The string literal may have embedded null characters. Find the first
7567 // one and truncate there.
7568 StringRef Str = S->getBytes();
7569 int64_t Off = String.Offset.getQuantity();
7570 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7571 S->getCharByteWidth() == 1 &&
7572 // FIXME: Add fast-path for wchar_t too.
7573 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7574 Str = Str.substr(Off);
7576 StringRef::size_type Pos = Str.find(0);
7577 if (Pos != StringRef::npos)
7578 Str = Str.substr(0, Pos);
7580 return Success(Str.size(), E);
7583 // Fall through to slow path to issue appropriate diagnostic.
7586 // Slow path: scan the bytes of the string looking for the terminating 0.
7587 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7589 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7593 return Success(Strlen, E);
7594 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7599 case Builtin::BIstrcmp:
7600 case Builtin::BIwcscmp:
7601 case Builtin::BIstrncmp:
7602 case Builtin::BIwcsncmp:
7603 case Builtin::BImemcmp:
7604 case Builtin::BIwmemcmp:
7605 // A call to strlen is not a constant expression.
7606 if (Info.getLangOpts().CPlusPlus11)
7607 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7608 << /*isConstexpr*/0 << /*isConstructor*/0
7609 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7611 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7613 case Builtin::BI__builtin_strcmp:
7614 case Builtin::BI__builtin_wcscmp:
7615 case Builtin::BI__builtin_strncmp:
7616 case Builtin::BI__builtin_wcsncmp:
7617 case Builtin::BI__builtin_memcmp:
7618 case Builtin::BI__builtin_wmemcmp: {
7619 LValue String1, String2;
7620 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7621 !EvaluatePointer(E->getArg(1), String2, Info))
7624 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7626 uint64_t MaxLength = uint64_t(-1);
7627 if (BuiltinOp != Builtin::BIstrcmp &&
7628 BuiltinOp != Builtin::BIwcscmp &&
7629 BuiltinOp != Builtin::BI__builtin_strcmp &&
7630 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7632 if (!EvaluateInteger(E->getArg(2), N, Info))
7634 MaxLength = N.getExtValue();
7636 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7637 BuiltinOp != Builtin::BIwmemcmp &&
7638 BuiltinOp != Builtin::BI__builtin_memcmp &&
7639 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7640 for (; MaxLength; --MaxLength) {
7641 APValue Char1, Char2;
7642 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7643 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7644 !Char1.isInt() || !Char2.isInt())
7646 if (Char1.getInt() != Char2.getInt())
7647 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7648 if (StopAtNull && !Char1.getInt())
7649 return Success(0, E);
7650 assert(!(StopAtNull && !Char2.getInt()));
7651 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7652 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7655 // We hit the strncmp / memcmp limit.
7656 return Success(0, E);
7659 case Builtin::BI__atomic_always_lock_free:
7660 case Builtin::BI__atomic_is_lock_free:
7661 case Builtin::BI__c11_atomic_is_lock_free: {
7663 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7666 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7667 // of two less than the maximum inline atomic width, we know it is
7668 // lock-free. If the size isn't a power of two, or greater than the
7669 // maximum alignment where we promote atomics, we know it is not lock-free
7670 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7671 // the answer can only be determined at runtime; for example, 16-byte
7672 // atomics have lock-free implementations on some, but not all,
7673 // x86-64 processors.
7675 // Check power-of-two.
7676 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7677 if (Size.isPowerOfTwo()) {
7678 // Check against inlining width.
7679 unsigned InlineWidthBits =
7680 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7681 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7682 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7683 Size == CharUnits::One() ||
7684 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7685 Expr::NPC_NeverValueDependent))
7686 // OK, we will inline appropriately-aligned operations of this size,
7687 // and _Atomic(T) is appropriately-aligned.
7688 return Success(1, E);
7690 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7691 castAs<PointerType>()->getPointeeType();
7692 if (!PointeeType->isIncompleteType() &&
7693 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7694 // OK, we will inline operations on this object.
7695 return Success(1, E);
7700 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7701 Success(0, E) : Error(E);
7706 static bool HasSameBase(const LValue &A, const LValue &B) {
7707 if (!A.getLValueBase())
7708 return !B.getLValueBase();
7709 if (!B.getLValueBase())
7712 if (A.getLValueBase().getOpaqueValue() !=
7713 B.getLValueBase().getOpaqueValue()) {
7714 const Decl *ADecl = GetLValueBaseDecl(A);
7717 const Decl *BDecl = GetLValueBaseDecl(B);
7718 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7722 return IsGlobalLValue(A.getLValueBase()) ||
7723 A.getLValueCallIndex() == B.getLValueCallIndex();
7726 /// \brief Determine whether this is a pointer past the end of the complete
7727 /// object referred to by the lvalue.
7728 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7730 // A null pointer can be viewed as being "past the end" but we don't
7731 // choose to look at it that way here.
7732 if (!LV.getLValueBase())
7735 // If the designator is valid and refers to a subobject, we're not pointing
7737 if (!LV.getLValueDesignator().Invalid &&
7738 !LV.getLValueDesignator().isOnePastTheEnd())
7741 // A pointer to an incomplete type might be past-the-end if the type's size is
7742 // zero. We cannot tell because the type is incomplete.
7743 QualType Ty = getType(LV.getLValueBase());
7744 if (Ty->isIncompleteType())
7747 // We're a past-the-end pointer if we point to the byte after the object,
7748 // no matter what our type or path is.
7749 auto Size = Ctx.getTypeSizeInChars(Ty);
7750 return LV.getLValueOffset() == Size;
7755 /// \brief Data recursive integer evaluator of certain binary operators.
7757 /// We use a data recursive algorithm for binary operators so that we are able
7758 /// to handle extreme cases of chained binary operators without causing stack
7760 class DataRecursiveIntBinOpEvaluator {
7765 EvalResult() : Failed(false) { }
7767 void swap(EvalResult &RHS) {
7769 Failed = RHS.Failed;
7776 EvalResult LHSResult; // meaningful only for binary operator expression.
7777 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7780 Job(Job &&) = default;
7782 void startSpeculativeEval(EvalInfo &Info) {
7783 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7787 SpeculativeEvaluationRAII SpecEvalRAII;
7790 SmallVector<Job, 16> Queue;
7792 IntExprEvaluator &IntEval;
7794 APValue &FinalResult;
7797 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7798 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7800 /// \brief True if \param E is a binary operator that we are going to handle
7801 /// data recursively.
7802 /// We handle binary operators that are comma, logical, or that have operands
7803 /// with integral or enumeration type.
7804 static bool shouldEnqueue(const BinaryOperator *E) {
7805 return E->getOpcode() == BO_Comma ||
7808 E->getType()->isIntegralOrEnumerationType() &&
7809 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7810 E->getRHS()->getType()->isIntegralOrEnumerationType());
7813 bool Traverse(const BinaryOperator *E) {
7815 EvalResult PrevResult;
7816 while (!Queue.empty())
7817 process(PrevResult);
7819 if (PrevResult.Failed) return false;
7821 FinalResult.swap(PrevResult.Val);
7826 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7827 return IntEval.Success(Value, E, Result);
7829 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7830 return IntEval.Success(Value, E, Result);
7832 bool Error(const Expr *E) {
7833 return IntEval.Error(E);
7835 bool Error(const Expr *E, diag::kind D) {
7836 return IntEval.Error(E, D);
7839 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7840 return Info.CCEDiag(E, D);
7843 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7844 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7845 bool &SuppressRHSDiags);
7847 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7848 const BinaryOperator *E, APValue &Result);
7850 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7851 Result.Failed = !Evaluate(Result.Val, Info, E);
7853 Result.Val = APValue();
7856 void process(EvalResult &Result);
7858 void enqueue(const Expr *E) {
7859 E = E->IgnoreParens();
7860 Queue.resize(Queue.size()+1);
7862 Queue.back().Kind = Job::AnyExprKind;
7868 bool DataRecursiveIntBinOpEvaluator::
7869 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7870 bool &SuppressRHSDiags) {
7871 if (E->getOpcode() == BO_Comma) {
7872 // Ignore LHS but note if we could not evaluate it.
7873 if (LHSResult.Failed)
7874 return Info.noteSideEffect();
7878 if (E->isLogicalOp()) {
7880 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7881 // We were able to evaluate the LHS, see if we can get away with not
7882 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7883 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7884 Success(LHSAsBool, E, LHSResult.Val);
7885 return false; // Ignore RHS
7888 LHSResult.Failed = true;
7890 // Since we weren't able to evaluate the left hand side, it
7891 // might have had side effects.
7892 if (!Info.noteSideEffect())
7895 // We can't evaluate the LHS; however, sometimes the result
7896 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7897 // Don't ignore RHS and suppress diagnostics from this arm.
7898 SuppressRHSDiags = true;
7904 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7905 E->getRHS()->getType()->isIntegralOrEnumerationType());
7907 if (LHSResult.Failed && !Info.noteFailure())
7908 return false; // Ignore RHS;
7913 bool DataRecursiveIntBinOpEvaluator::
7914 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7915 const BinaryOperator *E, APValue &Result) {
7916 if (E->getOpcode() == BO_Comma) {
7917 if (RHSResult.Failed)
7919 Result = RHSResult.Val;
7923 if (E->isLogicalOp()) {
7924 bool lhsResult, rhsResult;
7925 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7926 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7930 if (E->getOpcode() == BO_LOr)
7931 return Success(lhsResult || rhsResult, E, Result);
7933 return Success(lhsResult && rhsResult, E, Result);
7937 // We can't evaluate the LHS; however, sometimes the result
7938 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7939 if (rhsResult == (E->getOpcode() == BO_LOr))
7940 return Success(rhsResult, E, Result);
7947 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7948 E->getRHS()->getType()->isIntegralOrEnumerationType());
7950 if (LHSResult.Failed || RHSResult.Failed)
7953 const APValue &LHSVal = LHSResult.Val;
7954 const APValue &RHSVal = RHSResult.Val;
7956 // Handle cases like (unsigned long)&a + 4.
7957 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7959 CharUnits AdditionalOffset =
7960 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7961 if (E->getOpcode() == BO_Add)
7962 Result.getLValueOffset() += AdditionalOffset;
7964 Result.getLValueOffset() -= AdditionalOffset;
7968 // Handle cases like 4 + (unsigned long)&a
7969 if (E->getOpcode() == BO_Add &&
7970 RHSVal.isLValue() && LHSVal.isInt()) {
7972 Result.getLValueOffset() +=
7973 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
7977 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7978 // Handle (intptr_t)&&A - (intptr_t)&&B.
7979 if (!LHSVal.getLValueOffset().isZero() ||
7980 !RHSVal.getLValueOffset().isZero())
7982 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7983 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7984 if (!LHSExpr || !RHSExpr)
7986 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7987 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7988 if (!LHSAddrExpr || !RHSAddrExpr)
7990 // Make sure both labels come from the same function.
7991 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7992 RHSAddrExpr->getLabel()->getDeclContext())
7994 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7998 // All the remaining cases expect both operands to be an integer
7999 if (!LHSVal.isInt() || !RHSVal.isInt())
8002 // Set up the width and signedness manually, in case it can't be deduced
8003 // from the operation we're performing.
8004 // FIXME: Don't do this in the cases where we can deduce it.
8005 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8006 E->getType()->isUnsignedIntegerOrEnumerationType());
8007 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8008 RHSVal.getInt(), Value))
8010 return Success(Value, E, Result);
8013 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8014 Job &job = Queue.back();
8017 case Job::AnyExprKind: {
8018 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8019 if (shouldEnqueue(Bop)) {
8020 job.Kind = Job::BinOpKind;
8021 enqueue(Bop->getLHS());
8026 EvaluateExpr(job.E, Result);
8031 case Job::BinOpKind: {
8032 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8033 bool SuppressRHSDiags = false;
8034 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8038 if (SuppressRHSDiags)
8039 job.startSpeculativeEval(Info);
8040 job.LHSResult.swap(Result);
8041 job.Kind = Job::BinOpVisitedLHSKind;
8042 enqueue(Bop->getRHS());
8046 case Job::BinOpVisitedLHSKind: {
8047 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8050 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8056 llvm_unreachable("Invalid Job::Kind!");
8060 /// Used when we determine that we should fail, but can keep evaluating prior to
8061 /// noting that we had a failure.
8062 class DelayedNoteFailureRAII {
8067 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8068 : Info(Info), NoteFailure(NoteFailure) {}
8069 ~DelayedNoteFailureRAII() {
8071 bool ContinueAfterFailure = Info.noteFailure();
8072 (void)ContinueAfterFailure;
8073 assert(ContinueAfterFailure &&
8074 "Shouldn't have kept evaluating on failure.");
8080 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8081 // We don't call noteFailure immediately because the assignment happens after
8082 // we evaluate LHS and RHS.
8083 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8086 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8087 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8088 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8090 QualType LHSTy = E->getLHS()->getType();
8091 QualType RHSTy = E->getRHS()->getType();
8093 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8094 ComplexValue LHS, RHS;
8096 if (E->isAssignmentOp()) {
8098 EvaluateLValue(E->getLHS(), LV, Info);
8100 } else if (LHSTy->isRealFloatingType()) {
8101 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8103 LHS.makeComplexFloat();
8104 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8107 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8109 if (!LHSOK && !Info.noteFailure())
8112 if (E->getRHS()->getType()->isRealFloatingType()) {
8113 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8115 RHS.makeComplexFloat();
8116 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8117 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8120 if (LHS.isComplexFloat()) {
8121 APFloat::cmpResult CR_r =
8122 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8123 APFloat::cmpResult CR_i =
8124 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8126 if (E->getOpcode() == BO_EQ)
8127 return Success((CR_r == APFloat::cmpEqual &&
8128 CR_i == APFloat::cmpEqual), E);
8130 assert(E->getOpcode() == BO_NE &&
8131 "Invalid complex comparison.");
8132 return Success(((CR_r == APFloat::cmpGreaterThan ||
8133 CR_r == APFloat::cmpLessThan ||
8134 CR_r == APFloat::cmpUnordered) ||
8135 (CR_i == APFloat::cmpGreaterThan ||
8136 CR_i == APFloat::cmpLessThan ||
8137 CR_i == APFloat::cmpUnordered)), E);
8140 if (E->getOpcode() == BO_EQ)
8141 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8142 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8144 assert(E->getOpcode() == BO_NE &&
8145 "Invalid compex comparison.");
8146 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8147 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8152 if (LHSTy->isRealFloatingType() &&
8153 RHSTy->isRealFloatingType()) {
8154 APFloat RHS(0.0), LHS(0.0);
8156 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8157 if (!LHSOK && !Info.noteFailure())
8160 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8163 APFloat::cmpResult CR = LHS.compare(RHS);
8165 switch (E->getOpcode()) {
8167 llvm_unreachable("Invalid binary operator!");
8169 return Success(CR == APFloat::cmpLessThan, E);
8171 return Success(CR == APFloat::cmpGreaterThan, E);
8173 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8175 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8178 return Success(CR == APFloat::cmpEqual, E);
8180 return Success(CR == APFloat::cmpGreaterThan
8181 || CR == APFloat::cmpLessThan
8182 || CR == APFloat::cmpUnordered, E);
8186 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8187 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8188 LValue LHSValue, RHSValue;
8190 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8191 if (!LHSOK && !Info.noteFailure())
8194 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8197 // Reject differing bases from the normal codepath; we special-case
8198 // comparisons to null.
8199 if (!HasSameBase(LHSValue, RHSValue)) {
8200 if (E->getOpcode() == BO_Sub) {
8201 // Handle &&A - &&B.
8202 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8204 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8205 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8206 if (!LHSExpr || !RHSExpr)
8208 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8209 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8210 if (!LHSAddrExpr || !RHSAddrExpr)
8212 // Make sure both labels come from the same function.
8213 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8214 RHSAddrExpr->getLabel()->getDeclContext())
8216 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8218 // Inequalities and subtractions between unrelated pointers have
8219 // unspecified or undefined behavior.
8220 if (!E->isEqualityOp())
8222 // A constant address may compare equal to the address of a symbol.
8223 // The one exception is that address of an object cannot compare equal
8224 // to a null pointer constant.
8225 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8226 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8228 // It's implementation-defined whether distinct literals will have
8229 // distinct addresses. In clang, the result of such a comparison is
8230 // unspecified, so it is not a constant expression. However, we do know
8231 // that the address of a literal will be non-null.
8232 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8233 LHSValue.Base && RHSValue.Base)
8235 // We can't tell whether weak symbols will end up pointing to the same
8237 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8239 // We can't compare the address of the start of one object with the
8240 // past-the-end address of another object, per C++ DR1652.
8241 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8242 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8243 (RHSValue.Base && RHSValue.Offset.isZero() &&
8244 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8246 // We can't tell whether an object is at the same address as another
8247 // zero sized object.
8248 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8249 (LHSValue.Base && isZeroSized(RHSValue)))
8251 // Pointers with different bases cannot represent the same object.
8252 // (Note that clang defaults to -fmerge-all-constants, which can
8253 // lead to inconsistent results for comparisons involving the address
8254 // of a constant; this generally doesn't matter in practice.)
8255 return Success(E->getOpcode() == BO_NE, E);
8258 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8259 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8261 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8262 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8264 if (E->getOpcode() == BO_Sub) {
8265 // C++11 [expr.add]p6:
8266 // Unless both pointers point to elements of the same array object, or
8267 // one past the last element of the array object, the behavior is
8269 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8270 !AreElementsOfSameArray(getType(LHSValue.Base),
8271 LHSDesignator, RHSDesignator))
8272 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8274 QualType Type = E->getLHS()->getType();
8275 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8277 CharUnits ElementSize;
8278 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8281 // As an extension, a type may have zero size (empty struct or union in
8282 // C, array of zero length). Pointer subtraction in such cases has
8283 // undefined behavior, so is not constant.
8284 if (ElementSize.isZero()) {
8285 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8290 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8291 // and produce incorrect results when it overflows. Such behavior
8292 // appears to be non-conforming, but is common, so perhaps we should
8293 // assume the standard intended for such cases to be undefined behavior
8294 // and check for them.
8296 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8297 // overflow in the final conversion to ptrdiff_t.
8299 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8301 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8303 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8304 APSInt TrueResult = (LHS - RHS) / ElemSize;
8305 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8307 if (Result.extend(65) != TrueResult &&
8308 !HandleOverflow(Info, E, TrueResult, E->getType()))
8310 return Success(Result, E);
8313 // C++11 [expr.rel]p3:
8314 // Pointers to void (after pointer conversions) can be compared, with a
8315 // result defined as follows: If both pointers represent the same
8316 // address or are both the null pointer value, the result is true if the
8317 // operator is <= or >= and false otherwise; otherwise the result is
8319 // We interpret this as applying to pointers to *cv* void.
8320 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8321 E->isRelationalOp())
8322 CCEDiag(E, diag::note_constexpr_void_comparison);
8324 // C++11 [expr.rel]p2:
8325 // - If two pointers point to non-static data members of the same object,
8326 // or to subobjects or array elements fo such members, recursively, the
8327 // pointer to the later declared member compares greater provided the
8328 // two members have the same access control and provided their class is
8331 // - Otherwise pointer comparisons are unspecified.
8332 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8333 E->isRelationalOp()) {
8336 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8337 RHSDesignator, WasArrayIndex);
8338 // At the point where the designators diverge, the comparison has a
8339 // specified value if:
8340 // - we are comparing array indices
8341 // - we are comparing fields of a union, or fields with the same access
8342 // Otherwise, the result is unspecified and thus the comparison is not a
8343 // constant expression.
8344 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8345 Mismatch < RHSDesignator.Entries.size()) {
8346 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8347 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8349 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8351 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8352 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8353 << RF->getParent() << RF;
8355 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8356 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8357 << LF->getParent() << LF;
8358 else if (!LF->getParent()->isUnion() &&
8359 LF->getAccess() != RF->getAccess())
8360 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8361 << LF << LF->getAccess() << RF << RF->getAccess()
8366 // The comparison here must be unsigned, and performed with the same
8367 // width as the pointer.
8368 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8369 uint64_t CompareLHS = LHSOffset.getQuantity();
8370 uint64_t CompareRHS = RHSOffset.getQuantity();
8371 assert(PtrSize <= 64 && "Unexpected pointer width");
8372 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8376 // If there is a base and this is a relational operator, we can only
8377 // compare pointers within the object in question; otherwise, the result
8378 // depends on where the object is located in memory.
8379 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8380 QualType BaseTy = getType(LHSValue.Base);
8381 if (BaseTy->isIncompleteType())
8383 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8384 uint64_t OffsetLimit = Size.getQuantity();
8385 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8389 switch (E->getOpcode()) {
8390 default: llvm_unreachable("missing comparison operator");
8391 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8392 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8393 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8394 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8395 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8396 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8401 if (LHSTy->isMemberPointerType()) {
8402 assert(E->isEqualityOp() && "unexpected member pointer operation");
8403 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8405 MemberPtr LHSValue, RHSValue;
8407 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8408 if (!LHSOK && !Info.noteFailure())
8411 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8414 // C++11 [expr.eq]p2:
8415 // If both operands are null, they compare equal. Otherwise if only one is
8416 // null, they compare unequal.
8417 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8418 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8419 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8422 // Otherwise if either is a pointer to a virtual member function, the
8423 // result is unspecified.
8424 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8425 if (MD->isVirtual())
8426 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8427 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8428 if (MD->isVirtual())
8429 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8431 // Otherwise they compare equal if and only if they would refer to the
8432 // same member of the same most derived object or the same subobject if
8433 // they were dereferenced with a hypothetical object of the associated
8435 bool Equal = LHSValue == RHSValue;
8436 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8439 if (LHSTy->isNullPtrType()) {
8440 assert(E->isComparisonOp() && "unexpected nullptr operation");
8441 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8442 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8443 // are compared, the result is true of the operator is <=, >= or ==, and
8445 BinaryOperator::Opcode Opcode = E->getOpcode();
8446 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8449 assert((!LHSTy->isIntegralOrEnumerationType() ||
8450 !RHSTy->isIntegralOrEnumerationType()) &&
8451 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8452 // We can't continue from here for non-integral types.
8453 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8456 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8457 /// a result as the expression's type.
8458 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8459 const UnaryExprOrTypeTraitExpr *E) {
8460 switch(E->getKind()) {
8461 case UETT_AlignOf: {
8462 if (E->isArgumentType())
8463 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8465 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8468 case UETT_VecStep: {
8469 QualType Ty = E->getTypeOfArgument();
8471 if (Ty->isVectorType()) {
8472 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8474 // The vec_step built-in functions that take a 3-component
8475 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8479 return Success(n, E);
8481 return Success(1, E);
8485 QualType SrcTy = E->getTypeOfArgument();
8486 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8487 // the result is the size of the referenced type."
8488 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8489 SrcTy = Ref->getPointeeType();
8492 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8494 return Success(Sizeof, E);
8496 case UETT_OpenMPRequiredSimdAlign:
8497 assert(E->isArgumentType());
8499 Info.Ctx.toCharUnitsFromBits(
8500 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8505 llvm_unreachable("unknown expr/type trait");
8508 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8510 unsigned n = OOE->getNumComponents();
8513 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8514 for (unsigned i = 0; i != n; ++i) {
8515 OffsetOfNode ON = OOE->getComponent(i);
8516 switch (ON.getKind()) {
8517 case OffsetOfNode::Array: {
8518 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8520 if (!EvaluateInteger(Idx, IdxResult, Info))
8522 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8525 CurrentType = AT->getElementType();
8526 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8527 Result += IdxResult.getSExtValue() * ElementSize;
8531 case OffsetOfNode::Field: {
8532 FieldDecl *MemberDecl = ON.getField();
8533 const RecordType *RT = CurrentType->getAs<RecordType>();
8536 RecordDecl *RD = RT->getDecl();
8537 if (RD->isInvalidDecl()) return false;
8538 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8539 unsigned i = MemberDecl->getFieldIndex();
8540 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8541 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8542 CurrentType = MemberDecl->getType().getNonReferenceType();
8546 case OffsetOfNode::Identifier:
8547 llvm_unreachable("dependent __builtin_offsetof");
8549 case OffsetOfNode::Base: {
8550 CXXBaseSpecifier *BaseSpec = ON.getBase();
8551 if (BaseSpec->isVirtual())
8554 // Find the layout of the class whose base we are looking into.
8555 const RecordType *RT = CurrentType->getAs<RecordType>();
8558 RecordDecl *RD = RT->getDecl();
8559 if (RD->isInvalidDecl()) return false;
8560 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8562 // Find the base class itself.
8563 CurrentType = BaseSpec->getType();
8564 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8568 // Add the offset to the base.
8569 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8574 return Success(Result, OOE);
8577 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8578 switch (E->getOpcode()) {
8580 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8584 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8585 // If so, we could clear the diagnostic ID.
8586 return Visit(E->getSubExpr());
8588 // The result is just the value.
8589 return Visit(E->getSubExpr());
8591 if (!Visit(E->getSubExpr()))
8593 if (!Result.isInt()) return Error(E);
8594 const APSInt &Value = Result.getInt();
8595 if (Value.isSigned() && Value.isMinSignedValue() &&
8596 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8599 return Success(-Value, E);
8602 if (!Visit(E->getSubExpr()))
8604 if (!Result.isInt()) return Error(E);
8605 return Success(~Result.getInt(), E);
8609 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8611 return Success(!bres, E);
8616 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8617 /// result type is integer.
8618 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8619 const Expr *SubExpr = E->getSubExpr();
8620 QualType DestType = E->getType();
8621 QualType SrcType = SubExpr->getType();
8623 switch (E->getCastKind()) {
8624 case CK_BaseToDerived:
8625 case CK_DerivedToBase:
8626 case CK_UncheckedDerivedToBase:
8629 case CK_ArrayToPointerDecay:
8630 case CK_FunctionToPointerDecay:
8631 case CK_NullToPointer:
8632 case CK_NullToMemberPointer:
8633 case CK_BaseToDerivedMemberPointer:
8634 case CK_DerivedToBaseMemberPointer:
8635 case CK_ReinterpretMemberPointer:
8636 case CK_ConstructorConversion:
8637 case CK_IntegralToPointer:
8639 case CK_VectorSplat:
8640 case CK_IntegralToFloating:
8641 case CK_FloatingCast:
8642 case CK_CPointerToObjCPointerCast:
8643 case CK_BlockPointerToObjCPointerCast:
8644 case CK_AnyPointerToBlockPointerCast:
8645 case CK_ObjCObjectLValueCast:
8646 case CK_FloatingRealToComplex:
8647 case CK_FloatingComplexToReal:
8648 case CK_FloatingComplexCast:
8649 case CK_FloatingComplexToIntegralComplex:
8650 case CK_IntegralRealToComplex:
8651 case CK_IntegralComplexCast:
8652 case CK_IntegralComplexToFloatingComplex:
8653 case CK_BuiltinFnToFnPtr:
8654 case CK_ZeroToOCLEvent:
8655 case CK_ZeroToOCLQueue:
8656 case CK_NonAtomicToAtomic:
8657 case CK_AddressSpaceConversion:
8658 case CK_IntToOCLSampler:
8659 llvm_unreachable("invalid cast kind for integral value");
8663 case CK_LValueBitCast:
8664 case CK_ARCProduceObject:
8665 case CK_ARCConsumeObject:
8666 case CK_ARCReclaimReturnedObject:
8667 case CK_ARCExtendBlockObject:
8668 case CK_CopyAndAutoreleaseBlockObject:
8671 case CK_UserDefinedConversion:
8672 case CK_LValueToRValue:
8673 case CK_AtomicToNonAtomic:
8675 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8677 case CK_MemberPointerToBoolean:
8678 case CK_PointerToBoolean:
8679 case CK_IntegralToBoolean:
8680 case CK_FloatingToBoolean:
8681 case CK_BooleanToSignedIntegral:
8682 case CK_FloatingComplexToBoolean:
8683 case CK_IntegralComplexToBoolean: {
8685 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8687 uint64_t IntResult = BoolResult;
8688 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8689 IntResult = (uint64_t)-1;
8690 return Success(IntResult, E);
8693 case CK_IntegralCast: {
8694 if (!Visit(SubExpr))
8697 if (!Result.isInt()) {
8698 // Allow casts of address-of-label differences if they are no-ops
8699 // or narrowing. (The narrowing case isn't actually guaranteed to
8700 // be constant-evaluatable except in some narrow cases which are hard
8701 // to detect here. We let it through on the assumption the user knows
8702 // what they are doing.)
8703 if (Result.isAddrLabelDiff())
8704 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8705 // Only allow casts of lvalues if they are lossless.
8706 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8709 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8710 Result.getInt()), E);
8713 case CK_PointerToIntegral: {
8714 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8717 if (!EvaluatePointer(SubExpr, LV, Info))
8720 if (LV.getLValueBase()) {
8721 // Only allow based lvalue casts if they are lossless.
8722 // FIXME: Allow a larger integer size than the pointer size, and allow
8723 // narrowing back down to pointer width in subsequent integral casts.
8724 // FIXME: Check integer type's active bits, not its type size.
8725 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8728 LV.Designator.setInvalid();
8729 LV.moveInto(Result);
8734 if (LV.isNullPointer())
8735 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8737 V = LV.getLValueOffset().getQuantity();
8739 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8740 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8743 case CK_IntegralComplexToReal: {
8745 if (!EvaluateComplex(SubExpr, C, Info))
8747 return Success(C.getComplexIntReal(), E);
8750 case CK_FloatingToIntegral: {
8752 if (!EvaluateFloat(SubExpr, F, Info))
8756 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8758 return Success(Value, E);
8762 llvm_unreachable("unknown cast resulting in integral value");
8765 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8766 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8768 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8770 if (!LV.isComplexInt())
8772 return Success(LV.getComplexIntReal(), E);
8775 return Visit(E->getSubExpr());
8778 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8779 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8781 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8783 if (!LV.isComplexInt())
8785 return Success(LV.getComplexIntImag(), E);
8788 VisitIgnoredValue(E->getSubExpr());
8789 return Success(0, E);
8792 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8793 return Success(E->getPackLength(), E);
8796 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8797 return Success(E->getValue(), E);
8800 //===----------------------------------------------------------------------===//
8802 //===----------------------------------------------------------------------===//
8805 class FloatExprEvaluator
8806 : public ExprEvaluatorBase<FloatExprEvaluator> {
8809 FloatExprEvaluator(EvalInfo &info, APFloat &result)
8810 : ExprEvaluatorBaseTy(info), Result(result) {}
8812 bool Success(const APValue &V, const Expr *e) {
8813 Result = V.getFloat();
8817 bool ZeroInitialization(const Expr *E) {
8818 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8822 bool VisitCallExpr(const CallExpr *E);
8824 bool VisitUnaryOperator(const UnaryOperator *E);
8825 bool VisitBinaryOperator(const BinaryOperator *E);
8826 bool VisitFloatingLiteral(const FloatingLiteral *E);
8827 bool VisitCastExpr(const CastExpr *E);
8829 bool VisitUnaryReal(const UnaryOperator *E);
8830 bool VisitUnaryImag(const UnaryOperator *E);
8832 // FIXME: Missing: array subscript of vector, member of vector
8834 } // end anonymous namespace
8836 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
8837 assert(E->isRValue() && E->getType()->isRealFloatingType());
8838 return FloatExprEvaluator(Info, Result).Visit(E);
8841 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
8845 llvm::APFloat &Result) {
8846 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8847 if (!S) return false;
8849 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8853 // Treat empty strings as if they were zero.
8854 if (S->getString().empty())
8855 fill = llvm::APInt(32, 0);
8856 else if (S->getString().getAsInteger(0, fill))
8859 if (Context.getTargetInfo().isNan2008()) {
8861 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8863 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8865 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8866 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8867 // a different encoding to what became a standard in 2008, and for pre-
8868 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8869 // sNaN. This is now known as "legacy NaN" encoding.
8871 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8873 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8879 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
8880 switch (E->getBuiltinCallee()) {
8882 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8884 case Builtin::BI__builtin_huge_val:
8885 case Builtin::BI__builtin_huge_valf:
8886 case Builtin::BI__builtin_huge_vall:
8887 case Builtin::BI__builtin_inf:
8888 case Builtin::BI__builtin_inff:
8889 case Builtin::BI__builtin_infl: {
8890 const llvm::fltSemantics &Sem =
8891 Info.Ctx.getFloatTypeSemantics(E->getType());
8892 Result = llvm::APFloat::getInf(Sem);
8896 case Builtin::BI__builtin_nans:
8897 case Builtin::BI__builtin_nansf:
8898 case Builtin::BI__builtin_nansl:
8899 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8904 case Builtin::BI__builtin_nan:
8905 case Builtin::BI__builtin_nanf:
8906 case Builtin::BI__builtin_nanl:
8907 // If this is __builtin_nan() turn this into a nan, otherwise we
8908 // can't constant fold it.
8909 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8914 case Builtin::BI__builtin_fabs:
8915 case Builtin::BI__builtin_fabsf:
8916 case Builtin::BI__builtin_fabsl:
8917 if (!EvaluateFloat(E->getArg(0), Result, Info))
8920 if (Result.isNegative())
8921 Result.changeSign();
8924 // FIXME: Builtin::BI__builtin_powi
8925 // FIXME: Builtin::BI__builtin_powif
8926 // FIXME: Builtin::BI__builtin_powil
8928 case Builtin::BI__builtin_copysign:
8929 case Builtin::BI__builtin_copysignf:
8930 case Builtin::BI__builtin_copysignl: {
8932 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8933 !EvaluateFloat(E->getArg(1), RHS, Info))
8935 Result.copySign(RHS);
8941 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8942 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8944 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8946 Result = CV.FloatReal;
8950 return Visit(E->getSubExpr());
8953 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8954 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8956 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8958 Result = CV.FloatImag;
8962 VisitIgnoredValue(E->getSubExpr());
8963 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8964 Result = llvm::APFloat::getZero(Sem);
8968 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8969 switch (E->getOpcode()) {
8970 default: return Error(E);
8972 return EvaluateFloat(E->getSubExpr(), Result, Info);
8974 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8976 Result.changeSign();
8981 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8982 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8983 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8986 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
8987 if (!LHSOK && !Info.noteFailure())
8989 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8990 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
8993 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8994 Result = E->getValue();
8998 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8999 const Expr* SubExpr = E->getSubExpr();
9001 switch (E->getCastKind()) {
9003 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9005 case CK_IntegralToFloating: {
9007 return EvaluateInteger(SubExpr, IntResult, Info) &&
9008 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9009 E->getType(), Result);
9012 case CK_FloatingCast: {
9013 if (!Visit(SubExpr))
9015 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9019 case CK_FloatingComplexToReal: {
9021 if (!EvaluateComplex(SubExpr, V, Info))
9023 Result = V.getComplexFloatReal();
9029 //===----------------------------------------------------------------------===//
9030 // Complex Evaluation (for float and integer)
9031 //===----------------------------------------------------------------------===//
9034 class ComplexExprEvaluator
9035 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9036 ComplexValue &Result;
9039 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9040 : ExprEvaluatorBaseTy(info), Result(Result) {}
9042 bool Success(const APValue &V, const Expr *e) {
9047 bool ZeroInitialization(const Expr *E);
9049 //===--------------------------------------------------------------------===//
9051 //===--------------------------------------------------------------------===//
9053 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9054 bool VisitCastExpr(const CastExpr *E);
9055 bool VisitBinaryOperator(const BinaryOperator *E);
9056 bool VisitUnaryOperator(const UnaryOperator *E);
9057 bool VisitInitListExpr(const InitListExpr *E);
9059 } // end anonymous namespace
9061 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9063 assert(E->isRValue() && E->getType()->isAnyComplexType());
9064 return ComplexExprEvaluator(Info, Result).Visit(E);
9067 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9068 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9069 if (ElemTy->isRealFloatingType()) {
9070 Result.makeComplexFloat();
9071 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9072 Result.FloatReal = Zero;
9073 Result.FloatImag = Zero;
9075 Result.makeComplexInt();
9076 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9077 Result.IntReal = Zero;
9078 Result.IntImag = Zero;
9083 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9084 const Expr* SubExpr = E->getSubExpr();
9086 if (SubExpr->getType()->isRealFloatingType()) {
9087 Result.makeComplexFloat();
9088 APFloat &Imag = Result.FloatImag;
9089 if (!EvaluateFloat(SubExpr, Imag, Info))
9092 Result.FloatReal = APFloat(Imag.getSemantics());
9095 assert(SubExpr->getType()->isIntegerType() &&
9096 "Unexpected imaginary literal.");
9098 Result.makeComplexInt();
9099 APSInt &Imag = Result.IntImag;
9100 if (!EvaluateInteger(SubExpr, Imag, Info))
9103 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9108 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9110 switch (E->getCastKind()) {
9112 case CK_BaseToDerived:
9113 case CK_DerivedToBase:
9114 case CK_UncheckedDerivedToBase:
9117 case CK_ArrayToPointerDecay:
9118 case CK_FunctionToPointerDecay:
9119 case CK_NullToPointer:
9120 case CK_NullToMemberPointer:
9121 case CK_BaseToDerivedMemberPointer:
9122 case CK_DerivedToBaseMemberPointer:
9123 case CK_MemberPointerToBoolean:
9124 case CK_ReinterpretMemberPointer:
9125 case CK_ConstructorConversion:
9126 case CK_IntegralToPointer:
9127 case CK_PointerToIntegral:
9128 case CK_PointerToBoolean:
9130 case CK_VectorSplat:
9131 case CK_IntegralCast:
9132 case CK_BooleanToSignedIntegral:
9133 case CK_IntegralToBoolean:
9134 case CK_IntegralToFloating:
9135 case CK_FloatingToIntegral:
9136 case CK_FloatingToBoolean:
9137 case CK_FloatingCast:
9138 case CK_CPointerToObjCPointerCast:
9139 case CK_BlockPointerToObjCPointerCast:
9140 case CK_AnyPointerToBlockPointerCast:
9141 case CK_ObjCObjectLValueCast:
9142 case CK_FloatingComplexToReal:
9143 case CK_FloatingComplexToBoolean:
9144 case CK_IntegralComplexToReal:
9145 case CK_IntegralComplexToBoolean:
9146 case CK_ARCProduceObject:
9147 case CK_ARCConsumeObject:
9148 case CK_ARCReclaimReturnedObject:
9149 case CK_ARCExtendBlockObject:
9150 case CK_CopyAndAutoreleaseBlockObject:
9151 case CK_BuiltinFnToFnPtr:
9152 case CK_ZeroToOCLEvent:
9153 case CK_ZeroToOCLQueue:
9154 case CK_NonAtomicToAtomic:
9155 case CK_AddressSpaceConversion:
9156 case CK_IntToOCLSampler:
9157 llvm_unreachable("invalid cast kind for complex value");
9159 case CK_LValueToRValue:
9160 case CK_AtomicToNonAtomic:
9162 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9165 case CK_LValueBitCast:
9166 case CK_UserDefinedConversion:
9169 case CK_FloatingRealToComplex: {
9170 APFloat &Real = Result.FloatReal;
9171 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9174 Result.makeComplexFloat();
9175 Result.FloatImag = APFloat(Real.getSemantics());
9179 case CK_FloatingComplexCast: {
9180 if (!Visit(E->getSubExpr()))
9183 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9185 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9187 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9188 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9191 case CK_FloatingComplexToIntegralComplex: {
9192 if (!Visit(E->getSubExpr()))
9195 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9197 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9198 Result.makeComplexInt();
9199 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9200 To, Result.IntReal) &&
9201 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9202 To, Result.IntImag);
9205 case CK_IntegralRealToComplex: {
9206 APSInt &Real = Result.IntReal;
9207 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9210 Result.makeComplexInt();
9211 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9215 case CK_IntegralComplexCast: {
9216 if (!Visit(E->getSubExpr()))
9219 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9221 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9223 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9224 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9228 case CK_IntegralComplexToFloatingComplex: {
9229 if (!Visit(E->getSubExpr()))
9232 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9234 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9235 Result.makeComplexFloat();
9236 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9237 To, Result.FloatReal) &&
9238 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9239 To, Result.FloatImag);
9243 llvm_unreachable("unknown cast resulting in complex value");
9246 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9247 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9248 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9250 // Track whether the LHS or RHS is real at the type system level. When this is
9251 // the case we can simplify our evaluation strategy.
9252 bool LHSReal = false, RHSReal = false;
9255 if (E->getLHS()->getType()->isRealFloatingType()) {
9257 APFloat &Real = Result.FloatReal;
9258 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9260 Result.makeComplexFloat();
9261 Result.FloatImag = APFloat(Real.getSemantics());
9264 LHSOK = Visit(E->getLHS());
9266 if (!LHSOK && !Info.noteFailure())
9270 if (E->getRHS()->getType()->isRealFloatingType()) {
9272 APFloat &Real = RHS.FloatReal;
9273 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9275 RHS.makeComplexFloat();
9276 RHS.FloatImag = APFloat(Real.getSemantics());
9277 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9280 assert(!(LHSReal && RHSReal) &&
9281 "Cannot have both operands of a complex operation be real.");
9282 switch (E->getOpcode()) {
9283 default: return Error(E);
9285 if (Result.isComplexFloat()) {
9286 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9287 APFloat::rmNearestTiesToEven);
9289 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9291 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9292 APFloat::rmNearestTiesToEven);
9294 Result.getComplexIntReal() += RHS.getComplexIntReal();
9295 Result.getComplexIntImag() += RHS.getComplexIntImag();
9299 if (Result.isComplexFloat()) {
9300 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9301 APFloat::rmNearestTiesToEven);
9303 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9304 Result.getComplexFloatImag().changeSign();
9305 } else if (!RHSReal) {
9306 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9307 APFloat::rmNearestTiesToEven);
9310 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9311 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9315 if (Result.isComplexFloat()) {
9316 // This is an implementation of complex multiplication according to the
9317 // constraints laid out in C11 Annex G. The implemantion uses the
9318 // following naming scheme:
9319 // (a + ib) * (c + id)
9320 ComplexValue LHS = Result;
9321 APFloat &A = LHS.getComplexFloatReal();
9322 APFloat &B = LHS.getComplexFloatImag();
9323 APFloat &C = RHS.getComplexFloatReal();
9324 APFloat &D = RHS.getComplexFloatImag();
9325 APFloat &ResR = Result.getComplexFloatReal();
9326 APFloat &ResI = Result.getComplexFloatImag();
9328 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9331 } else if (RHSReal) {
9335 // In the fully general case, we need to handle NaNs and infinities
9343 if (ResR.isNaN() && ResI.isNaN()) {
9344 bool Recalc = false;
9345 if (A.isInfinity() || B.isInfinity()) {
9346 A = APFloat::copySign(
9347 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9348 B = APFloat::copySign(
9349 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9351 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9353 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9356 if (C.isInfinity() || D.isInfinity()) {
9357 C = APFloat::copySign(
9358 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9359 D = APFloat::copySign(
9360 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9362 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9364 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9367 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9368 AD.isInfinity() || BC.isInfinity())) {
9370 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9372 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9374 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9376 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9380 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9381 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9386 ComplexValue LHS = Result;
9387 Result.getComplexIntReal() =
9388 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9389 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9390 Result.getComplexIntImag() =
9391 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9392 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9396 if (Result.isComplexFloat()) {
9397 // This is an implementation of complex division according to the
9398 // constraints laid out in C11 Annex G. The implemantion uses the
9399 // following naming scheme:
9400 // (a + ib) / (c + id)
9401 ComplexValue LHS = Result;
9402 APFloat &A = LHS.getComplexFloatReal();
9403 APFloat &B = LHS.getComplexFloatImag();
9404 APFloat &C = RHS.getComplexFloatReal();
9405 APFloat &D = RHS.getComplexFloatImag();
9406 APFloat &ResR = Result.getComplexFloatReal();
9407 APFloat &ResI = Result.getComplexFloatImag();
9413 // No real optimizations we can do here, stub out with zero.
9414 B = APFloat::getZero(A.getSemantics());
9417 APFloat MaxCD = maxnum(abs(C), abs(D));
9418 if (MaxCD.isFinite()) {
9419 DenomLogB = ilogb(MaxCD);
9420 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9421 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9423 APFloat Denom = C * C + D * D;
9424 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9425 APFloat::rmNearestTiesToEven);
9426 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9427 APFloat::rmNearestTiesToEven);
9428 if (ResR.isNaN() && ResI.isNaN()) {
9429 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9430 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9431 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9432 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9434 A = APFloat::copySign(
9435 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9436 B = APFloat::copySign(
9437 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9438 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9439 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9440 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9441 C = APFloat::copySign(
9442 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9443 D = APFloat::copySign(
9444 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9445 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9446 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9451 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9452 return Error(E, diag::note_expr_divide_by_zero);
9454 ComplexValue LHS = Result;
9455 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9456 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9457 Result.getComplexIntReal() =
9458 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9459 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9460 Result.getComplexIntImag() =
9461 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9462 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9470 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9471 // Get the operand value into 'Result'.
9472 if (!Visit(E->getSubExpr()))
9475 switch (E->getOpcode()) {
9481 // The result is always just the subexpr.
9484 if (Result.isComplexFloat()) {
9485 Result.getComplexFloatReal().changeSign();
9486 Result.getComplexFloatImag().changeSign();
9489 Result.getComplexIntReal() = -Result.getComplexIntReal();
9490 Result.getComplexIntImag() = -Result.getComplexIntImag();
9494 if (Result.isComplexFloat())
9495 Result.getComplexFloatImag().changeSign();
9497 Result.getComplexIntImag() = -Result.getComplexIntImag();
9502 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9503 if (E->getNumInits() == 2) {
9504 if (E->getType()->isComplexType()) {
9505 Result.makeComplexFloat();
9506 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9508 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9511 Result.makeComplexInt();
9512 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9514 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9519 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9522 //===----------------------------------------------------------------------===//
9523 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9524 // implicit conversion.
9525 //===----------------------------------------------------------------------===//
9528 class AtomicExprEvaluator :
9529 public ExprEvaluatorBase<AtomicExprEvaluator> {
9532 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9533 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9535 bool Success(const APValue &V, const Expr *E) {
9540 bool ZeroInitialization(const Expr *E) {
9541 ImplicitValueInitExpr VIE(
9542 E->getType()->castAs<AtomicType>()->getValueType());
9543 return Evaluate(Result, Info, &VIE);
9546 bool VisitCastExpr(const CastExpr *E) {
9547 switch (E->getCastKind()) {
9549 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9550 case CK_NonAtomicToAtomic:
9551 return Evaluate(Result, Info, E->getSubExpr());
9555 } // end anonymous namespace
9557 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9558 assert(E->isRValue() && E->getType()->isAtomicType());
9559 return AtomicExprEvaluator(Info, Result).Visit(E);
9562 //===----------------------------------------------------------------------===//
9563 // Void expression evaluation, primarily for a cast to void on the LHS of a
9565 //===----------------------------------------------------------------------===//
9568 class VoidExprEvaluator
9569 : public ExprEvaluatorBase<VoidExprEvaluator> {
9571 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9573 bool Success(const APValue &V, const Expr *e) { return true; }
9575 bool VisitCastExpr(const CastExpr *E) {
9576 switch (E->getCastKind()) {
9578 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9580 VisitIgnoredValue(E->getSubExpr());
9585 bool VisitCallExpr(const CallExpr *E) {
9586 switch (E->getBuiltinCallee()) {
9588 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9589 case Builtin::BI__assume:
9590 case Builtin::BI__builtin_assume:
9591 // The argument is not evaluated!
9596 } // end anonymous namespace
9598 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9599 assert(E->isRValue() && E->getType()->isVoidType());
9600 return VoidExprEvaluator(Info).Visit(E);
9603 //===----------------------------------------------------------------------===//
9604 // Top level Expr::EvaluateAsRValue method.
9605 //===----------------------------------------------------------------------===//
9607 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9608 // In C, function designators are not lvalues, but we evaluate them as if they
9610 QualType T = E->getType();
9611 if (E->isGLValue() || T->isFunctionType()) {
9613 if (!EvaluateLValue(E, LV, Info))
9615 LV.moveInto(Result);
9616 } else if (T->isVectorType()) {
9617 if (!EvaluateVector(E, Result, Info))
9619 } else if (T->isIntegralOrEnumerationType()) {
9620 if (!IntExprEvaluator(Info, Result).Visit(E))
9622 } else if (T->hasPointerRepresentation()) {
9624 if (!EvaluatePointer(E, LV, Info))
9626 LV.moveInto(Result);
9627 } else if (T->isRealFloatingType()) {
9628 llvm::APFloat F(0.0);
9629 if (!EvaluateFloat(E, F, Info))
9631 Result = APValue(F);
9632 } else if (T->isAnyComplexType()) {
9634 if (!EvaluateComplex(E, C, Info))
9637 } else if (T->isMemberPointerType()) {
9639 if (!EvaluateMemberPointer(E, P, Info))
9643 } else if (T->isArrayType()) {
9645 LV.set(E, Info.CurrentCall->Index);
9646 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9647 if (!EvaluateArray(E, LV, Value, Info))
9650 } else if (T->isRecordType()) {
9652 LV.set(E, Info.CurrentCall->Index);
9653 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9654 if (!EvaluateRecord(E, LV, Value, Info))
9657 } else if (T->isVoidType()) {
9658 if (!Info.getLangOpts().CPlusPlus11)
9659 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9661 if (!EvaluateVoid(E, Info))
9663 } else if (T->isAtomicType()) {
9664 if (!EvaluateAtomic(E, Result, Info))
9666 } else if (Info.getLangOpts().CPlusPlus11) {
9667 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9670 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9677 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9678 /// cases, the in-place evaluation is essential, since later initializers for
9679 /// an object can indirectly refer to subobjects which were initialized earlier.
9680 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9681 const Expr *E, bool AllowNonLiteralTypes) {
9682 assert(!E->isValueDependent());
9684 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9687 if (E->isRValue()) {
9688 // Evaluate arrays and record types in-place, so that later initializers can
9689 // refer to earlier-initialized members of the object.
9690 if (E->getType()->isArrayType())
9691 return EvaluateArray(E, This, Result, Info);
9692 else if (E->getType()->isRecordType())
9693 return EvaluateRecord(E, This, Result, Info);
9696 // For any other type, in-place evaluation is unimportant.
9697 return Evaluate(Result, Info, E);
9700 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9701 /// lvalue-to-rvalue cast if it is an lvalue.
9702 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9703 if (E->getType().isNull())
9706 if (!CheckLiteralType(Info, E))
9709 if (!::Evaluate(Result, Info, E))
9712 if (E->isGLValue()) {
9714 LV.setFrom(Info.Ctx, Result);
9715 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9719 // Check this core constant expression is a constant expression.
9720 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9723 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9724 const ASTContext &Ctx, bool &IsConst) {
9725 // Fast-path evaluations of integer literals, since we sometimes see files
9726 // containing vast quantities of these.
9727 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9728 Result.Val = APValue(APSInt(L->getValue(),
9729 L->getType()->isUnsignedIntegerType()));
9734 // This case should be rare, but we need to check it before we check on
9736 if (Exp->getType().isNull()) {
9741 // FIXME: Evaluating values of large array and record types can cause
9742 // performance problems. Only do so in C++11 for now.
9743 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9744 Exp->getType()->isRecordType()) &&
9745 !Ctx.getLangOpts().CPlusPlus11) {
9753 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9754 /// any crazy technique (that has nothing to do with language standards) that
9755 /// we want to. If this function returns true, it returns the folded constant
9756 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9757 /// will be applied to the result.
9758 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9760 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9763 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9764 return ::EvaluateAsRValue(Info, this, Result.Val);
9767 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9768 const ASTContext &Ctx) const {
9770 return EvaluateAsRValue(Scratch, Ctx) &&
9771 HandleConversionToBool(Scratch.Val, Result);
9774 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9775 Expr::SideEffectsKind SEK) {
9776 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9777 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9780 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9781 SideEffectsKind AllowSideEffects) const {
9782 if (!getType()->isIntegralOrEnumerationType())
9785 EvalResult ExprResult;
9786 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9787 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9790 Result = ExprResult.Val.getInt();
9794 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9795 SideEffectsKind AllowSideEffects) const {
9796 if (!getType()->isRealFloatingType())
9799 EvalResult ExprResult;
9800 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9801 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9804 Result = ExprResult.Val.getFloat();
9808 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
9809 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
9812 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9813 !CheckLValueConstantExpression(Info, getExprLoc(),
9814 Ctx.getLValueReferenceType(getType()), LV))
9817 LV.moveInto(Result.Val);
9821 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9823 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
9824 // FIXME: Evaluating initializers for large array and record types can cause
9825 // performance problems. Only do so in C++11 for now.
9826 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
9827 !Ctx.getLangOpts().CPlusPlus11)
9830 Expr::EvalStatus EStatus;
9831 EStatus.Diag = &Notes;
9833 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9834 ? EvalInfo::EM_ConstantExpression
9835 : EvalInfo::EM_ConstantFold);
9836 InitInfo.setEvaluatingDecl(VD, Value);
9841 // C++11 [basic.start.init]p2:
9842 // Variables with static storage duration or thread storage duration shall be
9843 // zero-initialized before any other initialization takes place.
9844 // This behavior is not present in C.
9845 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
9846 !VD->getType()->isReferenceType()) {
9847 ImplicitValueInitExpr VIE(VD->getType());
9848 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
9849 /*AllowNonLiteralTypes=*/true))
9853 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9854 /*AllowNonLiteralTypes=*/true) ||
9855 EStatus.HasSideEffects)
9858 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9862 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9863 /// constant folded, but discard the result.
9864 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
9866 return EvaluateAsRValue(Result, Ctx) &&
9867 !hasUnacceptableSideEffect(Result, SEK);
9870 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
9871 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
9872 EvalResult EvalResult;
9873 EvalResult.Diag = Diag;
9874 bool Result = EvaluateAsRValue(EvalResult, Ctx);
9876 assert(Result && "Could not evaluate expression");
9877 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
9879 return EvalResult.Val.getInt();
9882 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
9884 EvalResult EvalResult;
9885 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
9886 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
9887 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9891 bool Expr::EvalResult::isGlobalLValue() const {
9892 assert(Val.isLValue());
9893 return IsGlobalLValue(Val.getLValueBase());
9897 /// isIntegerConstantExpr - this recursive routine will test if an expression is
9898 /// an integer constant expression.
9900 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9903 // CheckICE - This function does the fundamental ICE checking: the returned
9904 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9905 // and a (possibly null) SourceLocation indicating the location of the problem.
9907 // Note that to reduce code duplication, this helper does no evaluation
9908 // itself; the caller checks whether the expression is evaluatable, and
9909 // in the rare cases where CheckICE actually cares about the evaluated
9910 // value, it calls into Evalute.
9915 /// This expression is an ICE.
9917 /// This expression is not an ICE, but if it isn't evaluated, it's
9918 /// a legal subexpression for an ICE. This return value is used to handle
9919 /// the comma operator in C99 mode, and non-constant subexpressions.
9920 IK_ICEIfUnevaluated,
9921 /// This expression is not an ICE, and is not a legal subexpression for one.
9929 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9934 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9936 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9938 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9939 Expr::EvalResult EVResult;
9940 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9941 !EVResult.Val.isInt())
9942 return ICEDiag(IK_NotICE, E->getLocStart());
9947 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9948 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9949 if (!E->getType()->isIntegralOrEnumerationType())
9950 return ICEDiag(IK_NotICE, E->getLocStart());
9952 switch (E->getStmtClass()) {
9953 #define ABSTRACT_STMT(Node)
9954 #define STMT(Node, Base) case Expr::Node##Class:
9955 #define EXPR(Node, Base)
9956 #include "clang/AST/StmtNodes.inc"
9957 case Expr::PredefinedExprClass:
9958 case Expr::FloatingLiteralClass:
9959 case Expr::ImaginaryLiteralClass:
9960 case Expr::StringLiteralClass:
9961 case Expr::ArraySubscriptExprClass:
9962 case Expr::OMPArraySectionExprClass:
9963 case Expr::MemberExprClass:
9964 case Expr::CompoundAssignOperatorClass:
9965 case Expr::CompoundLiteralExprClass:
9966 case Expr::ExtVectorElementExprClass:
9967 case Expr::DesignatedInitExprClass:
9968 case Expr::ArrayInitLoopExprClass:
9969 case Expr::ArrayInitIndexExprClass:
9970 case Expr::NoInitExprClass:
9971 case Expr::DesignatedInitUpdateExprClass:
9972 case Expr::ImplicitValueInitExprClass:
9973 case Expr::ParenListExprClass:
9974 case Expr::VAArgExprClass:
9975 case Expr::AddrLabelExprClass:
9976 case Expr::StmtExprClass:
9977 case Expr::CXXMemberCallExprClass:
9978 case Expr::CUDAKernelCallExprClass:
9979 case Expr::CXXDynamicCastExprClass:
9980 case Expr::CXXTypeidExprClass:
9981 case Expr::CXXUuidofExprClass:
9982 case Expr::MSPropertyRefExprClass:
9983 case Expr::MSPropertySubscriptExprClass:
9984 case Expr::CXXNullPtrLiteralExprClass:
9985 case Expr::UserDefinedLiteralClass:
9986 case Expr::CXXThisExprClass:
9987 case Expr::CXXThrowExprClass:
9988 case Expr::CXXNewExprClass:
9989 case Expr::CXXDeleteExprClass:
9990 case Expr::CXXPseudoDestructorExprClass:
9991 case Expr::UnresolvedLookupExprClass:
9992 case Expr::TypoExprClass:
9993 case Expr::DependentScopeDeclRefExprClass:
9994 case Expr::CXXConstructExprClass:
9995 case Expr::CXXInheritedCtorInitExprClass:
9996 case Expr::CXXStdInitializerListExprClass:
9997 case Expr::CXXBindTemporaryExprClass:
9998 case Expr::ExprWithCleanupsClass:
9999 case Expr::CXXTemporaryObjectExprClass:
10000 case Expr::CXXUnresolvedConstructExprClass:
10001 case Expr::CXXDependentScopeMemberExprClass:
10002 case Expr::UnresolvedMemberExprClass:
10003 case Expr::ObjCStringLiteralClass:
10004 case Expr::ObjCBoxedExprClass:
10005 case Expr::ObjCArrayLiteralClass:
10006 case Expr::ObjCDictionaryLiteralClass:
10007 case Expr::ObjCEncodeExprClass:
10008 case Expr::ObjCMessageExprClass:
10009 case Expr::ObjCSelectorExprClass:
10010 case Expr::ObjCProtocolExprClass:
10011 case Expr::ObjCIvarRefExprClass:
10012 case Expr::ObjCPropertyRefExprClass:
10013 case Expr::ObjCSubscriptRefExprClass:
10014 case Expr::ObjCIsaExprClass:
10015 case Expr::ObjCAvailabilityCheckExprClass:
10016 case Expr::ShuffleVectorExprClass:
10017 case Expr::ConvertVectorExprClass:
10018 case Expr::BlockExprClass:
10019 case Expr::NoStmtClass:
10020 case Expr::OpaqueValueExprClass:
10021 case Expr::PackExpansionExprClass:
10022 case Expr::SubstNonTypeTemplateParmPackExprClass:
10023 case Expr::FunctionParmPackExprClass:
10024 case Expr::AsTypeExprClass:
10025 case Expr::ObjCIndirectCopyRestoreExprClass:
10026 case Expr::MaterializeTemporaryExprClass:
10027 case Expr::PseudoObjectExprClass:
10028 case Expr::AtomicExprClass:
10029 case Expr::LambdaExprClass:
10030 case Expr::CXXFoldExprClass:
10031 case Expr::CoawaitExprClass:
10032 case Expr::CoyieldExprClass:
10033 return ICEDiag(IK_NotICE, E->getLocStart());
10035 case Expr::InitListExprClass: {
10036 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10037 // form "T x = { a };" is equivalent to "T x = a;".
10038 // Unless we're initializing a reference, T is a scalar as it is known to be
10039 // of integral or enumeration type.
10041 if (cast<InitListExpr>(E)->getNumInits() == 1)
10042 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10043 return ICEDiag(IK_NotICE, E->getLocStart());
10046 case Expr::SizeOfPackExprClass:
10047 case Expr::GNUNullExprClass:
10048 // GCC considers the GNU __null value to be an integral constant expression.
10051 case Expr::SubstNonTypeTemplateParmExprClass:
10053 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10055 case Expr::ParenExprClass:
10056 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10057 case Expr::GenericSelectionExprClass:
10058 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10059 case Expr::IntegerLiteralClass:
10060 case Expr::CharacterLiteralClass:
10061 case Expr::ObjCBoolLiteralExprClass:
10062 case Expr::CXXBoolLiteralExprClass:
10063 case Expr::CXXScalarValueInitExprClass:
10064 case Expr::TypeTraitExprClass:
10065 case Expr::ArrayTypeTraitExprClass:
10066 case Expr::ExpressionTraitExprClass:
10067 case Expr::CXXNoexceptExprClass:
10069 case Expr::CallExprClass:
10070 case Expr::CXXOperatorCallExprClass: {
10071 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10072 // constant expressions, but they can never be ICEs because an ICE cannot
10073 // contain an operand of (pointer to) function type.
10074 const CallExpr *CE = cast<CallExpr>(E);
10075 if (CE->getBuiltinCallee())
10076 return CheckEvalInICE(E, Ctx);
10077 return ICEDiag(IK_NotICE, E->getLocStart());
10079 case Expr::DeclRefExprClass: {
10080 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10082 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10083 if (Ctx.getLangOpts().CPlusPlus &&
10084 D && IsConstNonVolatile(D->getType())) {
10085 // Parameter variables are never constants. Without this check,
10086 // getAnyInitializer() can find a default argument, which leads
10088 if (isa<ParmVarDecl>(D))
10089 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10092 // A variable of non-volatile const-qualified integral or enumeration
10093 // type initialized by an ICE can be used in ICEs.
10094 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10095 if (!Dcl->getType()->isIntegralOrEnumerationType())
10096 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10099 // Look for a declaration of this variable that has an initializer, and
10100 // check whether it is an ICE.
10101 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10104 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10107 return ICEDiag(IK_NotICE, E->getLocStart());
10109 case Expr::UnaryOperatorClass: {
10110 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10111 switch (Exp->getOpcode()) {
10119 // C99 6.6/3 allows increment and decrement within unevaluated
10120 // subexpressions of constant expressions, but they can never be ICEs
10121 // because an ICE cannot contain an lvalue operand.
10122 return ICEDiag(IK_NotICE, E->getLocStart());
10130 return CheckICE(Exp->getSubExpr(), Ctx);
10133 // OffsetOf falls through here.
10135 case Expr::OffsetOfExprClass: {
10136 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10137 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10138 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10139 // compliance: we should warn earlier for offsetof expressions with
10140 // array subscripts that aren't ICEs, and if the array subscripts
10141 // are ICEs, the value of the offsetof must be an integer constant.
10142 return CheckEvalInICE(E, Ctx);
10144 case Expr::UnaryExprOrTypeTraitExprClass: {
10145 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10146 if ((Exp->getKind() == UETT_SizeOf) &&
10147 Exp->getTypeOfArgument()->isVariableArrayType())
10148 return ICEDiag(IK_NotICE, E->getLocStart());
10151 case Expr::BinaryOperatorClass: {
10152 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10153 switch (Exp->getOpcode()) {
10167 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10168 // constant expressions, but they can never be ICEs because an ICE cannot
10169 // contain an lvalue operand.
10170 return ICEDiag(IK_NotICE, E->getLocStart());
10189 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10190 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10191 if (Exp->getOpcode() == BO_Div ||
10192 Exp->getOpcode() == BO_Rem) {
10193 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10194 // we don't evaluate one.
10195 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10196 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10198 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10199 if (REval.isSigned() && REval.isAllOnesValue()) {
10200 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10201 if (LEval.isMinSignedValue())
10202 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10206 if (Exp->getOpcode() == BO_Comma) {
10207 if (Ctx.getLangOpts().C99) {
10208 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10209 // if it isn't evaluated.
10210 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10211 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10213 // In both C89 and C++, commas in ICEs are illegal.
10214 return ICEDiag(IK_NotICE, E->getLocStart());
10217 return Worst(LHSResult, RHSResult);
10221 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10222 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10223 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10224 // Rare case where the RHS has a comma "side-effect"; we need
10225 // to actually check the condition to see whether the side
10226 // with the comma is evaluated.
10227 if ((Exp->getOpcode() == BO_LAnd) !=
10228 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10233 return Worst(LHSResult, RHSResult);
10237 case Expr::ImplicitCastExprClass:
10238 case Expr::CStyleCastExprClass:
10239 case Expr::CXXFunctionalCastExprClass:
10240 case Expr::CXXStaticCastExprClass:
10241 case Expr::CXXReinterpretCastExprClass:
10242 case Expr::CXXConstCastExprClass:
10243 case Expr::ObjCBridgedCastExprClass: {
10244 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10245 if (isa<ExplicitCastExpr>(E)) {
10246 if (const FloatingLiteral *FL
10247 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10248 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10249 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10250 APSInt IgnoredVal(DestWidth, !DestSigned);
10252 // If the value does not fit in the destination type, the behavior is
10253 // undefined, so we are not required to treat it as a constant
10255 if (FL->getValue().convertToInteger(IgnoredVal,
10256 llvm::APFloat::rmTowardZero,
10257 &Ignored) & APFloat::opInvalidOp)
10258 return ICEDiag(IK_NotICE, E->getLocStart());
10262 switch (cast<CastExpr>(E)->getCastKind()) {
10263 case CK_LValueToRValue:
10264 case CK_AtomicToNonAtomic:
10265 case CK_NonAtomicToAtomic:
10267 case CK_IntegralToBoolean:
10268 case CK_IntegralCast:
10269 return CheckICE(SubExpr, Ctx);
10271 return ICEDiag(IK_NotICE, E->getLocStart());
10274 case Expr::BinaryConditionalOperatorClass: {
10275 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10276 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10277 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10278 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10279 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10280 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10281 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10282 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10283 return FalseResult;
10285 case Expr::ConditionalOperatorClass: {
10286 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10287 // If the condition (ignoring parens) is a __builtin_constant_p call,
10288 // then only the true side is actually considered in an integer constant
10289 // expression, and it is fully evaluated. This is an important GNU
10290 // extension. See GCC PR38377 for discussion.
10291 if (const CallExpr *CallCE
10292 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10293 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10294 return CheckEvalInICE(E, Ctx);
10295 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10296 if (CondResult.Kind == IK_NotICE)
10299 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10300 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10302 if (TrueResult.Kind == IK_NotICE)
10304 if (FalseResult.Kind == IK_NotICE)
10305 return FalseResult;
10306 if (CondResult.Kind == IK_ICEIfUnevaluated)
10308 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10310 // Rare case where the diagnostics depend on which side is evaluated
10311 // Note that if we get here, CondResult is 0, and at least one of
10312 // TrueResult and FalseResult is non-zero.
10313 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10314 return FalseResult;
10317 case Expr::CXXDefaultArgExprClass:
10318 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10319 case Expr::CXXDefaultInitExprClass:
10320 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10321 case Expr::ChooseExprClass: {
10322 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10326 llvm_unreachable("Invalid StmtClass!");
10329 /// Evaluate an expression as a C++11 integral constant expression.
10330 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10332 llvm::APSInt *Value,
10333 SourceLocation *Loc) {
10334 if (!E->getType()->isIntegralOrEnumerationType()) {
10335 if (Loc) *Loc = E->getExprLoc();
10340 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10343 if (!Result.isInt()) {
10344 if (Loc) *Loc = E->getExprLoc();
10348 if (Value) *Value = Result.getInt();
10352 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10353 SourceLocation *Loc) const {
10354 if (Ctx.getLangOpts().CPlusPlus11)
10355 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10357 ICEDiag D = CheckICE(this, Ctx);
10358 if (D.Kind != IK_ICE) {
10359 if (Loc) *Loc = D.Loc;
10365 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10366 SourceLocation *Loc, bool isEvaluated) const {
10367 if (Ctx.getLangOpts().CPlusPlus11)
10368 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10370 if (!isIntegerConstantExpr(Ctx, Loc))
10372 // The only possible side-effects here are due to UB discovered in the
10373 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10374 // required to treat the expression as an ICE, so we produce the folded
10376 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10377 llvm_unreachable("ICE cannot be evaluated!");
10381 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10382 return CheckICE(this, Ctx).Kind == IK_ICE;
10385 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10386 SourceLocation *Loc) const {
10387 // We support this checking in C++98 mode in order to diagnose compatibility
10389 assert(Ctx.getLangOpts().CPlusPlus);
10391 // Build evaluation settings.
10392 Expr::EvalStatus Status;
10393 SmallVector<PartialDiagnosticAt, 8> Diags;
10394 Status.Diag = &Diags;
10395 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10398 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10400 if (!Diags.empty()) {
10401 IsConstExpr = false;
10402 if (Loc) *Loc = Diags[0].first;
10403 } else if (!IsConstExpr) {
10404 // FIXME: This shouldn't happen.
10405 if (Loc) *Loc = getExprLoc();
10408 return IsConstExpr;
10411 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10412 const FunctionDecl *Callee,
10413 ArrayRef<const Expr*> Args,
10414 const Expr *This) const {
10415 Expr::EvalStatus Status;
10416 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10419 const LValue *ThisPtr = nullptr;
10422 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10423 assert(MD && "Don't provide `this` for non-methods.");
10424 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10426 if (EvaluateObjectArgument(Info, This, ThisVal))
10427 ThisPtr = &ThisVal;
10428 if (Info.EvalStatus.HasSideEffects)
10432 ArgVector ArgValues(Args.size());
10433 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10435 if ((*I)->isValueDependent() ||
10436 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10437 // If evaluation fails, throw away the argument entirely.
10438 ArgValues[I - Args.begin()] = APValue();
10439 if (Info.EvalStatus.HasSideEffects)
10443 // Build fake call to Callee.
10444 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10446 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10449 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10451 PartialDiagnosticAt> &Diags) {
10452 // FIXME: It would be useful to check constexpr function templates, but at the
10453 // moment the constant expression evaluator cannot cope with the non-rigorous
10454 // ASTs which we build for dependent expressions.
10455 if (FD->isDependentContext())
10458 Expr::EvalStatus Status;
10459 Status.Diag = &Diags;
10461 EvalInfo Info(FD->getASTContext(), Status,
10462 EvalInfo::EM_PotentialConstantExpression);
10464 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10465 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10467 // Fabricate an arbitrary expression on the stack and pretend that it
10468 // is a temporary being used as the 'this' pointer.
10470 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10471 This.set(&VIE, Info.CurrentCall->Index);
10473 ArrayRef<const Expr*> Args;
10476 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10477 // Evaluate the call as a constant initializer, to allow the construction
10478 // of objects of non-literal types.
10479 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10480 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10482 SourceLocation Loc = FD->getLocation();
10483 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10484 Args, FD->getBody(), Info, Scratch, nullptr);
10487 return Diags.empty();
10490 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10491 const FunctionDecl *FD,
10493 PartialDiagnosticAt> &Diags) {
10494 Expr::EvalStatus Status;
10495 Status.Diag = &Diags;
10497 EvalInfo Info(FD->getASTContext(), Status,
10498 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10500 // Fabricate a call stack frame to give the arguments a plausible cover story.
10501 ArrayRef<const Expr*> Args;
10502 ArgVector ArgValues(0);
10503 bool Success = EvaluateArgs(Args, ArgValues, Info);
10506 "Failed to set up arguments for potential constant evaluation");
10507 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10509 APValue ResultScratch;
10510 Evaluate(ResultScratch, Info, E);
10511 return Diags.empty();
10514 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10515 unsigned Type) const {
10516 if (!getType()->isPointerType())
10519 Expr::EvalStatus Status;
10520 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10521 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);