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. In certain scenarios, if:
608 /// - we find a MemberExpr with a base that can't be evaluated, or
609 /// - we find a variable initialized with a call to a function that has
610 /// the alloc_size attribute on it
611 /// then we may consider evaluation to have succeeded.
613 /// In either case, the LValue returned shall have an invalid base; in the
614 /// former, the base will be the invalid MemberExpr, in the latter, the
615 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
620 /// Are we checking whether the expression is a potential constant
622 bool checkingPotentialConstantExpression() const {
623 return EvalMode == EM_PotentialConstantExpression ||
624 EvalMode == EM_PotentialConstantExpressionUnevaluated;
627 /// Are we checking an expression for overflow?
628 // FIXME: We should check for any kind of undefined or suspicious behavior
629 // in such constructs, not just overflow.
630 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
632 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
633 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
634 CallStackDepth(0), NextCallIndex(1),
635 StepsLeft(getLangOpts().ConstexprStepLimit),
636 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
637 EvaluatingDecl((const ValueDecl *)nullptr),
638 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
639 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
642 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
643 EvaluatingDecl = Base;
644 EvaluatingDeclValue = &Value;
647 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
649 bool CheckCallLimit(SourceLocation Loc) {
650 // Don't perform any constexpr calls (other than the call we're checking)
651 // when checking a potential constant expression.
652 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
654 if (NextCallIndex == 0) {
655 // NextCallIndex has wrapped around.
656 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
659 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
661 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
662 << getLangOpts().ConstexprCallDepth;
666 CallStackFrame *getCallFrame(unsigned CallIndex) {
667 assert(CallIndex && "no call index in getCallFrame");
668 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
669 // be null in this loop.
670 CallStackFrame *Frame = CurrentCall;
671 while (Frame->Index > CallIndex)
672 Frame = Frame->Caller;
673 return (Frame->Index == CallIndex) ? Frame : nullptr;
676 bool nextStep(const Stmt *S) {
678 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
686 /// Add a diagnostic to the diagnostics list.
687 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
688 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
689 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
690 return EvalStatus.Diag->back().second;
693 /// Add notes containing a call stack to the current point of evaluation.
694 void addCallStack(unsigned Limit);
697 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
698 unsigned ExtraNotes, bool IsCCEDiag) {
700 if (EvalStatus.Diag) {
701 // If we have a prior diagnostic, it will be noting that the expression
702 // isn't a constant expression. This diagnostic is more important,
703 // unless we require this evaluation to produce a constant expression.
705 // FIXME: We might want to show both diagnostics to the user in
706 // EM_ConstantFold mode.
707 if (!EvalStatus.Diag->empty()) {
709 case EM_ConstantFold:
710 case EM_IgnoreSideEffects:
711 case EM_EvaluateForOverflow:
712 if (!HasFoldFailureDiagnostic)
714 // We've already failed to fold something. Keep that diagnostic.
715 case EM_ConstantExpression:
716 case EM_PotentialConstantExpression:
717 case EM_ConstantExpressionUnevaluated:
718 case EM_PotentialConstantExpressionUnevaluated:
720 HasActiveDiagnostic = false;
721 return OptionalDiagnostic();
725 unsigned CallStackNotes = CallStackDepth - 1;
726 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
728 CallStackNotes = std::min(CallStackNotes, Limit + 1);
729 if (checkingPotentialConstantExpression())
732 HasActiveDiagnostic = true;
733 HasFoldFailureDiagnostic = !IsCCEDiag;
734 EvalStatus.Diag->clear();
735 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
736 addDiag(Loc, DiagId);
737 if (!checkingPotentialConstantExpression())
739 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
741 HasActiveDiagnostic = false;
742 return OptionalDiagnostic();
745 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
747 FFDiag(SourceLocation Loc,
748 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
749 unsigned ExtraNotes = 0) {
750 return Diag(Loc, DiagId, ExtraNotes, false);
753 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
754 = diag::note_invalid_subexpr_in_const_expr,
755 unsigned ExtraNotes = 0) {
757 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
758 HasActiveDiagnostic = false;
759 return OptionalDiagnostic();
762 /// Diagnose that the evaluation does not produce a C++11 core constant
765 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
766 /// EM_PotentialConstantExpression mode and we produce one of these.
767 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
768 = diag::note_invalid_subexpr_in_const_expr,
769 unsigned ExtraNotes = 0) {
770 // Don't override a previous diagnostic. Don't bother collecting
771 // diagnostics if we're evaluating for overflow.
772 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
773 HasActiveDiagnostic = false;
774 return OptionalDiagnostic();
776 return Diag(Loc, DiagId, ExtraNotes, true);
778 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
779 = diag::note_invalid_subexpr_in_const_expr,
780 unsigned ExtraNotes = 0) {
781 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
783 /// Add a note to a prior diagnostic.
784 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
785 if (!HasActiveDiagnostic)
786 return OptionalDiagnostic();
787 return OptionalDiagnostic(&addDiag(Loc, DiagId));
790 /// Add a stack of notes to a prior diagnostic.
791 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
792 if (HasActiveDiagnostic) {
793 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
794 Diags.begin(), Diags.end());
798 /// Should we continue evaluation after encountering a side-effect that we
800 bool keepEvaluatingAfterSideEffect() {
802 case EM_PotentialConstantExpression:
803 case EM_PotentialConstantExpressionUnevaluated:
804 case EM_EvaluateForOverflow:
805 case EM_IgnoreSideEffects:
808 case EM_ConstantExpression:
809 case EM_ConstantExpressionUnevaluated:
810 case EM_ConstantFold:
814 llvm_unreachable("Missed EvalMode case");
817 /// Note that we have had a side-effect, and determine whether we should
819 bool noteSideEffect() {
820 EvalStatus.HasSideEffects = true;
821 return keepEvaluatingAfterSideEffect();
824 /// Should we continue evaluation after encountering undefined behavior?
825 bool keepEvaluatingAfterUndefinedBehavior() {
827 case EM_EvaluateForOverflow:
828 case EM_IgnoreSideEffects:
829 case EM_ConstantFold:
833 case EM_PotentialConstantExpression:
834 case EM_PotentialConstantExpressionUnevaluated:
835 case EM_ConstantExpression:
836 case EM_ConstantExpressionUnevaluated:
839 llvm_unreachable("Missed EvalMode case");
842 /// Note that we hit something that was technically undefined behavior, but
843 /// that we can evaluate past it (such as signed overflow or floating-point
844 /// division by zero.)
845 bool noteUndefinedBehavior() {
846 EvalStatus.HasUndefinedBehavior = true;
847 return keepEvaluatingAfterUndefinedBehavior();
850 /// Should we continue evaluation as much as possible after encountering a
851 /// construct which can't be reduced to a value?
852 bool keepEvaluatingAfterFailure() {
857 case EM_PotentialConstantExpression:
858 case EM_PotentialConstantExpressionUnevaluated:
859 case EM_EvaluateForOverflow:
862 case EM_ConstantExpression:
863 case EM_ConstantExpressionUnevaluated:
864 case EM_ConstantFold:
865 case EM_IgnoreSideEffects:
869 llvm_unreachable("Missed EvalMode case");
872 /// Notes that we failed to evaluate an expression that other expressions
873 /// directly depend on, and determine if we should keep evaluating. This
874 /// should only be called if we actually intend to keep evaluating.
876 /// Call noteSideEffect() instead if we may be able to ignore the value that
877 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
879 /// (Foo(), 1) // use noteSideEffect
880 /// (Foo() || true) // use noteSideEffect
881 /// Foo() + 1 // use noteFailure
882 LLVM_NODISCARD bool noteFailure() {
883 // Failure when evaluating some expression often means there is some
884 // subexpression whose evaluation was skipped. Therefore, (because we
885 // don't track whether we skipped an expression when unwinding after an
886 // evaluation failure) every evaluation failure that bubbles up from a
887 // subexpression implies that a side-effect has potentially happened. We
888 // skip setting the HasSideEffects flag to true until we decide to
889 // continue evaluating after that point, which happens here.
890 bool KeepGoing = keepEvaluatingAfterFailure();
891 EvalStatus.HasSideEffects |= KeepGoing;
895 class ArrayInitLoopIndex {
900 ArrayInitLoopIndex(EvalInfo &Info)
901 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
902 Info.ArrayInitIndex = 0;
904 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
906 operator uint64_t&() { return Info.ArrayInitIndex; }
910 /// Object used to treat all foldable expressions as constant expressions.
911 struct FoldConstant {
914 bool HadNoPriorDiags;
915 EvalInfo::EvaluationMode OldMode;
917 explicit FoldConstant(EvalInfo &Info, bool Enabled)
920 HadNoPriorDiags(Info.EvalStatus.Diag &&
921 Info.EvalStatus.Diag->empty() &&
922 !Info.EvalStatus.HasSideEffects),
923 OldMode(Info.EvalMode) {
925 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
926 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
927 Info.EvalMode = EvalInfo::EM_ConstantFold;
929 void keepDiagnostics() { Enabled = false; }
931 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
932 !Info.EvalStatus.HasSideEffects)
933 Info.EvalStatus.Diag->clear();
934 Info.EvalMode = OldMode;
938 /// RAII object used to treat the current evaluation as the correct pointer
939 /// offset fold for the current EvalMode
940 struct FoldOffsetRAII {
942 EvalInfo::EvaluationMode OldMode;
943 explicit FoldOffsetRAII(EvalInfo &Info)
944 : Info(Info), OldMode(Info.EvalMode) {
945 if (!Info.checkingPotentialConstantExpression())
946 Info.EvalMode = EvalInfo::EM_OffsetFold;
949 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
952 /// RAII object used to optionally suppress diagnostics and side-effects from
953 /// a speculative evaluation.
954 class SpeculativeEvaluationRAII {
955 /// Pair of EvalInfo, and a bit that stores whether or not we were
956 /// speculatively evaluating when we created this RAII.
957 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
958 Expr::EvalStatus Old;
960 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
961 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
963 Other.InfoAndOldSpecEval.setPointer(nullptr);
966 void maybeRestoreState() {
967 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
971 Info->EvalStatus = Old;
972 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
976 SpeculativeEvaluationRAII() = default;
978 SpeculativeEvaluationRAII(
979 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
980 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
981 Old(Info.EvalStatus) {
982 Info.EvalStatus.Diag = NewDiag;
983 Info.IsSpeculativelyEvaluating = true;
986 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
987 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
988 moveFromAndCancel(std::move(Other));
991 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
993 moveFromAndCancel(std::move(Other));
997 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1000 /// RAII object wrapping a full-expression or block scope, and handling
1001 /// the ending of the lifetime of temporaries created within it.
1002 template<bool IsFullExpression>
1005 unsigned OldStackSize;
1007 ScopeRAII(EvalInfo &Info)
1008 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1010 // Body moved to a static method to encourage the compiler to inline away
1011 // instances of this class.
1012 cleanup(Info, OldStackSize);
1015 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1016 unsigned NewEnd = OldStackSize;
1017 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1019 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1020 // Full-expression cleanup of a lifetime-extended temporary: nothing
1021 // to do, just move this cleanup to the right place in the stack.
1022 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1025 // End the lifetime of the object.
1026 Info.CleanupStack[I].endLifetime();
1029 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1030 Info.CleanupStack.end());
1033 typedef ScopeRAII<false> BlockScopeRAII;
1034 typedef ScopeRAII<true> FullExpressionRAII;
1037 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1038 CheckSubobjectKind CSK) {
1041 if (isOnePastTheEnd()) {
1042 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1050 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1051 const Expr *E, uint64_t N) {
1052 // If we're complaining, we must be able to statically determine the size of
1053 // the most derived array.
1054 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1055 Info.CCEDiag(E, diag::note_constexpr_array_index)
1056 << static_cast<int>(N) << /*array*/ 0
1057 << static_cast<unsigned>(getMostDerivedArraySize());
1059 Info.CCEDiag(E, diag::note_constexpr_array_index)
1060 << static_cast<int>(N) << /*non-array*/ 1;
1064 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1065 const FunctionDecl *Callee, const LValue *This,
1067 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1068 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1069 Info.CurrentCall = this;
1070 ++Info.CallStackDepth;
1073 CallStackFrame::~CallStackFrame() {
1074 assert(Info.CurrentCall == this && "calls retired out of order");
1075 --Info.CallStackDepth;
1076 Info.CurrentCall = Caller;
1079 APValue &CallStackFrame::createTemporary(const void *Key,
1080 bool IsLifetimeExtended) {
1081 APValue &Result = Temporaries[Key];
1082 assert(Result.isUninit() && "temporary created multiple times");
1083 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1087 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1089 void EvalInfo::addCallStack(unsigned Limit) {
1090 // Determine which calls to skip, if any.
1091 unsigned ActiveCalls = CallStackDepth - 1;
1092 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1093 if (Limit && Limit < ActiveCalls) {
1094 SkipStart = Limit / 2 + Limit % 2;
1095 SkipEnd = ActiveCalls - Limit / 2;
1098 // Walk the call stack and add the diagnostics.
1099 unsigned CallIdx = 0;
1100 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1101 Frame = Frame->Caller, ++CallIdx) {
1103 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1104 if (CallIdx == SkipStart) {
1105 // Note that we're skipping calls.
1106 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1107 << unsigned(ActiveCalls - Limit);
1112 // Use a different note for an inheriting constructor, because from the
1113 // user's perspective it's not really a function at all.
1114 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1115 if (CD->isInheritingConstructor()) {
1116 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1122 SmallVector<char, 128> Buffer;
1123 llvm::raw_svector_ostream Out(Buffer);
1124 describeCall(Frame, Out);
1125 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1130 struct ComplexValue {
1135 APSInt IntReal, IntImag;
1136 APFloat FloatReal, FloatImag;
1138 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1140 void makeComplexFloat() { IsInt = false; }
1141 bool isComplexFloat() const { return !IsInt; }
1142 APFloat &getComplexFloatReal() { return FloatReal; }
1143 APFloat &getComplexFloatImag() { return FloatImag; }
1145 void makeComplexInt() { IsInt = true; }
1146 bool isComplexInt() const { return IsInt; }
1147 APSInt &getComplexIntReal() { return IntReal; }
1148 APSInt &getComplexIntImag() { return IntImag; }
1150 void moveInto(APValue &v) const {
1151 if (isComplexFloat())
1152 v = APValue(FloatReal, FloatImag);
1154 v = APValue(IntReal, IntImag);
1156 void setFrom(const APValue &v) {
1157 assert(v.isComplexFloat() || v.isComplexInt());
1158 if (v.isComplexFloat()) {
1160 FloatReal = v.getComplexFloatReal();
1161 FloatImag = v.getComplexFloatImag();
1164 IntReal = v.getComplexIntReal();
1165 IntImag = v.getComplexIntImag();
1171 APValue::LValueBase Base;
1173 unsigned InvalidBase : 1;
1174 unsigned CallIndex : 31;
1175 SubobjectDesignator Designator;
1178 const APValue::LValueBase getLValueBase() const { return Base; }
1179 CharUnits &getLValueOffset() { return Offset; }
1180 const CharUnits &getLValueOffset() const { return Offset; }
1181 unsigned getLValueCallIndex() const { return CallIndex; }
1182 SubobjectDesignator &getLValueDesignator() { return Designator; }
1183 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1184 bool isNullPointer() const { return IsNullPtr;}
1186 void moveInto(APValue &V) const {
1187 if (Designator.Invalid)
1188 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1191 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1192 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1193 "Unsized array with a valid base?");
1194 V = APValue(Base, Offset, Designator.Entries,
1195 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1198 void setFrom(ASTContext &Ctx, const APValue &V) {
1199 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1200 Base = V.getLValueBase();
1201 Offset = V.getLValueOffset();
1202 InvalidBase = false;
1203 CallIndex = V.getLValueCallIndex();
1204 Designator = SubobjectDesignator(Ctx, V);
1205 IsNullPtr = V.isNullPointer();
1208 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1209 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
1211 // We only allow a few types of invalid bases. Enforce that here.
1213 const auto *E = B.get<const Expr *>();
1214 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1215 "Unexpected type of invalid base");
1220 Offset = CharUnits::fromQuantity(Offset_);
1221 InvalidBase = BInvalid;
1223 Designator = SubobjectDesignator(getType(B));
1224 IsNullPtr = IsNullPtr_;
1227 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1231 // Check that this LValue is not based on a null pointer. If it is, produce
1232 // a diagnostic and mark the designator as invalid.
1233 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1234 CheckSubobjectKind CSK) {
1235 if (Designator.Invalid)
1238 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1240 Designator.setInvalid();
1246 // Check this LValue refers to an object. If not, set the designator to be
1247 // invalid and emit a diagnostic.
1248 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1249 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1250 Designator.checkSubobject(Info, E, CSK);
1253 void addDecl(EvalInfo &Info, const Expr *E,
1254 const Decl *D, bool Virtual = false) {
1255 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1256 Designator.addDeclUnchecked(D, Virtual);
1258 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1259 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1260 assert(isBaseAnAllocSizeCall(Base) &&
1261 "Only alloc_size bases can have unsized arrays");
1262 Designator.FirstEntryIsAnUnsizedArray = true;
1263 Designator.addUnsizedArrayUnchecked(ElemTy);
1265 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1266 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1267 Designator.addArrayUnchecked(CAT);
1269 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1270 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1271 Designator.addComplexUnchecked(EltTy, Imag);
1273 void clearIsNullPointer() {
1276 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1277 CharUnits ElementSize) {
1278 // Compute the new offset in the appropriate width.
1279 Offset += Index * ElementSize;
1280 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1281 Designator.adjustIndex(Info, E, Index);
1283 clearIsNullPointer();
1285 void adjustOffset(CharUnits N) {
1287 if (N.getQuantity())
1288 clearIsNullPointer();
1294 explicit MemberPtr(const ValueDecl *Decl) :
1295 DeclAndIsDerivedMember(Decl, false), Path() {}
1297 /// The member or (direct or indirect) field referred to by this member
1298 /// pointer, or 0 if this is a null member pointer.
1299 const ValueDecl *getDecl() const {
1300 return DeclAndIsDerivedMember.getPointer();
1302 /// Is this actually a member of some type derived from the relevant class?
1303 bool isDerivedMember() const {
1304 return DeclAndIsDerivedMember.getInt();
1306 /// Get the class which the declaration actually lives in.
1307 const CXXRecordDecl *getContainingRecord() const {
1308 return cast<CXXRecordDecl>(
1309 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1312 void moveInto(APValue &V) const {
1313 V = APValue(getDecl(), isDerivedMember(), Path);
1315 void setFrom(const APValue &V) {
1316 assert(V.isMemberPointer());
1317 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1318 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1320 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1321 Path.insert(Path.end(), P.begin(), P.end());
1324 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1325 /// whether the member is a member of some class derived from the class type
1326 /// of the member pointer.
1327 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1328 /// Path - The path of base/derived classes from the member declaration's
1329 /// class (exclusive) to the class type of the member pointer (inclusive).
1330 SmallVector<const CXXRecordDecl*, 4> Path;
1332 /// Perform a cast towards the class of the Decl (either up or down the
1334 bool castBack(const CXXRecordDecl *Class) {
1335 assert(!Path.empty());
1336 const CXXRecordDecl *Expected;
1337 if (Path.size() >= 2)
1338 Expected = Path[Path.size() - 2];
1340 Expected = getContainingRecord();
1341 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1342 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1343 // if B does not contain the original member and is not a base or
1344 // derived class of the class containing the original member, the result
1345 // of the cast is undefined.
1346 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1347 // (D::*). We consider that to be a language defect.
1353 /// Perform a base-to-derived member pointer cast.
1354 bool castToDerived(const CXXRecordDecl *Derived) {
1357 if (!isDerivedMember()) {
1358 Path.push_back(Derived);
1361 if (!castBack(Derived))
1364 DeclAndIsDerivedMember.setInt(false);
1367 /// Perform a derived-to-base member pointer cast.
1368 bool castToBase(const CXXRecordDecl *Base) {
1372 DeclAndIsDerivedMember.setInt(true);
1373 if (isDerivedMember()) {
1374 Path.push_back(Base);
1377 return castBack(Base);
1381 /// Compare two member pointers, which are assumed to be of the same type.
1382 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1383 if (!LHS.getDecl() || !RHS.getDecl())
1384 return !LHS.getDecl() && !RHS.getDecl();
1385 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1387 return LHS.Path == RHS.Path;
1391 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1392 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1393 const LValue &This, const Expr *E,
1394 bool AllowNonLiteralTypes = false);
1395 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1396 bool InvalidBaseOK = false);
1397 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1398 bool InvalidBaseOK = false);
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.
1631 // C++11 missed this detail for aggregates, so classes like this:
1632 // struct foo_t { union { int i; volatile int j; } u; };
1633 // are not (obviously) initializable like so:
1634 // __attribute__((__require_constant_initialization__))
1635 // static const foo_t x = {{0}};
1636 // because "i" is a subobject with non-literal initialization (due to the
1637 // volatile member of the union). See:
1638 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1639 // Therefore, we use the C++1y behavior.
1640 if (This && Info.EvaluatingDecl == This->getLValueBase())
1643 // Prvalue constant expressions must be of literal types.
1644 if (Info.getLangOpts().CPlusPlus11)
1645 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1648 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1652 /// Check that this core constant expression value is a valid value for a
1653 /// constant expression. If not, report an appropriate diagnostic. Does not
1654 /// check that the expression is of literal type.
1655 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1656 QualType Type, const APValue &Value) {
1657 if (Value.isUninit()) {
1658 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1663 // We allow _Atomic(T) to be initialized from anything that T can be
1664 // initialized from.
1665 if (const AtomicType *AT = Type->getAs<AtomicType>())
1666 Type = AT->getValueType();
1668 // Core issue 1454: For a literal constant expression of array or class type,
1669 // each subobject of its value shall have been initialized by a constant
1671 if (Value.isArray()) {
1672 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1673 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1674 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1675 Value.getArrayInitializedElt(I)))
1678 if (!Value.hasArrayFiller())
1680 return CheckConstantExpression(Info, DiagLoc, EltTy,
1681 Value.getArrayFiller());
1683 if (Value.isUnion() && Value.getUnionField()) {
1684 return CheckConstantExpression(Info, DiagLoc,
1685 Value.getUnionField()->getType(),
1686 Value.getUnionValue());
1688 if (Value.isStruct()) {
1689 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1690 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1691 unsigned BaseIndex = 0;
1692 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1693 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1694 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1695 Value.getStructBase(BaseIndex)))
1699 for (const auto *I : RD->fields()) {
1700 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1701 Value.getStructField(I->getFieldIndex())))
1706 if (Value.isLValue()) {
1708 LVal.setFrom(Info.Ctx, Value);
1709 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1712 // Everything else is fine.
1716 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1717 return LVal.Base.dyn_cast<const ValueDecl*>();
1720 static bool IsLiteralLValue(const LValue &Value) {
1721 if (Value.CallIndex)
1723 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1724 return E && !isa<MaterializeTemporaryExpr>(E);
1727 static bool IsWeakLValue(const LValue &Value) {
1728 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1729 return Decl && Decl->isWeak();
1732 static bool isZeroSized(const LValue &Value) {
1733 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1734 if (Decl && isa<VarDecl>(Decl)) {
1735 QualType Ty = Decl->getType();
1736 if (Ty->isArrayType())
1737 return Ty->isIncompleteType() ||
1738 Decl->getASTContext().getTypeSize(Ty) == 0;
1743 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1744 // A null base expression indicates a null pointer. These are always
1745 // evaluatable, and they are false unless the offset is zero.
1746 if (!Value.getLValueBase()) {
1747 Result = !Value.getLValueOffset().isZero();
1751 // We have a non-null base. These are generally known to be true, but if it's
1752 // a weak declaration it can be null at runtime.
1754 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1755 return !Decl || !Decl->isWeak();
1758 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1759 switch (Val.getKind()) {
1760 case APValue::Uninitialized:
1763 Result = Val.getInt().getBoolValue();
1765 case APValue::Float:
1766 Result = !Val.getFloat().isZero();
1768 case APValue::ComplexInt:
1769 Result = Val.getComplexIntReal().getBoolValue() ||
1770 Val.getComplexIntImag().getBoolValue();
1772 case APValue::ComplexFloat:
1773 Result = !Val.getComplexFloatReal().isZero() ||
1774 !Val.getComplexFloatImag().isZero();
1776 case APValue::LValue:
1777 return EvalPointerValueAsBool(Val, Result);
1778 case APValue::MemberPointer:
1779 Result = Val.getMemberPointerDecl();
1781 case APValue::Vector:
1782 case APValue::Array:
1783 case APValue::Struct:
1784 case APValue::Union:
1785 case APValue::AddrLabelDiff:
1789 llvm_unreachable("unknown APValue kind");
1792 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1794 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1796 if (!Evaluate(Val, Info, E))
1798 return HandleConversionToBool(Val, Result);
1801 template<typename T>
1802 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1803 const T &SrcValue, QualType DestType) {
1804 Info.CCEDiag(E, diag::note_constexpr_overflow)
1805 << SrcValue << DestType;
1806 return Info.noteUndefinedBehavior();
1809 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1810 QualType SrcType, const APFloat &Value,
1811 QualType DestType, APSInt &Result) {
1812 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1813 // Determine whether we are converting to unsigned or signed.
1814 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1816 Result = APSInt(DestWidth, !DestSigned);
1818 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1819 & APFloat::opInvalidOp)
1820 return HandleOverflow(Info, E, Value, DestType);
1824 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1825 QualType SrcType, QualType DestType,
1827 APFloat Value = Result;
1829 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1830 APFloat::rmNearestTiesToEven, &ignored)
1831 & APFloat::opOverflow)
1832 return HandleOverflow(Info, E, Value, DestType);
1836 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1837 QualType DestType, QualType SrcType,
1838 const APSInt &Value) {
1839 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1840 APSInt Result = Value;
1841 // Figure out if this is a truncate, extend or noop cast.
1842 // If the input is signed, do a sign extend, noop, or truncate.
1843 Result = Result.extOrTrunc(DestWidth);
1844 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1848 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1849 QualType SrcType, const APSInt &Value,
1850 QualType DestType, APFloat &Result) {
1851 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1852 if (Result.convertFromAPInt(Value, Value.isSigned(),
1853 APFloat::rmNearestTiesToEven)
1854 & APFloat::opOverflow)
1855 return HandleOverflow(Info, E, Value, DestType);
1859 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1860 APValue &Value, const FieldDecl *FD) {
1861 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1863 if (!Value.isInt()) {
1864 // Trying to store a pointer-cast-to-integer into a bitfield.
1865 // FIXME: In this case, we should provide the diagnostic for casting
1866 // a pointer to an integer.
1867 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1872 APSInt &Int = Value.getInt();
1873 unsigned OldBitWidth = Int.getBitWidth();
1874 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1875 if (NewBitWidth < OldBitWidth)
1876 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1880 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1883 if (!Evaluate(SVal, Info, E))
1886 Res = SVal.getInt();
1889 if (SVal.isFloat()) {
1890 Res = SVal.getFloat().bitcastToAPInt();
1893 if (SVal.isVector()) {
1894 QualType VecTy = E->getType();
1895 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1896 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1897 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1898 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1899 Res = llvm::APInt::getNullValue(VecSize);
1900 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1901 APValue &Elt = SVal.getVectorElt(i);
1902 llvm::APInt EltAsInt;
1904 EltAsInt = Elt.getInt();
1905 } else if (Elt.isFloat()) {
1906 EltAsInt = Elt.getFloat().bitcastToAPInt();
1908 // Don't try to handle vectors of anything other than int or float
1909 // (not sure if it's possible to hit this case).
1910 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1913 unsigned BaseEltSize = EltAsInt.getBitWidth();
1915 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1917 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1921 // Give up if the input isn't an int, float, or vector. For example, we
1922 // reject "(v4i16)(intptr_t)&a".
1923 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1927 /// Perform the given integer operation, which is known to need at most BitWidth
1928 /// bits, and check for overflow in the original type (if that type was not an
1930 template<typename Operation>
1931 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1932 const APSInt &LHS, const APSInt &RHS,
1933 unsigned BitWidth, Operation Op,
1935 if (LHS.isUnsigned()) {
1936 Result = Op(LHS, RHS);
1940 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1941 Result = Value.trunc(LHS.getBitWidth());
1942 if (Result.extend(BitWidth) != Value) {
1943 if (Info.checkingForOverflow())
1944 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1945 diag::warn_integer_constant_overflow)
1946 << Result.toString(10) << E->getType();
1948 return HandleOverflow(Info, E, Value, E->getType());
1953 /// Perform the given binary integer operation.
1954 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1955 BinaryOperatorKind Opcode, APSInt RHS,
1962 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1963 std::multiplies<APSInt>(), Result);
1965 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1966 std::plus<APSInt>(), Result);
1968 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1969 std::minus<APSInt>(), Result);
1970 case BO_And: Result = LHS & RHS; return true;
1971 case BO_Xor: Result = LHS ^ RHS; return true;
1972 case BO_Or: Result = LHS | RHS; return true;
1976 Info.FFDiag(E, diag::note_expr_divide_by_zero);
1979 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1980 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1981 // this operation and gives the two's complement result.
1982 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1983 LHS.isSigned() && LHS.isMinSignedValue())
1984 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1988 if (Info.getLangOpts().OpenCL)
1989 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1990 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1991 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1993 else if (RHS.isSigned() && RHS.isNegative()) {
1994 // During constant-folding, a negative shift is an opposite shift. Such
1995 // a shift is not a constant expression.
1996 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2001 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2002 // the shifted type.
2003 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2005 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2006 << RHS << E->getType() << LHS.getBitWidth();
2007 } else if (LHS.isSigned()) {
2008 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2009 // operand, and must not overflow the corresponding unsigned type.
2010 if (LHS.isNegative())
2011 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2012 else if (LHS.countLeadingZeros() < SA)
2013 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2019 if (Info.getLangOpts().OpenCL)
2020 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2021 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2022 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2024 else if (RHS.isSigned() && RHS.isNegative()) {
2025 // During constant-folding, a negative shift is an opposite shift. Such a
2026 // shift is not a constant expression.
2027 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2032 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2034 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2036 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2037 << RHS << E->getType() << LHS.getBitWidth();
2042 case BO_LT: Result = LHS < RHS; return true;
2043 case BO_GT: Result = LHS > RHS; return true;
2044 case BO_LE: Result = LHS <= RHS; return true;
2045 case BO_GE: Result = LHS >= RHS; return true;
2046 case BO_EQ: Result = LHS == RHS; return true;
2047 case BO_NE: Result = LHS != RHS; return true;
2051 /// Perform the given binary floating-point operation, in-place, on LHS.
2052 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2053 APFloat &LHS, BinaryOperatorKind Opcode,
2054 const APFloat &RHS) {
2060 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2063 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2066 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2069 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2073 if (LHS.isInfinity() || LHS.isNaN()) {
2074 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2075 return Info.noteUndefinedBehavior();
2080 /// Cast an lvalue referring to a base subobject to a derived class, by
2081 /// truncating the lvalue's path to the given length.
2082 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2083 const RecordDecl *TruncatedType,
2084 unsigned TruncatedElements) {
2085 SubobjectDesignator &D = Result.Designator;
2087 // Check we actually point to a derived class object.
2088 if (TruncatedElements == D.Entries.size())
2090 assert(TruncatedElements >= D.MostDerivedPathLength &&
2091 "not casting to a derived class");
2092 if (!Result.checkSubobject(Info, E, CSK_Derived))
2095 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2096 const RecordDecl *RD = TruncatedType;
2097 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2098 if (RD->isInvalidDecl()) return false;
2099 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2100 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2101 if (isVirtualBaseClass(D.Entries[I]))
2102 Result.Offset -= Layout.getVBaseClassOffset(Base);
2104 Result.Offset -= Layout.getBaseClassOffset(Base);
2107 D.Entries.resize(TruncatedElements);
2111 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2112 const CXXRecordDecl *Derived,
2113 const CXXRecordDecl *Base,
2114 const ASTRecordLayout *RL = nullptr) {
2116 if (Derived->isInvalidDecl()) return false;
2117 RL = &Info.Ctx.getASTRecordLayout(Derived);
2120 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2121 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2125 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2126 const CXXRecordDecl *DerivedDecl,
2127 const CXXBaseSpecifier *Base) {
2128 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2130 if (!Base->isVirtual())
2131 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2133 SubobjectDesignator &D = Obj.Designator;
2137 // Extract most-derived object and corresponding type.
2138 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2139 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2142 // Find the virtual base class.
2143 if (DerivedDecl->isInvalidDecl()) return false;
2144 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2145 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2146 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2150 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2151 QualType Type, LValue &Result) {
2152 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2153 PathE = E->path_end();
2154 PathI != PathE; ++PathI) {
2155 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2158 Type = (*PathI)->getType();
2163 /// Update LVal to refer to the given field, which must be a member of the type
2164 /// currently described by LVal.
2165 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2166 const FieldDecl *FD,
2167 const ASTRecordLayout *RL = nullptr) {
2169 if (FD->getParent()->isInvalidDecl()) return false;
2170 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2173 unsigned I = FD->getFieldIndex();
2174 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2175 LVal.addDecl(Info, E, FD);
2179 /// Update LVal to refer to the given indirect field.
2180 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2182 const IndirectFieldDecl *IFD) {
2183 for (const auto *C : IFD->chain())
2184 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2189 /// Get the size of the given type in char units.
2190 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2191 QualType Type, CharUnits &Size) {
2192 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2194 if (Type->isVoidType() || Type->isFunctionType()) {
2195 Size = CharUnits::One();
2199 if (Type->isDependentType()) {
2204 if (!Type->isConstantSizeType()) {
2205 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2206 // FIXME: Better diagnostic.
2211 Size = Info.Ctx.getTypeSizeInChars(Type);
2215 /// Update a pointer value to model pointer arithmetic.
2216 /// \param Info - Information about the ongoing evaluation.
2217 /// \param E - The expression being evaluated, for diagnostic purposes.
2218 /// \param LVal - The pointer value to be updated.
2219 /// \param EltTy - The pointee type represented by LVal.
2220 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2221 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2222 LValue &LVal, QualType EltTy,
2223 int64_t Adjustment) {
2224 CharUnits SizeOfPointee;
2225 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2228 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2232 /// Update an lvalue to refer to a component of a complex number.
2233 /// \param Info - Information about the ongoing evaluation.
2234 /// \param LVal - The lvalue to be updated.
2235 /// \param EltTy - The complex number's component type.
2236 /// \param Imag - False for the real component, true for the imaginary.
2237 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2238 LValue &LVal, QualType EltTy,
2241 CharUnits SizeOfComponent;
2242 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2244 LVal.Offset += SizeOfComponent;
2246 LVal.addComplex(Info, E, EltTy, Imag);
2250 /// Try to evaluate the initializer for a variable declaration.
2252 /// \param Info Information about the ongoing evaluation.
2253 /// \param E An expression to be used when printing diagnostics.
2254 /// \param VD The variable whose initializer should be obtained.
2255 /// \param Frame The frame in which the variable was created. Must be null
2256 /// if this variable is not local to the evaluation.
2257 /// \param Result Filled in with a pointer to the value of the variable.
2258 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2259 const VarDecl *VD, CallStackFrame *Frame,
2261 // If this is a parameter to an active constexpr function call, perform
2262 // argument substitution.
2263 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2264 // Assume arguments of a potential constant expression are unknown
2265 // constant expressions.
2266 if (Info.checkingPotentialConstantExpression())
2268 if (!Frame || !Frame->Arguments) {
2269 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2272 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2276 // If this is a local variable, dig out its value.
2278 Result = Frame->getTemporary(VD);
2280 // Assume variables referenced within a lambda's call operator that were
2281 // not declared within the call operator are captures and during checking
2282 // of a potential constant expression, assume they are unknown constant
2284 assert(isLambdaCallOperator(Frame->Callee) &&
2285 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2286 "missing value for local variable");
2287 if (Info.checkingPotentialConstantExpression())
2289 // FIXME: implement capture evaluation during constant expr evaluation.
2290 Info.FFDiag(E->getLocStart(),
2291 diag::note_unimplemented_constexpr_lambda_feature_ast)
2292 << "captures not currently allowed";
2298 // Dig out the initializer, and use the declaration which it's attached to.
2299 const Expr *Init = VD->getAnyInitializer(VD);
2300 if (!Init || Init->isValueDependent()) {
2301 // If we're checking a potential constant expression, the variable could be
2302 // initialized later.
2303 if (!Info.checkingPotentialConstantExpression())
2304 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2308 // If we're currently evaluating the initializer of this declaration, use that
2310 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2311 Result = Info.EvaluatingDeclValue;
2315 // Never evaluate the initializer of a weak variable. We can't be sure that
2316 // this is the definition which will be used.
2318 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2322 // Check that we can fold the initializer. In C++, we will have already done
2323 // this in the cases where it matters for conformance.
2324 SmallVector<PartialDiagnosticAt, 8> Notes;
2325 if (!VD->evaluateValue(Notes)) {
2326 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2327 Notes.size() + 1) << VD;
2328 Info.Note(VD->getLocation(), diag::note_declared_at);
2329 Info.addNotes(Notes);
2331 } else if (!VD->checkInitIsICE()) {
2332 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2333 Notes.size() + 1) << VD;
2334 Info.Note(VD->getLocation(), diag::note_declared_at);
2335 Info.addNotes(Notes);
2338 Result = VD->getEvaluatedValue();
2342 static bool IsConstNonVolatile(QualType T) {
2343 Qualifiers Quals = T.getQualifiers();
2344 return Quals.hasConst() && !Quals.hasVolatile();
2347 /// Get the base index of the given base class within an APValue representing
2348 /// the given derived class.
2349 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2350 const CXXRecordDecl *Base) {
2351 Base = Base->getCanonicalDecl();
2353 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2354 E = Derived->bases_end(); I != E; ++I, ++Index) {
2355 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2359 llvm_unreachable("base class missing from derived class's bases list");
2362 /// Extract the value of a character from a string literal.
2363 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2365 // FIXME: Support MakeStringConstant
2366 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2368 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2369 assert(Index <= Str.size() && "Index too large");
2370 return APSInt::getUnsigned(Str.c_str()[Index]);
2373 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2374 Lit = PE->getFunctionName();
2375 const StringLiteral *S = cast<StringLiteral>(Lit);
2376 const ConstantArrayType *CAT =
2377 Info.Ctx.getAsConstantArrayType(S->getType());
2378 assert(CAT && "string literal isn't an array");
2379 QualType CharType = CAT->getElementType();
2380 assert(CharType->isIntegerType() && "unexpected character type");
2382 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2383 CharType->isUnsignedIntegerType());
2384 if (Index < S->getLength())
2385 Value = S->getCodeUnit(Index);
2389 // Expand a string literal into an array of characters.
2390 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2392 const StringLiteral *S = cast<StringLiteral>(Lit);
2393 const ConstantArrayType *CAT =
2394 Info.Ctx.getAsConstantArrayType(S->getType());
2395 assert(CAT && "string literal isn't an array");
2396 QualType CharType = CAT->getElementType();
2397 assert(CharType->isIntegerType() && "unexpected character type");
2399 unsigned Elts = CAT->getSize().getZExtValue();
2400 Result = APValue(APValue::UninitArray(),
2401 std::min(S->getLength(), Elts), Elts);
2402 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2403 CharType->isUnsignedIntegerType());
2404 if (Result.hasArrayFiller())
2405 Result.getArrayFiller() = APValue(Value);
2406 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2407 Value = S->getCodeUnit(I);
2408 Result.getArrayInitializedElt(I) = APValue(Value);
2412 // Expand an array so that it has more than Index filled elements.
2413 static void expandArray(APValue &Array, unsigned Index) {
2414 unsigned Size = Array.getArraySize();
2415 assert(Index < Size);
2417 // Always at least double the number of elements for which we store a value.
2418 unsigned OldElts = Array.getArrayInitializedElts();
2419 unsigned NewElts = std::max(Index+1, OldElts * 2);
2420 NewElts = std::min(Size, std::max(NewElts, 8u));
2422 // Copy the data across.
2423 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2424 for (unsigned I = 0; I != OldElts; ++I)
2425 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2426 for (unsigned I = OldElts; I != NewElts; ++I)
2427 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2428 if (NewValue.hasArrayFiller())
2429 NewValue.getArrayFiller() = Array.getArrayFiller();
2430 Array.swap(NewValue);
2433 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2434 /// conversion. If it's of class type, we may assume that the copy operation
2435 /// is trivial. Note that this is never true for a union type with fields
2436 /// (because the copy always "reads" the active member) and always true for
2437 /// a non-class type.
2438 static bool isReadByLvalueToRvalueConversion(QualType T) {
2439 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2440 if (!RD || (RD->isUnion() && !RD->field_empty()))
2445 for (auto *Field : RD->fields())
2446 if (isReadByLvalueToRvalueConversion(Field->getType()))
2449 for (auto &BaseSpec : RD->bases())
2450 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2456 /// Diagnose an attempt to read from any unreadable field within the specified
2457 /// type, which might be a class type.
2458 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2460 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2464 if (!RD->hasMutableFields())
2467 for (auto *Field : RD->fields()) {
2468 // If we're actually going to read this field in some way, then it can't
2469 // be mutable. If we're in a union, then assigning to a mutable field
2470 // (even an empty one) can change the active member, so that's not OK.
2471 // FIXME: Add core issue number for the union case.
2472 if (Field->isMutable() &&
2473 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2474 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2475 Info.Note(Field->getLocation(), diag::note_declared_at);
2479 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2483 for (auto &BaseSpec : RD->bases())
2484 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2487 // All mutable fields were empty, and thus not actually read.
2491 /// Kinds of access we can perform on an object, for diagnostics.
2500 /// A handle to a complete object (an object that is not a subobject of
2501 /// another object).
2502 struct CompleteObject {
2503 /// The value of the complete object.
2505 /// The type of the complete object.
2508 CompleteObject() : Value(nullptr) {}
2509 CompleteObject(APValue *Value, QualType Type)
2510 : Value(Value), Type(Type) {
2511 assert(Value && "missing value for complete object");
2514 explicit operator bool() const { return Value; }
2516 } // end anonymous namespace
2518 /// Find the designated sub-object of an rvalue.
2519 template<typename SubobjectHandler>
2520 typename SubobjectHandler::result_type
2521 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2522 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2524 // A diagnostic will have already been produced.
2525 return handler.failed();
2526 if (Sub.isOnePastTheEnd()) {
2527 if (Info.getLangOpts().CPlusPlus11)
2528 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2529 << handler.AccessKind;
2532 return handler.failed();
2535 APValue *O = Obj.Value;
2536 QualType ObjType = Obj.Type;
2537 const FieldDecl *LastField = nullptr;
2539 // Walk the designator's path to find the subobject.
2540 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2541 if (O->isUninit()) {
2542 if (!Info.checkingPotentialConstantExpression())
2543 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2544 return handler.failed();
2548 // If we are reading an object of class type, there may still be more
2549 // things we need to check: if there are any mutable subobjects, we
2550 // cannot perform this read. (This only happens when performing a trivial
2551 // copy or assignment.)
2552 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2553 diagnoseUnreadableFields(Info, E, ObjType))
2554 return handler.failed();
2556 if (!handler.found(*O, ObjType))
2559 // If we modified a bit-field, truncate it to the right width.
2560 if (handler.AccessKind != AK_Read &&
2561 LastField && LastField->isBitField() &&
2562 !truncateBitfieldValue(Info, E, *O, LastField))
2568 LastField = nullptr;
2569 if (ObjType->isArrayType()) {
2570 // Next subobject is an array element.
2571 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2572 assert(CAT && "vla in literal type?");
2573 uint64_t Index = Sub.Entries[I].ArrayIndex;
2574 if (CAT->getSize().ule(Index)) {
2575 // Note, it should not be possible to form a pointer with a valid
2576 // designator which points more than one past the end of the array.
2577 if (Info.getLangOpts().CPlusPlus11)
2578 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2579 << handler.AccessKind;
2582 return handler.failed();
2585 ObjType = CAT->getElementType();
2587 // An array object is represented as either an Array APValue or as an
2588 // LValue which refers to a string literal.
2589 if (O->isLValue()) {
2590 assert(I == N - 1 && "extracting subobject of character?");
2591 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2592 if (handler.AccessKind != AK_Read)
2593 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2596 return handler.foundString(*O, ObjType, Index);
2599 if (O->getArrayInitializedElts() > Index)
2600 O = &O->getArrayInitializedElt(Index);
2601 else if (handler.AccessKind != AK_Read) {
2602 expandArray(*O, Index);
2603 O = &O->getArrayInitializedElt(Index);
2605 O = &O->getArrayFiller();
2606 } else if (ObjType->isAnyComplexType()) {
2607 // Next subobject is a complex number.
2608 uint64_t Index = Sub.Entries[I].ArrayIndex;
2610 if (Info.getLangOpts().CPlusPlus11)
2611 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2612 << handler.AccessKind;
2615 return handler.failed();
2618 bool WasConstQualified = ObjType.isConstQualified();
2619 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2620 if (WasConstQualified)
2623 assert(I == N - 1 && "extracting subobject of scalar?");
2624 if (O->isComplexInt()) {
2625 return handler.found(Index ? O->getComplexIntImag()
2626 : O->getComplexIntReal(), ObjType);
2628 assert(O->isComplexFloat());
2629 return handler.found(Index ? O->getComplexFloatImag()
2630 : O->getComplexFloatReal(), ObjType);
2632 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2633 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2634 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2636 Info.Note(Field->getLocation(), diag::note_declared_at);
2637 return handler.failed();
2640 // Next subobject is a class, struct or union field.
2641 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2642 if (RD->isUnion()) {
2643 const FieldDecl *UnionField = O->getUnionField();
2645 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2646 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2647 << handler.AccessKind << Field << !UnionField << UnionField;
2648 return handler.failed();
2650 O = &O->getUnionValue();
2652 O = &O->getStructField(Field->getFieldIndex());
2654 bool WasConstQualified = ObjType.isConstQualified();
2655 ObjType = Field->getType();
2656 if (WasConstQualified && !Field->isMutable())
2659 if (ObjType.isVolatileQualified()) {
2660 if (Info.getLangOpts().CPlusPlus) {
2661 // FIXME: Include a description of the path to the volatile subobject.
2662 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2663 << handler.AccessKind << 2 << Field;
2664 Info.Note(Field->getLocation(), diag::note_declared_at);
2666 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2668 return handler.failed();
2673 // Next subobject is a base class.
2674 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2675 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2676 O = &O->getStructBase(getBaseIndex(Derived, Base));
2678 bool WasConstQualified = ObjType.isConstQualified();
2679 ObjType = Info.Ctx.getRecordType(Base);
2680 if (WasConstQualified)
2687 struct ExtractSubobjectHandler {
2691 static const AccessKinds AccessKind = AK_Read;
2693 typedef bool result_type;
2694 bool failed() { return false; }
2695 bool found(APValue &Subobj, QualType SubobjType) {
2699 bool found(APSInt &Value, QualType SubobjType) {
2700 Result = APValue(Value);
2703 bool found(APFloat &Value, QualType SubobjType) {
2704 Result = APValue(Value);
2707 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2708 Result = APValue(extractStringLiteralCharacter(
2709 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2713 } // end anonymous namespace
2715 const AccessKinds ExtractSubobjectHandler::AccessKind;
2717 /// Extract the designated sub-object of an rvalue.
2718 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2719 const CompleteObject &Obj,
2720 const SubobjectDesignator &Sub,
2722 ExtractSubobjectHandler Handler = { Info, Result };
2723 return findSubobject(Info, E, Obj, Sub, Handler);
2727 struct ModifySubobjectHandler {
2732 typedef bool result_type;
2733 static const AccessKinds AccessKind = AK_Assign;
2735 bool checkConst(QualType QT) {
2736 // Assigning to a const object has undefined behavior.
2737 if (QT.isConstQualified()) {
2738 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2744 bool failed() { return false; }
2745 bool found(APValue &Subobj, QualType SubobjType) {
2746 if (!checkConst(SubobjType))
2748 // We've been given ownership of NewVal, so just swap it in.
2749 Subobj.swap(NewVal);
2752 bool found(APSInt &Value, QualType SubobjType) {
2753 if (!checkConst(SubobjType))
2755 if (!NewVal.isInt()) {
2756 // Maybe trying to write a cast pointer value into a complex?
2760 Value = NewVal.getInt();
2763 bool found(APFloat &Value, QualType SubobjType) {
2764 if (!checkConst(SubobjType))
2766 Value = NewVal.getFloat();
2769 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2770 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2773 } // end anonymous namespace
2775 const AccessKinds ModifySubobjectHandler::AccessKind;
2777 /// Update the designated sub-object of an rvalue to the given value.
2778 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2779 const CompleteObject &Obj,
2780 const SubobjectDesignator &Sub,
2782 ModifySubobjectHandler Handler = { Info, NewVal, E };
2783 return findSubobject(Info, E, Obj, Sub, Handler);
2786 /// Find the position where two subobject designators diverge, or equivalently
2787 /// the length of the common initial subsequence.
2788 static unsigned FindDesignatorMismatch(QualType ObjType,
2789 const SubobjectDesignator &A,
2790 const SubobjectDesignator &B,
2791 bool &WasArrayIndex) {
2792 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2793 for (/**/; I != N; ++I) {
2794 if (!ObjType.isNull() &&
2795 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2796 // Next subobject is an array element.
2797 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2798 WasArrayIndex = true;
2801 if (ObjType->isAnyComplexType())
2802 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2804 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2806 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2807 WasArrayIndex = false;
2810 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2811 // Next subobject is a field.
2812 ObjType = FD->getType();
2814 // Next subobject is a base class.
2815 ObjType = QualType();
2818 WasArrayIndex = false;
2822 /// Determine whether the given subobject designators refer to elements of the
2823 /// same array object.
2824 static bool AreElementsOfSameArray(QualType ObjType,
2825 const SubobjectDesignator &A,
2826 const SubobjectDesignator &B) {
2827 if (A.Entries.size() != B.Entries.size())
2830 bool IsArray = A.MostDerivedIsArrayElement;
2831 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2832 // A is a subobject of the array element.
2835 // If A (and B) designates an array element, the last entry will be the array
2836 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2837 // of length 1' case, and the entire path must match.
2839 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2840 return CommonLength >= A.Entries.size() - IsArray;
2843 /// Find the complete object to which an LValue refers.
2844 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2845 AccessKinds AK, const LValue &LVal,
2846 QualType LValType) {
2848 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2849 return CompleteObject();
2852 CallStackFrame *Frame = nullptr;
2853 if (LVal.CallIndex) {
2854 Frame = Info.getCallFrame(LVal.CallIndex);
2856 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2857 << AK << LVal.Base.is<const ValueDecl*>();
2858 NoteLValueLocation(Info, LVal.Base);
2859 return CompleteObject();
2863 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2864 // is not a constant expression (even if the object is non-volatile). We also
2865 // apply this rule to C++98, in order to conform to the expected 'volatile'
2867 if (LValType.isVolatileQualified()) {
2868 if (Info.getLangOpts().CPlusPlus)
2869 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2873 return CompleteObject();
2876 // Compute value storage location and type of base object.
2877 APValue *BaseVal = nullptr;
2878 QualType BaseType = getType(LVal.Base);
2880 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2881 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2882 // In C++11, constexpr, non-volatile variables initialized with constant
2883 // expressions are constant expressions too. Inside constexpr functions,
2884 // parameters are constant expressions even if they're non-const.
2885 // In C++1y, objects local to a constant expression (those with a Frame) are
2886 // both readable and writable inside constant expressions.
2887 // In C, such things can also be folded, although they are not ICEs.
2888 const VarDecl *VD = dyn_cast<VarDecl>(D);
2890 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2893 if (!VD || VD->isInvalidDecl()) {
2895 return CompleteObject();
2898 // Accesses of volatile-qualified objects are not allowed.
2899 if (BaseType.isVolatileQualified()) {
2900 if (Info.getLangOpts().CPlusPlus) {
2901 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2903 Info.Note(VD->getLocation(), diag::note_declared_at);
2907 return CompleteObject();
2910 // Unless we're looking at a local variable or argument in a constexpr call,
2911 // the variable we're reading must be const.
2913 if (Info.getLangOpts().CPlusPlus14 &&
2914 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2915 // OK, we can read and modify an object if we're in the process of
2916 // evaluating its initializer, because its lifetime began in this
2918 } else if (AK != AK_Read) {
2919 // All the remaining cases only permit reading.
2920 Info.FFDiag(E, diag::note_constexpr_modify_global);
2921 return CompleteObject();
2922 } else if (VD->isConstexpr()) {
2923 // OK, we can read this variable.
2924 } else if (BaseType->isIntegralOrEnumerationType()) {
2925 // In OpenCL if a variable is in constant address space it is a const value.
2926 if (!(BaseType.isConstQualified() ||
2927 (Info.getLangOpts().OpenCL &&
2928 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
2929 if (Info.getLangOpts().CPlusPlus) {
2930 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2931 Info.Note(VD->getLocation(), diag::note_declared_at);
2935 return CompleteObject();
2937 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2938 // We support folding of const floating-point types, in order to make
2939 // static const data members of such types (supported as an extension)
2941 if (Info.getLangOpts().CPlusPlus11) {
2942 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2943 Info.Note(VD->getLocation(), diag::note_declared_at);
2947 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2948 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2949 // Keep evaluating to see what we can do.
2951 // FIXME: Allow folding of values of any literal type in all languages.
2952 if (Info.checkingPotentialConstantExpression() &&
2953 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2954 // The definition of this variable could be constexpr. We can't
2955 // access it right now, but may be able to in future.
2956 } else if (Info.getLangOpts().CPlusPlus11) {
2957 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2958 Info.Note(VD->getLocation(), diag::note_declared_at);
2962 return CompleteObject();
2966 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2967 return CompleteObject();
2969 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2972 if (const MaterializeTemporaryExpr *MTE =
2973 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2974 assert(MTE->getStorageDuration() == SD_Static &&
2975 "should have a frame for a non-global materialized temporary");
2977 // Per C++1y [expr.const]p2:
2978 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2979 // - a [...] glvalue of integral or enumeration type that refers to
2980 // a non-volatile const object [...]
2982 // - a [...] glvalue of literal type that refers to a non-volatile
2983 // object whose lifetime began within the evaluation of e.
2985 // C++11 misses the 'began within the evaluation of e' check and
2986 // instead allows all temporaries, including things like:
2989 // constexpr int k = r;
2990 // Therefore we use the C++1y rules in C++11 too.
2991 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2992 const ValueDecl *ED = MTE->getExtendingDecl();
2993 if (!(BaseType.isConstQualified() &&
2994 BaseType->isIntegralOrEnumerationType()) &&
2995 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2996 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2997 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2998 return CompleteObject();
3001 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3002 assert(BaseVal && "got reference to unevaluated temporary");
3005 return CompleteObject();
3008 BaseVal = Frame->getTemporary(Base);
3009 assert(BaseVal && "missing value for temporary");
3012 // Volatile temporary objects cannot be accessed in constant expressions.
3013 if (BaseType.isVolatileQualified()) {
3014 if (Info.getLangOpts().CPlusPlus) {
3015 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3017 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3021 return CompleteObject();
3025 // During the construction of an object, it is not yet 'const'.
3026 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3027 // and this doesn't do quite the right thing for const subobjects of the
3028 // object under construction.
3029 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3030 BaseType = Info.Ctx.getCanonicalType(BaseType);
3031 BaseType.removeLocalConst();
3034 // In C++1y, we can't safely access any mutable state when we might be
3035 // evaluating after an unmodeled side effect.
3037 // FIXME: Not all local state is mutable. Allow local constant subobjects
3038 // to be read here (but take care with 'mutable' fields).
3039 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3040 Info.EvalStatus.HasSideEffects) ||
3041 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3042 return CompleteObject();
3044 return CompleteObject(BaseVal, BaseType);
3047 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3048 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3049 /// glvalue referred to by an entity of reference type.
3051 /// \param Info - Information about the ongoing evaluation.
3052 /// \param Conv - The expression for which we are performing the conversion.
3053 /// Used for diagnostics.
3054 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3055 /// case of a non-class type).
3056 /// \param LVal - The glvalue on which we are attempting to perform this action.
3057 /// \param RVal - The produced value will be placed here.
3058 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3060 const LValue &LVal, APValue &RVal) {
3061 if (LVal.Designator.Invalid)
3064 // Check for special cases where there is no existing APValue to look at.
3065 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3066 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3067 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3068 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3069 // initializer until now for such expressions. Such an expression can't be
3070 // an ICE in C, so this only matters for fold.
3071 if (Type.isVolatileQualified()) {
3076 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3078 CompleteObject LitObj(&Lit, Base->getType());
3079 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3080 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3081 // We represent a string literal array as an lvalue pointing at the
3082 // corresponding expression, rather than building an array of chars.
3083 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3084 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3085 CompleteObject StrObj(&Str, Base->getType());
3086 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3090 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3091 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3094 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3095 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3096 QualType LValType, APValue &Val) {
3097 if (LVal.Designator.Invalid)
3100 if (!Info.getLangOpts().CPlusPlus14) {
3105 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3106 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3109 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3110 return T->isSignedIntegerType() &&
3111 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3115 struct CompoundAssignSubobjectHandler {
3118 QualType PromotedLHSType;
3119 BinaryOperatorKind Opcode;
3122 static const AccessKinds AccessKind = AK_Assign;
3124 typedef bool result_type;
3126 bool checkConst(QualType QT) {
3127 // Assigning to a const object has undefined behavior.
3128 if (QT.isConstQualified()) {
3129 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3135 bool failed() { return false; }
3136 bool found(APValue &Subobj, QualType SubobjType) {
3137 switch (Subobj.getKind()) {
3139 return found(Subobj.getInt(), SubobjType);
3140 case APValue::Float:
3141 return found(Subobj.getFloat(), SubobjType);
3142 case APValue::ComplexInt:
3143 case APValue::ComplexFloat:
3144 // FIXME: Implement complex compound assignment.
3147 case APValue::LValue:
3148 return foundPointer(Subobj, SubobjType);
3150 // FIXME: can this happen?
3155 bool found(APSInt &Value, QualType SubobjType) {
3156 if (!checkConst(SubobjType))
3159 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3160 // We don't support compound assignment on integer-cast-to-pointer
3166 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3168 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3170 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3173 bool found(APFloat &Value, QualType SubobjType) {
3174 return checkConst(SubobjType) &&
3175 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3177 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3178 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3180 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3181 if (!checkConst(SubobjType))
3184 QualType PointeeType;
3185 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3186 PointeeType = PT->getPointeeType();
3188 if (PointeeType.isNull() || !RHS.isInt() ||
3189 (Opcode != BO_Add && Opcode != BO_Sub)) {
3194 int64_t Offset = getExtValue(RHS.getInt());
3195 if (Opcode == BO_Sub)
3199 LVal.setFrom(Info.Ctx, Subobj);
3200 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3202 LVal.moveInto(Subobj);
3205 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3206 llvm_unreachable("shouldn't encounter string elements here");
3209 } // end anonymous namespace
3211 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3213 /// Perform a compound assignment of LVal <op>= RVal.
3214 static bool handleCompoundAssignment(
3215 EvalInfo &Info, const Expr *E,
3216 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3217 BinaryOperatorKind Opcode, const APValue &RVal) {
3218 if (LVal.Designator.Invalid)
3221 if (!Info.getLangOpts().CPlusPlus14) {
3226 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3227 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3229 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3233 struct IncDecSubobjectHandler {
3236 AccessKinds AccessKind;
3239 typedef bool result_type;
3241 bool checkConst(QualType QT) {
3242 // Assigning to a const object has undefined behavior.
3243 if (QT.isConstQualified()) {
3244 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3250 bool failed() { return false; }
3251 bool found(APValue &Subobj, QualType SubobjType) {
3252 // Stash the old value. Also clear Old, so we don't clobber it later
3253 // if we're post-incrementing a complex.
3259 switch (Subobj.getKind()) {
3261 return found(Subobj.getInt(), SubobjType);
3262 case APValue::Float:
3263 return found(Subobj.getFloat(), SubobjType);
3264 case APValue::ComplexInt:
3265 return found(Subobj.getComplexIntReal(),
3266 SubobjType->castAs<ComplexType>()->getElementType()
3267 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3268 case APValue::ComplexFloat:
3269 return found(Subobj.getComplexFloatReal(),
3270 SubobjType->castAs<ComplexType>()->getElementType()
3271 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3272 case APValue::LValue:
3273 return foundPointer(Subobj, SubobjType);
3275 // FIXME: can this happen?
3280 bool found(APSInt &Value, QualType SubobjType) {
3281 if (!checkConst(SubobjType))
3284 if (!SubobjType->isIntegerType()) {
3285 // We don't support increment / decrement on integer-cast-to-pointer
3291 if (Old) *Old = APValue(Value);
3293 // bool arithmetic promotes to int, and the conversion back to bool
3294 // doesn't reduce mod 2^n, so special-case it.
3295 if (SubobjType->isBooleanType()) {
3296 if (AccessKind == AK_Increment)
3303 bool WasNegative = Value.isNegative();
3304 if (AccessKind == AK_Increment) {
3307 if (!WasNegative && Value.isNegative() &&
3308 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3309 APSInt ActualValue(Value, /*IsUnsigned*/true);
3310 return HandleOverflow(Info, E, ActualValue, SubobjType);
3315 if (WasNegative && !Value.isNegative() &&
3316 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3317 unsigned BitWidth = Value.getBitWidth();
3318 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3319 ActualValue.setBit(BitWidth);
3320 return HandleOverflow(Info, E, ActualValue, SubobjType);
3325 bool found(APFloat &Value, QualType SubobjType) {
3326 if (!checkConst(SubobjType))
3329 if (Old) *Old = APValue(Value);
3331 APFloat One(Value.getSemantics(), 1);
3332 if (AccessKind == AK_Increment)
3333 Value.add(One, APFloat::rmNearestTiesToEven);
3335 Value.subtract(One, APFloat::rmNearestTiesToEven);
3338 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3339 if (!checkConst(SubobjType))
3342 QualType PointeeType;
3343 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3344 PointeeType = PT->getPointeeType();
3351 LVal.setFrom(Info.Ctx, Subobj);
3352 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3353 AccessKind == AK_Increment ? 1 : -1))
3355 LVal.moveInto(Subobj);
3358 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3359 llvm_unreachable("shouldn't encounter string elements here");
3362 } // end anonymous namespace
3364 /// Perform an increment or decrement on LVal.
3365 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3366 QualType LValType, bool IsIncrement, APValue *Old) {
3367 if (LVal.Designator.Invalid)
3370 if (!Info.getLangOpts().CPlusPlus14) {
3375 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3376 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3377 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3378 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3381 /// Build an lvalue for the object argument of a member function call.
3382 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3384 if (Object->getType()->isPointerType())
3385 return EvaluatePointer(Object, This, Info);
3387 if (Object->isGLValue())
3388 return EvaluateLValue(Object, This, Info);
3390 if (Object->getType()->isLiteralType(Info.Ctx))
3391 return EvaluateTemporary(Object, This, Info);
3393 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3397 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3398 /// lvalue referring to the result.
3400 /// \param Info - Information about the ongoing evaluation.
3401 /// \param LV - An lvalue referring to the base of the member pointer.
3402 /// \param RHS - The member pointer expression.
3403 /// \param IncludeMember - Specifies whether the member itself is included in
3404 /// the resulting LValue subobject designator. This is not possible when
3405 /// creating a bound member function.
3406 /// \return The field or method declaration to which the member pointer refers,
3407 /// or 0 if evaluation fails.
3408 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3412 bool IncludeMember = true) {
3414 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3417 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3418 // member value, the behavior is undefined.
3419 if (!MemPtr.getDecl()) {
3420 // FIXME: Specific diagnostic.
3425 if (MemPtr.isDerivedMember()) {
3426 // This is a member of some derived class. Truncate LV appropriately.
3427 // The end of the derived-to-base path for the base object must match the
3428 // derived-to-base path for the member pointer.
3429 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3430 LV.Designator.Entries.size()) {
3434 unsigned PathLengthToMember =
3435 LV.Designator.Entries.size() - MemPtr.Path.size();
3436 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3437 const CXXRecordDecl *LVDecl = getAsBaseClass(
3438 LV.Designator.Entries[PathLengthToMember + I]);
3439 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3440 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3446 // Truncate the lvalue to the appropriate derived class.
3447 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3448 PathLengthToMember))
3450 } else if (!MemPtr.Path.empty()) {
3451 // Extend the LValue path with the member pointer's path.
3452 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3453 MemPtr.Path.size() + IncludeMember);
3455 // Walk down to the appropriate base class.
3456 if (const PointerType *PT = LVType->getAs<PointerType>())
3457 LVType = PT->getPointeeType();
3458 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3459 assert(RD && "member pointer access on non-class-type expression");
3460 // The first class in the path is that of the lvalue.
3461 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3462 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3463 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3467 // Finally cast to the class containing the member.
3468 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3469 MemPtr.getContainingRecord()))
3473 // Add the member. Note that we cannot build bound member functions here.
3474 if (IncludeMember) {
3475 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3476 if (!HandleLValueMember(Info, RHS, LV, FD))
3478 } else if (const IndirectFieldDecl *IFD =
3479 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3480 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3483 llvm_unreachable("can't construct reference to bound member function");
3487 return MemPtr.getDecl();
3490 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3491 const BinaryOperator *BO,
3493 bool IncludeMember = true) {
3494 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3496 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3497 if (Info.noteFailure()) {
3499 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3504 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3505 BO->getRHS(), IncludeMember);
3508 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3509 /// the provided lvalue, which currently refers to the base object.
3510 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3512 SubobjectDesignator &D = Result.Designator;
3513 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3516 QualType TargetQT = E->getType();
3517 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3518 TargetQT = PT->getPointeeType();
3520 // Check this cast lands within the final derived-to-base subobject path.
3521 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3522 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3523 << D.MostDerivedType << TargetQT;
3527 // Check the type of the final cast. We don't need to check the path,
3528 // since a cast can only be formed if the path is unique.
3529 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3530 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3531 const CXXRecordDecl *FinalType;
3532 if (NewEntriesSize == D.MostDerivedPathLength)
3533 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3535 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3536 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3537 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3538 << D.MostDerivedType << TargetQT;
3542 // Truncate the lvalue to the appropriate derived class.
3543 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3547 enum EvalStmtResult {
3548 /// Evaluation failed.
3550 /// Hit a 'return' statement.
3552 /// Evaluation succeeded.
3554 /// Hit a 'continue' statement.
3556 /// Hit a 'break' statement.
3558 /// Still scanning for 'case' or 'default' statement.
3563 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3564 // We don't need to evaluate the initializer for a static local.
3565 if (!VD->hasLocalStorage())
3569 Result.set(VD, Info.CurrentCall->Index);
3570 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3572 const Expr *InitE = VD->getInit();
3574 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3575 << false << VD->getType();
3580 if (InitE->isValueDependent())
3583 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3584 // Wipe out any partially-computed value, to allow tracking that this
3585 // evaluation failed.
3593 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3596 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3597 OK &= EvaluateVarDecl(Info, VD);
3599 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3600 for (auto *BD : DD->bindings())
3601 if (auto *VD = BD->getHoldingVar())
3602 OK &= EvaluateDecl(Info, VD);
3608 /// Evaluate a condition (either a variable declaration or an expression).
3609 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3610 const Expr *Cond, bool &Result) {
3611 FullExpressionRAII Scope(Info);
3612 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3614 return EvaluateAsBooleanCondition(Cond, Result, Info);
3618 /// \brief A location where the result (returned value) of evaluating a
3619 /// statement should be stored.
3621 /// The APValue that should be filled in with the returned value.
3623 /// The location containing the result, if any (used to support RVO).
3628 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3630 const SwitchCase *SC = nullptr);
3632 /// Evaluate the body of a loop, and translate the result as appropriate.
3633 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3635 const SwitchCase *Case = nullptr) {
3636 BlockScopeRAII Scope(Info);
3637 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3639 return ESR_Succeeded;
3642 return ESR_Continue;
3645 case ESR_CaseNotFound:
3648 llvm_unreachable("Invalid EvalStmtResult!");
3651 /// Evaluate a switch statement.
3652 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3653 const SwitchStmt *SS) {
3654 BlockScopeRAII Scope(Info);
3656 // Evaluate the switch condition.
3659 FullExpressionRAII Scope(Info);
3660 if (const Stmt *Init = SS->getInit()) {
3661 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3662 if (ESR != ESR_Succeeded)
3665 if (SS->getConditionVariable() &&
3666 !EvaluateDecl(Info, SS->getConditionVariable()))
3668 if (!EvaluateInteger(SS->getCond(), Value, Info))
3672 // Find the switch case corresponding to the value of the condition.
3673 // FIXME: Cache this lookup.
3674 const SwitchCase *Found = nullptr;
3675 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3676 SC = SC->getNextSwitchCase()) {
3677 if (isa<DefaultStmt>(SC)) {
3682 const CaseStmt *CS = cast<CaseStmt>(SC);
3683 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3684 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3686 if (LHS <= Value && Value <= RHS) {
3693 return ESR_Succeeded;
3695 // Search the switch body for the switch case and evaluate it from there.
3696 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3698 return ESR_Succeeded;
3704 case ESR_CaseNotFound:
3705 // This can only happen if the switch case is nested within a statement
3706 // expression. We have no intention of supporting that.
3707 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3710 llvm_unreachable("Invalid EvalStmtResult!");
3713 // Evaluate a statement.
3714 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3715 const Stmt *S, const SwitchCase *Case) {
3716 if (!Info.nextStep(S))
3719 // If we're hunting down a 'case' or 'default' label, recurse through
3720 // substatements until we hit the label.
3722 // FIXME: We don't start the lifetime of objects whose initialization we
3723 // jump over. However, such objects must be of class type with a trivial
3724 // default constructor that initialize all subobjects, so must be empty,
3725 // so this almost never matters.
3726 switch (S->getStmtClass()) {
3727 case Stmt::CompoundStmtClass:
3728 // FIXME: Precompute which substatement of a compound statement we
3729 // would jump to, and go straight there rather than performing a
3730 // linear scan each time.
3731 case Stmt::LabelStmtClass:
3732 case Stmt::AttributedStmtClass:
3733 case Stmt::DoStmtClass:
3736 case Stmt::CaseStmtClass:
3737 case Stmt::DefaultStmtClass:
3742 case Stmt::IfStmtClass: {
3743 // FIXME: Precompute which side of an 'if' we would jump to, and go
3744 // straight there rather than scanning both sides.
3745 const IfStmt *IS = cast<IfStmt>(S);
3747 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3748 // preceded by our switch label.
3749 BlockScopeRAII Scope(Info);
3751 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3752 if (ESR != ESR_CaseNotFound || !IS->getElse())
3754 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3757 case Stmt::WhileStmtClass: {
3758 EvalStmtResult ESR =
3759 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3760 if (ESR != ESR_Continue)
3765 case Stmt::ForStmtClass: {
3766 const ForStmt *FS = cast<ForStmt>(S);
3767 EvalStmtResult ESR =
3768 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3769 if (ESR != ESR_Continue)
3772 FullExpressionRAII IncScope(Info);
3773 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3779 case Stmt::DeclStmtClass:
3780 // FIXME: If the variable has initialization that can't be jumped over,
3781 // bail out of any immediately-surrounding compound-statement too.
3783 return ESR_CaseNotFound;
3787 switch (S->getStmtClass()) {
3789 if (const Expr *E = dyn_cast<Expr>(S)) {
3790 // Don't bother evaluating beyond an expression-statement which couldn't
3792 FullExpressionRAII Scope(Info);
3793 if (!EvaluateIgnoredValue(Info, E))
3795 return ESR_Succeeded;
3798 Info.FFDiag(S->getLocStart());
3801 case Stmt::NullStmtClass:
3802 return ESR_Succeeded;
3804 case Stmt::DeclStmtClass: {
3805 const DeclStmt *DS = cast<DeclStmt>(S);
3806 for (const auto *DclIt : DS->decls()) {
3807 // Each declaration initialization is its own full-expression.
3808 // FIXME: This isn't quite right; if we're performing aggregate
3809 // initialization, each braced subexpression is its own full-expression.
3810 FullExpressionRAII Scope(Info);
3811 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3814 return ESR_Succeeded;
3817 case Stmt::ReturnStmtClass: {
3818 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3819 FullExpressionRAII Scope(Info);
3822 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3823 : Evaluate(Result.Value, Info, RetExpr)))
3825 return ESR_Returned;
3828 case Stmt::CompoundStmtClass: {
3829 BlockScopeRAII Scope(Info);
3831 const CompoundStmt *CS = cast<CompoundStmt>(S);
3832 for (const auto *BI : CS->body()) {
3833 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3834 if (ESR == ESR_Succeeded)
3836 else if (ESR != ESR_CaseNotFound)
3839 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3842 case Stmt::IfStmtClass: {
3843 const IfStmt *IS = cast<IfStmt>(S);
3845 // Evaluate the condition, as either a var decl or as an expression.
3846 BlockScopeRAII Scope(Info);
3847 if (const Stmt *Init = IS->getInit()) {
3848 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3849 if (ESR != ESR_Succeeded)
3853 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3856 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3857 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3858 if (ESR != ESR_Succeeded)
3861 return ESR_Succeeded;
3864 case Stmt::WhileStmtClass: {
3865 const WhileStmt *WS = cast<WhileStmt>(S);
3867 BlockScopeRAII Scope(Info);
3869 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3875 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3876 if (ESR != ESR_Continue)
3879 return ESR_Succeeded;
3882 case Stmt::DoStmtClass: {
3883 const DoStmt *DS = cast<DoStmt>(S);
3886 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3887 if (ESR != ESR_Continue)
3891 FullExpressionRAII CondScope(Info);
3892 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3895 return ESR_Succeeded;
3898 case Stmt::ForStmtClass: {
3899 const ForStmt *FS = cast<ForStmt>(S);
3900 BlockScopeRAII Scope(Info);
3901 if (FS->getInit()) {
3902 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3903 if (ESR != ESR_Succeeded)
3907 BlockScopeRAII Scope(Info);
3908 bool Continue = true;
3909 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3910 FS->getCond(), Continue))
3915 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3916 if (ESR != ESR_Continue)
3920 FullExpressionRAII IncScope(Info);
3921 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3925 return ESR_Succeeded;
3928 case Stmt::CXXForRangeStmtClass: {
3929 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3930 BlockScopeRAII Scope(Info);
3932 // Initialize the __range variable.
3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3934 if (ESR != ESR_Succeeded)
3937 // Create the __begin and __end iterators.
3938 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3939 if (ESR != ESR_Succeeded)
3941 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3942 if (ESR != ESR_Succeeded)
3946 // Condition: __begin != __end.
3948 bool Continue = true;
3949 FullExpressionRAII CondExpr(Info);
3950 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3956 // User's variable declaration, initialized by *__begin.
3957 BlockScopeRAII InnerScope(Info);
3958 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3959 if (ESR != ESR_Succeeded)
3963 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3964 if (ESR != ESR_Continue)
3967 // Increment: ++__begin
3968 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3972 return ESR_Succeeded;
3975 case Stmt::SwitchStmtClass:
3976 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3978 case Stmt::ContinueStmtClass:
3979 return ESR_Continue;
3981 case Stmt::BreakStmtClass:
3984 case Stmt::LabelStmtClass:
3985 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3987 case Stmt::AttributedStmtClass:
3988 // As a general principle, C++11 attributes can be ignored without
3989 // any semantic impact.
3990 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3993 case Stmt::CaseStmtClass:
3994 case Stmt::DefaultStmtClass:
3995 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3999 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4000 /// default constructor. If so, we'll fold it whether or not it's marked as
4001 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4002 /// so we need special handling.
4003 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4004 const CXXConstructorDecl *CD,
4005 bool IsValueInitialization) {
4006 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4009 // Value-initialization does not call a trivial default constructor, so such a
4010 // call is a core constant expression whether or not the constructor is
4012 if (!CD->isConstexpr() && !IsValueInitialization) {
4013 if (Info.getLangOpts().CPlusPlus11) {
4014 // FIXME: If DiagDecl is an implicitly-declared special member function,
4015 // we should be much more explicit about why it's not constexpr.
4016 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4017 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4018 Info.Note(CD->getLocation(), diag::note_declared_at);
4020 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4026 /// CheckConstexprFunction - Check that a function can be called in a constant
4028 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4029 const FunctionDecl *Declaration,
4030 const FunctionDecl *Definition,
4032 // Potential constant expressions can contain calls to declared, but not yet
4033 // defined, constexpr functions.
4034 if (Info.checkingPotentialConstantExpression() && !Definition &&
4035 Declaration->isConstexpr())
4038 // Bail out with no diagnostic if the function declaration itself is invalid.
4039 // We will have produced a relevant diagnostic while parsing it.
4040 if (Declaration->isInvalidDecl())
4043 // Can we evaluate this function call?
4044 if (Definition && Definition->isConstexpr() &&
4045 !Definition->isInvalidDecl() && Body)
4048 if (Info.getLangOpts().CPlusPlus11) {
4049 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4051 // If this function is not constexpr because it is an inherited
4052 // non-constexpr constructor, diagnose that directly.
4053 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4054 if (CD && CD->isInheritingConstructor()) {
4055 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4056 if (!Inherited->isConstexpr())
4057 DiagDecl = CD = Inherited;
4060 // FIXME: If DiagDecl is an implicitly-declared special member function
4061 // or an inheriting constructor, we should be much more explicit about why
4062 // it's not constexpr.
4063 if (CD && CD->isInheritingConstructor())
4064 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4065 << CD->getInheritedConstructor().getConstructor()->getParent();
4067 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4068 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4069 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4071 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4076 /// Determine if a class has any fields that might need to be copied by a
4077 /// trivial copy or move operation.
4078 static bool hasFields(const CXXRecordDecl *RD) {
4079 if (!RD || RD->isEmpty())
4081 for (auto *FD : RD->fields()) {
4082 if (FD->isUnnamedBitfield())
4086 for (auto &Base : RD->bases())
4087 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4093 typedef SmallVector<APValue, 8> ArgVector;
4096 /// EvaluateArgs - Evaluate the arguments to a function call.
4097 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4099 bool Success = true;
4100 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4102 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4103 // If we're checking for a potential constant expression, evaluate all
4104 // initializers even if some of them fail.
4105 if (!Info.noteFailure())
4113 /// Evaluate a function call.
4114 static bool HandleFunctionCall(SourceLocation CallLoc,
4115 const FunctionDecl *Callee, const LValue *This,
4116 ArrayRef<const Expr*> Args, const Stmt *Body,
4117 EvalInfo &Info, APValue &Result,
4118 const LValue *ResultSlot) {
4119 ArgVector ArgValues(Args.size());
4120 if (!EvaluateArgs(Args, ArgValues, Info))
4123 if (!Info.CheckCallLimit(CallLoc))
4126 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4128 // For a trivial copy or move assignment, perform an APValue copy. This is
4129 // essential for unions, where the operations performed by the assignment
4130 // operator cannot be represented as statements.
4132 // Skip this for non-union classes with no fields; in that case, the defaulted
4133 // copy/move does not actually read the object.
4134 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4135 if (MD && MD->isDefaulted() &&
4136 (MD->getParent()->isUnion() ||
4137 (MD->isTrivial() && hasFields(MD->getParent())))) {
4139 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4141 RHS.setFrom(Info.Ctx, ArgValues[0]);
4143 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4146 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4149 This->moveInto(Result);
4153 StmtResult Ret = {Result, ResultSlot};
4154 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4155 if (ESR == ESR_Succeeded) {
4156 if (Callee->getReturnType()->isVoidType())
4158 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4160 return ESR == ESR_Returned;
4163 /// Evaluate a constructor call.
4164 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4166 const CXXConstructorDecl *Definition,
4167 EvalInfo &Info, APValue &Result) {
4168 SourceLocation CallLoc = E->getExprLoc();
4169 if (!Info.CheckCallLimit(CallLoc))
4172 const CXXRecordDecl *RD = Definition->getParent();
4173 if (RD->getNumVBases()) {
4174 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4178 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4180 // FIXME: Creating an APValue just to hold a nonexistent return value is
4183 StmtResult Ret = {RetVal, nullptr};
4185 // If it's a delegating constructor, delegate.
4186 if (Definition->isDelegatingConstructor()) {
4187 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4189 FullExpressionRAII InitScope(Info);
4190 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4193 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4196 // For a trivial copy or move constructor, perform an APValue copy. This is
4197 // essential for unions (or classes with anonymous union members), where the
4198 // operations performed by the constructor cannot be represented by
4199 // ctor-initializers.
4201 // Skip this for empty non-union classes; we should not perform an
4202 // lvalue-to-rvalue conversion on them because their copy constructor does not
4203 // actually read them.
4204 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4205 (Definition->getParent()->isUnion() ||
4206 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4208 RHS.setFrom(Info.Ctx, ArgValues[0]);
4209 return handleLValueToRValueConversion(
4210 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4214 // Reserve space for the struct members.
4215 if (!RD->isUnion() && Result.isUninit())
4216 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4217 std::distance(RD->field_begin(), RD->field_end()));
4219 if (RD->isInvalidDecl()) return false;
4220 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4222 // A scope for temporaries lifetime-extended by reference members.
4223 BlockScopeRAII LifetimeExtendedScope(Info);
4225 bool Success = true;
4226 unsigned BasesSeen = 0;
4228 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4230 for (const auto *I : Definition->inits()) {
4231 LValue Subobject = This;
4232 APValue *Value = &Result;
4234 // Determine the subobject to initialize.
4235 FieldDecl *FD = nullptr;
4236 if (I->isBaseInitializer()) {
4237 QualType BaseType(I->getBaseClass(), 0);
4239 // Non-virtual base classes are initialized in the order in the class
4240 // definition. We have already checked for virtual base classes.
4241 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4242 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4243 "base class initializers not in expected order");
4246 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4247 BaseType->getAsCXXRecordDecl(), &Layout))
4249 Value = &Result.getStructBase(BasesSeen++);
4250 } else if ((FD = I->getMember())) {
4251 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4253 if (RD->isUnion()) {
4254 Result = APValue(FD);
4255 Value = &Result.getUnionValue();
4257 Value = &Result.getStructField(FD->getFieldIndex());
4259 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4260 // Walk the indirect field decl's chain to find the object to initialize,
4261 // and make sure we've initialized every step along it.
4262 for (auto *C : IFD->chain()) {
4263 FD = cast<FieldDecl>(C);
4264 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4265 // Switch the union field if it differs. This happens if we had
4266 // preceding zero-initialization, and we're now initializing a union
4267 // subobject other than the first.
4268 // FIXME: In this case, the values of the other subobjects are
4269 // specified, since zero-initialization sets all padding bits to zero.
4270 if (Value->isUninit() ||
4271 (Value->isUnion() && Value->getUnionField() != FD)) {
4273 *Value = APValue(FD);
4275 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4276 std::distance(CD->field_begin(), CD->field_end()));
4278 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4281 Value = &Value->getUnionValue();
4283 Value = &Value->getStructField(FD->getFieldIndex());
4286 llvm_unreachable("unknown base initializer kind");
4289 FullExpressionRAII InitScope(Info);
4290 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4291 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4293 // If we're checking for a potential constant expression, evaluate all
4294 // initializers even if some of them fail.
4295 if (!Info.noteFailure())
4302 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4305 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4306 ArrayRef<const Expr*> Args,
4307 const CXXConstructorDecl *Definition,
4308 EvalInfo &Info, APValue &Result) {
4309 ArgVector ArgValues(Args.size());
4310 if (!EvaluateArgs(Args, ArgValues, Info))
4313 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4317 //===----------------------------------------------------------------------===//
4318 // Generic Evaluation
4319 //===----------------------------------------------------------------------===//
4322 template <class Derived>
4323 class ExprEvaluatorBase
4324 : public ConstStmtVisitor<Derived, bool> {
4326 Derived &getDerived() { return static_cast<Derived&>(*this); }
4327 bool DerivedSuccess(const APValue &V, const Expr *E) {
4328 return getDerived().Success(V, E);
4330 bool DerivedZeroInitialization(const Expr *E) {
4331 return getDerived().ZeroInitialization(E);
4334 // Check whether a conditional operator with a non-constant condition is a
4335 // potential constant expression. If neither arm is a potential constant
4336 // expression, then the conditional operator is not either.
4337 template<typename ConditionalOperator>
4338 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4339 assert(Info.checkingPotentialConstantExpression());
4341 // Speculatively evaluate both arms.
4342 SmallVector<PartialDiagnosticAt, 8> Diag;
4344 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4345 StmtVisitorTy::Visit(E->getFalseExpr());
4351 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4353 StmtVisitorTy::Visit(E->getTrueExpr());
4358 Error(E, diag::note_constexpr_conditional_never_const);
4362 template<typename ConditionalOperator>
4363 bool HandleConditionalOperator(const ConditionalOperator *E) {
4365 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4366 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4367 CheckPotentialConstantConditional(E);
4371 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4372 return StmtVisitorTy::Visit(EvalExpr);
4377 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4378 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4380 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4381 return Info.CCEDiag(E, D);
4384 bool ZeroInitialization(const Expr *E) { return Error(E); }
4387 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4389 EvalInfo &getEvalInfo() { return Info; }
4391 /// Report an evaluation error. This should only be called when an error is
4392 /// first discovered. When propagating an error, just return false.
4393 bool Error(const Expr *E, diag::kind D) {
4397 bool Error(const Expr *E) {
4398 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4401 bool VisitStmt(const Stmt *) {
4402 llvm_unreachable("Expression evaluator should not be called on stmts");
4404 bool VisitExpr(const Expr *E) {
4408 bool VisitParenExpr(const ParenExpr *E)
4409 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4410 bool VisitUnaryExtension(const UnaryOperator *E)
4411 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4412 bool VisitUnaryPlus(const UnaryOperator *E)
4413 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4414 bool VisitChooseExpr(const ChooseExpr *E)
4415 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4416 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4417 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4418 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4419 { return StmtVisitorTy::Visit(E->getReplacement()); }
4420 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4421 { return StmtVisitorTy::Visit(E->getExpr()); }
4422 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4423 // The initializer may not have been parsed yet, or might be erroneous.
4426 return StmtVisitorTy::Visit(E->getExpr());
4428 // We cannot create any objects for which cleanups are required, so there is
4429 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4430 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4431 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4433 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4434 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4435 return static_cast<Derived*>(this)->VisitCastExpr(E);
4437 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4438 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4439 return static_cast<Derived*>(this)->VisitCastExpr(E);
4442 bool VisitBinaryOperator(const BinaryOperator *E) {
4443 switch (E->getOpcode()) {
4448 VisitIgnoredValue(E->getLHS());
4449 return StmtVisitorTy::Visit(E->getRHS());
4454 if (!HandleMemberPointerAccess(Info, E, Obj))
4457 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4459 return DerivedSuccess(Result, E);
4464 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4465 // Evaluate and cache the common expression. We treat it as a temporary,
4466 // even though it's not quite the same thing.
4467 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4468 Info, E->getCommon()))
4471 return HandleConditionalOperator(E);
4474 bool VisitConditionalOperator(const ConditionalOperator *E) {
4475 bool IsBcpCall = false;
4476 // If the condition (ignoring parens) is a __builtin_constant_p call,
4477 // the result is a constant expression if it can be folded without
4478 // side-effects. This is an important GNU extension. See GCC PR38377
4480 if (const CallExpr *CallCE =
4481 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4482 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4485 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4486 // constant expression; we can't check whether it's potentially foldable.
4487 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4490 FoldConstant Fold(Info, IsBcpCall);
4491 if (!HandleConditionalOperator(E)) {
4492 Fold.keepDiagnostics();
4499 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4500 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4501 return DerivedSuccess(*Value, E);
4503 const Expr *Source = E->getSourceExpr();
4506 if (Source == E) { // sanity checking.
4507 assert(0 && "OpaqueValueExpr recursively refers to itself");
4510 return StmtVisitorTy::Visit(Source);
4513 bool VisitCallExpr(const CallExpr *E) {
4515 if (!handleCallExpr(E, Result, nullptr))
4517 return DerivedSuccess(Result, E);
4520 bool handleCallExpr(const CallExpr *E, APValue &Result,
4521 const LValue *ResultSlot) {
4522 const Expr *Callee = E->getCallee()->IgnoreParens();
4523 QualType CalleeType = Callee->getType();
4525 const FunctionDecl *FD = nullptr;
4526 LValue *This = nullptr, ThisVal;
4527 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4528 bool HasQualifier = false;
4530 // Extract function decl and 'this' pointer from the callee.
4531 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4532 const ValueDecl *Member = nullptr;
4533 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4534 // Explicit bound member calls, such as x.f() or p->g();
4535 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4537 Member = ME->getMemberDecl();
4539 HasQualifier = ME->hasQualifier();
4540 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4541 // Indirect bound member calls ('.*' or '->*').
4542 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4543 if (!Member) return false;
4546 return Error(Callee);
4548 FD = dyn_cast<FunctionDecl>(Member);
4550 return Error(Callee);
4551 } else if (CalleeType->isFunctionPointerType()) {
4553 if (!EvaluatePointer(Callee, Call, Info))
4556 if (!Call.getLValueOffset().isZero())
4557 return Error(Callee);
4558 FD = dyn_cast_or_null<FunctionDecl>(
4559 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4561 return Error(Callee);
4562 // Don't call function pointers which have been cast to some other type.
4563 // Per DR (no number yet), the caller and callee can differ in noexcept.
4564 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4565 CalleeType->getPointeeType(), FD->getType())) {
4569 // Overloaded operator calls to member functions are represented as normal
4570 // calls with '*this' as the first argument.
4571 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4572 if (MD && !MD->isStatic()) {
4573 // FIXME: When selecting an implicit conversion for an overloaded
4574 // operator delete, we sometimes try to evaluate calls to conversion
4575 // operators without a 'this' parameter!
4579 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4582 Args = Args.slice(1);
4583 } else if (MD && MD->isLambdaStaticInvoker()) {
4584 // Map the static invoker for the lambda back to the call operator.
4585 // Conveniently, we don't have to slice out the 'this' argument (as is
4586 // being done for the non-static case), since a static member function
4587 // doesn't have an implicit argument passed in.
4588 const CXXRecordDecl *ClosureClass = MD->getParent();
4590 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4591 "Number of captures must be zero for conversion to function-ptr");
4593 const CXXMethodDecl *LambdaCallOp =
4594 ClosureClass->getLambdaCallOperator();
4596 // Set 'FD', the function that will be called below, to the call
4597 // operator. If the closure object represents a generic lambda, find
4598 // the corresponding specialization of the call operator.
4600 if (ClosureClass->isGenericLambda()) {
4601 assert(MD->isFunctionTemplateSpecialization() &&
4602 "A generic lambda's static-invoker function must be a "
4603 "template specialization");
4604 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4605 FunctionTemplateDecl *CallOpTemplate =
4606 LambdaCallOp->getDescribedFunctionTemplate();
4607 void *InsertPos = nullptr;
4608 FunctionDecl *CorrespondingCallOpSpecialization =
4609 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4610 assert(CorrespondingCallOpSpecialization &&
4611 "We must always have a function call operator specialization "
4612 "that corresponds to our static invoker specialization");
4613 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4622 if (This && !This->checkSubobject(Info, E, CSK_This))
4625 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4626 // calls to such functions in constant expressions.
4627 if (This && !HasQualifier &&
4628 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4629 return Error(E, diag::note_constexpr_virtual_call);
4631 const FunctionDecl *Definition = nullptr;
4632 Stmt *Body = FD->getBody(Definition);
4634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4635 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4636 Result, ResultSlot))
4642 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4643 return StmtVisitorTy::Visit(E->getInitializer());
4645 bool VisitInitListExpr(const InitListExpr *E) {
4646 if (E->getNumInits() == 0)
4647 return DerivedZeroInitialization(E);
4648 if (E->getNumInits() == 1)
4649 return StmtVisitorTy::Visit(E->getInit(0));
4652 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4653 return DerivedZeroInitialization(E);
4655 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4656 return DerivedZeroInitialization(E);
4658 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4659 return DerivedZeroInitialization(E);
4662 /// A member expression where the object is a prvalue is itself a prvalue.
4663 bool VisitMemberExpr(const MemberExpr *E) {
4664 assert(!E->isArrow() && "missing call to bound member function?");
4667 if (!Evaluate(Val, Info, E->getBase()))
4670 QualType BaseTy = E->getBase()->getType();
4672 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4673 if (!FD) return Error(E);
4674 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4675 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4676 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4678 CompleteObject Obj(&Val, BaseTy);
4679 SubobjectDesignator Designator(BaseTy);
4680 Designator.addDeclUnchecked(FD);
4683 return extractSubobject(Info, E, Obj, Designator, Result) &&
4684 DerivedSuccess(Result, E);
4687 bool VisitCastExpr(const CastExpr *E) {
4688 switch (E->getCastKind()) {
4692 case CK_AtomicToNonAtomic: {
4694 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4696 return DerivedSuccess(AtomicVal, E);
4700 case CK_UserDefinedConversion:
4701 return StmtVisitorTy::Visit(E->getSubExpr());
4703 case CK_LValueToRValue: {
4705 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4708 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4709 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4712 return DerivedSuccess(RVal, E);
4719 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4720 return VisitUnaryPostIncDec(UO);
4722 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4723 return VisitUnaryPostIncDec(UO);
4725 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4726 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4730 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4733 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4734 UO->isIncrementOp(), &RVal))
4736 return DerivedSuccess(RVal, UO);
4739 bool VisitStmtExpr(const StmtExpr *E) {
4740 // We will have checked the full-expressions inside the statement expression
4741 // when they were completed, and don't need to check them again now.
4742 if (Info.checkingForOverflow())
4745 BlockScopeRAII Scope(Info);
4746 const CompoundStmt *CS = E->getSubStmt();
4747 if (CS->body_empty())
4750 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4751 BE = CS->body_end();
4754 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4756 Info.FFDiag((*BI)->getLocStart(),
4757 diag::note_constexpr_stmt_expr_unsupported);
4760 return this->Visit(FinalExpr);
4763 APValue ReturnValue;
4764 StmtResult Result = { ReturnValue, nullptr };
4765 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4766 if (ESR != ESR_Succeeded) {
4767 // FIXME: If the statement-expression terminated due to 'return',
4768 // 'break', or 'continue', it would be nice to propagate that to
4769 // the outer statement evaluation rather than bailing out.
4770 if (ESR != ESR_Failed)
4771 Info.FFDiag((*BI)->getLocStart(),
4772 diag::note_constexpr_stmt_expr_unsupported);
4777 llvm_unreachable("Return from function from the loop above.");
4780 /// Visit a value which is evaluated, but whose value is ignored.
4781 void VisitIgnoredValue(const Expr *E) {
4782 EvaluateIgnoredValue(Info, E);
4785 /// Potentially visit a MemberExpr's base expression.
4786 void VisitIgnoredBaseExpression(const Expr *E) {
4787 // While MSVC doesn't evaluate the base expression, it does diagnose the
4788 // presence of side-effecting behavior.
4789 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4791 VisitIgnoredValue(E);
4797 //===----------------------------------------------------------------------===//
4798 // Common base class for lvalue and temporary evaluation.
4799 //===----------------------------------------------------------------------===//
4801 template<class Derived>
4802 class LValueExprEvaluatorBase
4803 : public ExprEvaluatorBase<Derived> {
4807 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4808 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4810 bool Success(APValue::LValueBase B) {
4815 bool evaluatePointer(const Expr *E, LValue &Result) {
4816 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4820 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4821 : ExprEvaluatorBaseTy(Info), Result(Result),
4822 InvalidBaseOK(InvalidBaseOK) {}
4824 bool Success(const APValue &V, const Expr *E) {
4825 Result.setFrom(this->Info.Ctx, V);
4829 bool VisitMemberExpr(const MemberExpr *E) {
4830 // Handle non-static data members.
4834 EvalOK = evaluatePointer(E->getBase(), Result);
4835 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4836 } else if (E->getBase()->isRValue()) {
4837 assert(E->getBase()->getType()->isRecordType());
4838 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4839 BaseTy = E->getBase()->getType();
4841 EvalOK = this->Visit(E->getBase());
4842 BaseTy = E->getBase()->getType();
4847 Result.setInvalid(E);
4851 const ValueDecl *MD = E->getMemberDecl();
4852 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4853 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4854 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4856 if (!HandleLValueMember(this->Info, E, Result, FD))
4858 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4859 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4862 return this->Error(E);
4864 if (MD->getType()->isReferenceType()) {
4866 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4869 return Success(RefValue, E);
4874 bool VisitBinaryOperator(const BinaryOperator *E) {
4875 switch (E->getOpcode()) {
4877 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4881 return HandleMemberPointerAccess(this->Info, E, Result);
4885 bool VisitCastExpr(const CastExpr *E) {
4886 switch (E->getCastKind()) {
4888 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4890 case CK_DerivedToBase:
4891 case CK_UncheckedDerivedToBase:
4892 if (!this->Visit(E->getSubExpr()))
4895 // Now figure out the necessary offset to add to the base LV to get from
4896 // the derived class to the base class.
4897 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4904 //===----------------------------------------------------------------------===//
4905 // LValue Evaluation
4907 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4908 // function designators (in C), decl references to void objects (in C), and
4909 // temporaries (if building with -Wno-address-of-temporary).
4911 // LValue evaluation produces values comprising a base expression of one of the
4917 // * CompoundLiteralExpr in C (and in global scope in C++)
4921 // * ObjCStringLiteralExpr
4925 // * CallExpr for a MakeStringConstant builtin
4926 // - Locals and temporaries
4927 // * MaterializeTemporaryExpr
4928 // * Any Expr, with a CallIndex indicating the function in which the temporary
4929 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4930 // from the AST (FIXME).
4931 // * A MaterializeTemporaryExpr that has static storage duration, with no
4932 // CallIndex, for a lifetime-extended temporary.
4933 // plus an offset in bytes.
4934 //===----------------------------------------------------------------------===//
4936 class LValueExprEvaluator
4937 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4939 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4940 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
4942 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4943 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4945 bool VisitDeclRefExpr(const DeclRefExpr *E);
4946 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4947 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4948 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4949 bool VisitMemberExpr(const MemberExpr *E);
4950 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4951 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4952 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4953 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4954 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4955 bool VisitUnaryDeref(const UnaryOperator *E);
4956 bool VisitUnaryReal(const UnaryOperator *E);
4957 bool VisitUnaryImag(const UnaryOperator *E);
4958 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4959 return VisitUnaryPreIncDec(UO);
4961 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4962 return VisitUnaryPreIncDec(UO);
4964 bool VisitBinAssign(const BinaryOperator *BO);
4965 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4967 bool VisitCastExpr(const CastExpr *E) {
4968 switch (E->getCastKind()) {
4970 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4972 case CK_LValueBitCast:
4973 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4974 if (!Visit(E->getSubExpr()))
4976 Result.Designator.setInvalid();
4979 case CK_BaseToDerived:
4980 if (!Visit(E->getSubExpr()))
4982 return HandleBaseToDerivedCast(Info, E, Result);
4986 } // end anonymous namespace
4988 /// Evaluate an expression as an lvalue. This can be legitimately called on
4989 /// expressions which are not glvalues, in three cases:
4990 /// * function designators in C, and
4991 /// * "extern void" objects
4992 /// * @selector() expressions in Objective-C
4993 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
4994 bool InvalidBaseOK) {
4995 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4996 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4997 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5000 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5001 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5003 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5004 return VisitVarDecl(E, VD);
5005 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5006 return Visit(BD->getBinding());
5011 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5012 CallStackFrame *Frame = nullptr;
5013 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5014 // Only if a local variable was declared in the function currently being
5015 // evaluated, do we expect to be able to find its value in the current
5016 // frame. (Otherwise it was likely declared in an enclosing context and
5017 // could either have a valid evaluatable value (for e.g. a constexpr
5018 // variable) or be ill-formed (and trigger an appropriate evaluation
5020 if (Info.CurrentCall->Callee &&
5021 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5022 Frame = Info.CurrentCall;
5026 if (!VD->getType()->isReferenceType()) {
5028 Result.set(VD, Frame->Index);
5035 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5037 if (V->isUninit()) {
5038 if (!Info.checkingPotentialConstantExpression())
5039 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5042 return Success(*V, E);
5045 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5046 const MaterializeTemporaryExpr *E) {
5047 // Walk through the expression to find the materialized temporary itself.
5048 SmallVector<const Expr *, 2> CommaLHSs;
5049 SmallVector<SubobjectAdjustment, 2> Adjustments;
5050 const Expr *Inner = E->GetTemporaryExpr()->
5051 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5053 // If we passed any comma operators, evaluate their LHSs.
5054 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5055 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5058 // A materialized temporary with static storage duration can appear within the
5059 // result of a constant expression evaluation, so we need to preserve its
5060 // value for use outside this evaluation.
5062 if (E->getStorageDuration() == SD_Static) {
5063 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5067 Value = &Info.CurrentCall->
5068 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5069 Result.set(E, Info.CurrentCall->Index);
5072 QualType Type = Inner->getType();
5074 // Materialize the temporary itself.
5075 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5076 (E->getStorageDuration() == SD_Static &&
5077 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5082 // Adjust our lvalue to refer to the desired subobject.
5083 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5085 switch (Adjustments[I].Kind) {
5086 case SubobjectAdjustment::DerivedToBaseAdjustment:
5087 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5090 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5093 case SubobjectAdjustment::FieldAdjustment:
5094 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5096 Type = Adjustments[I].Field->getType();
5099 case SubobjectAdjustment::MemberPointerAdjustment:
5100 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5101 Adjustments[I].Ptr.RHS))
5103 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5112 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5113 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5114 "lvalue compound literal in c++?");
5115 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5116 // only see this when folding in C, so there's no standard to follow here.
5120 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5121 if (!E->isPotentiallyEvaluated())
5124 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5125 << E->getExprOperand()->getType()
5126 << E->getExprOperand()->getSourceRange();
5130 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5134 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5135 // Handle static data members.
5136 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5137 VisitIgnoredBaseExpression(E->getBase());
5138 return VisitVarDecl(E, VD);
5141 // Handle static member functions.
5142 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5143 if (MD->isStatic()) {
5144 VisitIgnoredBaseExpression(E->getBase());
5149 // Handle non-static data members.
5150 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5153 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5154 // FIXME: Deal with vectors as array subscript bases.
5155 if (E->getBase()->getType()->isVectorType())
5158 if (!evaluatePointer(E->getBase(), Result))
5162 if (!EvaluateInteger(E->getIdx(), Index, Info))
5165 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5166 getExtValue(Index));
5169 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5170 return evaluatePointer(E->getSubExpr(), Result);
5173 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5174 if (!Visit(E->getSubExpr()))
5176 // __real is a no-op on scalar lvalues.
5177 if (E->getSubExpr()->getType()->isAnyComplexType())
5178 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5182 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5183 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5184 "lvalue __imag__ on scalar?");
5185 if (!Visit(E->getSubExpr()))
5187 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5191 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5192 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5195 if (!this->Visit(UO->getSubExpr()))
5198 return handleIncDec(
5199 this->Info, UO, Result, UO->getSubExpr()->getType(),
5200 UO->isIncrementOp(), nullptr);
5203 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5204 const CompoundAssignOperator *CAO) {
5205 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5210 // The overall lvalue result is the result of evaluating the LHS.
5211 if (!this->Visit(CAO->getLHS())) {
5212 if (Info.noteFailure())
5213 Evaluate(RHS, this->Info, CAO->getRHS());
5217 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5220 return handleCompoundAssignment(
5222 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5223 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5226 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5227 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5232 if (!this->Visit(E->getLHS())) {
5233 if (Info.noteFailure())
5234 Evaluate(NewVal, this->Info, E->getRHS());
5238 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5241 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5245 //===----------------------------------------------------------------------===//
5246 // Pointer Evaluation
5247 //===----------------------------------------------------------------------===//
5249 /// \brief Attempts to compute the number of bytes available at the pointer
5250 /// returned by a function with the alloc_size attribute. Returns true if we
5251 /// were successful. Places an unsigned number into `Result`.
5253 /// This expects the given CallExpr to be a call to a function with an
5254 /// alloc_size attribute.
5255 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5256 const CallExpr *Call,
5257 llvm::APInt &Result) {
5258 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5260 // alloc_size args are 1-indexed, 0 means not present.
5261 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5262 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5263 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5264 if (Call->getNumArgs() <= SizeArgNo)
5267 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5268 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5270 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5272 Into = Into.zextOrSelf(BitsInSizeT);
5277 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5280 if (!AllocSize->getNumElemsParam()) {
5281 Result = std::move(SizeOfElem);
5285 APSInt NumberOfElems;
5286 // Argument numbers start at 1
5287 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5288 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5292 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5296 Result = std::move(BytesAvailable);
5300 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5302 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5304 llvm::APInt &Result) {
5305 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5306 "Can't get the size of a non alloc_size function");
5307 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5308 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5309 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5312 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5313 /// a function with the alloc_size attribute. If it was possible to do so, this
5314 /// function will return true, make Result's Base point to said function call,
5315 /// and mark Result's Base as invalid.
5316 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5321 // Because we do no form of static analysis, we only support const variables.
5323 // Additionally, we can't support parameters, nor can we support static
5324 // variables (in the latter case, use-before-assign isn't UB; in the former,
5325 // we have no clue what they'll be assigned to).
5327 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5328 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5331 const Expr *Init = VD->getAnyInitializer();
5335 const Expr *E = Init->IgnoreParens();
5336 if (!tryUnwrapAllocSizeCall(E))
5339 // Store E instead of E unwrapped so that the type of the LValue's base is
5340 // what the user wanted.
5341 Result.setInvalid(E);
5343 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5344 Result.addUnsizedArray(Info, Pointee);
5349 class PointerExprEvaluator
5350 : public ExprEvaluatorBase<PointerExprEvaluator> {
5354 bool Success(const Expr *E) {
5359 bool evaluateLValue(const Expr *E, LValue &Result) {
5360 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5363 bool evaluatePointer(const Expr *E, LValue &Result) {
5364 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5367 bool visitNonBuiltinCallExpr(const CallExpr *E);
5370 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5371 : ExprEvaluatorBaseTy(info), Result(Result),
5372 InvalidBaseOK(InvalidBaseOK) {}
5374 bool Success(const APValue &V, const Expr *E) {
5375 Result.setFrom(Info.Ctx, V);
5378 bool ZeroInitialization(const Expr *E) {
5379 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5380 Result.set((Expr*)nullptr, 0, false, true, Offset);
5384 bool VisitBinaryOperator(const BinaryOperator *E);
5385 bool VisitCastExpr(const CastExpr* E);
5386 bool VisitUnaryAddrOf(const UnaryOperator *E);
5387 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5388 { return Success(E); }
5389 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5390 { return Success(E); }
5391 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5392 { return Success(E); }
5393 bool VisitCallExpr(const CallExpr *E);
5394 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5395 bool VisitBlockExpr(const BlockExpr *E) {
5396 if (!E->getBlockDecl()->hasCaptures())
5400 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5401 // Can't look at 'this' when checking a potential constant expression.
5402 if (Info.checkingPotentialConstantExpression())
5404 if (!Info.CurrentCall->This) {
5405 if (Info.getLangOpts().CPlusPlus11)
5406 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5411 Result = *Info.CurrentCall->This;
5415 // FIXME: Missing: @protocol, @selector
5417 } // end anonymous namespace
5419 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5420 bool InvalidBaseOK) {
5421 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5422 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5425 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5426 if (E->getOpcode() != BO_Add &&
5427 E->getOpcode() != BO_Sub)
5428 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5430 const Expr *PExp = E->getLHS();
5431 const Expr *IExp = E->getRHS();
5432 if (IExp->getType()->isPointerType())
5433 std::swap(PExp, IExp);
5435 bool EvalPtrOK = evaluatePointer(PExp, Result);
5436 if (!EvalPtrOK && !Info.noteFailure())
5439 llvm::APSInt Offset;
5440 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5443 int64_t AdditionalOffset = getExtValue(Offset);
5444 if (E->getOpcode() == BO_Sub)
5445 AdditionalOffset = -AdditionalOffset;
5447 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5448 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5452 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5453 return evaluateLValue(E->getSubExpr(), Result);
5456 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5457 const Expr* SubExpr = E->getSubExpr();
5459 switch (E->getCastKind()) {
5464 case CK_CPointerToObjCPointerCast:
5465 case CK_BlockPointerToObjCPointerCast:
5466 case CK_AnyPointerToBlockPointerCast:
5467 case CK_AddressSpaceConversion:
5468 if (!Visit(SubExpr))
5470 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5471 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5472 // also static_casts, but we disallow them as a resolution to DR1312.
5473 if (!E->getType()->isVoidPointerType()) {
5474 Result.Designator.setInvalid();
5475 if (SubExpr->getType()->isVoidPointerType())
5476 CCEDiag(E, diag::note_constexpr_invalid_cast)
5477 << 3 << SubExpr->getType();
5479 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5481 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5482 ZeroInitialization(E);
5485 case CK_DerivedToBase:
5486 case CK_UncheckedDerivedToBase:
5487 if (!evaluatePointer(E->getSubExpr(), Result))
5489 if (!Result.Base && Result.Offset.isZero())
5492 // Now figure out the necessary offset to add to the base LV to get from
5493 // the derived class to the base class.
5494 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5495 castAs<PointerType>()->getPointeeType(),
5498 case CK_BaseToDerived:
5499 if (!Visit(E->getSubExpr()))
5501 if (!Result.Base && Result.Offset.isZero())
5503 return HandleBaseToDerivedCast(Info, E, Result);
5505 case CK_NullToPointer:
5506 VisitIgnoredValue(E->getSubExpr());
5507 return ZeroInitialization(E);
5509 case CK_IntegralToPointer: {
5510 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5513 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5516 if (Value.isInt()) {
5517 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5518 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5519 Result.Base = (Expr*)nullptr;
5520 Result.InvalidBase = false;
5521 Result.Offset = CharUnits::fromQuantity(N);
5522 Result.CallIndex = 0;
5523 Result.Designator.setInvalid();
5524 Result.IsNullPtr = false;
5527 // Cast is of an lvalue, no need to change value.
5528 Result.setFrom(Info.Ctx, Value);
5532 case CK_ArrayToPointerDecay:
5533 if (SubExpr->isGLValue()) {
5534 if (!evaluateLValue(SubExpr, Result))
5537 Result.set(SubExpr, Info.CurrentCall->Index);
5538 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5539 Info, Result, SubExpr))
5542 // The result is a pointer to the first element of the array.
5543 if (const ConstantArrayType *CAT
5544 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5545 Result.addArray(Info, E, CAT);
5547 Result.Designator.setInvalid();
5550 case CK_FunctionToPointerDecay:
5551 return evaluateLValue(SubExpr, Result);
5553 case CK_LValueToRValue: {
5555 if (!evaluateLValue(E->getSubExpr(), LVal))
5559 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5560 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5562 return InvalidBaseOK &&
5563 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5564 return Success(RVal, E);
5568 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5571 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5572 // C++ [expr.alignof]p3:
5573 // When alignof is applied to a reference type, the result is the
5574 // alignment of the referenced type.
5575 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5576 T = Ref->getPointeeType();
5578 // __alignof is defined to return the preferred alignment.
5579 return Info.Ctx.toCharUnitsFromBits(
5580 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5583 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5584 E = E->IgnoreParens();
5586 // The kinds of expressions that we have special-case logic here for
5587 // should be kept up to date with the special checks for those
5588 // expressions in Sema.
5590 // alignof decl is always accepted, even if it doesn't make sense: we default
5591 // to 1 in those cases.
5592 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5593 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5594 /*RefAsPointee*/true);
5596 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5597 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5598 /*RefAsPointee*/true);
5600 return GetAlignOfType(Info, E->getType());
5603 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5604 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5605 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5608 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5611 Result.setInvalid(E);
5612 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5613 Result.addUnsizedArray(Info, PointeeTy);
5617 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5618 if (IsStringLiteralCall(E))
5621 if (unsigned BuiltinOp = E->getBuiltinCallee())
5622 return VisitBuiltinCallExpr(E, BuiltinOp);
5624 return visitNonBuiltinCallExpr(E);
5627 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5628 unsigned BuiltinOp) {
5629 switch (BuiltinOp) {
5630 case Builtin::BI__builtin_addressof:
5631 return evaluateLValue(E->getArg(0), Result);
5632 case Builtin::BI__builtin_assume_aligned: {
5633 // We need to be very careful here because: if the pointer does not have the
5634 // asserted alignment, then the behavior is undefined, and undefined
5635 // behavior is non-constant.
5636 if (!evaluatePointer(E->getArg(0), Result))
5639 LValue OffsetResult(Result);
5641 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5643 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5645 if (E->getNumArgs() > 2) {
5647 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5650 int64_t AdditionalOffset = -getExtValue(Offset);
5651 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5654 // If there is a base object, then it must have the correct alignment.
5655 if (OffsetResult.Base) {
5656 CharUnits BaseAlignment;
5657 if (const ValueDecl *VD =
5658 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5659 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5662 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5665 if (BaseAlignment < Align) {
5666 Result.Designator.setInvalid();
5667 // FIXME: Quantities here cast to integers because the plural modifier
5668 // does not work on APSInts yet.
5669 CCEDiag(E->getArg(0),
5670 diag::note_constexpr_baa_insufficient_alignment) << 0
5671 << (int) BaseAlignment.getQuantity()
5672 << (unsigned) getExtValue(Alignment);
5677 // The offset must also have the correct alignment.
5678 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5679 Result.Designator.setInvalid();
5680 APSInt Offset(64, false);
5681 Offset = OffsetResult.Offset.getQuantity();
5683 if (OffsetResult.Base)
5684 CCEDiag(E->getArg(0),
5685 diag::note_constexpr_baa_insufficient_alignment) << 1
5686 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5688 CCEDiag(E->getArg(0),
5689 diag::note_constexpr_baa_value_insufficient_alignment)
5690 << Offset << (unsigned) getExtValue(Alignment);
5698 case Builtin::BIstrchr:
5699 case Builtin::BIwcschr:
5700 case Builtin::BImemchr:
5701 case Builtin::BIwmemchr:
5702 if (Info.getLangOpts().CPlusPlus11)
5703 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5704 << /*isConstexpr*/0 << /*isConstructor*/0
5705 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5707 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5709 case Builtin::BI__builtin_strchr:
5710 case Builtin::BI__builtin_wcschr:
5711 case Builtin::BI__builtin_memchr:
5712 case Builtin::BI__builtin_char_memchr:
5713 case Builtin::BI__builtin_wmemchr: {
5714 if (!Visit(E->getArg(0)))
5717 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5719 uint64_t MaxLength = uint64_t(-1);
5720 if (BuiltinOp != Builtin::BIstrchr &&
5721 BuiltinOp != Builtin::BIwcschr &&
5722 BuiltinOp != Builtin::BI__builtin_strchr &&
5723 BuiltinOp != Builtin::BI__builtin_wcschr) {
5725 if (!EvaluateInteger(E->getArg(2), N, Info))
5727 MaxLength = N.getExtValue();
5730 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5732 // Figure out what value we're actually looking for (after converting to
5733 // the corresponding unsigned type if necessary).
5734 uint64_t DesiredVal;
5735 bool StopAtNull = false;
5736 switch (BuiltinOp) {
5737 case Builtin::BIstrchr:
5738 case Builtin::BI__builtin_strchr:
5739 // strchr compares directly to the passed integer, and therefore
5740 // always fails if given an int that is not a char.
5741 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5742 E->getArg(1)->getType(),
5745 return ZeroInitialization(E);
5748 case Builtin::BImemchr:
5749 case Builtin::BI__builtin_memchr:
5750 case Builtin::BI__builtin_char_memchr:
5751 // memchr compares by converting both sides to unsigned char. That's also
5752 // correct for strchr if we get this far (to cope with plain char being
5753 // unsigned in the strchr case).
5754 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5757 case Builtin::BIwcschr:
5758 case Builtin::BI__builtin_wcschr:
5761 case Builtin::BIwmemchr:
5762 case Builtin::BI__builtin_wmemchr:
5763 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5764 DesiredVal = Desired.getZExtValue();
5768 for (; MaxLength; --MaxLength) {
5770 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5773 if (Char.getInt().getZExtValue() == DesiredVal)
5775 if (StopAtNull && !Char.getInt())
5777 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5780 // Not found: return nullptr.
5781 return ZeroInitialization(E);
5785 return visitNonBuiltinCallExpr(E);
5789 //===----------------------------------------------------------------------===//
5790 // Member Pointer Evaluation
5791 //===----------------------------------------------------------------------===//
5794 class MemberPointerExprEvaluator
5795 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5798 bool Success(const ValueDecl *D) {
5799 Result = MemberPtr(D);
5804 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5805 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5807 bool Success(const APValue &V, const Expr *E) {
5811 bool ZeroInitialization(const Expr *E) {
5812 return Success((const ValueDecl*)nullptr);
5815 bool VisitCastExpr(const CastExpr *E);
5816 bool VisitUnaryAddrOf(const UnaryOperator *E);
5818 } // end anonymous namespace
5820 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5822 assert(E->isRValue() && E->getType()->isMemberPointerType());
5823 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5826 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5827 switch (E->getCastKind()) {
5829 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5831 case CK_NullToMemberPointer:
5832 VisitIgnoredValue(E->getSubExpr());
5833 return ZeroInitialization(E);
5835 case CK_BaseToDerivedMemberPointer: {
5836 if (!Visit(E->getSubExpr()))
5838 if (E->path_empty())
5840 // Base-to-derived member pointer casts store the path in derived-to-base
5841 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5842 // the wrong end of the derived->base arc, so stagger the path by one class.
5843 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5844 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5845 PathI != PathE; ++PathI) {
5846 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5847 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5848 if (!Result.castToDerived(Derived))
5851 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5852 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5857 case CK_DerivedToBaseMemberPointer:
5858 if (!Visit(E->getSubExpr()))
5860 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5861 PathE = E->path_end(); PathI != PathE; ++PathI) {
5862 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5863 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5864 if (!Result.castToBase(Base))
5871 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5872 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5873 // member can be formed.
5874 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5877 //===----------------------------------------------------------------------===//
5878 // Record Evaluation
5879 //===----------------------------------------------------------------------===//
5882 class RecordExprEvaluator
5883 : public ExprEvaluatorBase<RecordExprEvaluator> {
5888 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5889 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5891 bool Success(const APValue &V, const Expr *E) {
5895 bool ZeroInitialization(const Expr *E) {
5896 return ZeroInitialization(E, E->getType());
5898 bool ZeroInitialization(const Expr *E, QualType T);
5900 bool VisitCallExpr(const CallExpr *E) {
5901 return handleCallExpr(E, Result, &This);
5903 bool VisitCastExpr(const CastExpr *E);
5904 bool VisitInitListExpr(const InitListExpr *E);
5905 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5906 return VisitCXXConstructExpr(E, E->getType());
5908 bool VisitLambdaExpr(const LambdaExpr *E);
5909 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
5910 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
5911 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5915 /// Perform zero-initialization on an object of non-union class type.
5916 /// C++11 [dcl.init]p5:
5917 /// To zero-initialize an object or reference of type T means:
5919 /// -- if T is a (possibly cv-qualified) non-union class type,
5920 /// each non-static data member and each base-class subobject is
5921 /// zero-initialized
5922 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5923 const RecordDecl *RD,
5924 const LValue &This, APValue &Result) {
5925 assert(!RD->isUnion() && "Expected non-union class type");
5926 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5927 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5928 std::distance(RD->field_begin(), RD->field_end()));
5930 if (RD->isInvalidDecl()) return false;
5931 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5935 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5936 End = CD->bases_end(); I != End; ++I, ++Index) {
5937 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5938 LValue Subobject = This;
5939 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5941 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5942 Result.getStructBase(Index)))
5947 for (const auto *I : RD->fields()) {
5948 // -- if T is a reference type, no initialization is performed.
5949 if (I->getType()->isReferenceType())
5952 LValue Subobject = This;
5953 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5956 ImplicitValueInitExpr VIE(I->getType());
5957 if (!EvaluateInPlace(
5958 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5965 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5966 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5967 if (RD->isInvalidDecl()) return false;
5968 if (RD->isUnion()) {
5969 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5970 // object's first non-static named data member is zero-initialized
5971 RecordDecl::field_iterator I = RD->field_begin();
5972 if (I == RD->field_end()) {
5973 Result = APValue((const FieldDecl*)nullptr);
5977 LValue Subobject = This;
5978 if (!HandleLValueMember(Info, E, Subobject, *I))
5980 Result = APValue(*I);
5981 ImplicitValueInitExpr VIE(I->getType());
5982 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5985 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5986 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
5990 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5993 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5994 switch (E->getCastKind()) {
5996 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5998 case CK_ConstructorConversion:
5999 return Visit(E->getSubExpr());
6001 case CK_DerivedToBase:
6002 case CK_UncheckedDerivedToBase: {
6003 APValue DerivedObject;
6004 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6006 if (!DerivedObject.isStruct())
6007 return Error(E->getSubExpr());
6009 // Derived-to-base rvalue conversion: just slice off the derived part.
6010 APValue *Value = &DerivedObject;
6011 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6012 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6013 PathE = E->path_end(); PathI != PathE; ++PathI) {
6014 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6015 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6016 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6025 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6026 if (E->isTransparent())
6027 return Visit(E->getInit(0));
6029 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6030 if (RD->isInvalidDecl()) return false;
6031 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6033 if (RD->isUnion()) {
6034 const FieldDecl *Field = E->getInitializedFieldInUnion();
6035 Result = APValue(Field);
6039 // If the initializer list for a union does not contain any elements, the
6040 // first element of the union is value-initialized.
6041 // FIXME: The element should be initialized from an initializer list.
6042 // Is this difference ever observable for initializer lists which
6044 ImplicitValueInitExpr VIE(Field->getType());
6045 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6047 LValue Subobject = This;
6048 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6051 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6052 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6053 isa<CXXDefaultInitExpr>(InitExpr));
6055 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6058 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6059 if (Result.isUninit())
6060 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6061 std::distance(RD->field_begin(), RD->field_end()));
6062 unsigned ElementNo = 0;
6063 bool Success = true;
6065 // Initialize base classes.
6067 for (const auto &Base : CXXRD->bases()) {
6068 assert(ElementNo < E->getNumInits() && "missing init for base class");
6069 const Expr *Init = E->getInit(ElementNo);
6071 LValue Subobject = This;
6072 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6075 APValue &FieldVal = Result.getStructBase(ElementNo);
6076 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6077 if (!Info.noteFailure())
6085 // Initialize members.
6086 for (const auto *Field : RD->fields()) {
6087 // Anonymous bit-fields are not considered members of the class for
6088 // purposes of aggregate initialization.
6089 if (Field->isUnnamedBitfield())
6092 LValue Subobject = This;
6094 bool HaveInit = ElementNo < E->getNumInits();
6096 // FIXME: Diagnostics here should point to the end of the initializer
6097 // list, not the start.
6098 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6099 Subobject, Field, &Layout))
6102 // Perform an implicit value-initialization for members beyond the end of
6103 // the initializer list.
6104 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6105 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6107 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6108 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6109 isa<CXXDefaultInitExpr>(Init));
6111 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6112 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6113 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6114 FieldVal, Field))) {
6115 if (!Info.noteFailure())
6124 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6126 // Note that E's type is not necessarily the type of our class here; we might
6127 // be initializing an array element instead.
6128 const CXXConstructorDecl *FD = E->getConstructor();
6129 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6131 bool ZeroInit = E->requiresZeroInitialization();
6132 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6133 // If we've already performed zero-initialization, we're already done.
6134 if (!Result.isUninit())
6137 // We can get here in two different ways:
6138 // 1) We're performing value-initialization, and should zero-initialize
6140 // 2) We're performing default-initialization of an object with a trivial
6141 // constexpr default constructor, in which case we should start the
6142 // lifetimes of all the base subobjects (there can be no data member
6143 // subobjects in this case) per [basic.life]p1.
6144 // Either way, ZeroInitialization is appropriate.
6145 return ZeroInitialization(E, T);
6148 const FunctionDecl *Definition = nullptr;
6149 auto Body = FD->getBody(Definition);
6151 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6154 // Avoid materializing a temporary for an elidable copy/move constructor.
6155 if (E->isElidable() && !ZeroInit)
6156 if (const MaterializeTemporaryExpr *ME
6157 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6158 return Visit(ME->GetTemporaryExpr());
6160 if (ZeroInit && !ZeroInitialization(E, T))
6163 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6164 return HandleConstructorCall(E, This, Args,
6165 cast<CXXConstructorDecl>(Definition), Info,
6169 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6170 const CXXInheritedCtorInitExpr *E) {
6171 if (!Info.CurrentCall) {
6172 assert(Info.checkingPotentialConstantExpression());
6176 const CXXConstructorDecl *FD = E->getConstructor();
6177 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6180 const FunctionDecl *Definition = nullptr;
6181 auto Body = FD->getBody(Definition);
6183 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6186 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6187 cast<CXXConstructorDecl>(Definition), Info,
6191 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6192 const CXXStdInitializerListExpr *E) {
6193 const ConstantArrayType *ArrayType =
6194 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6197 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6200 // Get a pointer to the first element of the array.
6201 Array.addArray(Info, E, ArrayType);
6203 // FIXME: Perform the checks on the field types in SemaInit.
6204 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6205 RecordDecl::field_iterator Field = Record->field_begin();
6206 if (Field == Record->field_end())
6210 if (!Field->getType()->isPointerType() ||
6211 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6212 ArrayType->getElementType()))
6215 // FIXME: What if the initializer_list type has base classes, etc?
6216 Result = APValue(APValue::UninitStruct(), 0, 2);
6217 Array.moveInto(Result.getStructField(0));
6219 if (++Field == Record->field_end())
6222 if (Field->getType()->isPointerType() &&
6223 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6224 ArrayType->getElementType())) {
6226 if (!HandleLValueArrayAdjustment(Info, E, Array,
6227 ArrayType->getElementType(),
6228 ArrayType->getSize().getZExtValue()))
6230 Array.moveInto(Result.getStructField(1));
6231 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6233 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6237 if (++Field != Record->field_end())
6243 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6244 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6245 if (ClosureClass->isInvalidDecl()) return false;
6247 if (Info.checkingPotentialConstantExpression()) return true;
6248 if (E->capture_size()) {
6249 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6250 << "can not evaluate lambda expressions with captures";
6253 // FIXME: Implement captures.
6254 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6258 static bool EvaluateRecord(const Expr *E, const LValue &This,
6259 APValue &Result, EvalInfo &Info) {
6260 assert(E->isRValue() && E->getType()->isRecordType() &&
6261 "can't evaluate expression as a record rvalue");
6262 return RecordExprEvaluator(Info, This, Result).Visit(E);
6265 //===----------------------------------------------------------------------===//
6266 // Temporary Evaluation
6268 // Temporaries are represented in the AST as rvalues, but generally behave like
6269 // lvalues. The full-object of which the temporary is a subobject is implicitly
6270 // materialized so that a reference can bind to it.
6271 //===----------------------------------------------------------------------===//
6273 class TemporaryExprEvaluator
6274 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6276 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6277 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6279 /// Visit an expression which constructs the value of this temporary.
6280 bool VisitConstructExpr(const Expr *E) {
6281 Result.set(E, Info.CurrentCall->Index);
6282 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6286 bool VisitCastExpr(const CastExpr *E) {
6287 switch (E->getCastKind()) {
6289 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6291 case CK_ConstructorConversion:
6292 return VisitConstructExpr(E->getSubExpr());
6295 bool VisitInitListExpr(const InitListExpr *E) {
6296 return VisitConstructExpr(E);
6298 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6299 return VisitConstructExpr(E);
6301 bool VisitCallExpr(const CallExpr *E) {
6302 return VisitConstructExpr(E);
6304 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6305 return VisitConstructExpr(E);
6307 bool VisitLambdaExpr(const LambdaExpr *E) {
6308 return VisitConstructExpr(E);
6311 } // end anonymous namespace
6313 /// Evaluate an expression of record type as a temporary.
6314 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6315 assert(E->isRValue() && E->getType()->isRecordType());
6316 return TemporaryExprEvaluator(Info, Result).Visit(E);
6319 //===----------------------------------------------------------------------===//
6320 // Vector Evaluation
6321 //===----------------------------------------------------------------------===//
6324 class VectorExprEvaluator
6325 : public ExprEvaluatorBase<VectorExprEvaluator> {
6329 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6330 : ExprEvaluatorBaseTy(info), Result(Result) {}
6332 bool Success(ArrayRef<APValue> V, const Expr *E) {
6333 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6334 // FIXME: remove this APValue copy.
6335 Result = APValue(V.data(), V.size());
6338 bool Success(const APValue &V, const Expr *E) {
6339 assert(V.isVector());
6343 bool ZeroInitialization(const Expr *E);
6345 bool VisitUnaryReal(const UnaryOperator *E)
6346 { return Visit(E->getSubExpr()); }
6347 bool VisitCastExpr(const CastExpr* E);
6348 bool VisitInitListExpr(const InitListExpr *E);
6349 bool VisitUnaryImag(const UnaryOperator *E);
6350 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6351 // binary comparisons, binary and/or/xor,
6352 // shufflevector, ExtVectorElementExpr
6354 } // end anonymous namespace
6356 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6357 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6358 return VectorExprEvaluator(Info, Result).Visit(E);
6361 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6362 const VectorType *VTy = E->getType()->castAs<VectorType>();
6363 unsigned NElts = VTy->getNumElements();
6365 const Expr *SE = E->getSubExpr();
6366 QualType SETy = SE->getType();
6368 switch (E->getCastKind()) {
6369 case CK_VectorSplat: {
6370 APValue Val = APValue();
6371 if (SETy->isIntegerType()) {
6373 if (!EvaluateInteger(SE, IntResult, Info))
6375 Val = APValue(std::move(IntResult));
6376 } else if (SETy->isRealFloatingType()) {
6377 APFloat FloatResult(0.0);
6378 if (!EvaluateFloat(SE, FloatResult, Info))
6380 Val = APValue(std::move(FloatResult));
6385 // Splat and create vector APValue.
6386 SmallVector<APValue, 4> Elts(NElts, Val);
6387 return Success(Elts, E);
6390 // Evaluate the operand into an APInt we can extract from.
6391 llvm::APInt SValInt;
6392 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6394 // Extract the elements
6395 QualType EltTy = VTy->getElementType();
6396 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6397 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6398 SmallVector<APValue, 4> Elts;
6399 if (EltTy->isRealFloatingType()) {
6400 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6401 unsigned FloatEltSize = EltSize;
6402 if (&Sem == &APFloat::x87DoubleExtended())
6404 for (unsigned i = 0; i < NElts; i++) {
6407 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6409 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6410 Elts.push_back(APValue(APFloat(Sem, Elt)));
6412 } else if (EltTy->isIntegerType()) {
6413 for (unsigned i = 0; i < NElts; i++) {
6416 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6418 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6419 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6424 return Success(Elts, E);
6427 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6432 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6433 const VectorType *VT = E->getType()->castAs<VectorType>();
6434 unsigned NumInits = E->getNumInits();
6435 unsigned NumElements = VT->getNumElements();
6437 QualType EltTy = VT->getElementType();
6438 SmallVector<APValue, 4> Elements;
6440 // The number of initializers can be less than the number of
6441 // vector elements. For OpenCL, this can be due to nested vector
6442 // initialization. For GCC compatibility, missing trailing elements
6443 // should be initialized with zeroes.
6444 unsigned CountInits = 0, CountElts = 0;
6445 while (CountElts < NumElements) {
6446 // Handle nested vector initialization.
6447 if (CountInits < NumInits
6448 && E->getInit(CountInits)->getType()->isVectorType()) {
6450 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6452 unsigned vlen = v.getVectorLength();
6453 for (unsigned j = 0; j < vlen; j++)
6454 Elements.push_back(v.getVectorElt(j));
6456 } else if (EltTy->isIntegerType()) {
6457 llvm::APSInt sInt(32);
6458 if (CountInits < NumInits) {
6459 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6461 } else // trailing integer zero.
6462 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6463 Elements.push_back(APValue(sInt));
6466 llvm::APFloat f(0.0);
6467 if (CountInits < NumInits) {
6468 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6470 } else // trailing float zero.
6471 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6472 Elements.push_back(APValue(f));
6477 return Success(Elements, E);
6481 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6482 const VectorType *VT = E->getType()->getAs<VectorType>();
6483 QualType EltTy = VT->getElementType();
6484 APValue ZeroElement;
6485 if (EltTy->isIntegerType())
6486 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6489 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6491 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6492 return Success(Elements, E);
6495 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6496 VisitIgnoredValue(E->getSubExpr());
6497 return ZeroInitialization(E);
6500 //===----------------------------------------------------------------------===//
6502 //===----------------------------------------------------------------------===//
6505 class ArrayExprEvaluator
6506 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6511 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6512 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6514 bool Success(const APValue &V, const Expr *E) {
6515 assert((V.isArray() || V.isLValue()) &&
6516 "expected array or string literal");
6521 bool ZeroInitialization(const Expr *E) {
6522 const ConstantArrayType *CAT =
6523 Info.Ctx.getAsConstantArrayType(E->getType());
6527 Result = APValue(APValue::UninitArray(), 0,
6528 CAT->getSize().getZExtValue());
6529 if (!Result.hasArrayFiller()) return true;
6531 // Zero-initialize all elements.
6532 LValue Subobject = This;
6533 Subobject.addArray(Info, E, CAT);
6534 ImplicitValueInitExpr VIE(CAT->getElementType());
6535 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6538 bool VisitCallExpr(const CallExpr *E) {
6539 return handleCallExpr(E, Result, &This);
6541 bool VisitInitListExpr(const InitListExpr *E);
6542 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6543 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6544 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6545 const LValue &Subobject,
6546 APValue *Value, QualType Type);
6548 } // end anonymous namespace
6550 static bool EvaluateArray(const Expr *E, const LValue &This,
6551 APValue &Result, EvalInfo &Info) {
6552 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6553 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6556 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6557 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6561 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6562 // an appropriately-typed string literal enclosed in braces.
6563 if (E->isStringLiteralInit()) {
6565 if (!EvaluateLValue(E->getInit(0), LV, Info))
6569 return Success(Val, E);
6572 bool Success = true;
6574 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6575 "zero-initialized array shouldn't have any initialized elts");
6577 if (Result.isArray() && Result.hasArrayFiller())
6578 Filler = Result.getArrayFiller();
6580 unsigned NumEltsToInit = E->getNumInits();
6581 unsigned NumElts = CAT->getSize().getZExtValue();
6582 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6584 // If the initializer might depend on the array index, run it for each
6585 // array element. For now, just whitelist non-class value-initialization.
6586 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6587 NumEltsToInit = NumElts;
6589 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6591 // If the array was previously zero-initialized, preserve the
6592 // zero-initialized values.
6593 if (!Filler.isUninit()) {
6594 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6595 Result.getArrayInitializedElt(I) = Filler;
6596 if (Result.hasArrayFiller())
6597 Result.getArrayFiller() = Filler;
6600 LValue Subobject = This;
6601 Subobject.addArray(Info, E, CAT);
6602 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6604 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6605 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6606 Info, Subobject, Init) ||
6607 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6608 CAT->getElementType(), 1)) {
6609 if (!Info.noteFailure())
6615 if (!Result.hasArrayFiller())
6618 // If we get here, we have a trivial filler, which we can just evaluate
6619 // once and splat over the rest of the array elements.
6620 assert(FillerExpr && "no array filler for incomplete init list");
6621 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6622 FillerExpr) && Success;
6625 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6626 if (E->getCommonExpr() &&
6627 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6628 Info, E->getCommonExpr()->getSourceExpr()))
6631 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6633 uint64_t Elements = CAT->getSize().getZExtValue();
6634 Result = APValue(APValue::UninitArray(), Elements, Elements);
6636 LValue Subobject = This;
6637 Subobject.addArray(Info, E, CAT);
6639 bool Success = true;
6640 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6641 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6642 Info, Subobject, E->getSubExpr()) ||
6643 !HandleLValueArrayAdjustment(Info, E, Subobject,
6644 CAT->getElementType(), 1)) {
6645 if (!Info.noteFailure())
6654 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6655 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6658 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6659 const LValue &Subobject,
6662 bool HadZeroInit = !Value->isUninit();
6664 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6665 unsigned N = CAT->getSize().getZExtValue();
6667 // Preserve the array filler if we had prior zero-initialization.
6669 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6672 *Value = APValue(APValue::UninitArray(), N, N);
6675 for (unsigned I = 0; I != N; ++I)
6676 Value->getArrayInitializedElt(I) = Filler;
6678 // Initialize the elements.
6679 LValue ArrayElt = Subobject;
6680 ArrayElt.addArray(Info, E, CAT);
6681 for (unsigned I = 0; I != N; ++I)
6682 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6683 CAT->getElementType()) ||
6684 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6685 CAT->getElementType(), 1))
6691 if (!Type->isRecordType())
6694 return RecordExprEvaluator(Info, Subobject, *Value)
6695 .VisitCXXConstructExpr(E, Type);
6698 //===----------------------------------------------------------------------===//
6699 // Integer Evaluation
6701 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6702 // types and back in constant folding. Integer values are thus represented
6703 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6704 //===----------------------------------------------------------------------===//
6707 class IntExprEvaluator
6708 : public ExprEvaluatorBase<IntExprEvaluator> {
6711 IntExprEvaluator(EvalInfo &info, APValue &result)
6712 : ExprEvaluatorBaseTy(info), Result(result) {}
6714 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6715 assert(E->getType()->isIntegralOrEnumerationType() &&
6716 "Invalid evaluation result.");
6717 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6718 "Invalid evaluation result.");
6719 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6720 "Invalid evaluation result.");
6721 Result = APValue(SI);
6724 bool Success(const llvm::APSInt &SI, const Expr *E) {
6725 return Success(SI, E, Result);
6728 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6729 assert(E->getType()->isIntegralOrEnumerationType() &&
6730 "Invalid evaluation result.");
6731 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6732 "Invalid evaluation result.");
6733 Result = APValue(APSInt(I));
6734 Result.getInt().setIsUnsigned(
6735 E->getType()->isUnsignedIntegerOrEnumerationType());
6738 bool Success(const llvm::APInt &I, const Expr *E) {
6739 return Success(I, E, Result);
6742 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6743 assert(E->getType()->isIntegralOrEnumerationType() &&
6744 "Invalid evaluation result.");
6745 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6748 bool Success(uint64_t Value, const Expr *E) {
6749 return Success(Value, E, Result);
6752 bool Success(CharUnits Size, const Expr *E) {
6753 return Success(Size.getQuantity(), E);
6756 bool Success(const APValue &V, const Expr *E) {
6757 if (V.isLValue() || V.isAddrLabelDiff()) {
6761 return Success(V.getInt(), E);
6764 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6766 //===--------------------------------------------------------------------===//
6768 //===--------------------------------------------------------------------===//
6770 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6771 return Success(E->getValue(), E);
6773 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6774 return Success(E->getValue(), E);
6777 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6778 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6779 if (CheckReferencedDecl(E, E->getDecl()))
6782 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6784 bool VisitMemberExpr(const MemberExpr *E) {
6785 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6786 VisitIgnoredBaseExpression(E->getBase());
6790 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6793 bool VisitCallExpr(const CallExpr *E);
6794 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6795 bool VisitBinaryOperator(const BinaryOperator *E);
6796 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6797 bool VisitUnaryOperator(const UnaryOperator *E);
6799 bool VisitCastExpr(const CastExpr* E);
6800 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6802 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6803 return Success(E->getValue(), E);
6806 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6807 return Success(E->getValue(), E);
6810 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6811 if (Info.ArrayInitIndex == uint64_t(-1)) {
6812 // We were asked to evaluate this subexpression independent of the
6813 // enclosing ArrayInitLoopExpr. We can't do that.
6817 return Success(Info.ArrayInitIndex, E);
6820 // Note, GNU defines __null as an integer, not a pointer.
6821 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6822 return ZeroInitialization(E);
6825 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6826 return Success(E->getValue(), E);
6829 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6830 return Success(E->getValue(), E);
6833 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6834 return Success(E->getValue(), E);
6837 bool VisitUnaryReal(const UnaryOperator *E);
6838 bool VisitUnaryImag(const UnaryOperator *E);
6840 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6841 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6843 // FIXME: Missing: array subscript of vector, member of vector
6845 } // end anonymous namespace
6847 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6848 /// produce either the integer value or a pointer.
6850 /// GCC has a heinous extension which folds casts between pointer types and
6851 /// pointer-sized integral types. We support this by allowing the evaluation of
6852 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6853 /// Some simple arithmetic on such values is supported (they are treated much
6855 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6857 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6858 return IntExprEvaluator(Info, Result).Visit(E);
6861 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6863 if (!EvaluateIntegerOrLValue(E, Val, Info))
6866 // FIXME: It would be better to produce the diagnostic for casting
6867 // a pointer to an integer.
6868 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6871 Result = Val.getInt();
6875 /// Check whether the given declaration can be directly converted to an integral
6876 /// rvalue. If not, no diagnostic is produced; there are other things we can
6878 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6879 // Enums are integer constant exprs.
6880 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6881 // Check for signedness/width mismatches between E type and ECD value.
6882 bool SameSign = (ECD->getInitVal().isSigned()
6883 == E->getType()->isSignedIntegerOrEnumerationType());
6884 bool SameWidth = (ECD->getInitVal().getBitWidth()
6885 == Info.Ctx.getIntWidth(E->getType()));
6886 if (SameSign && SameWidth)
6887 return Success(ECD->getInitVal(), E);
6889 // Get rid of mismatch (otherwise Success assertions will fail)
6890 // by computing a new value matching the type of E.
6891 llvm::APSInt Val = ECD->getInitVal();
6893 Val.setIsSigned(!ECD->getInitVal().isSigned());
6895 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6896 return Success(Val, E);
6902 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6904 static int EvaluateBuiltinClassifyType(const CallExpr *E,
6905 const LangOptions &LangOpts) {
6906 // The following enum mimics the values returned by GCC.
6907 // FIXME: Does GCC differ between lvalue and rvalue references here?
6908 enum gcc_type_class {
6910 void_type_class, integer_type_class, char_type_class,
6911 enumeral_type_class, boolean_type_class,
6912 pointer_type_class, reference_type_class, offset_type_class,
6913 real_type_class, complex_type_class,
6914 function_type_class, method_type_class,
6915 record_type_class, union_type_class,
6916 array_type_class, string_type_class,
6920 // If no argument was supplied, default to "no_type_class". This isn't
6921 // ideal, however it is what gcc does.
6922 if (E->getNumArgs() == 0)
6923 return no_type_class;
6925 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6926 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6928 switch (CanTy->getTypeClass()) {
6929 #define TYPE(ID, BASE)
6930 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6931 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6932 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6933 #include "clang/AST/TypeNodes.def"
6934 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6937 switch (BT->getKind()) {
6938 #define BUILTIN_TYPE(ID, SINGLETON_ID)
6939 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6940 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6941 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6942 #include "clang/AST/BuiltinTypes.def"
6943 case BuiltinType::Void:
6944 return void_type_class;
6946 case BuiltinType::Bool:
6947 return boolean_type_class;
6949 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6950 case BuiltinType::UChar:
6951 case BuiltinType::UShort:
6952 case BuiltinType::UInt:
6953 case BuiltinType::ULong:
6954 case BuiltinType::ULongLong:
6955 case BuiltinType::UInt128:
6956 return integer_type_class;
6958 case BuiltinType::NullPtr:
6959 return pointer_type_class;
6961 case BuiltinType::WChar_U:
6962 case BuiltinType::Char16:
6963 case BuiltinType::Char32:
6964 case BuiltinType::ObjCId:
6965 case BuiltinType::ObjCClass:
6966 case BuiltinType::ObjCSel:
6967 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6968 case BuiltinType::Id:
6969 #include "clang/Basic/OpenCLImageTypes.def"
6970 case BuiltinType::OCLSampler:
6971 case BuiltinType::OCLEvent:
6972 case BuiltinType::OCLClkEvent:
6973 case BuiltinType::OCLQueue:
6974 case BuiltinType::OCLNDRange:
6975 case BuiltinType::OCLReserveID:
6976 case BuiltinType::Dependent:
6977 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6981 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6985 return pointer_type_class;
6988 case Type::MemberPointer:
6989 if (CanTy->isMemberDataPointerType())
6990 return offset_type_class;
6992 // We expect member pointers to be either data or function pointers,
6994 assert(CanTy->isMemberFunctionPointerType());
6995 return method_type_class;
6999 return complex_type_class;
7001 case Type::FunctionNoProto:
7002 case Type::FunctionProto:
7003 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7006 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7007 switch (RT->getDecl()->getTagKind()) {
7008 case TagTypeKind::TTK_Struct:
7009 case TagTypeKind::TTK_Class:
7010 case TagTypeKind::TTK_Interface:
7011 return record_type_class;
7013 case TagTypeKind::TTK_Enum:
7014 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7016 case TagTypeKind::TTK_Union:
7017 return union_type_class;
7020 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7022 case Type::ConstantArray:
7023 case Type::VariableArray:
7024 case Type::IncompleteArray:
7025 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7027 case Type::BlockPointer:
7028 case Type::LValueReference:
7029 case Type::RValueReference:
7031 case Type::ExtVector:
7033 case Type::ObjCObject:
7034 case Type::ObjCInterface:
7035 case Type::ObjCObjectPointer:
7038 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7041 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7044 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7045 /// __builtin_constant_p when applied to the given lvalue.
7047 /// An lvalue is only "constant" if it is a pointer or reference to the first
7048 /// character of a string literal.
7049 template<typename LValue>
7050 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7051 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7052 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7055 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7056 /// GCC as we can manage.
7057 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7058 QualType ArgType = Arg->getType();
7060 // __builtin_constant_p always has one operand. The rules which gcc follows
7061 // are not precisely documented, but are as follows:
7063 // - If the operand is of integral, floating, complex or enumeration type,
7064 // and can be folded to a known value of that type, it returns 1.
7065 // - If the operand and can be folded to a pointer to the first character
7066 // of a string literal (or such a pointer cast to an integral type), it
7069 // Otherwise, it returns 0.
7071 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7072 // its support for this does not currently work.
7073 if (ArgType->isIntegralOrEnumerationType()) {
7074 Expr::EvalResult Result;
7075 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7078 APValue &V = Result.Val;
7079 if (V.getKind() == APValue::Int)
7081 if (V.getKind() == APValue::LValue)
7082 return EvaluateBuiltinConstantPForLValue(V);
7083 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7084 return Arg->isEvaluatable(Ctx);
7085 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7087 Expr::EvalStatus Status;
7088 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7089 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7090 : EvaluatePointer(Arg, LV, Info)) &&
7091 !Status.HasSideEffects)
7092 return EvaluateBuiltinConstantPForLValue(LV);
7095 // Anything else isn't considered to be sufficiently constant.
7099 /// Retrieves the "underlying object type" of the given expression,
7100 /// as used by __builtin_object_size.
7101 static QualType getObjectType(APValue::LValueBase B) {
7102 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7103 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7104 return VD->getType();
7105 } else if (const Expr *E = B.get<const Expr*>()) {
7106 if (isa<CompoundLiteralExpr>(E))
7107 return E->getType();
7113 /// A more selective version of E->IgnoreParenCasts for
7114 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7115 /// to change the type of E.
7116 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7118 /// Always returns an RValue with a pointer representation.
7119 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7120 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7122 auto *NoParens = E->IgnoreParens();
7123 auto *Cast = dyn_cast<CastExpr>(NoParens);
7124 if (Cast == nullptr)
7127 // We only conservatively allow a few kinds of casts, because this code is
7128 // inherently a simple solution that seeks to support the common case.
7129 auto CastKind = Cast->getCastKind();
7130 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7131 CastKind != CK_AddressSpaceConversion)
7134 auto *SubExpr = Cast->getSubExpr();
7135 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7137 return ignorePointerCastsAndParens(SubExpr);
7140 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7141 /// record layout. e.g.
7142 /// struct { struct { int a, b; } fst, snd; } obj;
7148 /// obj.snd.b // yes
7150 /// Please note: this function is specialized for how __builtin_object_size
7151 /// views "objects".
7153 /// If this encounters an invalid RecordDecl, it will always return true.
7154 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7155 assert(!LVal.Designator.Invalid);
7157 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7158 const RecordDecl *Parent = FD->getParent();
7159 Invalid = Parent->isInvalidDecl();
7160 if (Invalid || Parent->isUnion())
7162 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7163 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7166 auto &Base = LVal.getLValueBase();
7167 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7168 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7170 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7172 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7173 for (auto *FD : IFD->chain()) {
7175 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7182 QualType BaseType = getType(Base);
7183 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7184 assert(isBaseAnAllocSizeCall(Base) &&
7185 "Unsized array in non-alloc_size call?");
7186 // If this is an alloc_size base, we should ignore the initial array index
7188 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7191 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7192 const auto &Entry = LVal.Designator.Entries[I];
7193 if (BaseType->isArrayType()) {
7194 // Because __builtin_object_size treats arrays as objects, we can ignore
7195 // the index iff this is the last array in the Designator.
7198 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7199 uint64_t Index = Entry.ArrayIndex;
7200 if (Index + 1 != CAT->getSize())
7202 BaseType = CAT->getElementType();
7203 } else if (BaseType->isAnyComplexType()) {
7204 const auto *CT = BaseType->castAs<ComplexType>();
7205 uint64_t Index = Entry.ArrayIndex;
7208 BaseType = CT->getElementType();
7209 } else if (auto *FD = getAsField(Entry)) {
7211 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7213 BaseType = FD->getType();
7215 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7222 /// Tests to see if the LValue has a user-specified designator (that isn't
7223 /// necessarily valid). Note that this always returns 'true' if the LValue has
7224 /// an unsized array as its first designator entry, because there's currently no
7225 /// way to tell if the user typed *foo or foo[0].
7226 static bool refersToCompleteObject(const LValue &LVal) {
7227 if (LVal.Designator.Invalid)
7230 if (!LVal.Designator.Entries.empty())
7231 return LVal.Designator.isMostDerivedAnUnsizedArray();
7233 if (!LVal.InvalidBase)
7236 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7238 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7239 return !E || !isa<MemberExpr>(E);
7242 /// Attempts to detect a user writing into a piece of memory that's impossible
7243 /// to figure out the size of by just using types.
7244 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7245 const SubobjectDesignator &Designator = LVal.Designator;
7247 // - Users can only write off of the end when we have an invalid base. Invalid
7248 // bases imply we don't know where the memory came from.
7249 // - We used to be a bit more aggressive here; we'd only be conservative if
7250 // the array at the end was flexible, or if it had 0 or 1 elements. This
7251 // broke some common standard library extensions (PR30346), but was
7252 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7253 // with some sort of whitelist. OTOH, it seems that GCC is always
7254 // conservative with the last element in structs (if it's an array), so our
7255 // current behavior is more compatible than a whitelisting approach would
7257 return LVal.InvalidBase &&
7258 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7259 Designator.MostDerivedIsArrayElement &&
7260 isDesignatorAtObjectEnd(Ctx, LVal);
7263 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7264 /// Fails if the conversion would cause loss of precision.
7265 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7266 CharUnits &Result) {
7267 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7268 if (Int.ugt(CharUnitsMax))
7270 Result = CharUnits::fromQuantity(Int.getZExtValue());
7274 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7275 /// determine how many bytes exist from the beginning of the object to either
7276 /// the end of the current subobject, or the end of the object itself, depending
7277 /// on what the LValue looks like + the value of Type.
7279 /// If this returns false, the value of Result is undefined.
7280 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7281 unsigned Type, const LValue &LVal,
7282 CharUnits &EndOffset) {
7283 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7285 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7286 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7288 return HandleSizeof(Info, ExprLoc, Ty, Result);
7291 // We want to evaluate the size of the entire object. This is a valid fallback
7292 // for when Type=1 and the designator is invalid, because we're asked for an
7294 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7295 // Type=3 wants a lower bound, so we can't fall back to this.
7296 if (Type == 3 && !DetermineForCompleteObject)
7299 llvm::APInt APEndOffset;
7300 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7301 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7302 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7304 if (LVal.InvalidBase)
7307 QualType BaseTy = getObjectType(LVal.getLValueBase());
7308 return CheckedHandleSizeof(BaseTy, EndOffset);
7311 // We want to evaluate the size of a subobject.
7312 const SubobjectDesignator &Designator = LVal.Designator;
7314 // The following is a moderately common idiom in C:
7316 // struct Foo { int a; char c[1]; };
7317 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7318 // strcpy(&F->c[0], Bar);
7320 // In order to not break too much legacy code, we need to support it.
7321 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7322 // If we can resolve this to an alloc_size call, we can hand that back,
7323 // because we know for certain how many bytes there are to write to.
7324 llvm::APInt APEndOffset;
7325 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7326 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7327 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7329 // If we cannot determine the size of the initial allocation, then we can't
7330 // given an accurate upper-bound. However, we are still able to give
7331 // conservative lower-bounds for Type=3.
7336 CharUnits BytesPerElem;
7337 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7340 // According to the GCC documentation, we want the size of the subobject
7341 // denoted by the pointer. But that's not quite right -- what we actually
7342 // want is the size of the immediately-enclosing array, if there is one.
7343 int64_t ElemsRemaining;
7344 if (Designator.MostDerivedIsArrayElement &&
7345 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7346 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7347 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7348 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7350 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7353 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7357 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7358 /// returns true and stores the result in @p Size.
7360 /// If @p WasError is non-null, this will report whether the failure to evaluate
7361 /// is to be treated as an Error in IntExprEvaluator.
7362 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7363 EvalInfo &Info, uint64_t &Size) {
7364 // Determine the denoted object.
7367 // The operand of __builtin_object_size is never evaluated for side-effects.
7368 // If there are any, but we can determine the pointed-to object anyway, then
7369 // ignore the side-effects.
7370 SpeculativeEvaluationRAII SpeculativeEval(Info);
7371 FoldOffsetRAII Fold(Info);
7373 if (E->isGLValue()) {
7374 // It's possible for us to be given GLValues if we're called via
7375 // Expr::tryEvaluateObjectSize.
7377 if (!EvaluateAsRValue(Info, E, RVal))
7379 LVal.setFrom(Info.Ctx, RVal);
7380 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7381 /*InvalidBaseOK=*/true))
7385 // If we point to before the start of the object, there are no accessible
7387 if (LVal.getLValueOffset().isNegative()) {
7392 CharUnits EndOffset;
7393 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7396 // If we've fallen outside of the end offset, just pretend there's nothing to
7397 // write to/read from.
7398 if (EndOffset <= LVal.getLValueOffset())
7401 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7405 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7406 if (unsigned BuiltinOp = E->getBuiltinCallee())
7407 return VisitBuiltinCallExpr(E, BuiltinOp);
7409 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7412 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7413 unsigned BuiltinOp) {
7414 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7416 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7418 case Builtin::BI__builtin_object_size: {
7419 // The type was checked when we built the expression.
7421 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7422 assert(Type <= 3 && "unexpected type");
7425 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7426 return Success(Size, E);
7428 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7429 return Success((Type & 2) ? 0 : -1, E);
7431 // Expression had no side effects, but we couldn't statically determine the
7432 // size of the referenced object.
7433 switch (Info.EvalMode) {
7434 case EvalInfo::EM_ConstantExpression:
7435 case EvalInfo::EM_PotentialConstantExpression:
7436 case EvalInfo::EM_ConstantFold:
7437 case EvalInfo::EM_EvaluateForOverflow:
7438 case EvalInfo::EM_IgnoreSideEffects:
7439 case EvalInfo::EM_OffsetFold:
7440 // Leave it to IR generation.
7442 case EvalInfo::EM_ConstantExpressionUnevaluated:
7443 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7444 // Reduce it to a constant now.
7445 return Success((Type & 2) ? 0 : -1, E);
7448 llvm_unreachable("unexpected EvalMode");
7451 case Builtin::BI__builtin_bswap16:
7452 case Builtin::BI__builtin_bswap32:
7453 case Builtin::BI__builtin_bswap64: {
7455 if (!EvaluateInteger(E->getArg(0), Val, Info))
7458 return Success(Val.byteSwap(), E);
7461 case Builtin::BI__builtin_classify_type:
7462 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7464 // FIXME: BI__builtin_clrsb
7465 // FIXME: BI__builtin_clrsbl
7466 // FIXME: BI__builtin_clrsbll
7468 case Builtin::BI__builtin_clz:
7469 case Builtin::BI__builtin_clzl:
7470 case Builtin::BI__builtin_clzll:
7471 case Builtin::BI__builtin_clzs: {
7473 if (!EvaluateInteger(E->getArg(0), Val, Info))
7478 return Success(Val.countLeadingZeros(), E);
7481 case Builtin::BI__builtin_constant_p:
7482 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7484 case Builtin::BI__builtin_ctz:
7485 case Builtin::BI__builtin_ctzl:
7486 case Builtin::BI__builtin_ctzll:
7487 case Builtin::BI__builtin_ctzs: {
7489 if (!EvaluateInteger(E->getArg(0), Val, Info))
7494 return Success(Val.countTrailingZeros(), E);
7497 case Builtin::BI__builtin_eh_return_data_regno: {
7498 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7499 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7500 return Success(Operand, E);
7503 case Builtin::BI__builtin_expect:
7504 return Visit(E->getArg(0));
7506 case Builtin::BI__builtin_ffs:
7507 case Builtin::BI__builtin_ffsl:
7508 case Builtin::BI__builtin_ffsll: {
7510 if (!EvaluateInteger(E->getArg(0), Val, Info))
7513 unsigned N = Val.countTrailingZeros();
7514 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7517 case Builtin::BI__builtin_fpclassify: {
7519 if (!EvaluateFloat(E->getArg(5), Val, Info))
7522 switch (Val.getCategory()) {
7523 case APFloat::fcNaN: Arg = 0; break;
7524 case APFloat::fcInfinity: Arg = 1; break;
7525 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7526 case APFloat::fcZero: Arg = 4; break;
7528 return Visit(E->getArg(Arg));
7531 case Builtin::BI__builtin_isinf_sign: {
7533 return EvaluateFloat(E->getArg(0), Val, Info) &&
7534 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7537 case Builtin::BI__builtin_isinf: {
7539 return EvaluateFloat(E->getArg(0), Val, Info) &&
7540 Success(Val.isInfinity() ? 1 : 0, E);
7543 case Builtin::BI__builtin_isfinite: {
7545 return EvaluateFloat(E->getArg(0), Val, Info) &&
7546 Success(Val.isFinite() ? 1 : 0, E);
7549 case Builtin::BI__builtin_isnan: {
7551 return EvaluateFloat(E->getArg(0), Val, Info) &&
7552 Success(Val.isNaN() ? 1 : 0, E);
7555 case Builtin::BI__builtin_isnormal: {
7557 return EvaluateFloat(E->getArg(0), Val, Info) &&
7558 Success(Val.isNormal() ? 1 : 0, E);
7561 case Builtin::BI__builtin_parity:
7562 case Builtin::BI__builtin_parityl:
7563 case Builtin::BI__builtin_parityll: {
7565 if (!EvaluateInteger(E->getArg(0), Val, Info))
7568 return Success(Val.countPopulation() % 2, E);
7571 case Builtin::BI__builtin_popcount:
7572 case Builtin::BI__builtin_popcountl:
7573 case Builtin::BI__builtin_popcountll: {
7575 if (!EvaluateInteger(E->getArg(0), Val, Info))
7578 return Success(Val.countPopulation(), E);
7581 case Builtin::BIstrlen:
7582 case Builtin::BIwcslen:
7583 // A call to strlen is not a constant expression.
7584 if (Info.getLangOpts().CPlusPlus11)
7585 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7586 << /*isConstexpr*/0 << /*isConstructor*/0
7587 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7589 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7591 case Builtin::BI__builtin_strlen:
7592 case Builtin::BI__builtin_wcslen: {
7593 // As an extension, we support __builtin_strlen() as a constant expression,
7594 // and support folding strlen() to a constant.
7596 if (!EvaluatePointer(E->getArg(0), String, Info))
7599 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7601 // Fast path: if it's a string literal, search the string value.
7602 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7603 String.getLValueBase().dyn_cast<const Expr *>())) {
7604 // The string literal may have embedded null characters. Find the first
7605 // one and truncate there.
7606 StringRef Str = S->getBytes();
7607 int64_t Off = String.Offset.getQuantity();
7608 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7609 S->getCharByteWidth() == 1 &&
7610 // FIXME: Add fast-path for wchar_t too.
7611 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7612 Str = Str.substr(Off);
7614 StringRef::size_type Pos = Str.find(0);
7615 if (Pos != StringRef::npos)
7616 Str = Str.substr(0, Pos);
7618 return Success(Str.size(), E);
7621 // Fall through to slow path to issue appropriate diagnostic.
7624 // Slow path: scan the bytes of the string looking for the terminating 0.
7625 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7627 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7631 return Success(Strlen, E);
7632 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7637 case Builtin::BIstrcmp:
7638 case Builtin::BIwcscmp:
7639 case Builtin::BIstrncmp:
7640 case Builtin::BIwcsncmp:
7641 case Builtin::BImemcmp:
7642 case Builtin::BIwmemcmp:
7643 // A call to strlen is not a constant expression.
7644 if (Info.getLangOpts().CPlusPlus11)
7645 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7646 << /*isConstexpr*/0 << /*isConstructor*/0
7647 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7649 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7651 case Builtin::BI__builtin_strcmp:
7652 case Builtin::BI__builtin_wcscmp:
7653 case Builtin::BI__builtin_strncmp:
7654 case Builtin::BI__builtin_wcsncmp:
7655 case Builtin::BI__builtin_memcmp:
7656 case Builtin::BI__builtin_wmemcmp: {
7657 LValue String1, String2;
7658 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7659 !EvaluatePointer(E->getArg(1), String2, Info))
7662 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7664 uint64_t MaxLength = uint64_t(-1);
7665 if (BuiltinOp != Builtin::BIstrcmp &&
7666 BuiltinOp != Builtin::BIwcscmp &&
7667 BuiltinOp != Builtin::BI__builtin_strcmp &&
7668 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7670 if (!EvaluateInteger(E->getArg(2), N, Info))
7672 MaxLength = N.getExtValue();
7674 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7675 BuiltinOp != Builtin::BIwmemcmp &&
7676 BuiltinOp != Builtin::BI__builtin_memcmp &&
7677 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7678 for (; MaxLength; --MaxLength) {
7679 APValue Char1, Char2;
7680 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7681 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7682 !Char1.isInt() || !Char2.isInt())
7684 if (Char1.getInt() != Char2.getInt())
7685 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7686 if (StopAtNull && !Char1.getInt())
7687 return Success(0, E);
7688 assert(!(StopAtNull && !Char2.getInt()));
7689 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7690 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7693 // We hit the strncmp / memcmp limit.
7694 return Success(0, E);
7697 case Builtin::BI__atomic_always_lock_free:
7698 case Builtin::BI__atomic_is_lock_free:
7699 case Builtin::BI__c11_atomic_is_lock_free: {
7701 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7704 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7705 // of two less than the maximum inline atomic width, we know it is
7706 // lock-free. If the size isn't a power of two, or greater than the
7707 // maximum alignment where we promote atomics, we know it is not lock-free
7708 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7709 // the answer can only be determined at runtime; for example, 16-byte
7710 // atomics have lock-free implementations on some, but not all,
7711 // x86-64 processors.
7713 // Check power-of-two.
7714 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7715 if (Size.isPowerOfTwo()) {
7716 // Check against inlining width.
7717 unsigned InlineWidthBits =
7718 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7719 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7720 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7721 Size == CharUnits::One() ||
7722 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7723 Expr::NPC_NeverValueDependent))
7724 // OK, we will inline appropriately-aligned operations of this size,
7725 // and _Atomic(T) is appropriately-aligned.
7726 return Success(1, E);
7728 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7729 castAs<PointerType>()->getPointeeType();
7730 if (!PointeeType->isIncompleteType() &&
7731 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7732 // OK, we will inline operations on this object.
7733 return Success(1, E);
7738 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7739 Success(0, E) : Error(E);
7744 static bool HasSameBase(const LValue &A, const LValue &B) {
7745 if (!A.getLValueBase())
7746 return !B.getLValueBase();
7747 if (!B.getLValueBase())
7750 if (A.getLValueBase().getOpaqueValue() !=
7751 B.getLValueBase().getOpaqueValue()) {
7752 const Decl *ADecl = GetLValueBaseDecl(A);
7755 const Decl *BDecl = GetLValueBaseDecl(B);
7756 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7760 return IsGlobalLValue(A.getLValueBase()) ||
7761 A.getLValueCallIndex() == B.getLValueCallIndex();
7764 /// \brief Determine whether this is a pointer past the end of the complete
7765 /// object referred to by the lvalue.
7766 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7768 // A null pointer can be viewed as being "past the end" but we don't
7769 // choose to look at it that way here.
7770 if (!LV.getLValueBase())
7773 // If the designator is valid and refers to a subobject, we're not pointing
7775 if (!LV.getLValueDesignator().Invalid &&
7776 !LV.getLValueDesignator().isOnePastTheEnd())
7779 // A pointer to an incomplete type might be past-the-end if the type's size is
7780 // zero. We cannot tell because the type is incomplete.
7781 QualType Ty = getType(LV.getLValueBase());
7782 if (Ty->isIncompleteType())
7785 // We're a past-the-end pointer if we point to the byte after the object,
7786 // no matter what our type or path is.
7787 auto Size = Ctx.getTypeSizeInChars(Ty);
7788 return LV.getLValueOffset() == Size;
7793 /// \brief Data recursive integer evaluator of certain binary operators.
7795 /// We use a data recursive algorithm for binary operators so that we are able
7796 /// to handle extreme cases of chained binary operators without causing stack
7798 class DataRecursiveIntBinOpEvaluator {
7803 EvalResult() : Failed(false) { }
7805 void swap(EvalResult &RHS) {
7807 Failed = RHS.Failed;
7814 EvalResult LHSResult; // meaningful only for binary operator expression.
7815 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7818 Job(Job &&) = default;
7820 void startSpeculativeEval(EvalInfo &Info) {
7821 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7825 SpeculativeEvaluationRAII SpecEvalRAII;
7828 SmallVector<Job, 16> Queue;
7830 IntExprEvaluator &IntEval;
7832 APValue &FinalResult;
7835 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7836 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7838 /// \brief True if \param E is a binary operator that we are going to handle
7839 /// data recursively.
7840 /// We handle binary operators that are comma, logical, or that have operands
7841 /// with integral or enumeration type.
7842 static bool shouldEnqueue(const BinaryOperator *E) {
7843 return E->getOpcode() == BO_Comma ||
7846 E->getType()->isIntegralOrEnumerationType() &&
7847 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7848 E->getRHS()->getType()->isIntegralOrEnumerationType());
7851 bool Traverse(const BinaryOperator *E) {
7853 EvalResult PrevResult;
7854 while (!Queue.empty())
7855 process(PrevResult);
7857 if (PrevResult.Failed) return false;
7859 FinalResult.swap(PrevResult.Val);
7864 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7865 return IntEval.Success(Value, E, Result);
7867 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7868 return IntEval.Success(Value, E, Result);
7870 bool Error(const Expr *E) {
7871 return IntEval.Error(E);
7873 bool Error(const Expr *E, diag::kind D) {
7874 return IntEval.Error(E, D);
7877 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7878 return Info.CCEDiag(E, D);
7881 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7882 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7883 bool &SuppressRHSDiags);
7885 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7886 const BinaryOperator *E, APValue &Result);
7888 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7889 Result.Failed = !Evaluate(Result.Val, Info, E);
7891 Result.Val = APValue();
7894 void process(EvalResult &Result);
7896 void enqueue(const Expr *E) {
7897 E = E->IgnoreParens();
7898 Queue.resize(Queue.size()+1);
7900 Queue.back().Kind = Job::AnyExprKind;
7906 bool DataRecursiveIntBinOpEvaluator::
7907 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7908 bool &SuppressRHSDiags) {
7909 if (E->getOpcode() == BO_Comma) {
7910 // Ignore LHS but note if we could not evaluate it.
7911 if (LHSResult.Failed)
7912 return Info.noteSideEffect();
7916 if (E->isLogicalOp()) {
7918 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7919 // We were able to evaluate the LHS, see if we can get away with not
7920 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7921 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7922 Success(LHSAsBool, E, LHSResult.Val);
7923 return false; // Ignore RHS
7926 LHSResult.Failed = true;
7928 // Since we weren't able to evaluate the left hand side, it
7929 // might have had side effects.
7930 if (!Info.noteSideEffect())
7933 // We can't evaluate the LHS; however, sometimes the result
7934 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7935 // Don't ignore RHS and suppress diagnostics from this arm.
7936 SuppressRHSDiags = true;
7942 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7943 E->getRHS()->getType()->isIntegralOrEnumerationType());
7945 if (LHSResult.Failed && !Info.noteFailure())
7946 return false; // Ignore RHS;
7951 bool DataRecursiveIntBinOpEvaluator::
7952 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7953 const BinaryOperator *E, APValue &Result) {
7954 if (E->getOpcode() == BO_Comma) {
7955 if (RHSResult.Failed)
7957 Result = RHSResult.Val;
7961 if (E->isLogicalOp()) {
7962 bool lhsResult, rhsResult;
7963 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7964 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7968 if (E->getOpcode() == BO_LOr)
7969 return Success(lhsResult || rhsResult, E, Result);
7971 return Success(lhsResult && rhsResult, E, Result);
7975 // We can't evaluate the LHS; however, sometimes the result
7976 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7977 if (rhsResult == (E->getOpcode() == BO_LOr))
7978 return Success(rhsResult, E, Result);
7985 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7986 E->getRHS()->getType()->isIntegralOrEnumerationType());
7988 if (LHSResult.Failed || RHSResult.Failed)
7991 const APValue &LHSVal = LHSResult.Val;
7992 const APValue &RHSVal = RHSResult.Val;
7994 // Handle cases like (unsigned long)&a + 4.
7995 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7997 CharUnits AdditionalOffset =
7998 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7999 if (E->getOpcode() == BO_Add)
8000 Result.getLValueOffset() += AdditionalOffset;
8002 Result.getLValueOffset() -= AdditionalOffset;
8006 // Handle cases like 4 + (unsigned long)&a
8007 if (E->getOpcode() == BO_Add &&
8008 RHSVal.isLValue() && LHSVal.isInt()) {
8010 Result.getLValueOffset() +=
8011 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
8015 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8016 // Handle (intptr_t)&&A - (intptr_t)&&B.
8017 if (!LHSVal.getLValueOffset().isZero() ||
8018 !RHSVal.getLValueOffset().isZero())
8020 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8021 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8022 if (!LHSExpr || !RHSExpr)
8024 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8025 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8026 if (!LHSAddrExpr || !RHSAddrExpr)
8028 // Make sure both labels come from the same function.
8029 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8030 RHSAddrExpr->getLabel()->getDeclContext())
8032 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8036 // All the remaining cases expect both operands to be an integer
8037 if (!LHSVal.isInt() || !RHSVal.isInt())
8040 // Set up the width and signedness manually, in case it can't be deduced
8041 // from the operation we're performing.
8042 // FIXME: Don't do this in the cases where we can deduce it.
8043 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8044 E->getType()->isUnsignedIntegerOrEnumerationType());
8045 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8046 RHSVal.getInt(), Value))
8048 return Success(Value, E, Result);
8051 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8052 Job &job = Queue.back();
8055 case Job::AnyExprKind: {
8056 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8057 if (shouldEnqueue(Bop)) {
8058 job.Kind = Job::BinOpKind;
8059 enqueue(Bop->getLHS());
8064 EvaluateExpr(job.E, Result);
8069 case Job::BinOpKind: {
8070 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8071 bool SuppressRHSDiags = false;
8072 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8076 if (SuppressRHSDiags)
8077 job.startSpeculativeEval(Info);
8078 job.LHSResult.swap(Result);
8079 job.Kind = Job::BinOpVisitedLHSKind;
8080 enqueue(Bop->getRHS());
8084 case Job::BinOpVisitedLHSKind: {
8085 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8088 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8094 llvm_unreachable("Invalid Job::Kind!");
8098 /// Used when we determine that we should fail, but can keep evaluating prior to
8099 /// noting that we had a failure.
8100 class DelayedNoteFailureRAII {
8105 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8106 : Info(Info), NoteFailure(NoteFailure) {}
8107 ~DelayedNoteFailureRAII() {
8109 bool ContinueAfterFailure = Info.noteFailure();
8110 (void)ContinueAfterFailure;
8111 assert(ContinueAfterFailure &&
8112 "Shouldn't have kept evaluating on failure.");
8118 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8119 // We don't call noteFailure immediately because the assignment happens after
8120 // we evaluate LHS and RHS.
8121 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8124 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8125 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8126 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8128 QualType LHSTy = E->getLHS()->getType();
8129 QualType RHSTy = E->getRHS()->getType();
8131 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8132 ComplexValue LHS, RHS;
8134 if (E->isAssignmentOp()) {
8136 EvaluateLValue(E->getLHS(), LV, Info);
8138 } else if (LHSTy->isRealFloatingType()) {
8139 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8141 LHS.makeComplexFloat();
8142 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8145 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8147 if (!LHSOK && !Info.noteFailure())
8150 if (E->getRHS()->getType()->isRealFloatingType()) {
8151 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8153 RHS.makeComplexFloat();
8154 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8155 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8158 if (LHS.isComplexFloat()) {
8159 APFloat::cmpResult CR_r =
8160 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8161 APFloat::cmpResult CR_i =
8162 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8164 if (E->getOpcode() == BO_EQ)
8165 return Success((CR_r == APFloat::cmpEqual &&
8166 CR_i == APFloat::cmpEqual), E);
8168 assert(E->getOpcode() == BO_NE &&
8169 "Invalid complex comparison.");
8170 return Success(((CR_r == APFloat::cmpGreaterThan ||
8171 CR_r == APFloat::cmpLessThan ||
8172 CR_r == APFloat::cmpUnordered) ||
8173 (CR_i == APFloat::cmpGreaterThan ||
8174 CR_i == APFloat::cmpLessThan ||
8175 CR_i == APFloat::cmpUnordered)), E);
8178 if (E->getOpcode() == BO_EQ)
8179 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8180 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8182 assert(E->getOpcode() == BO_NE &&
8183 "Invalid compex comparison.");
8184 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8185 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8190 if (LHSTy->isRealFloatingType() &&
8191 RHSTy->isRealFloatingType()) {
8192 APFloat RHS(0.0), LHS(0.0);
8194 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8195 if (!LHSOK && !Info.noteFailure())
8198 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8201 APFloat::cmpResult CR = LHS.compare(RHS);
8203 switch (E->getOpcode()) {
8205 llvm_unreachable("Invalid binary operator!");
8207 return Success(CR == APFloat::cmpLessThan, E);
8209 return Success(CR == APFloat::cmpGreaterThan, E);
8211 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8213 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8216 return Success(CR == APFloat::cmpEqual, E);
8218 return Success(CR == APFloat::cmpGreaterThan
8219 || CR == APFloat::cmpLessThan
8220 || CR == APFloat::cmpUnordered, E);
8224 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8225 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8226 LValue LHSValue, RHSValue;
8228 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8229 if (!LHSOK && !Info.noteFailure())
8232 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8235 // Reject differing bases from the normal codepath; we special-case
8236 // comparisons to null.
8237 if (!HasSameBase(LHSValue, RHSValue)) {
8238 if (E->getOpcode() == BO_Sub) {
8239 // Handle &&A - &&B.
8240 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8242 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8243 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8244 if (!LHSExpr || !RHSExpr)
8246 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8247 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8248 if (!LHSAddrExpr || !RHSAddrExpr)
8250 // Make sure both labels come from the same function.
8251 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8252 RHSAddrExpr->getLabel()->getDeclContext())
8254 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8256 // Inequalities and subtractions between unrelated pointers have
8257 // unspecified or undefined behavior.
8258 if (!E->isEqualityOp())
8260 // A constant address may compare equal to the address of a symbol.
8261 // The one exception is that address of an object cannot compare equal
8262 // to a null pointer constant.
8263 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8264 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8266 // It's implementation-defined whether distinct literals will have
8267 // distinct addresses. In clang, the result of such a comparison is
8268 // unspecified, so it is not a constant expression. However, we do know
8269 // that the address of a literal will be non-null.
8270 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8271 LHSValue.Base && RHSValue.Base)
8273 // We can't tell whether weak symbols will end up pointing to the same
8275 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8277 // We can't compare the address of the start of one object with the
8278 // past-the-end address of another object, per C++ DR1652.
8279 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8280 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8281 (RHSValue.Base && RHSValue.Offset.isZero() &&
8282 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8284 // We can't tell whether an object is at the same address as another
8285 // zero sized object.
8286 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8287 (LHSValue.Base && isZeroSized(RHSValue)))
8289 // Pointers with different bases cannot represent the same object.
8290 // (Note that clang defaults to -fmerge-all-constants, which can
8291 // lead to inconsistent results for comparisons involving the address
8292 // of a constant; this generally doesn't matter in practice.)
8293 return Success(E->getOpcode() == BO_NE, E);
8296 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8297 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8299 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8300 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8302 if (E->getOpcode() == BO_Sub) {
8303 // C++11 [expr.add]p6:
8304 // Unless both pointers point to elements of the same array object, or
8305 // one past the last element of the array object, the behavior is
8307 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8308 !AreElementsOfSameArray(getType(LHSValue.Base),
8309 LHSDesignator, RHSDesignator))
8310 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8312 QualType Type = E->getLHS()->getType();
8313 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8315 CharUnits ElementSize;
8316 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8319 // As an extension, a type may have zero size (empty struct or union in
8320 // C, array of zero length). Pointer subtraction in such cases has
8321 // undefined behavior, so is not constant.
8322 if (ElementSize.isZero()) {
8323 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8328 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8329 // and produce incorrect results when it overflows. Such behavior
8330 // appears to be non-conforming, but is common, so perhaps we should
8331 // assume the standard intended for such cases to be undefined behavior
8332 // and check for them.
8334 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8335 // overflow in the final conversion to ptrdiff_t.
8337 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8339 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8341 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8342 APSInt TrueResult = (LHS - RHS) / ElemSize;
8343 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8345 if (Result.extend(65) != TrueResult &&
8346 !HandleOverflow(Info, E, TrueResult, E->getType()))
8348 return Success(Result, E);
8351 // C++11 [expr.rel]p3:
8352 // Pointers to void (after pointer conversions) can be compared, with a
8353 // result defined as follows: If both pointers represent the same
8354 // address or are both the null pointer value, the result is true if the
8355 // operator is <= or >= and false otherwise; otherwise the result is
8357 // We interpret this as applying to pointers to *cv* void.
8358 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8359 E->isRelationalOp())
8360 CCEDiag(E, diag::note_constexpr_void_comparison);
8362 // C++11 [expr.rel]p2:
8363 // - If two pointers point to non-static data members of the same object,
8364 // or to subobjects or array elements fo such members, recursively, the
8365 // pointer to the later declared member compares greater provided the
8366 // two members have the same access control and provided their class is
8369 // - Otherwise pointer comparisons are unspecified.
8370 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8371 E->isRelationalOp()) {
8374 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8375 RHSDesignator, WasArrayIndex);
8376 // At the point where the designators diverge, the comparison has a
8377 // specified value if:
8378 // - we are comparing array indices
8379 // - we are comparing fields of a union, or fields with the same access
8380 // Otherwise, the result is unspecified and thus the comparison is not a
8381 // constant expression.
8382 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8383 Mismatch < RHSDesignator.Entries.size()) {
8384 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8385 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8387 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8389 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8390 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8391 << RF->getParent() << RF;
8393 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8394 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8395 << LF->getParent() << LF;
8396 else if (!LF->getParent()->isUnion() &&
8397 LF->getAccess() != RF->getAccess())
8398 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8399 << LF << LF->getAccess() << RF << RF->getAccess()
8404 // The comparison here must be unsigned, and performed with the same
8405 // width as the pointer.
8406 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8407 uint64_t CompareLHS = LHSOffset.getQuantity();
8408 uint64_t CompareRHS = RHSOffset.getQuantity();
8409 assert(PtrSize <= 64 && "Unexpected pointer width");
8410 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8414 // If there is a base and this is a relational operator, we can only
8415 // compare pointers within the object in question; otherwise, the result
8416 // depends on where the object is located in memory.
8417 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8418 QualType BaseTy = getType(LHSValue.Base);
8419 if (BaseTy->isIncompleteType())
8421 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8422 uint64_t OffsetLimit = Size.getQuantity();
8423 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8427 switch (E->getOpcode()) {
8428 default: llvm_unreachable("missing comparison operator");
8429 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8430 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8431 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8432 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8433 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8434 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8439 if (LHSTy->isMemberPointerType()) {
8440 assert(E->isEqualityOp() && "unexpected member pointer operation");
8441 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8443 MemberPtr LHSValue, RHSValue;
8445 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8446 if (!LHSOK && !Info.noteFailure())
8449 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8452 // C++11 [expr.eq]p2:
8453 // If both operands are null, they compare equal. Otherwise if only one is
8454 // null, they compare unequal.
8455 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8456 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8457 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8460 // Otherwise if either is a pointer to a virtual member function, the
8461 // result is unspecified.
8462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8463 if (MD->isVirtual())
8464 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8465 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8466 if (MD->isVirtual())
8467 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8469 // Otherwise they compare equal if and only if they would refer to the
8470 // same member of the same most derived object or the same subobject if
8471 // they were dereferenced with a hypothetical object of the associated
8473 bool Equal = LHSValue == RHSValue;
8474 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8477 if (LHSTy->isNullPtrType()) {
8478 assert(E->isComparisonOp() && "unexpected nullptr operation");
8479 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8480 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8481 // are compared, the result is true of the operator is <=, >= or ==, and
8483 BinaryOperator::Opcode Opcode = E->getOpcode();
8484 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8487 assert((!LHSTy->isIntegralOrEnumerationType() ||
8488 !RHSTy->isIntegralOrEnumerationType()) &&
8489 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8490 // We can't continue from here for non-integral types.
8491 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8494 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8495 /// a result as the expression's type.
8496 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8497 const UnaryExprOrTypeTraitExpr *E) {
8498 switch(E->getKind()) {
8499 case UETT_AlignOf: {
8500 if (E->isArgumentType())
8501 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8503 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8506 case UETT_VecStep: {
8507 QualType Ty = E->getTypeOfArgument();
8509 if (Ty->isVectorType()) {
8510 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8512 // The vec_step built-in functions that take a 3-component
8513 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8517 return Success(n, E);
8519 return Success(1, E);
8523 QualType SrcTy = E->getTypeOfArgument();
8524 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8525 // the result is the size of the referenced type."
8526 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8527 SrcTy = Ref->getPointeeType();
8530 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8532 return Success(Sizeof, E);
8534 case UETT_OpenMPRequiredSimdAlign:
8535 assert(E->isArgumentType());
8537 Info.Ctx.toCharUnitsFromBits(
8538 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8543 llvm_unreachable("unknown expr/type trait");
8546 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8548 unsigned n = OOE->getNumComponents();
8551 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8552 for (unsigned i = 0; i != n; ++i) {
8553 OffsetOfNode ON = OOE->getComponent(i);
8554 switch (ON.getKind()) {
8555 case OffsetOfNode::Array: {
8556 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8558 if (!EvaluateInteger(Idx, IdxResult, Info))
8560 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8563 CurrentType = AT->getElementType();
8564 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8565 Result += IdxResult.getSExtValue() * ElementSize;
8569 case OffsetOfNode::Field: {
8570 FieldDecl *MemberDecl = ON.getField();
8571 const RecordType *RT = CurrentType->getAs<RecordType>();
8574 RecordDecl *RD = RT->getDecl();
8575 if (RD->isInvalidDecl()) return false;
8576 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8577 unsigned i = MemberDecl->getFieldIndex();
8578 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8579 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8580 CurrentType = MemberDecl->getType().getNonReferenceType();
8584 case OffsetOfNode::Identifier:
8585 llvm_unreachable("dependent __builtin_offsetof");
8587 case OffsetOfNode::Base: {
8588 CXXBaseSpecifier *BaseSpec = ON.getBase();
8589 if (BaseSpec->isVirtual())
8592 // Find the layout of the class whose base we are looking into.
8593 const RecordType *RT = CurrentType->getAs<RecordType>();
8596 RecordDecl *RD = RT->getDecl();
8597 if (RD->isInvalidDecl()) return false;
8598 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8600 // Find the base class itself.
8601 CurrentType = BaseSpec->getType();
8602 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8606 // Add the offset to the base.
8607 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8612 return Success(Result, OOE);
8615 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8616 switch (E->getOpcode()) {
8618 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8622 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8623 // If so, we could clear the diagnostic ID.
8624 return Visit(E->getSubExpr());
8626 // The result is just the value.
8627 return Visit(E->getSubExpr());
8629 if (!Visit(E->getSubExpr()))
8631 if (!Result.isInt()) return Error(E);
8632 const APSInt &Value = Result.getInt();
8633 if (Value.isSigned() && Value.isMinSignedValue() &&
8634 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8637 return Success(-Value, E);
8640 if (!Visit(E->getSubExpr()))
8642 if (!Result.isInt()) return Error(E);
8643 return Success(~Result.getInt(), E);
8647 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8649 return Success(!bres, E);
8654 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8655 /// result type is integer.
8656 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8657 const Expr *SubExpr = E->getSubExpr();
8658 QualType DestType = E->getType();
8659 QualType SrcType = SubExpr->getType();
8661 switch (E->getCastKind()) {
8662 case CK_BaseToDerived:
8663 case CK_DerivedToBase:
8664 case CK_UncheckedDerivedToBase:
8667 case CK_ArrayToPointerDecay:
8668 case CK_FunctionToPointerDecay:
8669 case CK_NullToPointer:
8670 case CK_NullToMemberPointer:
8671 case CK_BaseToDerivedMemberPointer:
8672 case CK_DerivedToBaseMemberPointer:
8673 case CK_ReinterpretMemberPointer:
8674 case CK_ConstructorConversion:
8675 case CK_IntegralToPointer:
8677 case CK_VectorSplat:
8678 case CK_IntegralToFloating:
8679 case CK_FloatingCast:
8680 case CK_CPointerToObjCPointerCast:
8681 case CK_BlockPointerToObjCPointerCast:
8682 case CK_AnyPointerToBlockPointerCast:
8683 case CK_ObjCObjectLValueCast:
8684 case CK_FloatingRealToComplex:
8685 case CK_FloatingComplexToReal:
8686 case CK_FloatingComplexCast:
8687 case CK_FloatingComplexToIntegralComplex:
8688 case CK_IntegralRealToComplex:
8689 case CK_IntegralComplexCast:
8690 case CK_IntegralComplexToFloatingComplex:
8691 case CK_BuiltinFnToFnPtr:
8692 case CK_ZeroToOCLEvent:
8693 case CK_ZeroToOCLQueue:
8694 case CK_NonAtomicToAtomic:
8695 case CK_AddressSpaceConversion:
8696 case CK_IntToOCLSampler:
8697 llvm_unreachable("invalid cast kind for integral value");
8701 case CK_LValueBitCast:
8702 case CK_ARCProduceObject:
8703 case CK_ARCConsumeObject:
8704 case CK_ARCReclaimReturnedObject:
8705 case CK_ARCExtendBlockObject:
8706 case CK_CopyAndAutoreleaseBlockObject:
8709 case CK_UserDefinedConversion:
8710 case CK_LValueToRValue:
8711 case CK_AtomicToNonAtomic:
8713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8715 case CK_MemberPointerToBoolean:
8716 case CK_PointerToBoolean:
8717 case CK_IntegralToBoolean:
8718 case CK_FloatingToBoolean:
8719 case CK_BooleanToSignedIntegral:
8720 case CK_FloatingComplexToBoolean:
8721 case CK_IntegralComplexToBoolean: {
8723 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8725 uint64_t IntResult = BoolResult;
8726 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8727 IntResult = (uint64_t)-1;
8728 return Success(IntResult, E);
8731 case CK_IntegralCast: {
8732 if (!Visit(SubExpr))
8735 if (!Result.isInt()) {
8736 // Allow casts of address-of-label differences if they are no-ops
8737 // or narrowing. (The narrowing case isn't actually guaranteed to
8738 // be constant-evaluatable except in some narrow cases which are hard
8739 // to detect here. We let it through on the assumption the user knows
8740 // what they are doing.)
8741 if (Result.isAddrLabelDiff())
8742 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8743 // Only allow casts of lvalues if they are lossless.
8744 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8747 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8748 Result.getInt()), E);
8751 case CK_PointerToIntegral: {
8752 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8755 if (!EvaluatePointer(SubExpr, LV, Info))
8758 if (LV.getLValueBase()) {
8759 // Only allow based lvalue casts if they are lossless.
8760 // FIXME: Allow a larger integer size than the pointer size, and allow
8761 // narrowing back down to pointer width in subsequent integral casts.
8762 // FIXME: Check integer type's active bits, not its type size.
8763 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8766 LV.Designator.setInvalid();
8767 LV.moveInto(Result);
8772 if (LV.isNullPointer())
8773 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8775 V = LV.getLValueOffset().getQuantity();
8777 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8778 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8781 case CK_IntegralComplexToReal: {
8783 if (!EvaluateComplex(SubExpr, C, Info))
8785 return Success(C.getComplexIntReal(), E);
8788 case CK_FloatingToIntegral: {
8790 if (!EvaluateFloat(SubExpr, F, Info))
8794 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8796 return Success(Value, E);
8800 llvm_unreachable("unknown cast resulting in integral value");
8803 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8804 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8806 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8808 if (!LV.isComplexInt())
8810 return Success(LV.getComplexIntReal(), E);
8813 return Visit(E->getSubExpr());
8816 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8817 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8819 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8821 if (!LV.isComplexInt())
8823 return Success(LV.getComplexIntImag(), E);
8826 VisitIgnoredValue(E->getSubExpr());
8827 return Success(0, E);
8830 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8831 return Success(E->getPackLength(), E);
8834 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8835 return Success(E->getValue(), E);
8838 //===----------------------------------------------------------------------===//
8840 //===----------------------------------------------------------------------===//
8843 class FloatExprEvaluator
8844 : public ExprEvaluatorBase<FloatExprEvaluator> {
8847 FloatExprEvaluator(EvalInfo &info, APFloat &result)
8848 : ExprEvaluatorBaseTy(info), Result(result) {}
8850 bool Success(const APValue &V, const Expr *e) {
8851 Result = V.getFloat();
8855 bool ZeroInitialization(const Expr *E) {
8856 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8860 bool VisitCallExpr(const CallExpr *E);
8862 bool VisitUnaryOperator(const UnaryOperator *E);
8863 bool VisitBinaryOperator(const BinaryOperator *E);
8864 bool VisitFloatingLiteral(const FloatingLiteral *E);
8865 bool VisitCastExpr(const CastExpr *E);
8867 bool VisitUnaryReal(const UnaryOperator *E);
8868 bool VisitUnaryImag(const UnaryOperator *E);
8870 // FIXME: Missing: array subscript of vector, member of vector
8872 } // end anonymous namespace
8874 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
8875 assert(E->isRValue() && E->getType()->isRealFloatingType());
8876 return FloatExprEvaluator(Info, Result).Visit(E);
8879 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
8883 llvm::APFloat &Result) {
8884 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8885 if (!S) return false;
8887 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8891 // Treat empty strings as if they were zero.
8892 if (S->getString().empty())
8893 fill = llvm::APInt(32, 0);
8894 else if (S->getString().getAsInteger(0, fill))
8897 if (Context.getTargetInfo().isNan2008()) {
8899 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8901 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8903 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8904 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8905 // a different encoding to what became a standard in 2008, and for pre-
8906 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8907 // sNaN. This is now known as "legacy NaN" encoding.
8909 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8911 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8917 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
8918 switch (E->getBuiltinCallee()) {
8920 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8922 case Builtin::BI__builtin_huge_val:
8923 case Builtin::BI__builtin_huge_valf:
8924 case Builtin::BI__builtin_huge_vall:
8925 case Builtin::BI__builtin_inf:
8926 case Builtin::BI__builtin_inff:
8927 case Builtin::BI__builtin_infl: {
8928 const llvm::fltSemantics &Sem =
8929 Info.Ctx.getFloatTypeSemantics(E->getType());
8930 Result = llvm::APFloat::getInf(Sem);
8934 case Builtin::BI__builtin_nans:
8935 case Builtin::BI__builtin_nansf:
8936 case Builtin::BI__builtin_nansl:
8937 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8942 case Builtin::BI__builtin_nan:
8943 case Builtin::BI__builtin_nanf:
8944 case Builtin::BI__builtin_nanl:
8945 // If this is __builtin_nan() turn this into a nan, otherwise we
8946 // can't constant fold it.
8947 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8952 case Builtin::BI__builtin_fabs:
8953 case Builtin::BI__builtin_fabsf:
8954 case Builtin::BI__builtin_fabsl:
8955 if (!EvaluateFloat(E->getArg(0), Result, Info))
8958 if (Result.isNegative())
8959 Result.changeSign();
8962 // FIXME: Builtin::BI__builtin_powi
8963 // FIXME: Builtin::BI__builtin_powif
8964 // FIXME: Builtin::BI__builtin_powil
8966 case Builtin::BI__builtin_copysign:
8967 case Builtin::BI__builtin_copysignf:
8968 case Builtin::BI__builtin_copysignl: {
8970 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8971 !EvaluateFloat(E->getArg(1), RHS, Info))
8973 Result.copySign(RHS);
8979 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8980 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8982 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8984 Result = CV.FloatReal;
8988 return Visit(E->getSubExpr());
8991 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8992 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8994 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8996 Result = CV.FloatImag;
9000 VisitIgnoredValue(E->getSubExpr());
9001 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9002 Result = llvm::APFloat::getZero(Sem);
9006 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9007 switch (E->getOpcode()) {
9008 default: return Error(E);
9010 return EvaluateFloat(E->getSubExpr(), Result, Info);
9012 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9014 Result.changeSign();
9019 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9020 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9021 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9024 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9025 if (!LHSOK && !Info.noteFailure())
9027 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9028 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9031 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9032 Result = E->getValue();
9036 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9037 const Expr* SubExpr = E->getSubExpr();
9039 switch (E->getCastKind()) {
9041 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9043 case CK_IntegralToFloating: {
9045 return EvaluateInteger(SubExpr, IntResult, Info) &&
9046 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9047 E->getType(), Result);
9050 case CK_FloatingCast: {
9051 if (!Visit(SubExpr))
9053 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9057 case CK_FloatingComplexToReal: {
9059 if (!EvaluateComplex(SubExpr, V, Info))
9061 Result = V.getComplexFloatReal();
9067 //===----------------------------------------------------------------------===//
9068 // Complex Evaluation (for float and integer)
9069 //===----------------------------------------------------------------------===//
9072 class ComplexExprEvaluator
9073 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9074 ComplexValue &Result;
9077 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9078 : ExprEvaluatorBaseTy(info), Result(Result) {}
9080 bool Success(const APValue &V, const Expr *e) {
9085 bool ZeroInitialization(const Expr *E);
9087 //===--------------------------------------------------------------------===//
9089 //===--------------------------------------------------------------------===//
9091 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9092 bool VisitCastExpr(const CastExpr *E);
9093 bool VisitBinaryOperator(const BinaryOperator *E);
9094 bool VisitUnaryOperator(const UnaryOperator *E);
9095 bool VisitInitListExpr(const InitListExpr *E);
9097 } // end anonymous namespace
9099 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9101 assert(E->isRValue() && E->getType()->isAnyComplexType());
9102 return ComplexExprEvaluator(Info, Result).Visit(E);
9105 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9106 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9107 if (ElemTy->isRealFloatingType()) {
9108 Result.makeComplexFloat();
9109 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9110 Result.FloatReal = Zero;
9111 Result.FloatImag = Zero;
9113 Result.makeComplexInt();
9114 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9115 Result.IntReal = Zero;
9116 Result.IntImag = Zero;
9121 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9122 const Expr* SubExpr = E->getSubExpr();
9124 if (SubExpr->getType()->isRealFloatingType()) {
9125 Result.makeComplexFloat();
9126 APFloat &Imag = Result.FloatImag;
9127 if (!EvaluateFloat(SubExpr, Imag, Info))
9130 Result.FloatReal = APFloat(Imag.getSemantics());
9133 assert(SubExpr->getType()->isIntegerType() &&
9134 "Unexpected imaginary literal.");
9136 Result.makeComplexInt();
9137 APSInt &Imag = Result.IntImag;
9138 if (!EvaluateInteger(SubExpr, Imag, Info))
9141 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9146 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9148 switch (E->getCastKind()) {
9150 case CK_BaseToDerived:
9151 case CK_DerivedToBase:
9152 case CK_UncheckedDerivedToBase:
9155 case CK_ArrayToPointerDecay:
9156 case CK_FunctionToPointerDecay:
9157 case CK_NullToPointer:
9158 case CK_NullToMemberPointer:
9159 case CK_BaseToDerivedMemberPointer:
9160 case CK_DerivedToBaseMemberPointer:
9161 case CK_MemberPointerToBoolean:
9162 case CK_ReinterpretMemberPointer:
9163 case CK_ConstructorConversion:
9164 case CK_IntegralToPointer:
9165 case CK_PointerToIntegral:
9166 case CK_PointerToBoolean:
9168 case CK_VectorSplat:
9169 case CK_IntegralCast:
9170 case CK_BooleanToSignedIntegral:
9171 case CK_IntegralToBoolean:
9172 case CK_IntegralToFloating:
9173 case CK_FloatingToIntegral:
9174 case CK_FloatingToBoolean:
9175 case CK_FloatingCast:
9176 case CK_CPointerToObjCPointerCast:
9177 case CK_BlockPointerToObjCPointerCast:
9178 case CK_AnyPointerToBlockPointerCast:
9179 case CK_ObjCObjectLValueCast:
9180 case CK_FloatingComplexToReal:
9181 case CK_FloatingComplexToBoolean:
9182 case CK_IntegralComplexToReal:
9183 case CK_IntegralComplexToBoolean:
9184 case CK_ARCProduceObject:
9185 case CK_ARCConsumeObject:
9186 case CK_ARCReclaimReturnedObject:
9187 case CK_ARCExtendBlockObject:
9188 case CK_CopyAndAutoreleaseBlockObject:
9189 case CK_BuiltinFnToFnPtr:
9190 case CK_ZeroToOCLEvent:
9191 case CK_ZeroToOCLQueue:
9192 case CK_NonAtomicToAtomic:
9193 case CK_AddressSpaceConversion:
9194 case CK_IntToOCLSampler:
9195 llvm_unreachable("invalid cast kind for complex value");
9197 case CK_LValueToRValue:
9198 case CK_AtomicToNonAtomic:
9200 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9203 case CK_LValueBitCast:
9204 case CK_UserDefinedConversion:
9207 case CK_FloatingRealToComplex: {
9208 APFloat &Real = Result.FloatReal;
9209 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9212 Result.makeComplexFloat();
9213 Result.FloatImag = APFloat(Real.getSemantics());
9217 case CK_FloatingComplexCast: {
9218 if (!Visit(E->getSubExpr()))
9221 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9223 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9225 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9226 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9229 case CK_FloatingComplexToIntegralComplex: {
9230 if (!Visit(E->getSubExpr()))
9233 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9235 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9236 Result.makeComplexInt();
9237 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9238 To, Result.IntReal) &&
9239 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9240 To, Result.IntImag);
9243 case CK_IntegralRealToComplex: {
9244 APSInt &Real = Result.IntReal;
9245 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9248 Result.makeComplexInt();
9249 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9253 case CK_IntegralComplexCast: {
9254 if (!Visit(E->getSubExpr()))
9257 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9259 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9261 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9262 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9266 case CK_IntegralComplexToFloatingComplex: {
9267 if (!Visit(E->getSubExpr()))
9270 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9272 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9273 Result.makeComplexFloat();
9274 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9275 To, Result.FloatReal) &&
9276 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9277 To, Result.FloatImag);
9281 llvm_unreachable("unknown cast resulting in complex value");
9284 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9285 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9286 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9288 // Track whether the LHS or RHS is real at the type system level. When this is
9289 // the case we can simplify our evaluation strategy.
9290 bool LHSReal = false, RHSReal = false;
9293 if (E->getLHS()->getType()->isRealFloatingType()) {
9295 APFloat &Real = Result.FloatReal;
9296 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9298 Result.makeComplexFloat();
9299 Result.FloatImag = APFloat(Real.getSemantics());
9302 LHSOK = Visit(E->getLHS());
9304 if (!LHSOK && !Info.noteFailure())
9308 if (E->getRHS()->getType()->isRealFloatingType()) {
9310 APFloat &Real = RHS.FloatReal;
9311 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9313 RHS.makeComplexFloat();
9314 RHS.FloatImag = APFloat(Real.getSemantics());
9315 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9318 assert(!(LHSReal && RHSReal) &&
9319 "Cannot have both operands of a complex operation be real.");
9320 switch (E->getOpcode()) {
9321 default: return Error(E);
9323 if (Result.isComplexFloat()) {
9324 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9325 APFloat::rmNearestTiesToEven);
9327 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9329 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9330 APFloat::rmNearestTiesToEven);
9332 Result.getComplexIntReal() += RHS.getComplexIntReal();
9333 Result.getComplexIntImag() += RHS.getComplexIntImag();
9337 if (Result.isComplexFloat()) {
9338 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9339 APFloat::rmNearestTiesToEven);
9341 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9342 Result.getComplexFloatImag().changeSign();
9343 } else if (!RHSReal) {
9344 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9345 APFloat::rmNearestTiesToEven);
9348 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9349 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9353 if (Result.isComplexFloat()) {
9354 // This is an implementation of complex multiplication according to the
9355 // constraints laid out in C11 Annex G. The implemantion uses the
9356 // following naming scheme:
9357 // (a + ib) * (c + id)
9358 ComplexValue LHS = Result;
9359 APFloat &A = LHS.getComplexFloatReal();
9360 APFloat &B = LHS.getComplexFloatImag();
9361 APFloat &C = RHS.getComplexFloatReal();
9362 APFloat &D = RHS.getComplexFloatImag();
9363 APFloat &ResR = Result.getComplexFloatReal();
9364 APFloat &ResI = Result.getComplexFloatImag();
9366 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9369 } else if (RHSReal) {
9373 // In the fully general case, we need to handle NaNs and infinities
9381 if (ResR.isNaN() && ResI.isNaN()) {
9382 bool Recalc = false;
9383 if (A.isInfinity() || B.isInfinity()) {
9384 A = APFloat::copySign(
9385 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9386 B = APFloat::copySign(
9387 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9389 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9391 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9394 if (C.isInfinity() || D.isInfinity()) {
9395 C = APFloat::copySign(
9396 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9397 D = APFloat::copySign(
9398 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9400 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9402 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9405 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9406 AD.isInfinity() || BC.isInfinity())) {
9408 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9410 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9412 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9414 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9418 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9419 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9424 ComplexValue LHS = Result;
9425 Result.getComplexIntReal() =
9426 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9427 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9428 Result.getComplexIntImag() =
9429 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9430 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9434 if (Result.isComplexFloat()) {
9435 // This is an implementation of complex division according to the
9436 // constraints laid out in C11 Annex G. The implemantion uses the
9437 // following naming scheme:
9438 // (a + ib) / (c + id)
9439 ComplexValue LHS = Result;
9440 APFloat &A = LHS.getComplexFloatReal();
9441 APFloat &B = LHS.getComplexFloatImag();
9442 APFloat &C = RHS.getComplexFloatReal();
9443 APFloat &D = RHS.getComplexFloatImag();
9444 APFloat &ResR = Result.getComplexFloatReal();
9445 APFloat &ResI = Result.getComplexFloatImag();
9451 // No real optimizations we can do here, stub out with zero.
9452 B = APFloat::getZero(A.getSemantics());
9455 APFloat MaxCD = maxnum(abs(C), abs(D));
9456 if (MaxCD.isFinite()) {
9457 DenomLogB = ilogb(MaxCD);
9458 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9459 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9461 APFloat Denom = C * C + D * D;
9462 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9463 APFloat::rmNearestTiesToEven);
9464 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9465 APFloat::rmNearestTiesToEven);
9466 if (ResR.isNaN() && ResI.isNaN()) {
9467 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9468 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9469 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9470 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9472 A = APFloat::copySign(
9473 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9474 B = APFloat::copySign(
9475 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9476 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9477 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9478 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9479 C = APFloat::copySign(
9480 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9481 D = APFloat::copySign(
9482 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9483 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9484 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9489 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9490 return Error(E, diag::note_expr_divide_by_zero);
9492 ComplexValue LHS = Result;
9493 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9494 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9495 Result.getComplexIntReal() =
9496 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9497 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9498 Result.getComplexIntImag() =
9499 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9500 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9508 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9509 // Get the operand value into 'Result'.
9510 if (!Visit(E->getSubExpr()))
9513 switch (E->getOpcode()) {
9519 // The result is always just the subexpr.
9522 if (Result.isComplexFloat()) {
9523 Result.getComplexFloatReal().changeSign();
9524 Result.getComplexFloatImag().changeSign();
9527 Result.getComplexIntReal() = -Result.getComplexIntReal();
9528 Result.getComplexIntImag() = -Result.getComplexIntImag();
9532 if (Result.isComplexFloat())
9533 Result.getComplexFloatImag().changeSign();
9535 Result.getComplexIntImag() = -Result.getComplexIntImag();
9540 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9541 if (E->getNumInits() == 2) {
9542 if (E->getType()->isComplexType()) {
9543 Result.makeComplexFloat();
9544 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9546 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9549 Result.makeComplexInt();
9550 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9552 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9557 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9560 //===----------------------------------------------------------------------===//
9561 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9562 // implicit conversion.
9563 //===----------------------------------------------------------------------===//
9566 class AtomicExprEvaluator :
9567 public ExprEvaluatorBase<AtomicExprEvaluator> {
9570 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9571 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9573 bool Success(const APValue &V, const Expr *E) {
9578 bool ZeroInitialization(const Expr *E) {
9579 ImplicitValueInitExpr VIE(
9580 E->getType()->castAs<AtomicType>()->getValueType());
9581 return Evaluate(Result, Info, &VIE);
9584 bool VisitCastExpr(const CastExpr *E) {
9585 switch (E->getCastKind()) {
9587 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9588 case CK_NonAtomicToAtomic:
9589 return Evaluate(Result, Info, E->getSubExpr());
9593 } // end anonymous namespace
9595 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9596 assert(E->isRValue() && E->getType()->isAtomicType());
9597 return AtomicExprEvaluator(Info, Result).Visit(E);
9600 //===----------------------------------------------------------------------===//
9601 // Void expression evaluation, primarily for a cast to void on the LHS of a
9603 //===----------------------------------------------------------------------===//
9606 class VoidExprEvaluator
9607 : public ExprEvaluatorBase<VoidExprEvaluator> {
9609 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9611 bool Success(const APValue &V, const Expr *e) { return true; }
9613 bool VisitCastExpr(const CastExpr *E) {
9614 switch (E->getCastKind()) {
9616 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9618 VisitIgnoredValue(E->getSubExpr());
9623 bool VisitCallExpr(const CallExpr *E) {
9624 switch (E->getBuiltinCallee()) {
9626 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9627 case Builtin::BI__assume:
9628 case Builtin::BI__builtin_assume:
9629 // The argument is not evaluated!
9634 } // end anonymous namespace
9636 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9637 assert(E->isRValue() && E->getType()->isVoidType());
9638 return VoidExprEvaluator(Info).Visit(E);
9641 //===----------------------------------------------------------------------===//
9642 // Top level Expr::EvaluateAsRValue method.
9643 //===----------------------------------------------------------------------===//
9645 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9646 // In C, function designators are not lvalues, but we evaluate them as if they
9648 QualType T = E->getType();
9649 if (E->isGLValue() || T->isFunctionType()) {
9651 if (!EvaluateLValue(E, LV, Info))
9653 LV.moveInto(Result);
9654 } else if (T->isVectorType()) {
9655 if (!EvaluateVector(E, Result, Info))
9657 } else if (T->isIntegralOrEnumerationType()) {
9658 if (!IntExprEvaluator(Info, Result).Visit(E))
9660 } else if (T->hasPointerRepresentation()) {
9662 if (!EvaluatePointer(E, LV, Info))
9664 LV.moveInto(Result);
9665 } else if (T->isRealFloatingType()) {
9666 llvm::APFloat F(0.0);
9667 if (!EvaluateFloat(E, F, Info))
9669 Result = APValue(F);
9670 } else if (T->isAnyComplexType()) {
9672 if (!EvaluateComplex(E, C, Info))
9675 } else if (T->isMemberPointerType()) {
9677 if (!EvaluateMemberPointer(E, P, Info))
9681 } else if (T->isArrayType()) {
9683 LV.set(E, Info.CurrentCall->Index);
9684 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9685 if (!EvaluateArray(E, LV, Value, Info))
9688 } else if (T->isRecordType()) {
9690 LV.set(E, Info.CurrentCall->Index);
9691 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9692 if (!EvaluateRecord(E, LV, Value, Info))
9695 } else if (T->isVoidType()) {
9696 if (!Info.getLangOpts().CPlusPlus11)
9697 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9699 if (!EvaluateVoid(E, Info))
9701 } else if (T->isAtomicType()) {
9702 if (!EvaluateAtomic(E, Result, Info))
9704 } else if (Info.getLangOpts().CPlusPlus11) {
9705 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9708 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9715 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9716 /// cases, the in-place evaluation is essential, since later initializers for
9717 /// an object can indirectly refer to subobjects which were initialized earlier.
9718 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9719 const Expr *E, bool AllowNonLiteralTypes) {
9720 assert(!E->isValueDependent());
9722 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9725 if (E->isRValue()) {
9726 // Evaluate arrays and record types in-place, so that later initializers can
9727 // refer to earlier-initialized members of the object.
9728 if (E->getType()->isArrayType())
9729 return EvaluateArray(E, This, Result, Info);
9730 else if (E->getType()->isRecordType())
9731 return EvaluateRecord(E, This, Result, Info);
9734 // For any other type, in-place evaluation is unimportant.
9735 return Evaluate(Result, Info, E);
9738 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9739 /// lvalue-to-rvalue cast if it is an lvalue.
9740 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9741 if (E->getType().isNull())
9744 if (!CheckLiteralType(Info, E))
9747 if (!::Evaluate(Result, Info, E))
9750 if (E->isGLValue()) {
9752 LV.setFrom(Info.Ctx, Result);
9753 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9757 // Check this core constant expression is a constant expression.
9758 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9761 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9762 const ASTContext &Ctx, bool &IsConst) {
9763 // Fast-path evaluations of integer literals, since we sometimes see files
9764 // containing vast quantities of these.
9765 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9766 Result.Val = APValue(APSInt(L->getValue(),
9767 L->getType()->isUnsignedIntegerType()));
9772 // This case should be rare, but we need to check it before we check on
9774 if (Exp->getType().isNull()) {
9779 // FIXME: Evaluating values of large array and record types can cause
9780 // performance problems. Only do so in C++11 for now.
9781 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9782 Exp->getType()->isRecordType()) &&
9783 !Ctx.getLangOpts().CPlusPlus11) {
9791 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9792 /// any crazy technique (that has nothing to do with language standards) that
9793 /// we want to. If this function returns true, it returns the folded constant
9794 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9795 /// will be applied to the result.
9796 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9798 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9801 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9802 return ::EvaluateAsRValue(Info, this, Result.Val);
9805 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9806 const ASTContext &Ctx) const {
9808 return EvaluateAsRValue(Scratch, Ctx) &&
9809 HandleConversionToBool(Scratch.Val, Result);
9812 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9813 Expr::SideEffectsKind SEK) {
9814 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9815 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9818 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9819 SideEffectsKind AllowSideEffects) const {
9820 if (!getType()->isIntegralOrEnumerationType())
9823 EvalResult ExprResult;
9824 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9825 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9828 Result = ExprResult.Val.getInt();
9832 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9833 SideEffectsKind AllowSideEffects) const {
9834 if (!getType()->isRealFloatingType())
9837 EvalResult ExprResult;
9838 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9839 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9842 Result = ExprResult.Val.getFloat();
9846 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
9847 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
9850 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9851 !CheckLValueConstantExpression(Info, getExprLoc(),
9852 Ctx.getLValueReferenceType(getType()), LV))
9855 LV.moveInto(Result.Val);
9859 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9861 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
9862 // FIXME: Evaluating initializers for large array and record types can cause
9863 // performance problems. Only do so in C++11 for now.
9864 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
9865 !Ctx.getLangOpts().CPlusPlus11)
9868 Expr::EvalStatus EStatus;
9869 EStatus.Diag = &Notes;
9871 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9872 ? EvalInfo::EM_ConstantExpression
9873 : EvalInfo::EM_ConstantFold);
9874 InitInfo.setEvaluatingDecl(VD, Value);
9879 // C++11 [basic.start.init]p2:
9880 // Variables with static storage duration or thread storage duration shall be
9881 // zero-initialized before any other initialization takes place.
9882 // This behavior is not present in C.
9883 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
9884 !VD->getType()->isReferenceType()) {
9885 ImplicitValueInitExpr VIE(VD->getType());
9886 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
9887 /*AllowNonLiteralTypes=*/true))
9891 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9892 /*AllowNonLiteralTypes=*/true) ||
9893 EStatus.HasSideEffects)
9896 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9900 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9901 /// constant folded, but discard the result.
9902 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
9904 return EvaluateAsRValue(Result, Ctx) &&
9905 !hasUnacceptableSideEffect(Result, SEK);
9908 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
9909 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
9910 EvalResult EvalResult;
9911 EvalResult.Diag = Diag;
9912 bool Result = EvaluateAsRValue(EvalResult, Ctx);
9914 assert(Result && "Could not evaluate expression");
9915 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
9917 return EvalResult.Val.getInt();
9920 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
9922 EvalResult EvalResult;
9923 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
9924 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
9925 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9929 bool Expr::EvalResult::isGlobalLValue() const {
9930 assert(Val.isLValue());
9931 return IsGlobalLValue(Val.getLValueBase());
9935 /// isIntegerConstantExpr - this recursive routine will test if an expression is
9936 /// an integer constant expression.
9938 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9941 // CheckICE - This function does the fundamental ICE checking: the returned
9942 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9943 // and a (possibly null) SourceLocation indicating the location of the problem.
9945 // Note that to reduce code duplication, this helper does no evaluation
9946 // itself; the caller checks whether the expression is evaluatable, and
9947 // in the rare cases where CheckICE actually cares about the evaluated
9948 // value, it calls into Evalute.
9953 /// This expression is an ICE.
9955 /// This expression is not an ICE, but if it isn't evaluated, it's
9956 /// a legal subexpression for an ICE. This return value is used to handle
9957 /// the comma operator in C99 mode, and non-constant subexpressions.
9958 IK_ICEIfUnevaluated,
9959 /// This expression is not an ICE, and is not a legal subexpression for one.
9967 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9972 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9974 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9976 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9977 Expr::EvalResult EVResult;
9978 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9979 !EVResult.Val.isInt())
9980 return ICEDiag(IK_NotICE, E->getLocStart());
9985 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9986 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9987 if (!E->getType()->isIntegralOrEnumerationType())
9988 return ICEDiag(IK_NotICE, E->getLocStart());
9990 switch (E->getStmtClass()) {
9991 #define ABSTRACT_STMT(Node)
9992 #define STMT(Node, Base) case Expr::Node##Class:
9993 #define EXPR(Node, Base)
9994 #include "clang/AST/StmtNodes.inc"
9995 case Expr::PredefinedExprClass:
9996 case Expr::FloatingLiteralClass:
9997 case Expr::ImaginaryLiteralClass:
9998 case Expr::StringLiteralClass:
9999 case Expr::ArraySubscriptExprClass:
10000 case Expr::OMPArraySectionExprClass:
10001 case Expr::MemberExprClass:
10002 case Expr::CompoundAssignOperatorClass:
10003 case Expr::CompoundLiteralExprClass:
10004 case Expr::ExtVectorElementExprClass:
10005 case Expr::DesignatedInitExprClass:
10006 case Expr::ArrayInitLoopExprClass:
10007 case Expr::ArrayInitIndexExprClass:
10008 case Expr::NoInitExprClass:
10009 case Expr::DesignatedInitUpdateExprClass:
10010 case Expr::ImplicitValueInitExprClass:
10011 case Expr::ParenListExprClass:
10012 case Expr::VAArgExprClass:
10013 case Expr::AddrLabelExprClass:
10014 case Expr::StmtExprClass:
10015 case Expr::CXXMemberCallExprClass:
10016 case Expr::CUDAKernelCallExprClass:
10017 case Expr::CXXDynamicCastExprClass:
10018 case Expr::CXXTypeidExprClass:
10019 case Expr::CXXUuidofExprClass:
10020 case Expr::MSPropertyRefExprClass:
10021 case Expr::MSPropertySubscriptExprClass:
10022 case Expr::CXXNullPtrLiteralExprClass:
10023 case Expr::UserDefinedLiteralClass:
10024 case Expr::CXXThisExprClass:
10025 case Expr::CXXThrowExprClass:
10026 case Expr::CXXNewExprClass:
10027 case Expr::CXXDeleteExprClass:
10028 case Expr::CXXPseudoDestructorExprClass:
10029 case Expr::UnresolvedLookupExprClass:
10030 case Expr::TypoExprClass:
10031 case Expr::DependentScopeDeclRefExprClass:
10032 case Expr::CXXConstructExprClass:
10033 case Expr::CXXInheritedCtorInitExprClass:
10034 case Expr::CXXStdInitializerListExprClass:
10035 case Expr::CXXBindTemporaryExprClass:
10036 case Expr::ExprWithCleanupsClass:
10037 case Expr::CXXTemporaryObjectExprClass:
10038 case Expr::CXXUnresolvedConstructExprClass:
10039 case Expr::CXXDependentScopeMemberExprClass:
10040 case Expr::UnresolvedMemberExprClass:
10041 case Expr::ObjCStringLiteralClass:
10042 case Expr::ObjCBoxedExprClass:
10043 case Expr::ObjCArrayLiteralClass:
10044 case Expr::ObjCDictionaryLiteralClass:
10045 case Expr::ObjCEncodeExprClass:
10046 case Expr::ObjCMessageExprClass:
10047 case Expr::ObjCSelectorExprClass:
10048 case Expr::ObjCProtocolExprClass:
10049 case Expr::ObjCIvarRefExprClass:
10050 case Expr::ObjCPropertyRefExprClass:
10051 case Expr::ObjCSubscriptRefExprClass:
10052 case Expr::ObjCIsaExprClass:
10053 case Expr::ObjCAvailabilityCheckExprClass:
10054 case Expr::ShuffleVectorExprClass:
10055 case Expr::ConvertVectorExprClass:
10056 case Expr::BlockExprClass:
10057 case Expr::NoStmtClass:
10058 case Expr::OpaqueValueExprClass:
10059 case Expr::PackExpansionExprClass:
10060 case Expr::SubstNonTypeTemplateParmPackExprClass:
10061 case Expr::FunctionParmPackExprClass:
10062 case Expr::AsTypeExprClass:
10063 case Expr::ObjCIndirectCopyRestoreExprClass:
10064 case Expr::MaterializeTemporaryExprClass:
10065 case Expr::PseudoObjectExprClass:
10066 case Expr::AtomicExprClass:
10067 case Expr::LambdaExprClass:
10068 case Expr::CXXFoldExprClass:
10069 case Expr::CoawaitExprClass:
10070 case Expr::CoyieldExprClass:
10071 return ICEDiag(IK_NotICE, E->getLocStart());
10073 case Expr::InitListExprClass: {
10074 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10075 // form "T x = { a };" is equivalent to "T x = a;".
10076 // Unless we're initializing a reference, T is a scalar as it is known to be
10077 // of integral or enumeration type.
10079 if (cast<InitListExpr>(E)->getNumInits() == 1)
10080 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10081 return ICEDiag(IK_NotICE, E->getLocStart());
10084 case Expr::SizeOfPackExprClass:
10085 case Expr::GNUNullExprClass:
10086 // GCC considers the GNU __null value to be an integral constant expression.
10089 case Expr::SubstNonTypeTemplateParmExprClass:
10091 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10093 case Expr::ParenExprClass:
10094 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10095 case Expr::GenericSelectionExprClass:
10096 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10097 case Expr::IntegerLiteralClass:
10098 case Expr::CharacterLiteralClass:
10099 case Expr::ObjCBoolLiteralExprClass:
10100 case Expr::CXXBoolLiteralExprClass:
10101 case Expr::CXXScalarValueInitExprClass:
10102 case Expr::TypeTraitExprClass:
10103 case Expr::ArrayTypeTraitExprClass:
10104 case Expr::ExpressionTraitExprClass:
10105 case Expr::CXXNoexceptExprClass:
10107 case Expr::CallExprClass:
10108 case Expr::CXXOperatorCallExprClass: {
10109 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10110 // constant expressions, but they can never be ICEs because an ICE cannot
10111 // contain an operand of (pointer to) function type.
10112 const CallExpr *CE = cast<CallExpr>(E);
10113 if (CE->getBuiltinCallee())
10114 return CheckEvalInICE(E, Ctx);
10115 return ICEDiag(IK_NotICE, E->getLocStart());
10117 case Expr::DeclRefExprClass: {
10118 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10120 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10121 if (Ctx.getLangOpts().CPlusPlus &&
10122 D && IsConstNonVolatile(D->getType())) {
10123 // Parameter variables are never constants. Without this check,
10124 // getAnyInitializer() can find a default argument, which leads
10126 if (isa<ParmVarDecl>(D))
10127 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10130 // A variable of non-volatile const-qualified integral or enumeration
10131 // type initialized by an ICE can be used in ICEs.
10132 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10133 if (!Dcl->getType()->isIntegralOrEnumerationType())
10134 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10137 // Look for a declaration of this variable that has an initializer, and
10138 // check whether it is an ICE.
10139 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10142 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10145 return ICEDiag(IK_NotICE, E->getLocStart());
10147 case Expr::UnaryOperatorClass: {
10148 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10149 switch (Exp->getOpcode()) {
10157 // C99 6.6/3 allows increment and decrement within unevaluated
10158 // subexpressions of constant expressions, but they can never be ICEs
10159 // because an ICE cannot contain an lvalue operand.
10160 return ICEDiag(IK_NotICE, E->getLocStart());
10168 return CheckICE(Exp->getSubExpr(), Ctx);
10171 // OffsetOf falls through here.
10173 case Expr::OffsetOfExprClass: {
10174 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10175 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10176 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10177 // compliance: we should warn earlier for offsetof expressions with
10178 // array subscripts that aren't ICEs, and if the array subscripts
10179 // are ICEs, the value of the offsetof must be an integer constant.
10180 return CheckEvalInICE(E, Ctx);
10182 case Expr::UnaryExprOrTypeTraitExprClass: {
10183 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10184 if ((Exp->getKind() == UETT_SizeOf) &&
10185 Exp->getTypeOfArgument()->isVariableArrayType())
10186 return ICEDiag(IK_NotICE, E->getLocStart());
10189 case Expr::BinaryOperatorClass: {
10190 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10191 switch (Exp->getOpcode()) {
10205 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10206 // constant expressions, but they can never be ICEs because an ICE cannot
10207 // contain an lvalue operand.
10208 return ICEDiag(IK_NotICE, E->getLocStart());
10227 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10228 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10229 if (Exp->getOpcode() == BO_Div ||
10230 Exp->getOpcode() == BO_Rem) {
10231 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10232 // we don't evaluate one.
10233 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10234 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10236 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10237 if (REval.isSigned() && REval.isAllOnesValue()) {
10238 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10239 if (LEval.isMinSignedValue())
10240 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10244 if (Exp->getOpcode() == BO_Comma) {
10245 if (Ctx.getLangOpts().C99) {
10246 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10247 // if it isn't evaluated.
10248 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10249 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10251 // In both C89 and C++, commas in ICEs are illegal.
10252 return ICEDiag(IK_NotICE, E->getLocStart());
10255 return Worst(LHSResult, RHSResult);
10259 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10260 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10261 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10262 // Rare case where the RHS has a comma "side-effect"; we need
10263 // to actually check the condition to see whether the side
10264 // with the comma is evaluated.
10265 if ((Exp->getOpcode() == BO_LAnd) !=
10266 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10271 return Worst(LHSResult, RHSResult);
10275 case Expr::ImplicitCastExprClass:
10276 case Expr::CStyleCastExprClass:
10277 case Expr::CXXFunctionalCastExprClass:
10278 case Expr::CXXStaticCastExprClass:
10279 case Expr::CXXReinterpretCastExprClass:
10280 case Expr::CXXConstCastExprClass:
10281 case Expr::ObjCBridgedCastExprClass: {
10282 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10283 if (isa<ExplicitCastExpr>(E)) {
10284 if (const FloatingLiteral *FL
10285 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10286 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10287 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10288 APSInt IgnoredVal(DestWidth, !DestSigned);
10290 // If the value does not fit in the destination type, the behavior is
10291 // undefined, so we are not required to treat it as a constant
10293 if (FL->getValue().convertToInteger(IgnoredVal,
10294 llvm::APFloat::rmTowardZero,
10295 &Ignored) & APFloat::opInvalidOp)
10296 return ICEDiag(IK_NotICE, E->getLocStart());
10300 switch (cast<CastExpr>(E)->getCastKind()) {
10301 case CK_LValueToRValue:
10302 case CK_AtomicToNonAtomic:
10303 case CK_NonAtomicToAtomic:
10305 case CK_IntegralToBoolean:
10306 case CK_IntegralCast:
10307 return CheckICE(SubExpr, Ctx);
10309 return ICEDiag(IK_NotICE, E->getLocStart());
10312 case Expr::BinaryConditionalOperatorClass: {
10313 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10314 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10315 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10316 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10317 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10318 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10319 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10320 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10321 return FalseResult;
10323 case Expr::ConditionalOperatorClass: {
10324 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10325 // If the condition (ignoring parens) is a __builtin_constant_p call,
10326 // then only the true side is actually considered in an integer constant
10327 // expression, and it is fully evaluated. This is an important GNU
10328 // extension. See GCC PR38377 for discussion.
10329 if (const CallExpr *CallCE
10330 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10331 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10332 return CheckEvalInICE(E, Ctx);
10333 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10334 if (CondResult.Kind == IK_NotICE)
10337 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10338 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10340 if (TrueResult.Kind == IK_NotICE)
10342 if (FalseResult.Kind == IK_NotICE)
10343 return FalseResult;
10344 if (CondResult.Kind == IK_ICEIfUnevaluated)
10346 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10348 // Rare case where the diagnostics depend on which side is evaluated
10349 // Note that if we get here, CondResult is 0, and at least one of
10350 // TrueResult and FalseResult is non-zero.
10351 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10352 return FalseResult;
10355 case Expr::CXXDefaultArgExprClass:
10356 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10357 case Expr::CXXDefaultInitExprClass:
10358 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10359 case Expr::ChooseExprClass: {
10360 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10364 llvm_unreachable("Invalid StmtClass!");
10367 /// Evaluate an expression as a C++11 integral constant expression.
10368 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10370 llvm::APSInt *Value,
10371 SourceLocation *Loc) {
10372 if (!E->getType()->isIntegralOrEnumerationType()) {
10373 if (Loc) *Loc = E->getExprLoc();
10378 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10381 if (!Result.isInt()) {
10382 if (Loc) *Loc = E->getExprLoc();
10386 if (Value) *Value = Result.getInt();
10390 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10391 SourceLocation *Loc) const {
10392 if (Ctx.getLangOpts().CPlusPlus11)
10393 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10395 ICEDiag D = CheckICE(this, Ctx);
10396 if (D.Kind != IK_ICE) {
10397 if (Loc) *Loc = D.Loc;
10403 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10404 SourceLocation *Loc, bool isEvaluated) const {
10405 if (Ctx.getLangOpts().CPlusPlus11)
10406 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10408 if (!isIntegerConstantExpr(Ctx, Loc))
10410 // The only possible side-effects here are due to UB discovered in the
10411 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10412 // required to treat the expression as an ICE, so we produce the folded
10414 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10415 llvm_unreachable("ICE cannot be evaluated!");
10419 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10420 return CheckICE(this, Ctx).Kind == IK_ICE;
10423 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10424 SourceLocation *Loc) const {
10425 // We support this checking in C++98 mode in order to diagnose compatibility
10427 assert(Ctx.getLangOpts().CPlusPlus);
10429 // Build evaluation settings.
10430 Expr::EvalStatus Status;
10431 SmallVector<PartialDiagnosticAt, 8> Diags;
10432 Status.Diag = &Diags;
10433 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10436 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10438 if (!Diags.empty()) {
10439 IsConstExpr = false;
10440 if (Loc) *Loc = Diags[0].first;
10441 } else if (!IsConstExpr) {
10442 // FIXME: This shouldn't happen.
10443 if (Loc) *Loc = getExprLoc();
10446 return IsConstExpr;
10449 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10450 const FunctionDecl *Callee,
10451 ArrayRef<const Expr*> Args,
10452 const Expr *This) const {
10453 Expr::EvalStatus Status;
10454 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10457 const LValue *ThisPtr = nullptr;
10460 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10461 assert(MD && "Don't provide `this` for non-methods.");
10462 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10464 if (EvaluateObjectArgument(Info, This, ThisVal))
10465 ThisPtr = &ThisVal;
10466 if (Info.EvalStatus.HasSideEffects)
10470 ArgVector ArgValues(Args.size());
10471 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10473 if ((*I)->isValueDependent() ||
10474 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10475 // If evaluation fails, throw away the argument entirely.
10476 ArgValues[I - Args.begin()] = APValue();
10477 if (Info.EvalStatus.HasSideEffects)
10481 // Build fake call to Callee.
10482 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10484 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10487 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10489 PartialDiagnosticAt> &Diags) {
10490 // FIXME: It would be useful to check constexpr function templates, but at the
10491 // moment the constant expression evaluator cannot cope with the non-rigorous
10492 // ASTs which we build for dependent expressions.
10493 if (FD->isDependentContext())
10496 Expr::EvalStatus Status;
10497 Status.Diag = &Diags;
10499 EvalInfo Info(FD->getASTContext(), Status,
10500 EvalInfo::EM_PotentialConstantExpression);
10502 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10503 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10505 // Fabricate an arbitrary expression on the stack and pretend that it
10506 // is a temporary being used as the 'this' pointer.
10508 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10509 This.set(&VIE, Info.CurrentCall->Index);
10511 ArrayRef<const Expr*> Args;
10514 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10515 // Evaluate the call as a constant initializer, to allow the construction
10516 // of objects of non-literal types.
10517 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10518 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10520 SourceLocation Loc = FD->getLocation();
10521 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10522 Args, FD->getBody(), Info, Scratch, nullptr);
10525 return Diags.empty();
10528 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10529 const FunctionDecl *FD,
10531 PartialDiagnosticAt> &Diags) {
10532 Expr::EvalStatus Status;
10533 Status.Diag = &Diags;
10535 EvalInfo Info(FD->getASTContext(), Status,
10536 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10538 // Fabricate a call stack frame to give the arguments a plausible cover story.
10539 ArrayRef<const Expr*> Args;
10540 ArgVector ArgValues(0);
10541 bool Success = EvaluateArgs(Args, ArgValues, Info);
10544 "Failed to set up arguments for potential constant evaluation");
10545 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10547 APValue ResultScratch;
10548 Evaluate(ResultScratch, Info, E);
10549 return Diags.empty();
10552 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10553 unsigned Type) const {
10554 if (!getType()->isPointerType())
10557 Expr::EvalStatus Status;
10558 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10559 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);