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*>()) {
65 // FIXME: It's unclear where we're supposed to take the type from, and
66 // this actually matters for arrays of unknown bound. Eg:
68 // extern int arr[]; void f() { extern int arr[3]; };
69 // constexpr int *p = &arr[1]; // valid?
71 // For now, we take the array bound from the most recent declaration.
72 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
73 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
74 QualType T = Redecl->getType();
75 if (!T->isIncompleteArrayType())
81 const Expr *Base = B.get<const Expr*>();
83 // For a materialized temporary, the type of the temporary we materialized
84 // may not be the type of the expression.
85 if (const MaterializeTemporaryExpr *MTE =
86 dyn_cast<MaterializeTemporaryExpr>(Base)) {
87 SmallVector<const Expr *, 2> CommaLHSs;
88 SmallVector<SubobjectAdjustment, 2> Adjustments;
89 const Expr *Temp = MTE->GetTemporaryExpr();
90 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
92 // Keep any cv-qualifiers from the reference if we generated a temporary
93 // for it directly. Otherwise use the type after adjustment.
94 if (!Adjustments.empty())
95 return Inner->getType();
98 return Base->getType();
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// field or base class.
104 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
105 APValue::BaseOrMemberType Value;
106 Value.setFromOpaqueValue(E.BaseOrMember);
110 /// Get an LValue path entry, which is known to not be an array index, as a
111 /// field declaration.
112 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
113 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
115 /// Get an LValue path entry, which is known to not be an array index, as a
116 /// base class declaration.
117 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
118 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
120 /// Determine whether this LValue path entry for a base class names a virtual
122 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
123 return getAsBaseOrMember(E).getInt();
126 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
127 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
128 const FunctionDecl *Callee = CE->getDirectCallee();
129 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
133 /// This will look through a single cast.
135 /// Returns null if we couldn't unwrap a function with alloc_size.
136 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
137 if (!E->getType()->isPointerType())
140 E = E->IgnoreParens();
141 // If we're doing a variable assignment from e.g. malloc(N), there will
142 // probably be a cast of some kind. Ignore it.
143 if (const auto *Cast = dyn_cast<CastExpr>(E))
144 E = Cast->getSubExpr()->IgnoreParens();
146 if (const auto *CE = dyn_cast<CallExpr>(E))
147 return getAllocSizeAttr(CE) ? CE : nullptr;
151 /// Determines whether or not the given Base contains a call to a function
152 /// with the alloc_size attribute.
153 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
154 const auto *E = Base.dyn_cast<const Expr *>();
155 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
158 /// The bound to claim that an array of unknown bound has.
159 /// The value in MostDerivedArraySize is undefined in this case. So, set it
160 /// to an arbitrary value that's likely to loudly break things if it's used.
161 static const uint64_t AssumedSizeForUnsizedArray =
162 std::numeric_limits<uint64_t>::max() / 2;
164 /// Determines if an LValue with the given LValueBase will have an unsized
165 /// array in its designator.
166 /// Find the path length and type of the most-derived subobject in the given
167 /// path, and find the size of the containing array, if any.
169 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
170 ArrayRef<APValue::LValuePathEntry> Path,
171 uint64_t &ArraySize, QualType &Type, bool &IsArray,
172 bool &FirstEntryIsUnsizedArray) {
173 // This only accepts LValueBases from APValues, and APValues don't support
174 // arrays that lack size info.
175 assert(!isBaseAnAllocSizeCall(Base) &&
176 "Unsized arrays shouldn't appear here");
177 unsigned MostDerivedLength = 0;
178 Type = getType(Base);
180 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
181 if (Type->isArrayType()) {
182 const ArrayType *AT = Ctx.getAsArrayType(Type);
183 Type = AT->getElementType();
184 MostDerivedLength = I + 1;
187 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
188 ArraySize = CAT->getSize().getZExtValue();
190 assert(I == 0 && "unexpected unsized array designator");
191 FirstEntryIsUnsizedArray = true;
192 ArraySize = AssumedSizeForUnsizedArray;
194 } else if (Type->isAnyComplexType()) {
195 const ComplexType *CT = Type->castAs<ComplexType>();
196 Type = CT->getElementType();
198 MostDerivedLength = I + 1;
200 } else if (const FieldDecl *FD = getAsField(Path[I])) {
201 Type = FD->getType();
203 MostDerivedLength = I + 1;
206 // Path[I] describes a base class.
211 return MostDerivedLength;
214 // The order of this enum is important for diagnostics.
215 enum CheckSubobjectKind {
216 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
217 CSK_This, CSK_Real, CSK_Imag
220 /// A path from a glvalue to a subobject of that glvalue.
221 struct SubobjectDesignator {
222 /// True if the subobject was named in a manner not supported by C++11. Such
223 /// lvalues can still be folded, but they are not core constant expressions
224 /// and we cannot perform lvalue-to-rvalue conversions on them.
225 unsigned Invalid : 1;
227 /// Is this a pointer one past the end of an object?
228 unsigned IsOnePastTheEnd : 1;
230 /// Indicator of whether the first entry is an unsized array.
231 unsigned FirstEntryIsAnUnsizedArray : 1;
233 /// Indicator of whether the most-derived object is an array element.
234 unsigned MostDerivedIsArrayElement : 1;
236 /// The length of the path to the most-derived object of which this is a
238 unsigned MostDerivedPathLength : 28;
240 /// The size of the array of which the most-derived object is an element.
241 /// This will always be 0 if the most-derived object is not an array
242 /// element. 0 is not an indicator of whether or not the most-derived object
243 /// is an array, however, because 0-length arrays are allowed.
245 /// If the current array is an unsized array, the value of this is
247 uint64_t MostDerivedArraySize;
249 /// The type of the most derived object referred to by this address.
250 QualType MostDerivedType;
252 typedef APValue::LValuePathEntry PathEntry;
254 /// The entries on the path from the glvalue to the designated subobject.
255 SmallVector<PathEntry, 8> Entries;
257 SubobjectDesignator() : Invalid(true) {}
259 explicit SubobjectDesignator(QualType T)
260 : Invalid(false), IsOnePastTheEnd(false),
261 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
262 MostDerivedPathLength(0), MostDerivedArraySize(0),
263 MostDerivedType(T) {}
265 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
266 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
268 MostDerivedPathLength(0), MostDerivedArraySize(0) {
269 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
271 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
272 ArrayRef<PathEntry> VEntries = V.getLValuePath();
273 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
274 if (V.getLValueBase()) {
275 bool IsArray = false;
276 bool FirstIsUnsizedArray = false;
277 MostDerivedPathLength = findMostDerivedSubobject(
278 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
279 MostDerivedType, IsArray, FirstIsUnsizedArray);
280 MostDerivedIsArrayElement = IsArray;
281 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
291 /// Determine whether the most derived subobject is an array without a
293 bool isMostDerivedAnUnsizedArray() const {
294 assert(!Invalid && "Calling this makes no sense on invalid designators");
295 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
298 /// Determine what the most derived array's size is. Results in an assertion
299 /// failure if the most derived array lacks a size.
300 uint64_t getMostDerivedArraySize() const {
301 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
302 return MostDerivedArraySize;
305 /// Determine whether this is a one-past-the-end pointer.
306 bool isOnePastTheEnd() const {
310 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
311 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
316 /// Check that this refers to a valid subobject.
317 bool isValidSubobject() const {
320 return !isOnePastTheEnd();
322 /// Check that this refers to a valid subobject, and if not, produce a
323 /// relevant diagnostic and set the designator as invalid.
324 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
326 /// Update this designator to refer to the first element within this array.
327 void addArrayUnchecked(const ConstantArrayType *CAT) {
329 Entry.ArrayIndex = 0;
330 Entries.push_back(Entry);
332 // This is a most-derived object.
333 MostDerivedType = CAT->getElementType();
334 MostDerivedIsArrayElement = true;
335 MostDerivedArraySize = CAT->getSize().getZExtValue();
336 MostDerivedPathLength = Entries.size();
338 /// Update this designator to refer to the first element within the array of
339 /// elements of type T. This is an array of unknown size.
340 void addUnsizedArrayUnchecked(QualType ElemTy) {
342 Entry.ArrayIndex = 0;
343 Entries.push_back(Entry);
345 MostDerivedType = ElemTy;
346 MostDerivedIsArrayElement = true;
347 // The value in MostDerivedArraySize is undefined in this case. So, set it
348 // to an arbitrary value that's likely to loudly break things if it's
350 MostDerivedArraySize = AssumedSizeForUnsizedArray;
351 MostDerivedPathLength = Entries.size();
353 /// Update this designator to refer to the given base or member of this
355 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
357 APValue::BaseOrMemberType Value(D, Virtual);
358 Entry.BaseOrMember = Value.getOpaqueValue();
359 Entries.push_back(Entry);
361 // If this isn't a base class, it's a new most-derived object.
362 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
363 MostDerivedType = FD->getType();
364 MostDerivedIsArrayElement = false;
365 MostDerivedArraySize = 0;
366 MostDerivedPathLength = Entries.size();
369 /// Update this designator to refer to the given complex component.
370 void addComplexUnchecked(QualType EltTy, bool Imag) {
372 Entry.ArrayIndex = Imag;
373 Entries.push_back(Entry);
375 // This is technically a most-derived object, though in practice this
376 // is unlikely to matter.
377 MostDerivedType = EltTy;
378 MostDerivedIsArrayElement = true;
379 MostDerivedArraySize = 2;
380 MostDerivedPathLength = Entries.size();
382 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
383 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
385 /// Add N to the address of this subobject.
386 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
387 if (Invalid || !N) return;
388 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
389 if (isMostDerivedAnUnsizedArray()) {
390 diagnoseUnsizedArrayPointerArithmetic(Info, E);
391 // Can't verify -- trust that the user is doing the right thing (or if
392 // not, trust that the caller will catch the bad behavior).
393 // FIXME: Should we reject if this overflows, at least?
394 Entries.back().ArrayIndex += TruncatedN;
398 // [expr.add]p4: For the purposes of these operators, a pointer to a
399 // nonarray object behaves the same as a pointer to the first element of
400 // an array of length one with the type of the object as its element type.
401 bool IsArray = MostDerivedPathLength == Entries.size() &&
402 MostDerivedIsArrayElement;
403 uint64_t ArrayIndex =
404 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
406 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
408 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
409 // Calculate the actual index in a wide enough type, so we can include
411 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
412 (llvm::APInt&)N += ArrayIndex;
413 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
414 diagnosePointerArithmetic(Info, E, N);
419 ArrayIndex += TruncatedN;
420 assert(ArrayIndex <= ArraySize &&
421 "bounds check succeeded for out-of-bounds index");
424 Entries.back().ArrayIndex = ArrayIndex;
426 IsOnePastTheEnd = (ArrayIndex != 0);
430 /// A stack frame in the constexpr call stack.
431 struct CallStackFrame {
434 /// Parent - The caller of this stack frame.
435 CallStackFrame *Caller;
437 /// Callee - The function which was called.
438 const FunctionDecl *Callee;
440 /// This - The binding for the this pointer in this call, if any.
443 /// Arguments - Parameter bindings for this function call, indexed by
444 /// parameters' function scope indices.
447 // Note that we intentionally use std::map here so that references to
448 // values are stable.
449 typedef std::map<const void*, APValue> MapTy;
450 typedef MapTy::const_iterator temp_iterator;
451 /// Temporaries - Temporary lvalues materialized within this stack frame.
454 /// CallLoc - The location of the call expression for this call.
455 SourceLocation CallLoc;
457 /// Index - The call index of this call.
460 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
461 // on the overall stack usage of deeply-recursing constexpr evaluataions.
462 // (We should cache this map rather than recomputing it repeatedly.)
463 // But let's try this and see how it goes; we can look into caching the map
464 // as a later change.
466 /// LambdaCaptureFields - Mapping from captured variables/this to
467 /// corresponding data members in the closure class.
468 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
469 FieldDecl *LambdaThisCaptureField;
471 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
472 const FunctionDecl *Callee, const LValue *This,
476 APValue *getTemporary(const void *Key) {
477 MapTy::iterator I = Temporaries.find(Key);
478 return I == Temporaries.end() ? nullptr : &I->second;
480 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
483 /// Temporarily override 'this'.
484 class ThisOverrideRAII {
486 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
487 : Frame(Frame), OldThis(Frame.This) {
489 Frame.This = NewThis;
491 ~ThisOverrideRAII() {
492 Frame.This = OldThis;
495 CallStackFrame &Frame;
496 const LValue *OldThis;
499 /// A partial diagnostic which we might know in advance that we are not going
501 class OptionalDiagnostic {
502 PartialDiagnostic *Diag;
505 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
509 OptionalDiagnostic &operator<<(const T &v) {
515 OptionalDiagnostic &operator<<(const APSInt &I) {
517 SmallVector<char, 32> Buffer;
519 *Diag << StringRef(Buffer.data(), Buffer.size());
524 OptionalDiagnostic &operator<<(const APFloat &F) {
526 // FIXME: Force the precision of the source value down so we don't
527 // print digits which are usually useless (we don't really care here if
528 // we truncate a digit by accident in edge cases). Ideally,
529 // APFloat::toString would automatically print the shortest
530 // representation which rounds to the correct value, but it's a bit
531 // tricky to implement.
533 llvm::APFloat::semanticsPrecision(F.getSemantics());
534 precision = (precision * 59 + 195) / 196;
535 SmallVector<char, 32> Buffer;
536 F.toString(Buffer, precision);
537 *Diag << StringRef(Buffer.data(), Buffer.size());
543 /// A cleanup, and a flag indicating whether it is lifetime-extended.
545 llvm::PointerIntPair<APValue*, 1, bool> Value;
548 Cleanup(APValue *Val, bool IsLifetimeExtended)
549 : Value(Val, IsLifetimeExtended) {}
551 bool isLifetimeExtended() const { return Value.getInt(); }
553 *Value.getPointer() = APValue();
557 /// EvalInfo - This is a private struct used by the evaluator to capture
558 /// information about a subexpression as it is folded. It retains information
559 /// about the AST context, but also maintains information about the folded
562 /// If an expression could be evaluated, it is still possible it is not a C
563 /// "integer constant expression" or constant expression. If not, this struct
564 /// captures information about how and why not.
566 /// One bit of information passed *into* the request for constant folding
567 /// indicates whether the subexpression is "evaluated" or not according to C
568 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
569 /// evaluate the expression regardless of what the RHS is, but C only allows
570 /// certain things in certain situations.
574 /// EvalStatus - Contains information about the evaluation.
575 Expr::EvalStatus &EvalStatus;
577 /// CurrentCall - The top of the constexpr call stack.
578 CallStackFrame *CurrentCall;
580 /// CallStackDepth - The number of calls in the call stack right now.
581 unsigned CallStackDepth;
583 /// NextCallIndex - The next call index to assign.
584 unsigned NextCallIndex;
586 /// StepsLeft - The remaining number of evaluation steps we're permitted
587 /// to perform. This is essentially a limit for the number of statements
588 /// we will evaluate.
591 /// BottomFrame - The frame in which evaluation started. This must be
592 /// initialized after CurrentCall and CallStackDepth.
593 CallStackFrame BottomFrame;
595 /// A stack of values whose lifetimes end at the end of some surrounding
596 /// evaluation frame.
597 llvm::SmallVector<Cleanup, 16> CleanupStack;
599 /// EvaluatingDecl - This is the declaration whose initializer is being
600 /// evaluated, if any.
601 APValue::LValueBase EvaluatingDecl;
603 /// EvaluatingDeclValue - This is the value being constructed for the
604 /// declaration whose initializer is being evaluated, if any.
605 APValue *EvaluatingDeclValue;
607 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
608 /// the call index that that lvalue was allocated in.
609 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
611 /// EvaluatingConstructors - Set of objects that are currently being
613 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
615 struct EvaluatingConstructorRAII {
617 EvaluatingObject Object;
619 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
620 : EI(EI), Object(Object) {
621 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
623 ~EvaluatingConstructorRAII() {
624 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
628 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
629 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
632 /// The current array initialization index, if we're performing array
634 uint64_t ArrayInitIndex = -1;
636 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
637 /// notes attached to it will also be stored, otherwise they will not be.
638 bool HasActiveDiagnostic;
640 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
641 /// fold (not just why it's not strictly a constant expression)?
642 bool HasFoldFailureDiagnostic;
644 /// \brief Whether or not we're currently speculatively evaluating.
645 bool IsSpeculativelyEvaluating;
647 enum EvaluationMode {
648 /// Evaluate as a constant expression. Stop if we find that the expression
649 /// is not a constant expression.
650 EM_ConstantExpression,
652 /// Evaluate as a potential constant expression. Keep going if we hit a
653 /// construct that we can't evaluate yet (because we don't yet know the
654 /// value of something) but stop if we hit something that could never be
655 /// a constant expression.
656 EM_PotentialConstantExpression,
658 /// Fold the expression to a constant. Stop if we hit a side-effect that
662 /// Evaluate the expression looking for integer overflow and similar
663 /// issues. Don't worry about side-effects, and try to visit all
665 EM_EvaluateForOverflow,
667 /// Evaluate in any way we know how. Don't worry about side-effects that
668 /// can't be modeled.
669 EM_IgnoreSideEffects,
671 /// Evaluate as a constant expression. Stop if we find that the expression
672 /// is not a constant expression. Some expressions can be retried in the
673 /// optimizer if we don't constant fold them here, but in an unevaluated
674 /// context we try to fold them immediately since the optimizer never
675 /// gets a chance to look at it.
676 EM_ConstantExpressionUnevaluated,
678 /// Evaluate as a potential constant expression. Keep going if we hit a
679 /// construct that we can't evaluate yet (because we don't yet know the
680 /// value of something) but stop if we hit something that could never be
681 /// a constant expression. Some expressions can be retried in the
682 /// optimizer if we don't constant fold them here, but in an unevaluated
683 /// context we try to fold them immediately since the optimizer never
684 /// gets a chance to look at it.
685 EM_PotentialConstantExpressionUnevaluated,
687 /// Evaluate as a constant expression. In certain scenarios, if:
688 /// - we find a MemberExpr with a base that can't be evaluated, or
689 /// - we find a variable initialized with a call to a function that has
690 /// the alloc_size attribute on it
691 /// then we may consider evaluation to have succeeded.
693 /// In either case, the LValue returned shall have an invalid base; in the
694 /// former, the base will be the invalid MemberExpr, in the latter, the
695 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
700 /// Are we checking whether the expression is a potential constant
702 bool checkingPotentialConstantExpression() const {
703 return EvalMode == EM_PotentialConstantExpression ||
704 EvalMode == EM_PotentialConstantExpressionUnevaluated;
707 /// Are we checking an expression for overflow?
708 // FIXME: We should check for any kind of undefined or suspicious behavior
709 // in such constructs, not just overflow.
710 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
712 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
713 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
714 CallStackDepth(0), NextCallIndex(1),
715 StepsLeft(getLangOpts().ConstexprStepLimit),
716 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
717 EvaluatingDecl((const ValueDecl *)nullptr),
718 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
719 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
722 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
723 EvaluatingDecl = Base;
724 EvaluatingDeclValue = &Value;
725 EvaluatingConstructors.insert({Base, 0});
728 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
730 bool CheckCallLimit(SourceLocation Loc) {
731 // Don't perform any constexpr calls (other than the call we're checking)
732 // when checking a potential constant expression.
733 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
735 if (NextCallIndex == 0) {
736 // NextCallIndex has wrapped around.
737 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
740 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
742 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
743 << getLangOpts().ConstexprCallDepth;
747 CallStackFrame *getCallFrame(unsigned CallIndex) {
748 assert(CallIndex && "no call index in getCallFrame");
749 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
750 // be null in this loop.
751 CallStackFrame *Frame = CurrentCall;
752 while (Frame->Index > CallIndex)
753 Frame = Frame->Caller;
754 return (Frame->Index == CallIndex) ? Frame : nullptr;
757 bool nextStep(const Stmt *S) {
759 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
767 /// Add a diagnostic to the diagnostics list.
768 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
769 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
770 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
771 return EvalStatus.Diag->back().second;
774 /// Add notes containing a call stack to the current point of evaluation.
775 void addCallStack(unsigned Limit);
778 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
779 unsigned ExtraNotes, bool IsCCEDiag) {
781 if (EvalStatus.Diag) {
782 // If we have a prior diagnostic, it will be noting that the expression
783 // isn't a constant expression. This diagnostic is more important,
784 // unless we require this evaluation to produce a constant expression.
786 // FIXME: We might want to show both diagnostics to the user in
787 // EM_ConstantFold mode.
788 if (!EvalStatus.Diag->empty()) {
790 case EM_ConstantFold:
791 case EM_IgnoreSideEffects:
792 case EM_EvaluateForOverflow:
793 if (!HasFoldFailureDiagnostic)
795 // We've already failed to fold something. Keep that diagnostic.
797 case EM_ConstantExpression:
798 case EM_PotentialConstantExpression:
799 case EM_ConstantExpressionUnevaluated:
800 case EM_PotentialConstantExpressionUnevaluated:
802 HasActiveDiagnostic = false;
803 return OptionalDiagnostic();
807 unsigned CallStackNotes = CallStackDepth - 1;
808 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
810 CallStackNotes = std::min(CallStackNotes, Limit + 1);
811 if (checkingPotentialConstantExpression())
814 HasActiveDiagnostic = true;
815 HasFoldFailureDiagnostic = !IsCCEDiag;
816 EvalStatus.Diag->clear();
817 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
818 addDiag(Loc, DiagId);
819 if (!checkingPotentialConstantExpression())
821 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
823 HasActiveDiagnostic = false;
824 return OptionalDiagnostic();
827 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
829 FFDiag(SourceLocation Loc,
830 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
831 unsigned ExtraNotes = 0) {
832 return Diag(Loc, DiagId, ExtraNotes, false);
835 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
836 = diag::note_invalid_subexpr_in_const_expr,
837 unsigned ExtraNotes = 0) {
839 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
840 HasActiveDiagnostic = false;
841 return OptionalDiagnostic();
844 /// Diagnose that the evaluation does not produce a C++11 core constant
847 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
848 /// EM_PotentialConstantExpression mode and we produce one of these.
849 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
850 = diag::note_invalid_subexpr_in_const_expr,
851 unsigned ExtraNotes = 0) {
852 // Don't override a previous diagnostic. Don't bother collecting
853 // diagnostics if we're evaluating for overflow.
854 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
855 HasActiveDiagnostic = false;
856 return OptionalDiagnostic();
858 return Diag(Loc, DiagId, ExtraNotes, true);
860 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
861 = diag::note_invalid_subexpr_in_const_expr,
862 unsigned ExtraNotes = 0) {
863 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
865 /// Add a note to a prior diagnostic.
866 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
867 if (!HasActiveDiagnostic)
868 return OptionalDiagnostic();
869 return OptionalDiagnostic(&addDiag(Loc, DiagId));
872 /// Add a stack of notes to a prior diagnostic.
873 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
874 if (HasActiveDiagnostic) {
875 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
876 Diags.begin(), Diags.end());
880 /// Should we continue evaluation after encountering a side-effect that we
882 bool keepEvaluatingAfterSideEffect() {
884 case EM_PotentialConstantExpression:
885 case EM_PotentialConstantExpressionUnevaluated:
886 case EM_EvaluateForOverflow:
887 case EM_IgnoreSideEffects:
890 case EM_ConstantExpression:
891 case EM_ConstantExpressionUnevaluated:
892 case EM_ConstantFold:
896 llvm_unreachable("Missed EvalMode case");
899 /// Note that we have had a side-effect, and determine whether we should
901 bool noteSideEffect() {
902 EvalStatus.HasSideEffects = true;
903 return keepEvaluatingAfterSideEffect();
906 /// Should we continue evaluation after encountering undefined behavior?
907 bool keepEvaluatingAfterUndefinedBehavior() {
909 case EM_EvaluateForOverflow:
910 case EM_IgnoreSideEffects:
911 case EM_ConstantFold:
915 case EM_PotentialConstantExpression:
916 case EM_PotentialConstantExpressionUnevaluated:
917 case EM_ConstantExpression:
918 case EM_ConstantExpressionUnevaluated:
921 llvm_unreachable("Missed EvalMode case");
924 /// Note that we hit something that was technically undefined behavior, but
925 /// that we can evaluate past it (such as signed overflow or floating-point
926 /// division by zero.)
927 bool noteUndefinedBehavior() {
928 EvalStatus.HasUndefinedBehavior = true;
929 return keepEvaluatingAfterUndefinedBehavior();
932 /// Should we continue evaluation as much as possible after encountering a
933 /// construct which can't be reduced to a value?
934 bool keepEvaluatingAfterFailure() {
939 case EM_PotentialConstantExpression:
940 case EM_PotentialConstantExpressionUnevaluated:
941 case EM_EvaluateForOverflow:
944 case EM_ConstantExpression:
945 case EM_ConstantExpressionUnevaluated:
946 case EM_ConstantFold:
947 case EM_IgnoreSideEffects:
951 llvm_unreachable("Missed EvalMode case");
954 /// Notes that we failed to evaluate an expression that other expressions
955 /// directly depend on, and determine if we should keep evaluating. This
956 /// should only be called if we actually intend to keep evaluating.
958 /// Call noteSideEffect() instead if we may be able to ignore the value that
959 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
961 /// (Foo(), 1) // use noteSideEffect
962 /// (Foo() || true) // use noteSideEffect
963 /// Foo() + 1 // use noteFailure
964 LLVM_NODISCARD bool noteFailure() {
965 // Failure when evaluating some expression often means there is some
966 // subexpression whose evaluation was skipped. Therefore, (because we
967 // don't track whether we skipped an expression when unwinding after an
968 // evaluation failure) every evaluation failure that bubbles up from a
969 // subexpression implies that a side-effect has potentially happened. We
970 // skip setting the HasSideEffects flag to true until we decide to
971 // continue evaluating after that point, which happens here.
972 bool KeepGoing = keepEvaluatingAfterFailure();
973 EvalStatus.HasSideEffects |= KeepGoing;
977 class ArrayInitLoopIndex {
982 ArrayInitLoopIndex(EvalInfo &Info)
983 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
984 Info.ArrayInitIndex = 0;
986 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
988 operator uint64_t&() { return Info.ArrayInitIndex; }
992 /// Object used to treat all foldable expressions as constant expressions.
993 struct FoldConstant {
996 bool HadNoPriorDiags;
997 EvalInfo::EvaluationMode OldMode;
999 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1002 HadNoPriorDiags(Info.EvalStatus.Diag &&
1003 Info.EvalStatus.Diag->empty() &&
1004 !Info.EvalStatus.HasSideEffects),
1005 OldMode(Info.EvalMode) {
1007 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1008 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1009 Info.EvalMode = EvalInfo::EM_ConstantFold;
1011 void keepDiagnostics() { Enabled = false; }
1013 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1014 !Info.EvalStatus.HasSideEffects)
1015 Info.EvalStatus.Diag->clear();
1016 Info.EvalMode = OldMode;
1020 /// RAII object used to treat the current evaluation as the correct pointer
1021 /// offset fold for the current EvalMode
1022 struct FoldOffsetRAII {
1024 EvalInfo::EvaluationMode OldMode;
1025 explicit FoldOffsetRAII(EvalInfo &Info)
1026 : Info(Info), OldMode(Info.EvalMode) {
1027 if (!Info.checkingPotentialConstantExpression())
1028 Info.EvalMode = EvalInfo::EM_OffsetFold;
1031 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1034 /// RAII object used to optionally suppress diagnostics and side-effects from
1035 /// a speculative evaluation.
1036 class SpeculativeEvaluationRAII {
1037 EvalInfo *Info = nullptr;
1038 Expr::EvalStatus OldStatus;
1039 bool OldIsSpeculativelyEvaluating;
1041 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1043 OldStatus = Other.OldStatus;
1044 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1045 Other.Info = nullptr;
1048 void maybeRestoreState() {
1052 Info->EvalStatus = OldStatus;
1053 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1057 SpeculativeEvaluationRAII() = default;
1059 SpeculativeEvaluationRAII(
1060 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1061 : Info(&Info), OldStatus(Info.EvalStatus),
1062 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1063 Info.EvalStatus.Diag = NewDiag;
1064 Info.IsSpeculativelyEvaluating = true;
1067 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1068 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1069 moveFromAndCancel(std::move(Other));
1072 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1073 maybeRestoreState();
1074 moveFromAndCancel(std::move(Other));
1078 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1081 /// RAII object wrapping a full-expression or block scope, and handling
1082 /// the ending of the lifetime of temporaries created within it.
1083 template<bool IsFullExpression>
1086 unsigned OldStackSize;
1088 ScopeRAII(EvalInfo &Info)
1089 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1091 // Body moved to a static method to encourage the compiler to inline away
1092 // instances of this class.
1093 cleanup(Info, OldStackSize);
1096 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1097 unsigned NewEnd = OldStackSize;
1098 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1100 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1101 // Full-expression cleanup of a lifetime-extended temporary: nothing
1102 // to do, just move this cleanup to the right place in the stack.
1103 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1106 // End the lifetime of the object.
1107 Info.CleanupStack[I].endLifetime();
1110 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1111 Info.CleanupStack.end());
1114 typedef ScopeRAII<false> BlockScopeRAII;
1115 typedef ScopeRAII<true> FullExpressionRAII;
1118 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1119 CheckSubobjectKind CSK) {
1122 if (isOnePastTheEnd()) {
1123 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1128 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1129 // must actually be at least one array element; even a VLA cannot have a
1130 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1134 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1136 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1137 // Do not set the designator as invalid: we can represent this situation,
1138 // and correct handling of __builtin_object_size requires us to do so.
1141 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1144 // If we're complaining, we must be able to statically determine the size of
1145 // the most derived array.
1146 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1147 Info.CCEDiag(E, diag::note_constexpr_array_index)
1149 << static_cast<unsigned>(getMostDerivedArraySize());
1151 Info.CCEDiag(E, diag::note_constexpr_array_index)
1152 << N << /*non-array*/ 1;
1156 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1157 const FunctionDecl *Callee, const LValue *This,
1159 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1160 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1161 Info.CurrentCall = this;
1162 ++Info.CallStackDepth;
1165 CallStackFrame::~CallStackFrame() {
1166 assert(Info.CurrentCall == this && "calls retired out of order");
1167 --Info.CallStackDepth;
1168 Info.CurrentCall = Caller;
1171 APValue &CallStackFrame::createTemporary(const void *Key,
1172 bool IsLifetimeExtended) {
1173 APValue &Result = Temporaries[Key];
1174 assert(Result.isUninit() && "temporary created multiple times");
1175 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1179 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1181 void EvalInfo::addCallStack(unsigned Limit) {
1182 // Determine which calls to skip, if any.
1183 unsigned ActiveCalls = CallStackDepth - 1;
1184 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1185 if (Limit && Limit < ActiveCalls) {
1186 SkipStart = Limit / 2 + Limit % 2;
1187 SkipEnd = ActiveCalls - Limit / 2;
1190 // Walk the call stack and add the diagnostics.
1191 unsigned CallIdx = 0;
1192 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1193 Frame = Frame->Caller, ++CallIdx) {
1195 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1196 if (CallIdx == SkipStart) {
1197 // Note that we're skipping calls.
1198 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1199 << unsigned(ActiveCalls - Limit);
1204 // Use a different note for an inheriting constructor, because from the
1205 // user's perspective it's not really a function at all.
1206 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1207 if (CD->isInheritingConstructor()) {
1208 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1214 SmallVector<char, 128> Buffer;
1215 llvm::raw_svector_ostream Out(Buffer);
1216 describeCall(Frame, Out);
1217 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1222 struct ComplexValue {
1227 APSInt IntReal, IntImag;
1228 APFloat FloatReal, FloatImag;
1230 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1232 void makeComplexFloat() { IsInt = false; }
1233 bool isComplexFloat() const { return !IsInt; }
1234 APFloat &getComplexFloatReal() { return FloatReal; }
1235 APFloat &getComplexFloatImag() { return FloatImag; }
1237 void makeComplexInt() { IsInt = true; }
1238 bool isComplexInt() const { return IsInt; }
1239 APSInt &getComplexIntReal() { return IntReal; }
1240 APSInt &getComplexIntImag() { return IntImag; }
1242 void moveInto(APValue &v) const {
1243 if (isComplexFloat())
1244 v = APValue(FloatReal, FloatImag);
1246 v = APValue(IntReal, IntImag);
1248 void setFrom(const APValue &v) {
1249 assert(v.isComplexFloat() || v.isComplexInt());
1250 if (v.isComplexFloat()) {
1252 FloatReal = v.getComplexFloatReal();
1253 FloatImag = v.getComplexFloatImag();
1256 IntReal = v.getComplexIntReal();
1257 IntImag = v.getComplexIntImag();
1263 APValue::LValueBase Base;
1265 unsigned InvalidBase : 1;
1266 unsigned CallIndex : 31;
1267 SubobjectDesignator Designator;
1270 const APValue::LValueBase getLValueBase() const { return Base; }
1271 CharUnits &getLValueOffset() { return Offset; }
1272 const CharUnits &getLValueOffset() const { return Offset; }
1273 unsigned getLValueCallIndex() const { return CallIndex; }
1274 SubobjectDesignator &getLValueDesignator() { return Designator; }
1275 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1276 bool isNullPointer() const { return IsNullPtr;}
1278 void moveInto(APValue &V) const {
1279 if (Designator.Invalid)
1280 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1283 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1284 V = APValue(Base, Offset, Designator.Entries,
1285 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1288 void setFrom(ASTContext &Ctx, const APValue &V) {
1289 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1290 Base = V.getLValueBase();
1291 Offset = V.getLValueOffset();
1292 InvalidBase = false;
1293 CallIndex = V.getLValueCallIndex();
1294 Designator = SubobjectDesignator(Ctx, V);
1295 IsNullPtr = V.isNullPointer();
1298 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1300 // We only allow a few types of invalid bases. Enforce that here.
1302 const auto *E = B.get<const Expr *>();
1303 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1304 "Unexpected type of invalid base");
1309 Offset = CharUnits::fromQuantity(0);
1310 InvalidBase = BInvalid;
1312 Designator = SubobjectDesignator(getType(B));
1316 void setNull(QualType PointerTy, uint64_t TargetVal) {
1317 Base = (Expr *)nullptr;
1318 Offset = CharUnits::fromQuantity(TargetVal);
1319 InvalidBase = false;
1321 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1325 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1329 // Check that this LValue is not based on a null pointer. If it is, produce
1330 // a diagnostic and mark the designator as invalid.
1331 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1332 CheckSubobjectKind CSK) {
1333 if (Designator.Invalid)
1336 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1338 Designator.setInvalid();
1344 // Check this LValue refers to an object. If not, set the designator to be
1345 // invalid and emit a diagnostic.
1346 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1347 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1348 Designator.checkSubobject(Info, E, CSK);
1351 void addDecl(EvalInfo &Info, const Expr *E,
1352 const Decl *D, bool Virtual = false) {
1353 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1354 Designator.addDeclUnchecked(D, Virtual);
1356 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1357 if (!Designator.Entries.empty()) {
1358 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1359 Designator.setInvalid();
1362 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1363 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1364 Designator.FirstEntryIsAnUnsizedArray = true;
1365 Designator.addUnsizedArrayUnchecked(ElemTy);
1368 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1369 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1370 Designator.addArrayUnchecked(CAT);
1372 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1373 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1374 Designator.addComplexUnchecked(EltTy, Imag);
1376 void clearIsNullPointer() {
1379 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1380 const APSInt &Index, CharUnits ElementSize) {
1381 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1382 // but we're not required to diagnose it and it's valid in C++.)
1386 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1387 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1389 uint64_t Offset64 = Offset.getQuantity();
1390 uint64_t ElemSize64 = ElementSize.getQuantity();
1391 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1392 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1394 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1395 Designator.adjustIndex(Info, E, Index);
1396 clearIsNullPointer();
1398 void adjustOffset(CharUnits N) {
1400 if (N.getQuantity())
1401 clearIsNullPointer();
1407 explicit MemberPtr(const ValueDecl *Decl) :
1408 DeclAndIsDerivedMember(Decl, false), Path() {}
1410 /// The member or (direct or indirect) field referred to by this member
1411 /// pointer, or 0 if this is a null member pointer.
1412 const ValueDecl *getDecl() const {
1413 return DeclAndIsDerivedMember.getPointer();
1415 /// Is this actually a member of some type derived from the relevant class?
1416 bool isDerivedMember() const {
1417 return DeclAndIsDerivedMember.getInt();
1419 /// Get the class which the declaration actually lives in.
1420 const CXXRecordDecl *getContainingRecord() const {
1421 return cast<CXXRecordDecl>(
1422 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1425 void moveInto(APValue &V) const {
1426 V = APValue(getDecl(), isDerivedMember(), Path);
1428 void setFrom(const APValue &V) {
1429 assert(V.isMemberPointer());
1430 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1431 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1433 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1434 Path.insert(Path.end(), P.begin(), P.end());
1437 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1438 /// whether the member is a member of some class derived from the class type
1439 /// of the member pointer.
1440 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1441 /// Path - The path of base/derived classes from the member declaration's
1442 /// class (exclusive) to the class type of the member pointer (inclusive).
1443 SmallVector<const CXXRecordDecl*, 4> Path;
1445 /// Perform a cast towards the class of the Decl (either up or down the
1447 bool castBack(const CXXRecordDecl *Class) {
1448 assert(!Path.empty());
1449 const CXXRecordDecl *Expected;
1450 if (Path.size() >= 2)
1451 Expected = Path[Path.size() - 2];
1453 Expected = getContainingRecord();
1454 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1455 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1456 // if B does not contain the original member and is not a base or
1457 // derived class of the class containing the original member, the result
1458 // of the cast is undefined.
1459 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1460 // (D::*). We consider that to be a language defect.
1466 /// Perform a base-to-derived member pointer cast.
1467 bool castToDerived(const CXXRecordDecl *Derived) {
1470 if (!isDerivedMember()) {
1471 Path.push_back(Derived);
1474 if (!castBack(Derived))
1477 DeclAndIsDerivedMember.setInt(false);
1480 /// Perform a derived-to-base member pointer cast.
1481 bool castToBase(const CXXRecordDecl *Base) {
1485 DeclAndIsDerivedMember.setInt(true);
1486 if (isDerivedMember()) {
1487 Path.push_back(Base);
1490 return castBack(Base);
1494 /// Compare two member pointers, which are assumed to be of the same type.
1495 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1496 if (!LHS.getDecl() || !RHS.getDecl())
1497 return !LHS.getDecl() && !RHS.getDecl();
1498 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1500 return LHS.Path == RHS.Path;
1504 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1505 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1506 const LValue &This, const Expr *E,
1507 bool AllowNonLiteralTypes = false);
1508 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1509 bool InvalidBaseOK = false);
1510 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1511 bool InvalidBaseOK = false);
1512 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1514 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1515 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1516 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1518 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1519 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1520 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1522 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1524 //===----------------------------------------------------------------------===//
1526 //===----------------------------------------------------------------------===//
1528 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1529 /// preserving its value (by extending by up to one bit as needed).
1530 static void negateAsSigned(APSInt &Int) {
1531 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1532 Int = Int.extend(Int.getBitWidth() + 1);
1533 Int.setIsSigned(true);
1538 /// Produce a string describing the given constexpr call.
1539 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1540 unsigned ArgIndex = 0;
1541 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1542 !isa<CXXConstructorDecl>(Frame->Callee) &&
1543 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1546 Out << *Frame->Callee << '(';
1548 if (Frame->This && IsMemberCall) {
1550 Frame->This->moveInto(Val);
1551 Val.printPretty(Out, Frame->Info.Ctx,
1552 Frame->This->Designator.MostDerivedType);
1553 // FIXME: Add parens around Val if needed.
1554 Out << "->" << *Frame->Callee << '(';
1555 IsMemberCall = false;
1558 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1559 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1560 if (ArgIndex > (unsigned)IsMemberCall)
1563 const ParmVarDecl *Param = *I;
1564 const APValue &Arg = Frame->Arguments[ArgIndex];
1565 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1567 if (ArgIndex == 0 && IsMemberCall)
1568 Out << "->" << *Frame->Callee << '(';
1574 /// Evaluate an expression to see if it had side-effects, and discard its
1576 /// \return \c true if the caller should keep evaluating.
1577 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1579 if (!Evaluate(Scratch, Info, E))
1580 // We don't need the value, but we might have skipped a side effect here.
1581 return Info.noteSideEffect();
1585 /// Should this call expression be treated as a string literal?
1586 static bool IsStringLiteralCall(const CallExpr *E) {
1587 unsigned Builtin = E->getBuiltinCallee();
1588 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1589 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1592 static bool IsGlobalLValue(APValue::LValueBase B) {
1593 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1594 // constant expression of pointer type that evaluates to...
1596 // ... a null pointer value, or a prvalue core constant expression of type
1598 if (!B) return true;
1600 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1601 // ... the address of an object with static storage duration,
1602 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1603 return VD->hasGlobalStorage();
1604 // ... the address of a function,
1605 return isa<FunctionDecl>(D);
1608 const Expr *E = B.get<const Expr*>();
1609 switch (E->getStmtClass()) {
1612 case Expr::CompoundLiteralExprClass: {
1613 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1614 return CLE->isFileScope() && CLE->isLValue();
1616 case Expr::MaterializeTemporaryExprClass:
1617 // A materialized temporary might have been lifetime-extended to static
1618 // storage duration.
1619 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1620 // A string literal has static storage duration.
1621 case Expr::StringLiteralClass:
1622 case Expr::PredefinedExprClass:
1623 case Expr::ObjCStringLiteralClass:
1624 case Expr::ObjCEncodeExprClass:
1625 case Expr::CXXTypeidExprClass:
1626 case Expr::CXXUuidofExprClass:
1628 case Expr::CallExprClass:
1629 return IsStringLiteralCall(cast<CallExpr>(E));
1630 // For GCC compatibility, &&label has static storage duration.
1631 case Expr::AddrLabelExprClass:
1633 // A Block literal expression may be used as the initialization value for
1634 // Block variables at global or local static scope.
1635 case Expr::BlockExprClass:
1636 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1637 case Expr::ImplicitValueInitExprClass:
1639 // We can never form an lvalue with an implicit value initialization as its
1640 // base through expression evaluation, so these only appear in one case: the
1641 // implicit variable declaration we invent when checking whether a constexpr
1642 // constructor can produce a constant expression. We must assume that such
1643 // an expression might be a global lvalue.
1648 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1649 assert(Base && "no location for a null lvalue");
1650 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1652 Info.Note(VD->getLocation(), diag::note_declared_at);
1654 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1655 diag::note_constexpr_temporary_here);
1658 /// Check that this reference or pointer core constant expression is a valid
1659 /// value for an address or reference constant expression. Return true if we
1660 /// can fold this expression, whether or not it's a constant expression.
1661 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1662 QualType Type, const LValue &LVal) {
1663 bool IsReferenceType = Type->isReferenceType();
1665 APValue::LValueBase Base = LVal.getLValueBase();
1666 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1668 // Check that the object is a global. Note that the fake 'this' object we
1669 // manufacture when checking potential constant expressions is conservatively
1670 // assumed to be global here.
1671 if (!IsGlobalLValue(Base)) {
1672 if (Info.getLangOpts().CPlusPlus11) {
1673 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1674 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1675 << IsReferenceType << !Designator.Entries.empty()
1677 NoteLValueLocation(Info, Base);
1681 // Don't allow references to temporaries to escape.
1684 assert((Info.checkingPotentialConstantExpression() ||
1685 LVal.getLValueCallIndex() == 0) &&
1686 "have call index for global lvalue");
1688 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1689 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1690 // Check if this is a thread-local variable.
1691 if (Var->getTLSKind())
1694 // A dllimport variable never acts like a constant.
1695 if (Var->hasAttr<DLLImportAttr>())
1698 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1699 // __declspec(dllimport) must be handled very carefully:
1700 // We must never initialize an expression with the thunk in C++.
1701 // Doing otherwise would allow the same id-expression to yield
1702 // different addresses for the same function in different translation
1703 // units. However, this means that we must dynamically initialize the
1704 // expression with the contents of the import address table at runtime.
1706 // The C language has no notion of ODR; furthermore, it has no notion of
1707 // dynamic initialization. This means that we are permitted to
1708 // perform initialization with the address of the thunk.
1709 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1714 // Allow address constant expressions to be past-the-end pointers. This is
1715 // an extension: the standard requires them to point to an object.
1716 if (!IsReferenceType)
1719 // A reference constant expression must refer to an object.
1721 // FIXME: diagnostic
1726 // Does this refer one past the end of some object?
1727 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1728 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1729 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1730 << !Designator.Entries.empty() << !!VD << VD;
1731 NoteLValueLocation(Info, Base);
1737 /// Member pointers are constant expressions unless they point to a
1738 /// non-virtual dllimport member function.
1739 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1742 const APValue &Value) {
1743 const ValueDecl *Member = Value.getMemberPointerDecl();
1744 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1747 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1750 /// Check that this core constant expression is of literal type, and if not,
1751 /// produce an appropriate diagnostic.
1752 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1753 const LValue *This = nullptr) {
1754 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1757 // C++1y: A constant initializer for an object o [...] may also invoke
1758 // constexpr constructors for o and its subobjects even if those objects
1759 // are of non-literal class types.
1761 // C++11 missed this detail for aggregates, so classes like this:
1762 // struct foo_t { union { int i; volatile int j; } u; };
1763 // are not (obviously) initializable like so:
1764 // __attribute__((__require_constant_initialization__))
1765 // static const foo_t x = {{0}};
1766 // because "i" is a subobject with non-literal initialization (due to the
1767 // volatile member of the union). See:
1768 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1769 // Therefore, we use the C++1y behavior.
1770 if (This && Info.EvaluatingDecl == This->getLValueBase())
1773 // Prvalue constant expressions must be of literal types.
1774 if (Info.getLangOpts().CPlusPlus11)
1775 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1778 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1782 /// Check that this core constant expression value is a valid value for a
1783 /// constant expression. If not, report an appropriate diagnostic. Does not
1784 /// check that the expression is of literal type.
1785 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1786 QualType Type, const APValue &Value) {
1787 if (Value.isUninit()) {
1788 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1793 // We allow _Atomic(T) to be initialized from anything that T can be
1794 // initialized from.
1795 if (const AtomicType *AT = Type->getAs<AtomicType>())
1796 Type = AT->getValueType();
1798 // Core issue 1454: For a literal constant expression of array or class type,
1799 // each subobject of its value shall have been initialized by a constant
1801 if (Value.isArray()) {
1802 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1803 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1804 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1805 Value.getArrayInitializedElt(I)))
1808 if (!Value.hasArrayFiller())
1810 return CheckConstantExpression(Info, DiagLoc, EltTy,
1811 Value.getArrayFiller());
1813 if (Value.isUnion() && Value.getUnionField()) {
1814 return CheckConstantExpression(Info, DiagLoc,
1815 Value.getUnionField()->getType(),
1816 Value.getUnionValue());
1818 if (Value.isStruct()) {
1819 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1820 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1821 unsigned BaseIndex = 0;
1822 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1823 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1824 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1825 Value.getStructBase(BaseIndex)))
1829 for (const auto *I : RD->fields()) {
1830 if (I->isUnnamedBitfield())
1833 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1834 Value.getStructField(I->getFieldIndex())))
1839 if (Value.isLValue()) {
1841 LVal.setFrom(Info.Ctx, Value);
1842 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1845 if (Value.isMemberPointer())
1846 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1848 // Everything else is fine.
1852 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1853 return LVal.Base.dyn_cast<const ValueDecl*>();
1856 static bool IsLiteralLValue(const LValue &Value) {
1857 if (Value.CallIndex)
1859 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1860 return E && !isa<MaterializeTemporaryExpr>(E);
1863 static bool IsWeakLValue(const LValue &Value) {
1864 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1865 return Decl && Decl->isWeak();
1868 static bool isZeroSized(const LValue &Value) {
1869 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1870 if (Decl && isa<VarDecl>(Decl)) {
1871 QualType Ty = Decl->getType();
1872 if (Ty->isArrayType())
1873 return Ty->isIncompleteType() ||
1874 Decl->getASTContext().getTypeSize(Ty) == 0;
1879 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1880 // A null base expression indicates a null pointer. These are always
1881 // evaluatable, and they are false unless the offset is zero.
1882 if (!Value.getLValueBase()) {
1883 Result = !Value.getLValueOffset().isZero();
1887 // We have a non-null base. These are generally known to be true, but if it's
1888 // a weak declaration it can be null at runtime.
1890 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1891 return !Decl || !Decl->isWeak();
1894 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1895 switch (Val.getKind()) {
1896 case APValue::Uninitialized:
1899 Result = Val.getInt().getBoolValue();
1901 case APValue::Float:
1902 Result = !Val.getFloat().isZero();
1904 case APValue::ComplexInt:
1905 Result = Val.getComplexIntReal().getBoolValue() ||
1906 Val.getComplexIntImag().getBoolValue();
1908 case APValue::ComplexFloat:
1909 Result = !Val.getComplexFloatReal().isZero() ||
1910 !Val.getComplexFloatImag().isZero();
1912 case APValue::LValue:
1913 return EvalPointerValueAsBool(Val, Result);
1914 case APValue::MemberPointer:
1915 Result = Val.getMemberPointerDecl();
1917 case APValue::Vector:
1918 case APValue::Array:
1919 case APValue::Struct:
1920 case APValue::Union:
1921 case APValue::AddrLabelDiff:
1925 llvm_unreachable("unknown APValue kind");
1928 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1930 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1932 if (!Evaluate(Val, Info, E))
1934 return HandleConversionToBool(Val, Result);
1937 template<typename T>
1938 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1939 const T &SrcValue, QualType DestType) {
1940 Info.CCEDiag(E, diag::note_constexpr_overflow)
1941 << SrcValue << DestType;
1942 return Info.noteUndefinedBehavior();
1945 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1946 QualType SrcType, const APFloat &Value,
1947 QualType DestType, APSInt &Result) {
1948 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1949 // Determine whether we are converting to unsigned or signed.
1950 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1952 Result = APSInt(DestWidth, !DestSigned);
1954 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1955 & APFloat::opInvalidOp)
1956 return HandleOverflow(Info, E, Value, DestType);
1960 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1961 QualType SrcType, QualType DestType,
1963 APFloat Value = Result;
1965 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1966 APFloat::rmNearestTiesToEven, &ignored)
1967 & APFloat::opOverflow)
1968 return HandleOverflow(Info, E, Value, DestType);
1972 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1973 QualType DestType, QualType SrcType,
1974 const APSInt &Value) {
1975 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1976 APSInt Result = Value;
1977 // Figure out if this is a truncate, extend or noop cast.
1978 // If the input is signed, do a sign extend, noop, or truncate.
1979 Result = Result.extOrTrunc(DestWidth);
1980 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1984 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1985 QualType SrcType, const APSInt &Value,
1986 QualType DestType, APFloat &Result) {
1987 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1988 if (Result.convertFromAPInt(Value, Value.isSigned(),
1989 APFloat::rmNearestTiesToEven)
1990 & APFloat::opOverflow)
1991 return HandleOverflow(Info, E, Value, DestType);
1995 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1996 APValue &Value, const FieldDecl *FD) {
1997 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1999 if (!Value.isInt()) {
2000 // Trying to store a pointer-cast-to-integer into a bitfield.
2001 // FIXME: In this case, we should provide the diagnostic for casting
2002 // a pointer to an integer.
2003 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2008 APSInt &Int = Value.getInt();
2009 unsigned OldBitWidth = Int.getBitWidth();
2010 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2011 if (NewBitWidth < OldBitWidth)
2012 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2016 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2019 if (!Evaluate(SVal, Info, E))
2022 Res = SVal.getInt();
2025 if (SVal.isFloat()) {
2026 Res = SVal.getFloat().bitcastToAPInt();
2029 if (SVal.isVector()) {
2030 QualType VecTy = E->getType();
2031 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2032 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2033 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2034 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2035 Res = llvm::APInt::getNullValue(VecSize);
2036 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2037 APValue &Elt = SVal.getVectorElt(i);
2038 llvm::APInt EltAsInt;
2040 EltAsInt = Elt.getInt();
2041 } else if (Elt.isFloat()) {
2042 EltAsInt = Elt.getFloat().bitcastToAPInt();
2044 // Don't try to handle vectors of anything other than int or float
2045 // (not sure if it's possible to hit this case).
2046 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2049 unsigned BaseEltSize = EltAsInt.getBitWidth();
2051 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2053 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2057 // Give up if the input isn't an int, float, or vector. For example, we
2058 // reject "(v4i16)(intptr_t)&a".
2059 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2063 /// Perform the given integer operation, which is known to need at most BitWidth
2064 /// bits, and check for overflow in the original type (if that type was not an
2066 template<typename Operation>
2067 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2068 const APSInt &LHS, const APSInt &RHS,
2069 unsigned BitWidth, Operation Op,
2071 if (LHS.isUnsigned()) {
2072 Result = Op(LHS, RHS);
2076 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2077 Result = Value.trunc(LHS.getBitWidth());
2078 if (Result.extend(BitWidth) != Value) {
2079 if (Info.checkingForOverflow())
2080 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2081 diag::warn_integer_constant_overflow)
2082 << Result.toString(10) << E->getType();
2084 return HandleOverflow(Info, E, Value, E->getType());
2089 /// Perform the given binary integer operation.
2090 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2091 BinaryOperatorKind Opcode, APSInt RHS,
2098 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2099 std::multiplies<APSInt>(), Result);
2101 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2102 std::plus<APSInt>(), Result);
2104 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2105 std::minus<APSInt>(), Result);
2106 case BO_And: Result = LHS & RHS; return true;
2107 case BO_Xor: Result = LHS ^ RHS; return true;
2108 case BO_Or: Result = LHS | RHS; return true;
2112 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2115 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2116 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2117 // this operation and gives the two's complement result.
2118 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2119 LHS.isSigned() && LHS.isMinSignedValue())
2120 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2124 if (Info.getLangOpts().OpenCL)
2125 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2126 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2127 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2129 else if (RHS.isSigned() && RHS.isNegative()) {
2130 // During constant-folding, a negative shift is an opposite shift. Such
2131 // a shift is not a constant expression.
2132 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2137 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2138 // the shifted type.
2139 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2141 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2142 << RHS << E->getType() << LHS.getBitWidth();
2143 } else if (LHS.isSigned()) {
2144 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2145 // operand, and must not overflow the corresponding unsigned type.
2146 if (LHS.isNegative())
2147 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2148 else if (LHS.countLeadingZeros() < SA)
2149 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2155 if (Info.getLangOpts().OpenCL)
2156 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2157 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2158 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2160 else if (RHS.isSigned() && RHS.isNegative()) {
2161 // During constant-folding, a negative shift is an opposite shift. Such a
2162 // shift is not a constant expression.
2163 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2168 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2170 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2172 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2173 << RHS << E->getType() << LHS.getBitWidth();
2178 case BO_LT: Result = LHS < RHS; return true;
2179 case BO_GT: Result = LHS > RHS; return true;
2180 case BO_LE: Result = LHS <= RHS; return true;
2181 case BO_GE: Result = LHS >= RHS; return true;
2182 case BO_EQ: Result = LHS == RHS; return true;
2183 case BO_NE: Result = LHS != RHS; return true;
2187 /// Perform the given binary floating-point operation, in-place, on LHS.
2188 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2189 APFloat &LHS, BinaryOperatorKind Opcode,
2190 const APFloat &RHS) {
2196 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2199 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2202 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2205 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2209 if (LHS.isInfinity() || LHS.isNaN()) {
2210 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2211 return Info.noteUndefinedBehavior();
2216 /// Cast an lvalue referring to a base subobject to a derived class, by
2217 /// truncating the lvalue's path to the given length.
2218 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2219 const RecordDecl *TruncatedType,
2220 unsigned TruncatedElements) {
2221 SubobjectDesignator &D = Result.Designator;
2223 // Check we actually point to a derived class object.
2224 if (TruncatedElements == D.Entries.size())
2226 assert(TruncatedElements >= D.MostDerivedPathLength &&
2227 "not casting to a derived class");
2228 if (!Result.checkSubobject(Info, E, CSK_Derived))
2231 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2232 const RecordDecl *RD = TruncatedType;
2233 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2234 if (RD->isInvalidDecl()) return false;
2235 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2236 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2237 if (isVirtualBaseClass(D.Entries[I]))
2238 Result.Offset -= Layout.getVBaseClassOffset(Base);
2240 Result.Offset -= Layout.getBaseClassOffset(Base);
2243 D.Entries.resize(TruncatedElements);
2247 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2248 const CXXRecordDecl *Derived,
2249 const CXXRecordDecl *Base,
2250 const ASTRecordLayout *RL = nullptr) {
2252 if (Derived->isInvalidDecl()) return false;
2253 RL = &Info.Ctx.getASTRecordLayout(Derived);
2256 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2257 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2261 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2262 const CXXRecordDecl *DerivedDecl,
2263 const CXXBaseSpecifier *Base) {
2264 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2266 if (!Base->isVirtual())
2267 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2269 SubobjectDesignator &D = Obj.Designator;
2273 // Extract most-derived object and corresponding type.
2274 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2275 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2278 // Find the virtual base class.
2279 if (DerivedDecl->isInvalidDecl()) return false;
2280 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2281 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2282 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2286 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2287 QualType Type, LValue &Result) {
2288 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2289 PathE = E->path_end();
2290 PathI != PathE; ++PathI) {
2291 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2294 Type = (*PathI)->getType();
2299 /// Update LVal to refer to the given field, which must be a member of the type
2300 /// currently described by LVal.
2301 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2302 const FieldDecl *FD,
2303 const ASTRecordLayout *RL = nullptr) {
2305 if (FD->getParent()->isInvalidDecl()) return false;
2306 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2309 unsigned I = FD->getFieldIndex();
2310 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2311 LVal.addDecl(Info, E, FD);
2315 /// Update LVal to refer to the given indirect field.
2316 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2318 const IndirectFieldDecl *IFD) {
2319 for (const auto *C : IFD->chain())
2320 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2325 /// Get the size of the given type in char units.
2326 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2327 QualType Type, CharUnits &Size) {
2328 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2330 if (Type->isVoidType() || Type->isFunctionType()) {
2331 Size = CharUnits::One();
2335 if (Type->isDependentType()) {
2340 if (!Type->isConstantSizeType()) {
2341 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2342 // FIXME: Better diagnostic.
2347 Size = Info.Ctx.getTypeSizeInChars(Type);
2351 /// Update a pointer value to model pointer arithmetic.
2352 /// \param Info - Information about the ongoing evaluation.
2353 /// \param E - The expression being evaluated, for diagnostic purposes.
2354 /// \param LVal - The pointer value to be updated.
2355 /// \param EltTy - The pointee type represented by LVal.
2356 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2357 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2358 LValue &LVal, QualType EltTy,
2359 APSInt Adjustment) {
2360 CharUnits SizeOfPointee;
2361 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2364 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2368 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2369 LValue &LVal, QualType EltTy,
2370 int64_t Adjustment) {
2371 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2372 APSInt::get(Adjustment));
2375 /// Update an lvalue to refer to a component of a complex number.
2376 /// \param Info - Information about the ongoing evaluation.
2377 /// \param LVal - The lvalue to be updated.
2378 /// \param EltTy - The complex number's component type.
2379 /// \param Imag - False for the real component, true for the imaginary.
2380 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2381 LValue &LVal, QualType EltTy,
2384 CharUnits SizeOfComponent;
2385 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2387 LVal.Offset += SizeOfComponent;
2389 LVal.addComplex(Info, E, EltTy, Imag);
2393 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2394 QualType Type, const LValue &LVal,
2397 /// Try to evaluate the initializer for a variable declaration.
2399 /// \param Info Information about the ongoing evaluation.
2400 /// \param E An expression to be used when printing diagnostics.
2401 /// \param VD The variable whose initializer should be obtained.
2402 /// \param Frame The frame in which the variable was created. Must be null
2403 /// if this variable is not local to the evaluation.
2404 /// \param Result Filled in with a pointer to the value of the variable.
2405 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2406 const VarDecl *VD, CallStackFrame *Frame,
2409 // If this is a parameter to an active constexpr function call, perform
2410 // argument substitution.
2411 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2412 // Assume arguments of a potential constant expression are unknown
2413 // constant expressions.
2414 if (Info.checkingPotentialConstantExpression())
2416 if (!Frame || !Frame->Arguments) {
2417 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2420 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2424 // If this is a local variable, dig out its value.
2426 Result = Frame->getTemporary(VD);
2428 // Assume variables referenced within a lambda's call operator that were
2429 // not declared within the call operator are captures and during checking
2430 // of a potential constant expression, assume they are unknown constant
2432 assert(isLambdaCallOperator(Frame->Callee) &&
2433 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2434 "missing value for local variable");
2435 if (Info.checkingPotentialConstantExpression())
2437 // FIXME: implement capture evaluation during constant expr evaluation.
2438 Info.FFDiag(E->getLocStart(),
2439 diag::note_unimplemented_constexpr_lambda_feature_ast)
2440 << "captures not currently allowed";
2446 // Dig out the initializer, and use the declaration which it's attached to.
2447 const Expr *Init = VD->getAnyInitializer(VD);
2448 if (!Init || Init->isValueDependent()) {
2449 // If we're checking a potential constant expression, the variable could be
2450 // initialized later.
2451 if (!Info.checkingPotentialConstantExpression())
2452 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2456 // If we're currently evaluating the initializer of this declaration, use that
2458 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2459 Result = Info.EvaluatingDeclValue;
2463 // Never evaluate the initializer of a weak variable. We can't be sure that
2464 // this is the definition which will be used.
2466 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2470 // Check that we can fold the initializer. In C++, we will have already done
2471 // this in the cases where it matters for conformance.
2472 SmallVector<PartialDiagnosticAt, 8> Notes;
2473 if (!VD->evaluateValue(Notes)) {
2474 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2475 Notes.size() + 1) << VD;
2476 Info.Note(VD->getLocation(), diag::note_declared_at);
2477 Info.addNotes(Notes);
2479 } else if (!VD->checkInitIsICE()) {
2480 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2481 Notes.size() + 1) << VD;
2482 Info.Note(VD->getLocation(), diag::note_declared_at);
2483 Info.addNotes(Notes);
2486 Result = VD->getEvaluatedValue();
2490 static bool IsConstNonVolatile(QualType T) {
2491 Qualifiers Quals = T.getQualifiers();
2492 return Quals.hasConst() && !Quals.hasVolatile();
2495 /// Get the base index of the given base class within an APValue representing
2496 /// the given derived class.
2497 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2498 const CXXRecordDecl *Base) {
2499 Base = Base->getCanonicalDecl();
2501 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2502 E = Derived->bases_end(); I != E; ++I, ++Index) {
2503 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2507 llvm_unreachable("base class missing from derived class's bases list");
2510 /// Extract the value of a character from a string literal.
2511 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2513 // FIXME: Support MakeStringConstant
2514 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2516 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2517 assert(Index <= Str.size() && "Index too large");
2518 return APSInt::getUnsigned(Str.c_str()[Index]);
2521 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2522 Lit = PE->getFunctionName();
2523 const StringLiteral *S = cast<StringLiteral>(Lit);
2524 const ConstantArrayType *CAT =
2525 Info.Ctx.getAsConstantArrayType(S->getType());
2526 assert(CAT && "string literal isn't an array");
2527 QualType CharType = CAT->getElementType();
2528 assert(CharType->isIntegerType() && "unexpected character type");
2530 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2531 CharType->isUnsignedIntegerType());
2532 if (Index < S->getLength())
2533 Value = S->getCodeUnit(Index);
2537 // Expand a string literal into an array of characters.
2538 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2540 const StringLiteral *S = cast<StringLiteral>(Lit);
2541 const ConstantArrayType *CAT =
2542 Info.Ctx.getAsConstantArrayType(S->getType());
2543 assert(CAT && "string literal isn't an array");
2544 QualType CharType = CAT->getElementType();
2545 assert(CharType->isIntegerType() && "unexpected character type");
2547 unsigned Elts = CAT->getSize().getZExtValue();
2548 Result = APValue(APValue::UninitArray(),
2549 std::min(S->getLength(), Elts), Elts);
2550 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2551 CharType->isUnsignedIntegerType());
2552 if (Result.hasArrayFiller())
2553 Result.getArrayFiller() = APValue(Value);
2554 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2555 Value = S->getCodeUnit(I);
2556 Result.getArrayInitializedElt(I) = APValue(Value);
2560 // Expand an array so that it has more than Index filled elements.
2561 static void expandArray(APValue &Array, unsigned Index) {
2562 unsigned Size = Array.getArraySize();
2563 assert(Index < Size);
2565 // Always at least double the number of elements for which we store a value.
2566 unsigned OldElts = Array.getArrayInitializedElts();
2567 unsigned NewElts = std::max(Index+1, OldElts * 2);
2568 NewElts = std::min(Size, std::max(NewElts, 8u));
2570 // Copy the data across.
2571 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2572 for (unsigned I = 0; I != OldElts; ++I)
2573 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2574 for (unsigned I = OldElts; I != NewElts; ++I)
2575 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2576 if (NewValue.hasArrayFiller())
2577 NewValue.getArrayFiller() = Array.getArrayFiller();
2578 Array.swap(NewValue);
2581 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2582 /// conversion. If it's of class type, we may assume that the copy operation
2583 /// is trivial. Note that this is never true for a union type with fields
2584 /// (because the copy always "reads" the active member) and always true for
2585 /// a non-class type.
2586 static bool isReadByLvalueToRvalueConversion(QualType T) {
2587 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2588 if (!RD || (RD->isUnion() && !RD->field_empty()))
2593 for (auto *Field : RD->fields())
2594 if (isReadByLvalueToRvalueConversion(Field->getType()))
2597 for (auto &BaseSpec : RD->bases())
2598 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2604 /// Diagnose an attempt to read from any unreadable field within the specified
2605 /// type, which might be a class type.
2606 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2608 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2612 if (!RD->hasMutableFields())
2615 for (auto *Field : RD->fields()) {
2616 // If we're actually going to read this field in some way, then it can't
2617 // be mutable. If we're in a union, then assigning to a mutable field
2618 // (even an empty one) can change the active member, so that's not OK.
2619 // FIXME: Add core issue number for the union case.
2620 if (Field->isMutable() &&
2621 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2622 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2623 Info.Note(Field->getLocation(), diag::note_declared_at);
2627 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2631 for (auto &BaseSpec : RD->bases())
2632 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2635 // All mutable fields were empty, and thus not actually read.
2639 /// Kinds of access we can perform on an object, for diagnostics.
2648 /// A handle to a complete object (an object that is not a subobject of
2649 /// another object).
2650 struct CompleteObject {
2651 /// The value of the complete object.
2653 /// The type of the complete object.
2656 CompleteObject() : Value(nullptr) {}
2657 CompleteObject(APValue *Value, QualType Type)
2658 : Value(Value), Type(Type) {
2659 assert(Value && "missing value for complete object");
2662 explicit operator bool() const { return Value; }
2664 } // end anonymous namespace
2666 /// Find the designated sub-object of an rvalue.
2667 template<typename SubobjectHandler>
2668 typename SubobjectHandler::result_type
2669 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2670 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2672 // A diagnostic will have already been produced.
2673 return handler.failed();
2674 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2675 if (Info.getLangOpts().CPlusPlus11)
2676 Info.FFDiag(E, Sub.isOnePastTheEnd()
2677 ? diag::note_constexpr_access_past_end
2678 : diag::note_constexpr_access_unsized_array)
2679 << handler.AccessKind;
2682 return handler.failed();
2685 APValue *O = Obj.Value;
2686 QualType ObjType = Obj.Type;
2687 const FieldDecl *LastField = nullptr;
2689 // Walk the designator's path to find the subobject.
2690 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2691 if (O->isUninit()) {
2692 if (!Info.checkingPotentialConstantExpression())
2693 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2694 return handler.failed();
2698 // If we are reading an object of class type, there may still be more
2699 // things we need to check: if there are any mutable subobjects, we
2700 // cannot perform this read. (This only happens when performing a trivial
2701 // copy or assignment.)
2702 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2703 diagnoseUnreadableFields(Info, E, ObjType))
2704 return handler.failed();
2706 if (!handler.found(*O, ObjType))
2709 // If we modified a bit-field, truncate it to the right width.
2710 if (handler.AccessKind != AK_Read &&
2711 LastField && LastField->isBitField() &&
2712 !truncateBitfieldValue(Info, E, *O, LastField))
2718 LastField = nullptr;
2719 if (ObjType->isArrayType()) {
2720 // Next subobject is an array element.
2721 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2722 assert(CAT && "vla in literal type?");
2723 uint64_t Index = Sub.Entries[I].ArrayIndex;
2724 if (CAT->getSize().ule(Index)) {
2725 // Note, it should not be possible to form a pointer with a valid
2726 // designator which points more than one past the end of the array.
2727 if (Info.getLangOpts().CPlusPlus11)
2728 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2729 << handler.AccessKind;
2732 return handler.failed();
2735 ObjType = CAT->getElementType();
2737 // An array object is represented as either an Array APValue or as an
2738 // LValue which refers to a string literal.
2739 if (O->isLValue()) {
2740 assert(I == N - 1 && "extracting subobject of character?");
2741 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2742 if (handler.AccessKind != AK_Read)
2743 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2746 return handler.foundString(*O, ObjType, Index);
2749 if (O->getArrayInitializedElts() > Index)
2750 O = &O->getArrayInitializedElt(Index);
2751 else if (handler.AccessKind != AK_Read) {
2752 expandArray(*O, Index);
2753 O = &O->getArrayInitializedElt(Index);
2755 O = &O->getArrayFiller();
2756 } else if (ObjType->isAnyComplexType()) {
2757 // Next subobject is a complex number.
2758 uint64_t Index = Sub.Entries[I].ArrayIndex;
2760 if (Info.getLangOpts().CPlusPlus11)
2761 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2762 << handler.AccessKind;
2765 return handler.failed();
2768 bool WasConstQualified = ObjType.isConstQualified();
2769 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2770 if (WasConstQualified)
2773 assert(I == N - 1 && "extracting subobject of scalar?");
2774 if (O->isComplexInt()) {
2775 return handler.found(Index ? O->getComplexIntImag()
2776 : O->getComplexIntReal(), ObjType);
2778 assert(O->isComplexFloat());
2779 return handler.found(Index ? O->getComplexFloatImag()
2780 : O->getComplexFloatReal(), ObjType);
2782 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2783 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2784 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2786 Info.Note(Field->getLocation(), diag::note_declared_at);
2787 return handler.failed();
2790 // Next subobject is a class, struct or union field.
2791 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2792 if (RD->isUnion()) {
2793 const FieldDecl *UnionField = O->getUnionField();
2795 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2796 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2797 << handler.AccessKind << Field << !UnionField << UnionField;
2798 return handler.failed();
2800 O = &O->getUnionValue();
2802 O = &O->getStructField(Field->getFieldIndex());
2804 bool WasConstQualified = ObjType.isConstQualified();
2805 ObjType = Field->getType();
2806 if (WasConstQualified && !Field->isMutable())
2809 if (ObjType.isVolatileQualified()) {
2810 if (Info.getLangOpts().CPlusPlus) {
2811 // FIXME: Include a description of the path to the volatile subobject.
2812 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2813 << handler.AccessKind << 2 << Field;
2814 Info.Note(Field->getLocation(), diag::note_declared_at);
2816 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2818 return handler.failed();
2823 // Next subobject is a base class.
2824 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2825 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2826 O = &O->getStructBase(getBaseIndex(Derived, Base));
2828 bool WasConstQualified = ObjType.isConstQualified();
2829 ObjType = Info.Ctx.getRecordType(Base);
2830 if (WasConstQualified)
2837 struct ExtractSubobjectHandler {
2841 static const AccessKinds AccessKind = AK_Read;
2843 typedef bool result_type;
2844 bool failed() { return false; }
2845 bool found(APValue &Subobj, QualType SubobjType) {
2849 bool found(APSInt &Value, QualType SubobjType) {
2850 Result = APValue(Value);
2853 bool found(APFloat &Value, QualType SubobjType) {
2854 Result = APValue(Value);
2857 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2858 Result = APValue(extractStringLiteralCharacter(
2859 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2863 } // end anonymous namespace
2865 const AccessKinds ExtractSubobjectHandler::AccessKind;
2867 /// Extract the designated sub-object of an rvalue.
2868 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2869 const CompleteObject &Obj,
2870 const SubobjectDesignator &Sub,
2872 ExtractSubobjectHandler Handler = { Info, Result };
2873 return findSubobject(Info, E, Obj, Sub, Handler);
2877 struct ModifySubobjectHandler {
2882 typedef bool result_type;
2883 static const AccessKinds AccessKind = AK_Assign;
2885 bool checkConst(QualType QT) {
2886 // Assigning to a const object has undefined behavior.
2887 if (QT.isConstQualified()) {
2888 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2894 bool failed() { return false; }
2895 bool found(APValue &Subobj, QualType SubobjType) {
2896 if (!checkConst(SubobjType))
2898 // We've been given ownership of NewVal, so just swap it in.
2899 Subobj.swap(NewVal);
2902 bool found(APSInt &Value, QualType SubobjType) {
2903 if (!checkConst(SubobjType))
2905 if (!NewVal.isInt()) {
2906 // Maybe trying to write a cast pointer value into a complex?
2910 Value = NewVal.getInt();
2913 bool found(APFloat &Value, QualType SubobjType) {
2914 if (!checkConst(SubobjType))
2916 Value = NewVal.getFloat();
2919 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2920 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2923 } // end anonymous namespace
2925 const AccessKinds ModifySubobjectHandler::AccessKind;
2927 /// Update the designated sub-object of an rvalue to the given value.
2928 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2929 const CompleteObject &Obj,
2930 const SubobjectDesignator &Sub,
2932 ModifySubobjectHandler Handler = { Info, NewVal, E };
2933 return findSubobject(Info, E, Obj, Sub, Handler);
2936 /// Find the position where two subobject designators diverge, or equivalently
2937 /// the length of the common initial subsequence.
2938 static unsigned FindDesignatorMismatch(QualType ObjType,
2939 const SubobjectDesignator &A,
2940 const SubobjectDesignator &B,
2941 bool &WasArrayIndex) {
2942 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2943 for (/**/; I != N; ++I) {
2944 if (!ObjType.isNull() &&
2945 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2946 // Next subobject is an array element.
2947 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2948 WasArrayIndex = true;
2951 if (ObjType->isAnyComplexType())
2952 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2954 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2956 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2957 WasArrayIndex = false;
2960 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2961 // Next subobject is a field.
2962 ObjType = FD->getType();
2964 // Next subobject is a base class.
2965 ObjType = QualType();
2968 WasArrayIndex = false;
2972 /// Determine whether the given subobject designators refer to elements of the
2973 /// same array object.
2974 static bool AreElementsOfSameArray(QualType ObjType,
2975 const SubobjectDesignator &A,
2976 const SubobjectDesignator &B) {
2977 if (A.Entries.size() != B.Entries.size())
2980 bool IsArray = A.MostDerivedIsArrayElement;
2981 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2982 // A is a subobject of the array element.
2985 // If A (and B) designates an array element, the last entry will be the array
2986 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2987 // of length 1' case, and the entire path must match.
2989 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2990 return CommonLength >= A.Entries.size() - IsArray;
2993 /// Find the complete object to which an LValue refers.
2994 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2995 AccessKinds AK, const LValue &LVal,
2996 QualType LValType) {
2998 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2999 return CompleteObject();
3002 CallStackFrame *Frame = nullptr;
3003 if (LVal.CallIndex) {
3004 Frame = Info.getCallFrame(LVal.CallIndex);
3006 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3007 << AK << LVal.Base.is<const ValueDecl*>();
3008 NoteLValueLocation(Info, LVal.Base);
3009 return CompleteObject();
3013 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3014 // is not a constant expression (even if the object is non-volatile). We also
3015 // apply this rule to C++98, in order to conform to the expected 'volatile'
3017 if (LValType.isVolatileQualified()) {
3018 if (Info.getLangOpts().CPlusPlus)
3019 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3023 return CompleteObject();
3026 // Compute value storage location and type of base object.
3027 APValue *BaseVal = nullptr;
3028 QualType BaseType = getType(LVal.Base);
3030 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3031 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3032 // In C++11, constexpr, non-volatile variables initialized with constant
3033 // expressions are constant expressions too. Inside constexpr functions,
3034 // parameters are constant expressions even if they're non-const.
3035 // In C++1y, objects local to a constant expression (those with a Frame) are
3036 // both readable and writable inside constant expressions.
3037 // In C, such things can also be folded, although they are not ICEs.
3038 const VarDecl *VD = dyn_cast<VarDecl>(D);
3040 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3043 if (!VD || VD->isInvalidDecl()) {
3045 return CompleteObject();
3048 // Accesses of volatile-qualified objects are not allowed.
3049 if (BaseType.isVolatileQualified()) {
3050 if (Info.getLangOpts().CPlusPlus) {
3051 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3053 Info.Note(VD->getLocation(), diag::note_declared_at);
3057 return CompleteObject();
3060 // Unless we're looking at a local variable or argument in a constexpr call,
3061 // the variable we're reading must be const.
3063 if (Info.getLangOpts().CPlusPlus14 &&
3064 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3065 // OK, we can read and modify an object if we're in the process of
3066 // evaluating its initializer, because its lifetime began in this
3068 } else if (AK != AK_Read) {
3069 // All the remaining cases only permit reading.
3070 Info.FFDiag(E, diag::note_constexpr_modify_global);
3071 return CompleteObject();
3072 } else if (VD->isConstexpr()) {
3073 // OK, we can read this variable.
3074 } else if (BaseType->isIntegralOrEnumerationType()) {
3075 // In OpenCL if a variable is in constant address space it is a const value.
3076 if (!(BaseType.isConstQualified() ||
3077 (Info.getLangOpts().OpenCL &&
3078 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3079 if (Info.getLangOpts().CPlusPlus) {
3080 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3081 Info.Note(VD->getLocation(), diag::note_declared_at);
3085 return CompleteObject();
3087 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3088 // We support folding of const floating-point types, in order to make
3089 // static const data members of such types (supported as an extension)
3091 if (Info.getLangOpts().CPlusPlus11) {
3092 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3093 Info.Note(VD->getLocation(), diag::note_declared_at);
3097 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3098 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3099 // Keep evaluating to see what we can do.
3101 // FIXME: Allow folding of values of any literal type in all languages.
3102 if (Info.checkingPotentialConstantExpression() &&
3103 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3104 // The definition of this variable could be constexpr. We can't
3105 // access it right now, but may be able to in future.
3106 } else if (Info.getLangOpts().CPlusPlus11) {
3107 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3108 Info.Note(VD->getLocation(), diag::note_declared_at);
3112 return CompleteObject();
3116 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3117 return CompleteObject();
3119 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3122 if (const MaterializeTemporaryExpr *MTE =
3123 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3124 assert(MTE->getStorageDuration() == SD_Static &&
3125 "should have a frame for a non-global materialized temporary");
3127 // Per C++1y [expr.const]p2:
3128 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3129 // - a [...] glvalue of integral or enumeration type that refers to
3130 // a non-volatile const object [...]
3132 // - a [...] glvalue of literal type that refers to a non-volatile
3133 // object whose lifetime began within the evaluation of e.
3135 // C++11 misses the 'began within the evaluation of e' check and
3136 // instead allows all temporaries, including things like:
3139 // constexpr int k = r;
3140 // Therefore we use the C++1y rules in C++11 too.
3141 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3142 const ValueDecl *ED = MTE->getExtendingDecl();
3143 if (!(BaseType.isConstQualified() &&
3144 BaseType->isIntegralOrEnumerationType()) &&
3145 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3146 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3147 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3148 return CompleteObject();
3151 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3152 assert(BaseVal && "got reference to unevaluated temporary");
3155 return CompleteObject();
3158 BaseVal = Frame->getTemporary(Base);
3159 assert(BaseVal && "missing value for temporary");
3162 // Volatile temporary objects cannot be accessed in constant expressions.
3163 if (BaseType.isVolatileQualified()) {
3164 if (Info.getLangOpts().CPlusPlus) {
3165 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3167 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3171 return CompleteObject();
3175 // During the construction of an object, it is not yet 'const'.
3176 // FIXME: This doesn't do quite the right thing for const subobjects of the
3177 // object under construction.
3178 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
3179 BaseType = Info.Ctx.getCanonicalType(BaseType);
3180 BaseType.removeLocalConst();
3183 // In C++1y, we can't safely access any mutable state when we might be
3184 // evaluating after an unmodeled side effect.
3186 // FIXME: Not all local state is mutable. Allow local constant subobjects
3187 // to be read here (but take care with 'mutable' fields).
3188 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3189 Info.EvalStatus.HasSideEffects) ||
3190 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3191 return CompleteObject();
3193 return CompleteObject(BaseVal, BaseType);
3196 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3197 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3198 /// glvalue referred to by an entity of reference type.
3200 /// \param Info - Information about the ongoing evaluation.
3201 /// \param Conv - The expression for which we are performing the conversion.
3202 /// Used for diagnostics.
3203 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3204 /// case of a non-class type).
3205 /// \param LVal - The glvalue on which we are attempting to perform this action.
3206 /// \param RVal - The produced value will be placed here.
3207 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3209 const LValue &LVal, APValue &RVal) {
3210 if (LVal.Designator.Invalid)
3213 // Check for special cases where there is no existing APValue to look at.
3214 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3215 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3216 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3217 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3218 // initializer until now for such expressions. Such an expression can't be
3219 // an ICE in C, so this only matters for fold.
3220 if (Type.isVolatileQualified()) {
3225 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3227 CompleteObject LitObj(&Lit, Base->getType());
3228 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3229 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3230 // We represent a string literal array as an lvalue pointing at the
3231 // corresponding expression, rather than building an array of chars.
3232 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3233 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3234 CompleteObject StrObj(&Str, Base->getType());
3235 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3239 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3240 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3243 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3244 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3245 QualType LValType, APValue &Val) {
3246 if (LVal.Designator.Invalid)
3249 if (!Info.getLangOpts().CPlusPlus14) {
3254 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3255 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3258 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3259 return T->isSignedIntegerType() &&
3260 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3264 struct CompoundAssignSubobjectHandler {
3267 QualType PromotedLHSType;
3268 BinaryOperatorKind Opcode;
3271 static const AccessKinds AccessKind = AK_Assign;
3273 typedef bool result_type;
3275 bool checkConst(QualType QT) {
3276 // Assigning to a const object has undefined behavior.
3277 if (QT.isConstQualified()) {
3278 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3284 bool failed() { return false; }
3285 bool found(APValue &Subobj, QualType SubobjType) {
3286 switch (Subobj.getKind()) {
3288 return found(Subobj.getInt(), SubobjType);
3289 case APValue::Float:
3290 return found(Subobj.getFloat(), SubobjType);
3291 case APValue::ComplexInt:
3292 case APValue::ComplexFloat:
3293 // FIXME: Implement complex compound assignment.
3296 case APValue::LValue:
3297 return foundPointer(Subobj, SubobjType);
3299 // FIXME: can this happen?
3304 bool found(APSInt &Value, QualType SubobjType) {
3305 if (!checkConst(SubobjType))
3308 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3309 // We don't support compound assignment on integer-cast-to-pointer
3315 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3317 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3319 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3322 bool found(APFloat &Value, QualType SubobjType) {
3323 return checkConst(SubobjType) &&
3324 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3326 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3327 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3329 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3330 if (!checkConst(SubobjType))
3333 QualType PointeeType;
3334 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3335 PointeeType = PT->getPointeeType();
3337 if (PointeeType.isNull() || !RHS.isInt() ||
3338 (Opcode != BO_Add && Opcode != BO_Sub)) {
3343 APSInt Offset = RHS.getInt();
3344 if (Opcode == BO_Sub)
3345 negateAsSigned(Offset);
3348 LVal.setFrom(Info.Ctx, Subobj);
3349 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3351 LVal.moveInto(Subobj);
3354 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3355 llvm_unreachable("shouldn't encounter string elements here");
3358 } // end anonymous namespace
3360 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3362 /// Perform a compound assignment of LVal <op>= RVal.
3363 static bool handleCompoundAssignment(
3364 EvalInfo &Info, const Expr *E,
3365 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3366 BinaryOperatorKind Opcode, const APValue &RVal) {
3367 if (LVal.Designator.Invalid)
3370 if (!Info.getLangOpts().CPlusPlus14) {
3375 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3376 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3378 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3382 struct IncDecSubobjectHandler {
3385 AccessKinds AccessKind;
3388 typedef bool result_type;
3390 bool checkConst(QualType QT) {
3391 // Assigning to a const object has undefined behavior.
3392 if (QT.isConstQualified()) {
3393 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3399 bool failed() { return false; }
3400 bool found(APValue &Subobj, QualType SubobjType) {
3401 // Stash the old value. Also clear Old, so we don't clobber it later
3402 // if we're post-incrementing a complex.
3408 switch (Subobj.getKind()) {
3410 return found(Subobj.getInt(), SubobjType);
3411 case APValue::Float:
3412 return found(Subobj.getFloat(), SubobjType);
3413 case APValue::ComplexInt:
3414 return found(Subobj.getComplexIntReal(),
3415 SubobjType->castAs<ComplexType>()->getElementType()
3416 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3417 case APValue::ComplexFloat:
3418 return found(Subobj.getComplexFloatReal(),
3419 SubobjType->castAs<ComplexType>()->getElementType()
3420 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3421 case APValue::LValue:
3422 return foundPointer(Subobj, SubobjType);
3424 // FIXME: can this happen?
3429 bool found(APSInt &Value, QualType SubobjType) {
3430 if (!checkConst(SubobjType))
3433 if (!SubobjType->isIntegerType()) {
3434 // We don't support increment / decrement on integer-cast-to-pointer
3440 if (Old) *Old = APValue(Value);
3442 // bool arithmetic promotes to int, and the conversion back to bool
3443 // doesn't reduce mod 2^n, so special-case it.
3444 if (SubobjType->isBooleanType()) {
3445 if (AccessKind == AK_Increment)
3452 bool WasNegative = Value.isNegative();
3453 if (AccessKind == AK_Increment) {
3456 if (!WasNegative && Value.isNegative() &&
3457 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3458 APSInt ActualValue(Value, /*IsUnsigned*/true);
3459 return HandleOverflow(Info, E, ActualValue, SubobjType);
3464 if (WasNegative && !Value.isNegative() &&
3465 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3466 unsigned BitWidth = Value.getBitWidth();
3467 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3468 ActualValue.setBit(BitWidth);
3469 return HandleOverflow(Info, E, ActualValue, SubobjType);
3474 bool found(APFloat &Value, QualType SubobjType) {
3475 if (!checkConst(SubobjType))
3478 if (Old) *Old = APValue(Value);
3480 APFloat One(Value.getSemantics(), 1);
3481 if (AccessKind == AK_Increment)
3482 Value.add(One, APFloat::rmNearestTiesToEven);
3484 Value.subtract(One, APFloat::rmNearestTiesToEven);
3487 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3488 if (!checkConst(SubobjType))
3491 QualType PointeeType;
3492 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3493 PointeeType = PT->getPointeeType();
3500 LVal.setFrom(Info.Ctx, Subobj);
3501 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3502 AccessKind == AK_Increment ? 1 : -1))
3504 LVal.moveInto(Subobj);
3507 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3508 llvm_unreachable("shouldn't encounter string elements here");
3511 } // end anonymous namespace
3513 /// Perform an increment or decrement on LVal.
3514 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3515 QualType LValType, bool IsIncrement, APValue *Old) {
3516 if (LVal.Designator.Invalid)
3519 if (!Info.getLangOpts().CPlusPlus14) {
3524 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3525 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3526 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3527 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3530 /// Build an lvalue for the object argument of a member function call.
3531 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3533 if (Object->getType()->isPointerType())
3534 return EvaluatePointer(Object, This, Info);
3536 if (Object->isGLValue())
3537 return EvaluateLValue(Object, This, Info);
3539 if (Object->getType()->isLiteralType(Info.Ctx))
3540 return EvaluateTemporary(Object, This, Info);
3542 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3546 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3547 /// lvalue referring to the result.
3549 /// \param Info - Information about the ongoing evaluation.
3550 /// \param LV - An lvalue referring to the base of the member pointer.
3551 /// \param RHS - The member pointer expression.
3552 /// \param IncludeMember - Specifies whether the member itself is included in
3553 /// the resulting LValue subobject designator. This is not possible when
3554 /// creating a bound member function.
3555 /// \return The field or method declaration to which the member pointer refers,
3556 /// or 0 if evaluation fails.
3557 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3561 bool IncludeMember = true) {
3563 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3566 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3567 // member value, the behavior is undefined.
3568 if (!MemPtr.getDecl()) {
3569 // FIXME: Specific diagnostic.
3574 if (MemPtr.isDerivedMember()) {
3575 // This is a member of some derived class. Truncate LV appropriately.
3576 // The end of the derived-to-base path for the base object must match the
3577 // derived-to-base path for the member pointer.
3578 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3579 LV.Designator.Entries.size()) {
3583 unsigned PathLengthToMember =
3584 LV.Designator.Entries.size() - MemPtr.Path.size();
3585 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3586 const CXXRecordDecl *LVDecl = getAsBaseClass(
3587 LV.Designator.Entries[PathLengthToMember + I]);
3588 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3589 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3595 // Truncate the lvalue to the appropriate derived class.
3596 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3597 PathLengthToMember))
3599 } else if (!MemPtr.Path.empty()) {
3600 // Extend the LValue path with the member pointer's path.
3601 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3602 MemPtr.Path.size() + IncludeMember);
3604 // Walk down to the appropriate base class.
3605 if (const PointerType *PT = LVType->getAs<PointerType>())
3606 LVType = PT->getPointeeType();
3607 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3608 assert(RD && "member pointer access on non-class-type expression");
3609 // The first class in the path is that of the lvalue.
3610 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3611 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3612 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3616 // Finally cast to the class containing the member.
3617 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3618 MemPtr.getContainingRecord()))
3622 // Add the member. Note that we cannot build bound member functions here.
3623 if (IncludeMember) {
3624 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3625 if (!HandleLValueMember(Info, RHS, LV, FD))
3627 } else if (const IndirectFieldDecl *IFD =
3628 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3629 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3632 llvm_unreachable("can't construct reference to bound member function");
3636 return MemPtr.getDecl();
3639 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3640 const BinaryOperator *BO,
3642 bool IncludeMember = true) {
3643 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3645 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3646 if (Info.noteFailure()) {
3648 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3653 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3654 BO->getRHS(), IncludeMember);
3657 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3658 /// the provided lvalue, which currently refers to the base object.
3659 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3661 SubobjectDesignator &D = Result.Designator;
3662 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3665 QualType TargetQT = E->getType();
3666 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3667 TargetQT = PT->getPointeeType();
3669 // Check this cast lands within the final derived-to-base subobject path.
3670 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3671 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3672 << D.MostDerivedType << TargetQT;
3676 // Check the type of the final cast. We don't need to check the path,
3677 // since a cast can only be formed if the path is unique.
3678 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3679 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3680 const CXXRecordDecl *FinalType;
3681 if (NewEntriesSize == D.MostDerivedPathLength)
3682 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3684 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3685 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3686 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3687 << D.MostDerivedType << TargetQT;
3691 // Truncate the lvalue to the appropriate derived class.
3692 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3696 enum EvalStmtResult {
3697 /// Evaluation failed.
3699 /// Hit a 'return' statement.
3701 /// Evaluation succeeded.
3703 /// Hit a 'continue' statement.
3705 /// Hit a 'break' statement.
3707 /// Still scanning for 'case' or 'default' statement.
3712 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3713 // We don't need to evaluate the initializer for a static local.
3714 if (!VD->hasLocalStorage())
3718 Result.set(VD, Info.CurrentCall->Index);
3719 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3721 const Expr *InitE = VD->getInit();
3723 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3724 << false << VD->getType();
3729 if (InitE->isValueDependent())
3732 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3733 // Wipe out any partially-computed value, to allow tracking that this
3734 // evaluation failed.
3742 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3745 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3746 OK &= EvaluateVarDecl(Info, VD);
3748 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3749 for (auto *BD : DD->bindings())
3750 if (auto *VD = BD->getHoldingVar())
3751 OK &= EvaluateDecl(Info, VD);
3757 /// Evaluate a condition (either a variable declaration or an expression).
3758 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3759 const Expr *Cond, bool &Result) {
3760 FullExpressionRAII Scope(Info);
3761 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3763 return EvaluateAsBooleanCondition(Cond, Result, Info);
3767 /// \brief A location where the result (returned value) of evaluating a
3768 /// statement should be stored.
3770 /// The APValue that should be filled in with the returned value.
3772 /// The location containing the result, if any (used to support RVO).
3777 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3779 const SwitchCase *SC = nullptr);
3781 /// Evaluate the body of a loop, and translate the result as appropriate.
3782 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3784 const SwitchCase *Case = nullptr) {
3785 BlockScopeRAII Scope(Info);
3786 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3788 return ESR_Succeeded;
3791 return ESR_Continue;
3794 case ESR_CaseNotFound:
3797 llvm_unreachable("Invalid EvalStmtResult!");
3800 /// Evaluate a switch statement.
3801 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3802 const SwitchStmt *SS) {
3803 BlockScopeRAII Scope(Info);
3805 // Evaluate the switch condition.
3808 FullExpressionRAII Scope(Info);
3809 if (const Stmt *Init = SS->getInit()) {
3810 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3811 if (ESR != ESR_Succeeded)
3814 if (SS->getConditionVariable() &&
3815 !EvaluateDecl(Info, SS->getConditionVariable()))
3817 if (!EvaluateInteger(SS->getCond(), Value, Info))
3821 // Find the switch case corresponding to the value of the condition.
3822 // FIXME: Cache this lookup.
3823 const SwitchCase *Found = nullptr;
3824 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3825 SC = SC->getNextSwitchCase()) {
3826 if (isa<DefaultStmt>(SC)) {
3831 const CaseStmt *CS = cast<CaseStmt>(SC);
3832 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3833 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3835 if (LHS <= Value && Value <= RHS) {
3842 return ESR_Succeeded;
3844 // Search the switch body for the switch case and evaluate it from there.
3845 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3847 return ESR_Succeeded;
3853 case ESR_CaseNotFound:
3854 // This can only happen if the switch case is nested within a statement
3855 // expression. We have no intention of supporting that.
3856 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3859 llvm_unreachable("Invalid EvalStmtResult!");
3862 // Evaluate a statement.
3863 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3864 const Stmt *S, const SwitchCase *Case) {
3865 if (!Info.nextStep(S))
3868 // If we're hunting down a 'case' or 'default' label, recurse through
3869 // substatements until we hit the label.
3871 // FIXME: We don't start the lifetime of objects whose initialization we
3872 // jump over. However, such objects must be of class type with a trivial
3873 // default constructor that initialize all subobjects, so must be empty,
3874 // so this almost never matters.
3875 switch (S->getStmtClass()) {
3876 case Stmt::CompoundStmtClass:
3877 // FIXME: Precompute which substatement of a compound statement we
3878 // would jump to, and go straight there rather than performing a
3879 // linear scan each time.
3880 case Stmt::LabelStmtClass:
3881 case Stmt::AttributedStmtClass:
3882 case Stmt::DoStmtClass:
3885 case Stmt::CaseStmtClass:
3886 case Stmt::DefaultStmtClass:
3891 case Stmt::IfStmtClass: {
3892 // FIXME: Precompute which side of an 'if' we would jump to, and go
3893 // straight there rather than scanning both sides.
3894 const IfStmt *IS = cast<IfStmt>(S);
3896 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3897 // preceded by our switch label.
3898 BlockScopeRAII Scope(Info);
3900 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3901 if (ESR != ESR_CaseNotFound || !IS->getElse())
3903 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3906 case Stmt::WhileStmtClass: {
3907 EvalStmtResult ESR =
3908 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3909 if (ESR != ESR_Continue)
3914 case Stmt::ForStmtClass: {
3915 const ForStmt *FS = cast<ForStmt>(S);
3916 EvalStmtResult ESR =
3917 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3918 if (ESR != ESR_Continue)
3921 FullExpressionRAII IncScope(Info);
3922 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3928 case Stmt::DeclStmtClass:
3929 // FIXME: If the variable has initialization that can't be jumped over,
3930 // bail out of any immediately-surrounding compound-statement too.
3932 return ESR_CaseNotFound;
3936 switch (S->getStmtClass()) {
3938 if (const Expr *E = dyn_cast<Expr>(S)) {
3939 // Don't bother evaluating beyond an expression-statement which couldn't
3941 FullExpressionRAII Scope(Info);
3942 if (!EvaluateIgnoredValue(Info, E))
3944 return ESR_Succeeded;
3947 Info.FFDiag(S->getLocStart());
3950 case Stmt::NullStmtClass:
3951 return ESR_Succeeded;
3953 case Stmt::DeclStmtClass: {
3954 const DeclStmt *DS = cast<DeclStmt>(S);
3955 for (const auto *DclIt : DS->decls()) {
3956 // Each declaration initialization is its own full-expression.
3957 // FIXME: This isn't quite right; if we're performing aggregate
3958 // initialization, each braced subexpression is its own full-expression.
3959 FullExpressionRAII Scope(Info);
3960 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3963 return ESR_Succeeded;
3966 case Stmt::ReturnStmtClass: {
3967 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3968 FullExpressionRAII Scope(Info);
3971 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3972 : Evaluate(Result.Value, Info, RetExpr)))
3974 return ESR_Returned;
3977 case Stmt::CompoundStmtClass: {
3978 BlockScopeRAII Scope(Info);
3980 const CompoundStmt *CS = cast<CompoundStmt>(S);
3981 for (const auto *BI : CS->body()) {
3982 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3983 if (ESR == ESR_Succeeded)
3985 else if (ESR != ESR_CaseNotFound)
3988 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3991 case Stmt::IfStmtClass: {
3992 const IfStmt *IS = cast<IfStmt>(S);
3994 // Evaluate the condition, as either a var decl or as an expression.
3995 BlockScopeRAII Scope(Info);
3996 if (const Stmt *Init = IS->getInit()) {
3997 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3998 if (ESR != ESR_Succeeded)
4002 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4005 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4006 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4007 if (ESR != ESR_Succeeded)
4010 return ESR_Succeeded;
4013 case Stmt::WhileStmtClass: {
4014 const WhileStmt *WS = cast<WhileStmt>(S);
4016 BlockScopeRAII Scope(Info);
4018 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4024 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4025 if (ESR != ESR_Continue)
4028 return ESR_Succeeded;
4031 case Stmt::DoStmtClass: {
4032 const DoStmt *DS = cast<DoStmt>(S);
4035 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4036 if (ESR != ESR_Continue)
4040 FullExpressionRAII CondScope(Info);
4041 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4044 return ESR_Succeeded;
4047 case Stmt::ForStmtClass: {
4048 const ForStmt *FS = cast<ForStmt>(S);
4049 BlockScopeRAII Scope(Info);
4050 if (FS->getInit()) {
4051 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4052 if (ESR != ESR_Succeeded)
4056 BlockScopeRAII Scope(Info);
4057 bool Continue = true;
4058 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4059 FS->getCond(), Continue))
4064 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4065 if (ESR != ESR_Continue)
4069 FullExpressionRAII IncScope(Info);
4070 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4074 return ESR_Succeeded;
4077 case Stmt::CXXForRangeStmtClass: {
4078 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4079 BlockScopeRAII Scope(Info);
4081 // Initialize the __range variable.
4082 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4083 if (ESR != ESR_Succeeded)
4086 // Create the __begin and __end iterators.
4087 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4088 if (ESR != ESR_Succeeded)
4090 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4091 if (ESR != ESR_Succeeded)
4095 // Condition: __begin != __end.
4097 bool Continue = true;
4098 FullExpressionRAII CondExpr(Info);
4099 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4105 // User's variable declaration, initialized by *__begin.
4106 BlockScopeRAII InnerScope(Info);
4107 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4108 if (ESR != ESR_Succeeded)
4112 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4113 if (ESR != ESR_Continue)
4116 // Increment: ++__begin
4117 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4121 return ESR_Succeeded;
4124 case Stmt::SwitchStmtClass:
4125 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4127 case Stmt::ContinueStmtClass:
4128 return ESR_Continue;
4130 case Stmt::BreakStmtClass:
4133 case Stmt::LabelStmtClass:
4134 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4136 case Stmt::AttributedStmtClass:
4137 // As a general principle, C++11 attributes can be ignored without
4138 // any semantic impact.
4139 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4142 case Stmt::CaseStmtClass:
4143 case Stmt::DefaultStmtClass:
4144 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4148 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4149 /// default constructor. If so, we'll fold it whether or not it's marked as
4150 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4151 /// so we need special handling.
4152 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4153 const CXXConstructorDecl *CD,
4154 bool IsValueInitialization) {
4155 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4158 // Value-initialization does not call a trivial default constructor, so such a
4159 // call is a core constant expression whether or not the constructor is
4161 if (!CD->isConstexpr() && !IsValueInitialization) {
4162 if (Info.getLangOpts().CPlusPlus11) {
4163 // FIXME: If DiagDecl is an implicitly-declared special member function,
4164 // we should be much more explicit about why it's not constexpr.
4165 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4166 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4167 Info.Note(CD->getLocation(), diag::note_declared_at);
4169 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4175 /// CheckConstexprFunction - Check that a function can be called in a constant
4177 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4178 const FunctionDecl *Declaration,
4179 const FunctionDecl *Definition,
4181 // Potential constant expressions can contain calls to declared, but not yet
4182 // defined, constexpr functions.
4183 if (Info.checkingPotentialConstantExpression() && !Definition &&
4184 Declaration->isConstexpr())
4187 // Bail out with no diagnostic if the function declaration itself is invalid.
4188 // We will have produced a relevant diagnostic while parsing it.
4189 if (Declaration->isInvalidDecl())
4192 // Can we evaluate this function call?
4193 if (Definition && Definition->isConstexpr() &&
4194 !Definition->isInvalidDecl() && Body)
4197 if (Info.getLangOpts().CPlusPlus11) {
4198 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4200 // If this function is not constexpr because it is an inherited
4201 // non-constexpr constructor, diagnose that directly.
4202 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4203 if (CD && CD->isInheritingConstructor()) {
4204 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4205 if (!Inherited->isConstexpr())
4206 DiagDecl = CD = Inherited;
4209 // FIXME: If DiagDecl is an implicitly-declared special member function
4210 // or an inheriting constructor, we should be much more explicit about why
4211 // it's not constexpr.
4212 if (CD && CD->isInheritingConstructor())
4213 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4214 << CD->getInheritedConstructor().getConstructor()->getParent();
4216 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4217 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4218 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4220 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4225 /// Determine if a class has any fields that might need to be copied by a
4226 /// trivial copy or move operation.
4227 static bool hasFields(const CXXRecordDecl *RD) {
4228 if (!RD || RD->isEmpty())
4230 for (auto *FD : RD->fields()) {
4231 if (FD->isUnnamedBitfield())
4235 for (auto &Base : RD->bases())
4236 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4242 typedef SmallVector<APValue, 8> ArgVector;
4245 /// EvaluateArgs - Evaluate the arguments to a function call.
4246 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4248 bool Success = true;
4249 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4251 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4252 // If we're checking for a potential constant expression, evaluate all
4253 // initializers even if some of them fail.
4254 if (!Info.noteFailure())
4262 /// Evaluate a function call.
4263 static bool HandleFunctionCall(SourceLocation CallLoc,
4264 const FunctionDecl *Callee, const LValue *This,
4265 ArrayRef<const Expr*> Args, const Stmt *Body,
4266 EvalInfo &Info, APValue &Result,
4267 const LValue *ResultSlot) {
4268 ArgVector ArgValues(Args.size());
4269 if (!EvaluateArgs(Args, ArgValues, Info))
4272 if (!Info.CheckCallLimit(CallLoc))
4275 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4277 // For a trivial copy or move assignment, perform an APValue copy. This is
4278 // essential for unions, where the operations performed by the assignment
4279 // operator cannot be represented as statements.
4281 // Skip this for non-union classes with no fields; in that case, the defaulted
4282 // copy/move does not actually read the object.
4283 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4284 if (MD && MD->isDefaulted() &&
4285 (MD->getParent()->isUnion() ||
4286 (MD->isTrivial() && hasFields(MD->getParent())))) {
4288 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4290 RHS.setFrom(Info.Ctx, ArgValues[0]);
4292 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4295 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4298 This->moveInto(Result);
4300 } else if (MD && isLambdaCallOperator(MD)) {
4301 // We're in a lambda; determine the lambda capture field maps.
4302 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4303 Frame.LambdaThisCaptureField);
4306 StmtResult Ret = {Result, ResultSlot};
4307 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4308 if (ESR == ESR_Succeeded) {
4309 if (Callee->getReturnType()->isVoidType())
4311 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4313 return ESR == ESR_Returned;
4316 /// Evaluate a constructor call.
4317 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4319 const CXXConstructorDecl *Definition,
4320 EvalInfo &Info, APValue &Result) {
4321 SourceLocation CallLoc = E->getExprLoc();
4322 if (!Info.CheckCallLimit(CallLoc))
4325 const CXXRecordDecl *RD = Definition->getParent();
4326 if (RD->getNumVBases()) {
4327 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4331 EvalInfo::EvaluatingConstructorRAII EvalObj(
4332 Info, {This.getLValueBase(), This.CallIndex});
4333 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4335 // FIXME: Creating an APValue just to hold a nonexistent return value is
4338 StmtResult Ret = {RetVal, nullptr};
4340 // If it's a delegating constructor, delegate.
4341 if (Definition->isDelegatingConstructor()) {
4342 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4344 FullExpressionRAII InitScope(Info);
4345 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4348 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4351 // For a trivial copy or move constructor, perform an APValue copy. This is
4352 // essential for unions (or classes with anonymous union members), where the
4353 // operations performed by the constructor cannot be represented by
4354 // ctor-initializers.
4356 // Skip this for empty non-union classes; we should not perform an
4357 // lvalue-to-rvalue conversion on them because their copy constructor does not
4358 // actually read them.
4359 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4360 (Definition->getParent()->isUnion() ||
4361 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4363 RHS.setFrom(Info.Ctx, ArgValues[0]);
4364 return handleLValueToRValueConversion(
4365 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4369 // Reserve space for the struct members.
4370 if (!RD->isUnion() && Result.isUninit())
4371 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4372 std::distance(RD->field_begin(), RD->field_end()));
4374 if (RD->isInvalidDecl()) return false;
4375 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4377 // A scope for temporaries lifetime-extended by reference members.
4378 BlockScopeRAII LifetimeExtendedScope(Info);
4380 bool Success = true;
4381 unsigned BasesSeen = 0;
4383 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4385 for (const auto *I : Definition->inits()) {
4386 LValue Subobject = This;
4387 APValue *Value = &Result;
4389 // Determine the subobject to initialize.
4390 FieldDecl *FD = nullptr;
4391 if (I->isBaseInitializer()) {
4392 QualType BaseType(I->getBaseClass(), 0);
4394 // Non-virtual base classes are initialized in the order in the class
4395 // definition. We have already checked for virtual base classes.
4396 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4397 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4398 "base class initializers not in expected order");
4401 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4402 BaseType->getAsCXXRecordDecl(), &Layout))
4404 Value = &Result.getStructBase(BasesSeen++);
4405 } else if ((FD = I->getMember())) {
4406 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4408 if (RD->isUnion()) {
4409 Result = APValue(FD);
4410 Value = &Result.getUnionValue();
4412 Value = &Result.getStructField(FD->getFieldIndex());
4414 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4415 // Walk the indirect field decl's chain to find the object to initialize,
4416 // and make sure we've initialized every step along it.
4417 for (auto *C : IFD->chain()) {
4418 FD = cast<FieldDecl>(C);
4419 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4420 // Switch the union field if it differs. This happens if we had
4421 // preceding zero-initialization, and we're now initializing a union
4422 // subobject other than the first.
4423 // FIXME: In this case, the values of the other subobjects are
4424 // specified, since zero-initialization sets all padding bits to zero.
4425 if (Value->isUninit() ||
4426 (Value->isUnion() && Value->getUnionField() != FD)) {
4428 *Value = APValue(FD);
4430 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4431 std::distance(CD->field_begin(), CD->field_end()));
4433 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4436 Value = &Value->getUnionValue();
4438 Value = &Value->getStructField(FD->getFieldIndex());
4441 llvm_unreachable("unknown base initializer kind");
4444 FullExpressionRAII InitScope(Info);
4445 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4446 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4448 // If we're checking for a potential constant expression, evaluate all
4449 // initializers even if some of them fail.
4450 if (!Info.noteFailure())
4457 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4460 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4461 ArrayRef<const Expr*> Args,
4462 const CXXConstructorDecl *Definition,
4463 EvalInfo &Info, APValue &Result) {
4464 ArgVector ArgValues(Args.size());
4465 if (!EvaluateArgs(Args, ArgValues, Info))
4468 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4472 //===----------------------------------------------------------------------===//
4473 // Generic Evaluation
4474 //===----------------------------------------------------------------------===//
4477 template <class Derived>
4478 class ExprEvaluatorBase
4479 : public ConstStmtVisitor<Derived, bool> {
4481 Derived &getDerived() { return static_cast<Derived&>(*this); }
4482 bool DerivedSuccess(const APValue &V, const Expr *E) {
4483 return getDerived().Success(V, E);
4485 bool DerivedZeroInitialization(const Expr *E) {
4486 return getDerived().ZeroInitialization(E);
4489 // Check whether a conditional operator with a non-constant condition is a
4490 // potential constant expression. If neither arm is a potential constant
4491 // expression, then the conditional operator is not either.
4492 template<typename ConditionalOperator>
4493 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4494 assert(Info.checkingPotentialConstantExpression());
4496 // Speculatively evaluate both arms.
4497 SmallVector<PartialDiagnosticAt, 8> Diag;
4499 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4500 StmtVisitorTy::Visit(E->getFalseExpr());
4506 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4508 StmtVisitorTy::Visit(E->getTrueExpr());
4513 Error(E, diag::note_constexpr_conditional_never_const);
4517 template<typename ConditionalOperator>
4518 bool HandleConditionalOperator(const ConditionalOperator *E) {
4520 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4521 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4522 CheckPotentialConstantConditional(E);
4525 if (Info.noteFailure()) {
4526 StmtVisitorTy::Visit(E->getTrueExpr());
4527 StmtVisitorTy::Visit(E->getFalseExpr());
4532 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4533 return StmtVisitorTy::Visit(EvalExpr);
4538 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4539 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4541 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4542 return Info.CCEDiag(E, D);
4545 bool ZeroInitialization(const Expr *E) { return Error(E); }
4548 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4550 EvalInfo &getEvalInfo() { return Info; }
4552 /// Report an evaluation error. This should only be called when an error is
4553 /// first discovered. When propagating an error, just return false.
4554 bool Error(const Expr *E, diag::kind D) {
4558 bool Error(const Expr *E) {
4559 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4562 bool VisitStmt(const Stmt *) {
4563 llvm_unreachable("Expression evaluator should not be called on stmts");
4565 bool VisitExpr(const Expr *E) {
4569 bool VisitParenExpr(const ParenExpr *E)
4570 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4571 bool VisitUnaryExtension(const UnaryOperator *E)
4572 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4573 bool VisitUnaryPlus(const UnaryOperator *E)
4574 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4575 bool VisitChooseExpr(const ChooseExpr *E)
4576 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4577 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4578 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4579 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4580 { return StmtVisitorTy::Visit(E->getReplacement()); }
4581 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4582 { return StmtVisitorTy::Visit(E->getExpr()); }
4583 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4584 // The initializer may not have been parsed yet, or might be erroneous.
4587 return StmtVisitorTy::Visit(E->getExpr());
4589 // We cannot create any objects for which cleanups are required, so there is
4590 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4591 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4592 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4594 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4595 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4596 return static_cast<Derived*>(this)->VisitCastExpr(E);
4598 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4599 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4600 return static_cast<Derived*>(this)->VisitCastExpr(E);
4603 bool VisitBinaryOperator(const BinaryOperator *E) {
4604 switch (E->getOpcode()) {
4609 VisitIgnoredValue(E->getLHS());
4610 return StmtVisitorTy::Visit(E->getRHS());
4615 if (!HandleMemberPointerAccess(Info, E, Obj))
4618 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4620 return DerivedSuccess(Result, E);
4625 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4626 // Evaluate and cache the common expression. We treat it as a temporary,
4627 // even though it's not quite the same thing.
4628 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4629 Info, E->getCommon()))
4632 return HandleConditionalOperator(E);
4635 bool VisitConditionalOperator(const ConditionalOperator *E) {
4636 bool IsBcpCall = false;
4637 // If the condition (ignoring parens) is a __builtin_constant_p call,
4638 // the result is a constant expression if it can be folded without
4639 // side-effects. This is an important GNU extension. See GCC PR38377
4641 if (const CallExpr *CallCE =
4642 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4643 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4646 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4647 // constant expression; we can't check whether it's potentially foldable.
4648 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4651 FoldConstant Fold(Info, IsBcpCall);
4652 if (!HandleConditionalOperator(E)) {
4653 Fold.keepDiagnostics();
4660 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4661 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4662 return DerivedSuccess(*Value, E);
4664 const Expr *Source = E->getSourceExpr();
4667 if (Source == E) { // sanity checking.
4668 assert(0 && "OpaqueValueExpr recursively refers to itself");
4671 return StmtVisitorTy::Visit(Source);
4674 bool VisitCallExpr(const CallExpr *E) {
4676 if (!handleCallExpr(E, Result, nullptr))
4678 return DerivedSuccess(Result, E);
4681 bool handleCallExpr(const CallExpr *E, APValue &Result,
4682 const LValue *ResultSlot) {
4683 const Expr *Callee = E->getCallee()->IgnoreParens();
4684 QualType CalleeType = Callee->getType();
4686 const FunctionDecl *FD = nullptr;
4687 LValue *This = nullptr, ThisVal;
4688 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4689 bool HasQualifier = false;
4691 // Extract function decl and 'this' pointer from the callee.
4692 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4693 const ValueDecl *Member = nullptr;
4694 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4695 // Explicit bound member calls, such as x.f() or p->g();
4696 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4698 Member = ME->getMemberDecl();
4700 HasQualifier = ME->hasQualifier();
4701 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4702 // Indirect bound member calls ('.*' or '->*').
4703 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4704 if (!Member) return false;
4707 return Error(Callee);
4709 FD = dyn_cast<FunctionDecl>(Member);
4711 return Error(Callee);
4712 } else if (CalleeType->isFunctionPointerType()) {
4714 if (!EvaluatePointer(Callee, Call, Info))
4717 if (!Call.getLValueOffset().isZero())
4718 return Error(Callee);
4719 FD = dyn_cast_or_null<FunctionDecl>(
4720 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4722 return Error(Callee);
4723 // Don't call function pointers which have been cast to some other type.
4724 // Per DR (no number yet), the caller and callee can differ in noexcept.
4725 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4726 CalleeType->getPointeeType(), FD->getType())) {
4730 // Overloaded operator calls to member functions are represented as normal
4731 // calls with '*this' as the first argument.
4732 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4733 if (MD && !MD->isStatic()) {
4734 // FIXME: When selecting an implicit conversion for an overloaded
4735 // operator delete, we sometimes try to evaluate calls to conversion
4736 // operators without a 'this' parameter!
4740 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4743 Args = Args.slice(1);
4744 } else if (MD && MD->isLambdaStaticInvoker()) {
4745 // Map the static invoker for the lambda back to the call operator.
4746 // Conveniently, we don't have to slice out the 'this' argument (as is
4747 // being done for the non-static case), since a static member function
4748 // doesn't have an implicit argument passed in.
4749 const CXXRecordDecl *ClosureClass = MD->getParent();
4751 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4752 "Number of captures must be zero for conversion to function-ptr");
4754 const CXXMethodDecl *LambdaCallOp =
4755 ClosureClass->getLambdaCallOperator();
4757 // Set 'FD', the function that will be called below, to the call
4758 // operator. If the closure object represents a generic lambda, find
4759 // the corresponding specialization of the call operator.
4761 if (ClosureClass->isGenericLambda()) {
4762 assert(MD->isFunctionTemplateSpecialization() &&
4763 "A generic lambda's static-invoker function must be a "
4764 "template specialization");
4765 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4766 FunctionTemplateDecl *CallOpTemplate =
4767 LambdaCallOp->getDescribedFunctionTemplate();
4768 void *InsertPos = nullptr;
4769 FunctionDecl *CorrespondingCallOpSpecialization =
4770 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4771 assert(CorrespondingCallOpSpecialization &&
4772 "We must always have a function call operator specialization "
4773 "that corresponds to our static invoker specialization");
4774 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4783 if (This && !This->checkSubobject(Info, E, CSK_This))
4786 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4787 // calls to such functions in constant expressions.
4788 if (This && !HasQualifier &&
4789 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4790 return Error(E, diag::note_constexpr_virtual_call);
4792 const FunctionDecl *Definition = nullptr;
4793 Stmt *Body = FD->getBody(Definition);
4795 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4796 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4797 Result, ResultSlot))
4803 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4804 return StmtVisitorTy::Visit(E->getInitializer());
4806 bool VisitInitListExpr(const InitListExpr *E) {
4807 if (E->getNumInits() == 0)
4808 return DerivedZeroInitialization(E);
4809 if (E->getNumInits() == 1)
4810 return StmtVisitorTy::Visit(E->getInit(0));
4813 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4814 return DerivedZeroInitialization(E);
4816 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4817 return DerivedZeroInitialization(E);
4819 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4820 return DerivedZeroInitialization(E);
4823 /// A member expression where the object is a prvalue is itself a prvalue.
4824 bool VisitMemberExpr(const MemberExpr *E) {
4825 assert(!E->isArrow() && "missing call to bound member function?");
4828 if (!Evaluate(Val, Info, E->getBase()))
4831 QualType BaseTy = E->getBase()->getType();
4833 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4834 if (!FD) return Error(E);
4835 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4836 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4837 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4839 CompleteObject Obj(&Val, BaseTy);
4840 SubobjectDesignator Designator(BaseTy);
4841 Designator.addDeclUnchecked(FD);
4844 return extractSubobject(Info, E, Obj, Designator, Result) &&
4845 DerivedSuccess(Result, E);
4848 bool VisitCastExpr(const CastExpr *E) {
4849 switch (E->getCastKind()) {
4853 case CK_AtomicToNonAtomic: {
4855 // This does not need to be done in place even for class/array types:
4856 // atomic-to-non-atomic conversion implies copying the object
4858 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4860 return DerivedSuccess(AtomicVal, E);
4864 case CK_UserDefinedConversion:
4865 return StmtVisitorTy::Visit(E->getSubExpr());
4867 case CK_LValueToRValue: {
4869 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4872 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4873 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4876 return DerivedSuccess(RVal, E);
4883 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4884 return VisitUnaryPostIncDec(UO);
4886 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4887 return VisitUnaryPostIncDec(UO);
4889 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4890 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4894 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4897 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4898 UO->isIncrementOp(), &RVal))
4900 return DerivedSuccess(RVal, UO);
4903 bool VisitStmtExpr(const StmtExpr *E) {
4904 // We will have checked the full-expressions inside the statement expression
4905 // when they were completed, and don't need to check them again now.
4906 if (Info.checkingForOverflow())
4909 BlockScopeRAII Scope(Info);
4910 const CompoundStmt *CS = E->getSubStmt();
4911 if (CS->body_empty())
4914 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4915 BE = CS->body_end();
4918 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4920 Info.FFDiag((*BI)->getLocStart(),
4921 diag::note_constexpr_stmt_expr_unsupported);
4924 return this->Visit(FinalExpr);
4927 APValue ReturnValue;
4928 StmtResult Result = { ReturnValue, nullptr };
4929 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4930 if (ESR != ESR_Succeeded) {
4931 // FIXME: If the statement-expression terminated due to 'return',
4932 // 'break', or 'continue', it would be nice to propagate that to
4933 // the outer statement evaluation rather than bailing out.
4934 if (ESR != ESR_Failed)
4935 Info.FFDiag((*BI)->getLocStart(),
4936 diag::note_constexpr_stmt_expr_unsupported);
4941 llvm_unreachable("Return from function from the loop above.");
4944 /// Visit a value which is evaluated, but whose value is ignored.
4945 void VisitIgnoredValue(const Expr *E) {
4946 EvaluateIgnoredValue(Info, E);
4949 /// Potentially visit a MemberExpr's base expression.
4950 void VisitIgnoredBaseExpression(const Expr *E) {
4951 // While MSVC doesn't evaluate the base expression, it does diagnose the
4952 // presence of side-effecting behavior.
4953 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4955 VisitIgnoredValue(E);
4961 //===----------------------------------------------------------------------===//
4962 // Common base class for lvalue and temporary evaluation.
4963 //===----------------------------------------------------------------------===//
4965 template<class Derived>
4966 class LValueExprEvaluatorBase
4967 : public ExprEvaluatorBase<Derived> {
4971 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4972 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4974 bool Success(APValue::LValueBase B) {
4979 bool evaluatePointer(const Expr *E, LValue &Result) {
4980 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4984 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4985 : ExprEvaluatorBaseTy(Info), Result(Result),
4986 InvalidBaseOK(InvalidBaseOK) {}
4988 bool Success(const APValue &V, const Expr *E) {
4989 Result.setFrom(this->Info.Ctx, V);
4993 bool VisitMemberExpr(const MemberExpr *E) {
4994 // Handle non-static data members.
4998 EvalOK = evaluatePointer(E->getBase(), Result);
4999 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5000 } else if (E->getBase()->isRValue()) {
5001 assert(E->getBase()->getType()->isRecordType());
5002 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5003 BaseTy = E->getBase()->getType();
5005 EvalOK = this->Visit(E->getBase());
5006 BaseTy = E->getBase()->getType();
5011 Result.setInvalid(E);
5015 const ValueDecl *MD = E->getMemberDecl();
5016 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5017 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5018 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5020 if (!HandleLValueMember(this->Info, E, Result, FD))
5022 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5023 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5026 return this->Error(E);
5028 if (MD->getType()->isReferenceType()) {
5030 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5033 return Success(RefValue, E);
5038 bool VisitBinaryOperator(const BinaryOperator *E) {
5039 switch (E->getOpcode()) {
5041 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5045 return HandleMemberPointerAccess(this->Info, E, Result);
5049 bool VisitCastExpr(const CastExpr *E) {
5050 switch (E->getCastKind()) {
5052 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5054 case CK_DerivedToBase:
5055 case CK_UncheckedDerivedToBase:
5056 if (!this->Visit(E->getSubExpr()))
5059 // Now figure out the necessary offset to add to the base LV to get from
5060 // the derived class to the base class.
5061 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5068 //===----------------------------------------------------------------------===//
5069 // LValue Evaluation
5071 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5072 // function designators (in C), decl references to void objects (in C), and
5073 // temporaries (if building with -Wno-address-of-temporary).
5075 // LValue evaluation produces values comprising a base expression of one of the
5081 // * CompoundLiteralExpr in C (and in global scope in C++)
5085 // * ObjCStringLiteralExpr
5089 // * CallExpr for a MakeStringConstant builtin
5090 // - Locals and temporaries
5091 // * MaterializeTemporaryExpr
5092 // * Any Expr, with a CallIndex indicating the function in which the temporary
5093 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5094 // from the AST (FIXME).
5095 // * A MaterializeTemporaryExpr that has static storage duration, with no
5096 // CallIndex, for a lifetime-extended temporary.
5097 // plus an offset in bytes.
5098 //===----------------------------------------------------------------------===//
5100 class LValueExprEvaluator
5101 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5103 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5104 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5106 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5107 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5109 bool VisitDeclRefExpr(const DeclRefExpr *E);
5110 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5111 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5112 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5113 bool VisitMemberExpr(const MemberExpr *E);
5114 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5115 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5116 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5117 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5118 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5119 bool VisitUnaryDeref(const UnaryOperator *E);
5120 bool VisitUnaryReal(const UnaryOperator *E);
5121 bool VisitUnaryImag(const UnaryOperator *E);
5122 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5123 return VisitUnaryPreIncDec(UO);
5125 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5126 return VisitUnaryPreIncDec(UO);
5128 bool VisitBinAssign(const BinaryOperator *BO);
5129 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5131 bool VisitCastExpr(const CastExpr *E) {
5132 switch (E->getCastKind()) {
5134 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5136 case CK_LValueBitCast:
5137 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5138 if (!Visit(E->getSubExpr()))
5140 Result.Designator.setInvalid();
5143 case CK_BaseToDerived:
5144 if (!Visit(E->getSubExpr()))
5146 return HandleBaseToDerivedCast(Info, E, Result);
5150 } // end anonymous namespace
5152 /// Evaluate an expression as an lvalue. This can be legitimately called on
5153 /// expressions which are not glvalues, in three cases:
5154 /// * function designators in C, and
5155 /// * "extern void" objects
5156 /// * @selector() expressions in Objective-C
5157 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5158 bool InvalidBaseOK) {
5159 assert(E->isGLValue() || E->getType()->isFunctionType() ||
5160 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5161 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5164 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5165 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5167 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5168 return VisitVarDecl(E, VD);
5169 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5170 return Visit(BD->getBinding());
5175 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5177 // If we are within a lambda's call operator, check whether the 'VD' referred
5178 // to within 'E' actually represents a lambda-capture that maps to a
5179 // data-member/field within the closure object, and if so, evaluate to the
5180 // field or what the field refers to.
5181 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5182 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5183 if (Info.checkingPotentialConstantExpression())
5185 // Start with 'Result' referring to the complete closure object...
5186 Result = *Info.CurrentCall->This;
5187 // ... then update it to refer to the field of the closure object
5188 // that represents the capture.
5189 if (!HandleLValueMember(Info, E, Result, FD))
5191 // And if the field is of reference type, update 'Result' to refer to what
5192 // the field refers to.
5193 if (FD->getType()->isReferenceType()) {
5195 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5198 Result.setFrom(Info.Ctx, RVal);
5203 CallStackFrame *Frame = nullptr;
5204 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5205 // Only if a local variable was declared in the function currently being
5206 // evaluated, do we expect to be able to find its value in the current
5207 // frame. (Otherwise it was likely declared in an enclosing context and
5208 // could either have a valid evaluatable value (for e.g. a constexpr
5209 // variable) or be ill-formed (and trigger an appropriate evaluation
5211 if (Info.CurrentCall->Callee &&
5212 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5213 Frame = Info.CurrentCall;
5217 if (!VD->getType()->isReferenceType()) {
5219 Result.set(VD, Frame->Index);
5226 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5228 if (V->isUninit()) {
5229 if (!Info.checkingPotentialConstantExpression())
5230 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5233 return Success(*V, E);
5236 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5237 const MaterializeTemporaryExpr *E) {
5238 // Walk through the expression to find the materialized temporary itself.
5239 SmallVector<const Expr *, 2> CommaLHSs;
5240 SmallVector<SubobjectAdjustment, 2> Adjustments;
5241 const Expr *Inner = E->GetTemporaryExpr()->
5242 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5244 // If we passed any comma operators, evaluate their LHSs.
5245 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5246 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5249 // A materialized temporary with static storage duration can appear within the
5250 // result of a constant expression evaluation, so we need to preserve its
5251 // value for use outside this evaluation.
5253 if (E->getStorageDuration() == SD_Static) {
5254 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5258 Value = &Info.CurrentCall->
5259 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5260 Result.set(E, Info.CurrentCall->Index);
5263 QualType Type = Inner->getType();
5265 // Materialize the temporary itself.
5266 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5267 (E->getStorageDuration() == SD_Static &&
5268 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5273 // Adjust our lvalue to refer to the desired subobject.
5274 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5276 switch (Adjustments[I].Kind) {
5277 case SubobjectAdjustment::DerivedToBaseAdjustment:
5278 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5281 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5284 case SubobjectAdjustment::FieldAdjustment:
5285 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5287 Type = Adjustments[I].Field->getType();
5290 case SubobjectAdjustment::MemberPointerAdjustment:
5291 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5292 Adjustments[I].Ptr.RHS))
5294 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5303 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5304 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5305 "lvalue compound literal in c++?");
5306 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5307 // only see this when folding in C, so there's no standard to follow here.
5311 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5312 if (!E->isPotentiallyEvaluated())
5315 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5316 << E->getExprOperand()->getType()
5317 << E->getExprOperand()->getSourceRange();
5321 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5325 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5326 // Handle static data members.
5327 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5328 VisitIgnoredBaseExpression(E->getBase());
5329 return VisitVarDecl(E, VD);
5332 // Handle static member functions.
5333 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5334 if (MD->isStatic()) {
5335 VisitIgnoredBaseExpression(E->getBase());
5340 // Handle non-static data members.
5341 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5344 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5345 // FIXME: Deal with vectors as array subscript bases.
5346 if (E->getBase()->getType()->isVectorType())
5349 bool Success = true;
5350 if (!evaluatePointer(E->getBase(), Result)) {
5351 if (!Info.noteFailure())
5357 if (!EvaluateInteger(E->getIdx(), Index, Info))
5361 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5364 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5365 return evaluatePointer(E->getSubExpr(), Result);
5368 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5369 if (!Visit(E->getSubExpr()))
5371 // __real is a no-op on scalar lvalues.
5372 if (E->getSubExpr()->getType()->isAnyComplexType())
5373 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5377 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5378 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5379 "lvalue __imag__ on scalar?");
5380 if (!Visit(E->getSubExpr()))
5382 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5386 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5387 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5390 if (!this->Visit(UO->getSubExpr()))
5393 return handleIncDec(
5394 this->Info, UO, Result, UO->getSubExpr()->getType(),
5395 UO->isIncrementOp(), nullptr);
5398 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5399 const CompoundAssignOperator *CAO) {
5400 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5405 // The overall lvalue result is the result of evaluating the LHS.
5406 if (!this->Visit(CAO->getLHS())) {
5407 if (Info.noteFailure())
5408 Evaluate(RHS, this->Info, CAO->getRHS());
5412 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5415 return handleCompoundAssignment(
5417 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5418 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5421 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5422 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5427 if (!this->Visit(E->getLHS())) {
5428 if (Info.noteFailure())
5429 Evaluate(NewVal, this->Info, E->getRHS());
5433 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5436 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5440 //===----------------------------------------------------------------------===//
5441 // Pointer Evaluation
5442 //===----------------------------------------------------------------------===//
5444 /// \brief Attempts to compute the number of bytes available at the pointer
5445 /// returned by a function with the alloc_size attribute. Returns true if we
5446 /// were successful. Places an unsigned number into `Result`.
5448 /// This expects the given CallExpr to be a call to a function with an
5449 /// alloc_size attribute.
5450 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5451 const CallExpr *Call,
5452 llvm::APInt &Result) {
5453 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5455 // alloc_size args are 1-indexed, 0 means not present.
5456 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5457 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5458 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5459 if (Call->getNumArgs() <= SizeArgNo)
5462 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5463 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5465 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5467 Into = Into.zextOrSelf(BitsInSizeT);
5472 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5475 if (!AllocSize->getNumElemsParam()) {
5476 Result = std::move(SizeOfElem);
5480 APSInt NumberOfElems;
5481 // Argument numbers start at 1
5482 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5483 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5487 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5491 Result = std::move(BytesAvailable);
5495 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5497 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5499 llvm::APInt &Result) {
5500 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5501 "Can't get the size of a non alloc_size function");
5502 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5503 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5504 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5507 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5508 /// a function with the alloc_size attribute. If it was possible to do so, this
5509 /// function will return true, make Result's Base point to said function call,
5510 /// and mark Result's Base as invalid.
5511 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5516 // Because we do no form of static analysis, we only support const variables.
5518 // Additionally, we can't support parameters, nor can we support static
5519 // variables (in the latter case, use-before-assign isn't UB; in the former,
5520 // we have no clue what they'll be assigned to).
5522 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5523 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5526 const Expr *Init = VD->getAnyInitializer();
5530 const Expr *E = Init->IgnoreParens();
5531 if (!tryUnwrapAllocSizeCall(E))
5534 // Store E instead of E unwrapped so that the type of the LValue's base is
5535 // what the user wanted.
5536 Result.setInvalid(E);
5538 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5539 Result.addUnsizedArray(Info, E, Pointee);
5544 class PointerExprEvaluator
5545 : public ExprEvaluatorBase<PointerExprEvaluator> {
5549 bool Success(const Expr *E) {
5554 bool evaluateLValue(const Expr *E, LValue &Result) {
5555 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5558 bool evaluatePointer(const Expr *E, LValue &Result) {
5559 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5562 bool visitNonBuiltinCallExpr(const CallExpr *E);
5565 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5566 : ExprEvaluatorBaseTy(info), Result(Result),
5567 InvalidBaseOK(InvalidBaseOK) {}
5569 bool Success(const APValue &V, const Expr *E) {
5570 Result.setFrom(Info.Ctx, V);
5573 bool ZeroInitialization(const Expr *E) {
5574 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5575 Result.setNull(E->getType(), TargetVal);
5579 bool VisitBinaryOperator(const BinaryOperator *E);
5580 bool VisitCastExpr(const CastExpr* E);
5581 bool VisitUnaryAddrOf(const UnaryOperator *E);
5582 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5583 { return Success(E); }
5584 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5585 if (Info.noteFailure())
5586 EvaluateIgnoredValue(Info, E->getSubExpr());
5589 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5590 { return Success(E); }
5591 bool VisitCallExpr(const CallExpr *E);
5592 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5593 bool VisitBlockExpr(const BlockExpr *E) {
5594 if (!E->getBlockDecl()->hasCaptures())
5598 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5599 // Can't look at 'this' when checking a potential constant expression.
5600 if (Info.checkingPotentialConstantExpression())
5602 if (!Info.CurrentCall->This) {
5603 if (Info.getLangOpts().CPlusPlus11)
5604 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5609 Result = *Info.CurrentCall->This;
5610 // If we are inside a lambda's call operator, the 'this' expression refers
5611 // to the enclosing '*this' object (either by value or reference) which is
5612 // either copied into the closure object's field that represents the '*this'
5613 // or refers to '*this'.
5614 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5615 // Update 'Result' to refer to the data member/field of the closure object
5616 // that represents the '*this' capture.
5617 if (!HandleLValueMember(Info, E, Result,
5618 Info.CurrentCall->LambdaThisCaptureField))
5620 // If we captured '*this' by reference, replace the field with its referent.
5621 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5622 ->isPointerType()) {
5624 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5628 Result.setFrom(Info.Ctx, RVal);
5634 // FIXME: Missing: @protocol, @selector
5636 } // end anonymous namespace
5638 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5639 bool InvalidBaseOK) {
5640 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5641 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5644 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5645 if (E->getOpcode() != BO_Add &&
5646 E->getOpcode() != BO_Sub)
5647 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5649 const Expr *PExp = E->getLHS();
5650 const Expr *IExp = E->getRHS();
5651 if (IExp->getType()->isPointerType())
5652 std::swap(PExp, IExp);
5654 bool EvalPtrOK = evaluatePointer(PExp, Result);
5655 if (!EvalPtrOK && !Info.noteFailure())
5658 llvm::APSInt Offset;
5659 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5662 if (E->getOpcode() == BO_Sub)
5663 negateAsSigned(Offset);
5665 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5666 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5669 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5670 return evaluateLValue(E->getSubExpr(), Result);
5673 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5674 const Expr* SubExpr = E->getSubExpr();
5676 switch (E->getCastKind()) {
5681 case CK_CPointerToObjCPointerCast:
5682 case CK_BlockPointerToObjCPointerCast:
5683 case CK_AnyPointerToBlockPointerCast:
5684 case CK_AddressSpaceConversion:
5685 if (!Visit(SubExpr))
5687 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5688 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5689 // also static_casts, but we disallow them as a resolution to DR1312.
5690 if (!E->getType()->isVoidPointerType()) {
5691 Result.Designator.setInvalid();
5692 if (SubExpr->getType()->isVoidPointerType())
5693 CCEDiag(E, diag::note_constexpr_invalid_cast)
5694 << 3 << SubExpr->getType();
5696 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5698 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5699 ZeroInitialization(E);
5702 case CK_DerivedToBase:
5703 case CK_UncheckedDerivedToBase:
5704 if (!evaluatePointer(E->getSubExpr(), Result))
5706 if (!Result.Base && Result.Offset.isZero())
5709 // Now figure out the necessary offset to add to the base LV to get from
5710 // the derived class to the base class.
5711 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5712 castAs<PointerType>()->getPointeeType(),
5715 case CK_BaseToDerived:
5716 if (!Visit(E->getSubExpr()))
5718 if (!Result.Base && Result.Offset.isZero())
5720 return HandleBaseToDerivedCast(Info, E, Result);
5722 case CK_NullToPointer:
5723 VisitIgnoredValue(E->getSubExpr());
5724 return ZeroInitialization(E);
5726 case CK_IntegralToPointer: {
5727 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5730 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5733 if (Value.isInt()) {
5734 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5735 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5736 Result.Base = (Expr*)nullptr;
5737 Result.InvalidBase = false;
5738 Result.Offset = CharUnits::fromQuantity(N);
5739 Result.CallIndex = 0;
5740 Result.Designator.setInvalid();
5741 Result.IsNullPtr = false;
5744 // Cast is of an lvalue, no need to change value.
5745 Result.setFrom(Info.Ctx, Value);
5750 case CK_ArrayToPointerDecay: {
5751 if (SubExpr->isGLValue()) {
5752 if (!evaluateLValue(SubExpr, Result))
5755 Result.set(SubExpr, Info.CurrentCall->Index);
5756 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5757 Info, Result, SubExpr))
5760 // The result is a pointer to the first element of the array.
5761 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5762 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5763 Result.addArray(Info, E, CAT);
5765 Result.addUnsizedArray(Info, E, AT->getElementType());
5769 case CK_FunctionToPointerDecay:
5770 return evaluateLValue(SubExpr, Result);
5772 case CK_LValueToRValue: {
5774 if (!evaluateLValue(E->getSubExpr(), LVal))
5778 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5779 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5781 return InvalidBaseOK &&
5782 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5783 return Success(RVal, E);
5787 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5790 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5791 // C++ [expr.alignof]p3:
5792 // When alignof is applied to a reference type, the result is the
5793 // alignment of the referenced type.
5794 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5795 T = Ref->getPointeeType();
5797 // __alignof is defined to return the preferred alignment.
5798 if (T.getQualifiers().hasUnaligned())
5799 return CharUnits::One();
5800 return Info.Ctx.toCharUnitsFromBits(
5801 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5804 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5805 E = E->IgnoreParens();
5807 // The kinds of expressions that we have special-case logic here for
5808 // should be kept up to date with the special checks for those
5809 // expressions in Sema.
5811 // alignof decl is always accepted, even if it doesn't make sense: we default
5812 // to 1 in those cases.
5813 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5814 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5815 /*RefAsPointee*/true);
5817 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5818 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5819 /*RefAsPointee*/true);
5821 return GetAlignOfType(Info, E->getType());
5824 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5825 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5826 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5829 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5832 Result.setInvalid(E);
5833 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5834 Result.addUnsizedArray(Info, E, PointeeTy);
5838 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5839 if (IsStringLiteralCall(E))
5842 if (unsigned BuiltinOp = E->getBuiltinCallee())
5843 return VisitBuiltinCallExpr(E, BuiltinOp);
5845 return visitNonBuiltinCallExpr(E);
5848 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5849 unsigned BuiltinOp) {
5850 switch (BuiltinOp) {
5851 case Builtin::BI__builtin_addressof:
5852 return evaluateLValue(E->getArg(0), Result);
5853 case Builtin::BI__builtin_assume_aligned: {
5854 // We need to be very careful here because: if the pointer does not have the
5855 // asserted alignment, then the behavior is undefined, and undefined
5856 // behavior is non-constant.
5857 if (!evaluatePointer(E->getArg(0), Result))
5860 LValue OffsetResult(Result);
5862 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5864 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5866 if (E->getNumArgs() > 2) {
5868 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5871 int64_t AdditionalOffset = -Offset.getZExtValue();
5872 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5875 // If there is a base object, then it must have the correct alignment.
5876 if (OffsetResult.Base) {
5877 CharUnits BaseAlignment;
5878 if (const ValueDecl *VD =
5879 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5880 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5883 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5886 if (BaseAlignment < Align) {
5887 Result.Designator.setInvalid();
5888 // FIXME: Add support to Diagnostic for long / long long.
5889 CCEDiag(E->getArg(0),
5890 diag::note_constexpr_baa_insufficient_alignment) << 0
5891 << (unsigned)BaseAlignment.getQuantity()
5892 << (unsigned)Align.getQuantity();
5897 // The offset must also have the correct alignment.
5898 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5899 Result.Designator.setInvalid();
5902 ? CCEDiag(E->getArg(0),
5903 diag::note_constexpr_baa_insufficient_alignment) << 1
5904 : CCEDiag(E->getArg(0),
5905 diag::note_constexpr_baa_value_insufficient_alignment))
5906 << (int)OffsetResult.Offset.getQuantity()
5907 << (unsigned)Align.getQuantity();
5914 case Builtin::BIstrchr:
5915 case Builtin::BIwcschr:
5916 case Builtin::BImemchr:
5917 case Builtin::BIwmemchr:
5918 if (Info.getLangOpts().CPlusPlus11)
5919 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5920 << /*isConstexpr*/0 << /*isConstructor*/0
5921 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5923 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5925 case Builtin::BI__builtin_strchr:
5926 case Builtin::BI__builtin_wcschr:
5927 case Builtin::BI__builtin_memchr:
5928 case Builtin::BI__builtin_char_memchr:
5929 case Builtin::BI__builtin_wmemchr: {
5930 if (!Visit(E->getArg(0)))
5933 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5935 uint64_t MaxLength = uint64_t(-1);
5936 if (BuiltinOp != Builtin::BIstrchr &&
5937 BuiltinOp != Builtin::BIwcschr &&
5938 BuiltinOp != Builtin::BI__builtin_strchr &&
5939 BuiltinOp != Builtin::BI__builtin_wcschr) {
5941 if (!EvaluateInteger(E->getArg(2), N, Info))
5943 MaxLength = N.getExtValue();
5946 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5948 // Figure out what value we're actually looking for (after converting to
5949 // the corresponding unsigned type if necessary).
5950 uint64_t DesiredVal;
5951 bool StopAtNull = false;
5952 switch (BuiltinOp) {
5953 case Builtin::BIstrchr:
5954 case Builtin::BI__builtin_strchr:
5955 // strchr compares directly to the passed integer, and therefore
5956 // always fails if given an int that is not a char.
5957 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5958 E->getArg(1)->getType(),
5961 return ZeroInitialization(E);
5964 case Builtin::BImemchr:
5965 case Builtin::BI__builtin_memchr:
5966 case Builtin::BI__builtin_char_memchr:
5967 // memchr compares by converting both sides to unsigned char. That's also
5968 // correct for strchr if we get this far (to cope with plain char being
5969 // unsigned in the strchr case).
5970 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5973 case Builtin::BIwcschr:
5974 case Builtin::BI__builtin_wcschr:
5977 case Builtin::BIwmemchr:
5978 case Builtin::BI__builtin_wmemchr:
5979 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5980 DesiredVal = Desired.getZExtValue();
5984 for (; MaxLength; --MaxLength) {
5986 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5989 if (Char.getInt().getZExtValue() == DesiredVal)
5991 if (StopAtNull && !Char.getInt())
5993 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5996 // Not found: return nullptr.
5997 return ZeroInitialization(E);
6001 return visitNonBuiltinCallExpr(E);
6005 //===----------------------------------------------------------------------===//
6006 // Member Pointer Evaluation
6007 //===----------------------------------------------------------------------===//
6010 class MemberPointerExprEvaluator
6011 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6014 bool Success(const ValueDecl *D) {
6015 Result = MemberPtr(D);
6020 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6021 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6023 bool Success(const APValue &V, const Expr *E) {
6027 bool ZeroInitialization(const Expr *E) {
6028 return Success((const ValueDecl*)nullptr);
6031 bool VisitCastExpr(const CastExpr *E);
6032 bool VisitUnaryAddrOf(const UnaryOperator *E);
6034 } // end anonymous namespace
6036 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6038 assert(E->isRValue() && E->getType()->isMemberPointerType());
6039 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6042 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6043 switch (E->getCastKind()) {
6045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6047 case CK_NullToMemberPointer:
6048 VisitIgnoredValue(E->getSubExpr());
6049 return ZeroInitialization(E);
6051 case CK_BaseToDerivedMemberPointer: {
6052 if (!Visit(E->getSubExpr()))
6054 if (E->path_empty())
6056 // Base-to-derived member pointer casts store the path in derived-to-base
6057 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6058 // the wrong end of the derived->base arc, so stagger the path by one class.
6059 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6060 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6061 PathI != PathE; ++PathI) {
6062 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6063 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6064 if (!Result.castToDerived(Derived))
6067 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6068 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6073 case CK_DerivedToBaseMemberPointer:
6074 if (!Visit(E->getSubExpr()))
6076 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6077 PathE = E->path_end(); PathI != PathE; ++PathI) {
6078 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6079 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6080 if (!Result.castToBase(Base))
6087 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6088 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6089 // member can be formed.
6090 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6093 //===----------------------------------------------------------------------===//
6094 // Record Evaluation
6095 //===----------------------------------------------------------------------===//
6098 class RecordExprEvaluator
6099 : public ExprEvaluatorBase<RecordExprEvaluator> {
6104 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6105 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6107 bool Success(const APValue &V, const Expr *E) {
6111 bool ZeroInitialization(const Expr *E) {
6112 return ZeroInitialization(E, E->getType());
6114 bool ZeroInitialization(const Expr *E, QualType T);
6116 bool VisitCallExpr(const CallExpr *E) {
6117 return handleCallExpr(E, Result, &This);
6119 bool VisitCastExpr(const CastExpr *E);
6120 bool VisitInitListExpr(const InitListExpr *E);
6121 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6122 return VisitCXXConstructExpr(E, E->getType());
6124 bool VisitLambdaExpr(const LambdaExpr *E);
6125 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6126 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6127 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6131 /// Perform zero-initialization on an object of non-union class type.
6132 /// C++11 [dcl.init]p5:
6133 /// To zero-initialize an object or reference of type T means:
6135 /// -- if T is a (possibly cv-qualified) non-union class type,
6136 /// each non-static data member and each base-class subobject is
6137 /// zero-initialized
6138 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6139 const RecordDecl *RD,
6140 const LValue &This, APValue &Result) {
6141 assert(!RD->isUnion() && "Expected non-union class type");
6142 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6143 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6144 std::distance(RD->field_begin(), RD->field_end()));
6146 if (RD->isInvalidDecl()) return false;
6147 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6151 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6152 End = CD->bases_end(); I != End; ++I, ++Index) {
6153 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6154 LValue Subobject = This;
6155 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6157 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6158 Result.getStructBase(Index)))
6163 for (const auto *I : RD->fields()) {
6164 // -- if T is a reference type, no initialization is performed.
6165 if (I->getType()->isReferenceType())
6168 LValue Subobject = This;
6169 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6172 ImplicitValueInitExpr VIE(I->getType());
6173 if (!EvaluateInPlace(
6174 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6181 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6182 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6183 if (RD->isInvalidDecl()) return false;
6184 if (RD->isUnion()) {
6185 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6186 // object's first non-static named data member is zero-initialized
6187 RecordDecl::field_iterator I = RD->field_begin();
6188 if (I == RD->field_end()) {
6189 Result = APValue((const FieldDecl*)nullptr);
6193 LValue Subobject = This;
6194 if (!HandleLValueMember(Info, E, Subobject, *I))
6196 Result = APValue(*I);
6197 ImplicitValueInitExpr VIE(I->getType());
6198 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6201 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6202 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6206 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6209 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6210 switch (E->getCastKind()) {
6212 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6214 case CK_ConstructorConversion:
6215 return Visit(E->getSubExpr());
6217 case CK_DerivedToBase:
6218 case CK_UncheckedDerivedToBase: {
6219 APValue DerivedObject;
6220 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6222 if (!DerivedObject.isStruct())
6223 return Error(E->getSubExpr());
6225 // Derived-to-base rvalue conversion: just slice off the derived part.
6226 APValue *Value = &DerivedObject;
6227 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6228 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6229 PathE = E->path_end(); PathI != PathE; ++PathI) {
6230 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6231 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6232 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6241 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6242 if (E->isTransparent())
6243 return Visit(E->getInit(0));
6245 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6246 if (RD->isInvalidDecl()) return false;
6247 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6249 if (RD->isUnion()) {
6250 const FieldDecl *Field = E->getInitializedFieldInUnion();
6251 Result = APValue(Field);
6255 // If the initializer list for a union does not contain any elements, the
6256 // first element of the union is value-initialized.
6257 // FIXME: The element should be initialized from an initializer list.
6258 // Is this difference ever observable for initializer lists which
6260 ImplicitValueInitExpr VIE(Field->getType());
6261 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6263 LValue Subobject = This;
6264 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6267 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6268 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6269 isa<CXXDefaultInitExpr>(InitExpr));
6271 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6274 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6275 if (Result.isUninit())
6276 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6277 std::distance(RD->field_begin(), RD->field_end()));
6278 unsigned ElementNo = 0;
6279 bool Success = true;
6281 // Initialize base classes.
6283 for (const auto &Base : CXXRD->bases()) {
6284 assert(ElementNo < E->getNumInits() && "missing init for base class");
6285 const Expr *Init = E->getInit(ElementNo);
6287 LValue Subobject = This;
6288 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6291 APValue &FieldVal = Result.getStructBase(ElementNo);
6292 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6293 if (!Info.noteFailure())
6301 // Initialize members.
6302 for (const auto *Field : RD->fields()) {
6303 // Anonymous bit-fields are not considered members of the class for
6304 // purposes of aggregate initialization.
6305 if (Field->isUnnamedBitfield())
6308 LValue Subobject = This;
6310 bool HaveInit = ElementNo < E->getNumInits();
6312 // FIXME: Diagnostics here should point to the end of the initializer
6313 // list, not the start.
6314 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6315 Subobject, Field, &Layout))
6318 // Perform an implicit value-initialization for members beyond the end of
6319 // the initializer list.
6320 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6321 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6323 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6324 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6325 isa<CXXDefaultInitExpr>(Init));
6327 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6328 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6329 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6330 FieldVal, Field))) {
6331 if (!Info.noteFailure())
6340 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6342 // Note that E's type is not necessarily the type of our class here; we might
6343 // be initializing an array element instead.
6344 const CXXConstructorDecl *FD = E->getConstructor();
6345 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6347 bool ZeroInit = E->requiresZeroInitialization();
6348 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6349 // If we've already performed zero-initialization, we're already done.
6350 if (!Result.isUninit())
6353 // We can get here in two different ways:
6354 // 1) We're performing value-initialization, and should zero-initialize
6356 // 2) We're performing default-initialization of an object with a trivial
6357 // constexpr default constructor, in which case we should start the
6358 // lifetimes of all the base subobjects (there can be no data member
6359 // subobjects in this case) per [basic.life]p1.
6360 // Either way, ZeroInitialization is appropriate.
6361 return ZeroInitialization(E, T);
6364 const FunctionDecl *Definition = nullptr;
6365 auto Body = FD->getBody(Definition);
6367 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6370 // Avoid materializing a temporary for an elidable copy/move constructor.
6371 if (E->isElidable() && !ZeroInit)
6372 if (const MaterializeTemporaryExpr *ME
6373 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6374 return Visit(ME->GetTemporaryExpr());
6376 if (ZeroInit && !ZeroInitialization(E, T))
6379 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6380 return HandleConstructorCall(E, This, Args,
6381 cast<CXXConstructorDecl>(Definition), Info,
6385 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6386 const CXXInheritedCtorInitExpr *E) {
6387 if (!Info.CurrentCall) {
6388 assert(Info.checkingPotentialConstantExpression());
6392 const CXXConstructorDecl *FD = E->getConstructor();
6393 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6396 const FunctionDecl *Definition = nullptr;
6397 auto Body = FD->getBody(Definition);
6399 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6402 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6403 cast<CXXConstructorDecl>(Definition), Info,
6407 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6408 const CXXStdInitializerListExpr *E) {
6409 const ConstantArrayType *ArrayType =
6410 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6413 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6416 // Get a pointer to the first element of the array.
6417 Array.addArray(Info, E, ArrayType);
6419 // FIXME: Perform the checks on the field types in SemaInit.
6420 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6421 RecordDecl::field_iterator Field = Record->field_begin();
6422 if (Field == Record->field_end())
6426 if (!Field->getType()->isPointerType() ||
6427 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6428 ArrayType->getElementType()))
6431 // FIXME: What if the initializer_list type has base classes, etc?
6432 Result = APValue(APValue::UninitStruct(), 0, 2);
6433 Array.moveInto(Result.getStructField(0));
6435 if (++Field == Record->field_end())
6438 if (Field->getType()->isPointerType() &&
6439 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6440 ArrayType->getElementType())) {
6442 if (!HandleLValueArrayAdjustment(Info, E, Array,
6443 ArrayType->getElementType(),
6444 ArrayType->getSize().getZExtValue()))
6446 Array.moveInto(Result.getStructField(1));
6447 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6449 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6453 if (++Field != Record->field_end())
6459 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6460 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6461 if (ClosureClass->isInvalidDecl()) return false;
6463 if (Info.checkingPotentialConstantExpression()) return true;
6465 const size_t NumFields =
6466 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6468 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6469 E->capture_init_end()) &&
6470 "The number of lambda capture initializers should equal the number of "
6471 "fields within the closure type");
6473 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6474 // Iterate through all the lambda's closure object's fields and initialize
6476 auto *CaptureInitIt = E->capture_init_begin();
6477 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6478 bool Success = true;
6479 for (const auto *Field : ClosureClass->fields()) {
6480 assert(CaptureInitIt != E->capture_init_end());
6481 // Get the initializer for this field
6482 Expr *const CurFieldInit = *CaptureInitIt++;
6484 // If there is no initializer, either this is a VLA or an error has
6489 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6490 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6491 if (!Info.keepEvaluatingAfterFailure())
6500 static bool EvaluateRecord(const Expr *E, const LValue &This,
6501 APValue &Result, EvalInfo &Info) {
6502 assert(E->isRValue() && E->getType()->isRecordType() &&
6503 "can't evaluate expression as a record rvalue");
6504 return RecordExprEvaluator(Info, This, Result).Visit(E);
6507 //===----------------------------------------------------------------------===//
6508 // Temporary Evaluation
6510 // Temporaries are represented in the AST as rvalues, but generally behave like
6511 // lvalues. The full-object of which the temporary is a subobject is implicitly
6512 // materialized so that a reference can bind to it.
6513 //===----------------------------------------------------------------------===//
6515 class TemporaryExprEvaluator
6516 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6518 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6519 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6521 /// Visit an expression which constructs the value of this temporary.
6522 bool VisitConstructExpr(const Expr *E) {
6523 Result.set(E, Info.CurrentCall->Index);
6524 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6528 bool VisitCastExpr(const CastExpr *E) {
6529 switch (E->getCastKind()) {
6531 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6533 case CK_ConstructorConversion:
6534 return VisitConstructExpr(E->getSubExpr());
6537 bool VisitInitListExpr(const InitListExpr *E) {
6538 return VisitConstructExpr(E);
6540 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6541 return VisitConstructExpr(E);
6543 bool VisitCallExpr(const CallExpr *E) {
6544 return VisitConstructExpr(E);
6546 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6547 return VisitConstructExpr(E);
6549 bool VisitLambdaExpr(const LambdaExpr *E) {
6550 return VisitConstructExpr(E);
6553 } // end anonymous namespace
6555 /// Evaluate an expression of record type as a temporary.
6556 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6557 assert(E->isRValue() && E->getType()->isRecordType());
6558 return TemporaryExprEvaluator(Info, Result).Visit(E);
6561 //===----------------------------------------------------------------------===//
6562 // Vector Evaluation
6563 //===----------------------------------------------------------------------===//
6566 class VectorExprEvaluator
6567 : public ExprEvaluatorBase<VectorExprEvaluator> {
6571 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6572 : ExprEvaluatorBaseTy(info), Result(Result) {}
6574 bool Success(ArrayRef<APValue> V, const Expr *E) {
6575 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6576 // FIXME: remove this APValue copy.
6577 Result = APValue(V.data(), V.size());
6580 bool Success(const APValue &V, const Expr *E) {
6581 assert(V.isVector());
6585 bool ZeroInitialization(const Expr *E);
6587 bool VisitUnaryReal(const UnaryOperator *E)
6588 { return Visit(E->getSubExpr()); }
6589 bool VisitCastExpr(const CastExpr* E);
6590 bool VisitInitListExpr(const InitListExpr *E);
6591 bool VisitUnaryImag(const UnaryOperator *E);
6592 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6593 // binary comparisons, binary and/or/xor,
6594 // shufflevector, ExtVectorElementExpr
6596 } // end anonymous namespace
6598 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6599 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6600 return VectorExprEvaluator(Info, Result).Visit(E);
6603 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6604 const VectorType *VTy = E->getType()->castAs<VectorType>();
6605 unsigned NElts = VTy->getNumElements();
6607 const Expr *SE = E->getSubExpr();
6608 QualType SETy = SE->getType();
6610 switch (E->getCastKind()) {
6611 case CK_VectorSplat: {
6612 APValue Val = APValue();
6613 if (SETy->isIntegerType()) {
6615 if (!EvaluateInteger(SE, IntResult, Info))
6617 Val = APValue(std::move(IntResult));
6618 } else if (SETy->isRealFloatingType()) {
6619 APFloat FloatResult(0.0);
6620 if (!EvaluateFloat(SE, FloatResult, Info))
6622 Val = APValue(std::move(FloatResult));
6627 // Splat and create vector APValue.
6628 SmallVector<APValue, 4> Elts(NElts, Val);
6629 return Success(Elts, E);
6632 // Evaluate the operand into an APInt we can extract from.
6633 llvm::APInt SValInt;
6634 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6636 // Extract the elements
6637 QualType EltTy = VTy->getElementType();
6638 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6639 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6640 SmallVector<APValue, 4> Elts;
6641 if (EltTy->isRealFloatingType()) {
6642 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6643 unsigned FloatEltSize = EltSize;
6644 if (&Sem == &APFloat::x87DoubleExtended())
6646 for (unsigned i = 0; i < NElts; i++) {
6649 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6651 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6652 Elts.push_back(APValue(APFloat(Sem, Elt)));
6654 } else if (EltTy->isIntegerType()) {
6655 for (unsigned i = 0; i < NElts; i++) {
6658 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6660 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6661 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6666 return Success(Elts, E);
6669 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6674 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6675 const VectorType *VT = E->getType()->castAs<VectorType>();
6676 unsigned NumInits = E->getNumInits();
6677 unsigned NumElements = VT->getNumElements();
6679 QualType EltTy = VT->getElementType();
6680 SmallVector<APValue, 4> Elements;
6682 // The number of initializers can be less than the number of
6683 // vector elements. For OpenCL, this can be due to nested vector
6684 // initialization. For GCC compatibility, missing trailing elements
6685 // should be initialized with zeroes.
6686 unsigned CountInits = 0, CountElts = 0;
6687 while (CountElts < NumElements) {
6688 // Handle nested vector initialization.
6689 if (CountInits < NumInits
6690 && E->getInit(CountInits)->getType()->isVectorType()) {
6692 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6694 unsigned vlen = v.getVectorLength();
6695 for (unsigned j = 0; j < vlen; j++)
6696 Elements.push_back(v.getVectorElt(j));
6698 } else if (EltTy->isIntegerType()) {
6699 llvm::APSInt sInt(32);
6700 if (CountInits < NumInits) {
6701 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6703 } else // trailing integer zero.
6704 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6705 Elements.push_back(APValue(sInt));
6708 llvm::APFloat f(0.0);
6709 if (CountInits < NumInits) {
6710 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6712 } else // trailing float zero.
6713 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6714 Elements.push_back(APValue(f));
6719 return Success(Elements, E);
6723 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6724 const VectorType *VT = E->getType()->getAs<VectorType>();
6725 QualType EltTy = VT->getElementType();
6726 APValue ZeroElement;
6727 if (EltTy->isIntegerType())
6728 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6731 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6733 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6734 return Success(Elements, E);
6737 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6738 VisitIgnoredValue(E->getSubExpr());
6739 return ZeroInitialization(E);
6742 //===----------------------------------------------------------------------===//
6744 //===----------------------------------------------------------------------===//
6747 class ArrayExprEvaluator
6748 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6753 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6754 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6756 bool Success(const APValue &V, const Expr *E) {
6757 assert((V.isArray() || V.isLValue()) &&
6758 "expected array or string literal");
6763 bool ZeroInitialization(const Expr *E) {
6764 const ConstantArrayType *CAT =
6765 Info.Ctx.getAsConstantArrayType(E->getType());
6769 Result = APValue(APValue::UninitArray(), 0,
6770 CAT->getSize().getZExtValue());
6771 if (!Result.hasArrayFiller()) return true;
6773 // Zero-initialize all elements.
6774 LValue Subobject = This;
6775 Subobject.addArray(Info, E, CAT);
6776 ImplicitValueInitExpr VIE(CAT->getElementType());
6777 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6780 bool VisitCallExpr(const CallExpr *E) {
6781 return handleCallExpr(E, Result, &This);
6783 bool VisitInitListExpr(const InitListExpr *E);
6784 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6785 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6786 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6787 const LValue &Subobject,
6788 APValue *Value, QualType Type);
6790 } // end anonymous namespace
6792 static bool EvaluateArray(const Expr *E, const LValue &This,
6793 APValue &Result, EvalInfo &Info) {
6794 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6795 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6798 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6799 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6803 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6804 // an appropriately-typed string literal enclosed in braces.
6805 if (E->isStringLiteralInit()) {
6807 if (!EvaluateLValue(E->getInit(0), LV, Info))
6811 return Success(Val, E);
6814 bool Success = true;
6816 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6817 "zero-initialized array shouldn't have any initialized elts");
6819 if (Result.isArray() && Result.hasArrayFiller())
6820 Filler = Result.getArrayFiller();
6822 unsigned NumEltsToInit = E->getNumInits();
6823 unsigned NumElts = CAT->getSize().getZExtValue();
6824 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6826 // If the initializer might depend on the array index, run it for each
6827 // array element. For now, just whitelist non-class value-initialization.
6828 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6829 NumEltsToInit = NumElts;
6831 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6833 // If the array was previously zero-initialized, preserve the
6834 // zero-initialized values.
6835 if (!Filler.isUninit()) {
6836 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6837 Result.getArrayInitializedElt(I) = Filler;
6838 if (Result.hasArrayFiller())
6839 Result.getArrayFiller() = Filler;
6842 LValue Subobject = This;
6843 Subobject.addArray(Info, E, CAT);
6844 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6846 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6847 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6848 Info, Subobject, Init) ||
6849 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6850 CAT->getElementType(), 1)) {
6851 if (!Info.noteFailure())
6857 if (!Result.hasArrayFiller())
6860 // If we get here, we have a trivial filler, which we can just evaluate
6861 // once and splat over the rest of the array elements.
6862 assert(FillerExpr && "no array filler for incomplete init list");
6863 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6864 FillerExpr) && Success;
6867 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6868 if (E->getCommonExpr() &&
6869 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6870 Info, E->getCommonExpr()->getSourceExpr()))
6873 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6875 uint64_t Elements = CAT->getSize().getZExtValue();
6876 Result = APValue(APValue::UninitArray(), Elements, Elements);
6878 LValue Subobject = This;
6879 Subobject.addArray(Info, E, CAT);
6881 bool Success = true;
6882 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6883 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6884 Info, Subobject, E->getSubExpr()) ||
6885 !HandleLValueArrayAdjustment(Info, E, Subobject,
6886 CAT->getElementType(), 1)) {
6887 if (!Info.noteFailure())
6896 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6897 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6900 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6901 const LValue &Subobject,
6904 bool HadZeroInit = !Value->isUninit();
6906 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6907 unsigned N = CAT->getSize().getZExtValue();
6909 // Preserve the array filler if we had prior zero-initialization.
6911 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6914 *Value = APValue(APValue::UninitArray(), N, N);
6917 for (unsigned I = 0; I != N; ++I)
6918 Value->getArrayInitializedElt(I) = Filler;
6920 // Initialize the elements.
6921 LValue ArrayElt = Subobject;
6922 ArrayElt.addArray(Info, E, CAT);
6923 for (unsigned I = 0; I != N; ++I)
6924 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6925 CAT->getElementType()) ||
6926 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6927 CAT->getElementType(), 1))
6933 if (!Type->isRecordType())
6936 return RecordExprEvaluator(Info, Subobject, *Value)
6937 .VisitCXXConstructExpr(E, Type);
6940 //===----------------------------------------------------------------------===//
6941 // Integer Evaluation
6943 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6944 // types and back in constant folding. Integer values are thus represented
6945 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6946 //===----------------------------------------------------------------------===//
6949 class IntExprEvaluator
6950 : public ExprEvaluatorBase<IntExprEvaluator> {
6953 IntExprEvaluator(EvalInfo &info, APValue &result)
6954 : ExprEvaluatorBaseTy(info), Result(result) {}
6956 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6957 assert(E->getType()->isIntegralOrEnumerationType() &&
6958 "Invalid evaluation result.");
6959 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6960 "Invalid evaluation result.");
6961 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6962 "Invalid evaluation result.");
6963 Result = APValue(SI);
6966 bool Success(const llvm::APSInt &SI, const Expr *E) {
6967 return Success(SI, E, Result);
6970 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6971 assert(E->getType()->isIntegralOrEnumerationType() &&
6972 "Invalid evaluation result.");
6973 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6974 "Invalid evaluation result.");
6975 Result = APValue(APSInt(I));
6976 Result.getInt().setIsUnsigned(
6977 E->getType()->isUnsignedIntegerOrEnumerationType());
6980 bool Success(const llvm::APInt &I, const Expr *E) {
6981 return Success(I, E, Result);
6984 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6985 assert(E->getType()->isIntegralOrEnumerationType() &&
6986 "Invalid evaluation result.");
6987 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6990 bool Success(uint64_t Value, const Expr *E) {
6991 return Success(Value, E, Result);
6994 bool Success(CharUnits Size, const Expr *E) {
6995 return Success(Size.getQuantity(), E);
6998 bool Success(const APValue &V, const Expr *E) {
6999 if (V.isLValue() || V.isAddrLabelDiff()) {
7003 return Success(V.getInt(), E);
7006 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7008 //===--------------------------------------------------------------------===//
7010 //===--------------------------------------------------------------------===//
7012 bool VisitIntegerLiteral(const IntegerLiteral *E) {
7013 return Success(E->getValue(), E);
7015 bool VisitCharacterLiteral(const CharacterLiteral *E) {
7016 return Success(E->getValue(), E);
7019 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7020 bool VisitDeclRefExpr(const DeclRefExpr *E) {
7021 if (CheckReferencedDecl(E, E->getDecl()))
7024 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7026 bool VisitMemberExpr(const MemberExpr *E) {
7027 if (CheckReferencedDecl(E, E->getMemberDecl())) {
7028 VisitIgnoredBaseExpression(E->getBase());
7032 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7035 bool VisitCallExpr(const CallExpr *E);
7036 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7037 bool VisitBinaryOperator(const BinaryOperator *E);
7038 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7039 bool VisitUnaryOperator(const UnaryOperator *E);
7041 bool VisitCastExpr(const CastExpr* E);
7042 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7044 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7045 return Success(E->getValue(), E);
7048 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7049 return Success(E->getValue(), E);
7052 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7053 if (Info.ArrayInitIndex == uint64_t(-1)) {
7054 // We were asked to evaluate this subexpression independent of the
7055 // enclosing ArrayInitLoopExpr. We can't do that.
7059 return Success(Info.ArrayInitIndex, E);
7062 // Note, GNU defines __null as an integer, not a pointer.
7063 bool VisitGNUNullExpr(const GNUNullExpr *E) {
7064 return ZeroInitialization(E);
7067 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7068 return Success(E->getValue(), E);
7071 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7072 return Success(E->getValue(), E);
7075 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7076 return Success(E->getValue(), E);
7079 bool VisitUnaryReal(const UnaryOperator *E);
7080 bool VisitUnaryImag(const UnaryOperator *E);
7082 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7083 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7085 // FIXME: Missing: array subscript of vector, member of vector
7087 } // end anonymous namespace
7089 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7090 /// produce either the integer value or a pointer.
7092 /// GCC has a heinous extension which folds casts between pointer types and
7093 /// pointer-sized integral types. We support this by allowing the evaluation of
7094 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7095 /// Some simple arithmetic on such values is supported (they are treated much
7097 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7099 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7100 return IntExprEvaluator(Info, Result).Visit(E);
7103 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7105 if (!EvaluateIntegerOrLValue(E, Val, Info))
7108 // FIXME: It would be better to produce the diagnostic for casting
7109 // a pointer to an integer.
7110 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7113 Result = Val.getInt();
7117 /// Check whether the given declaration can be directly converted to an integral
7118 /// rvalue. If not, no diagnostic is produced; there are other things we can
7120 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7121 // Enums are integer constant exprs.
7122 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7123 // Check for signedness/width mismatches between E type and ECD value.
7124 bool SameSign = (ECD->getInitVal().isSigned()
7125 == E->getType()->isSignedIntegerOrEnumerationType());
7126 bool SameWidth = (ECD->getInitVal().getBitWidth()
7127 == Info.Ctx.getIntWidth(E->getType()));
7128 if (SameSign && SameWidth)
7129 return Success(ECD->getInitVal(), E);
7131 // Get rid of mismatch (otherwise Success assertions will fail)
7132 // by computing a new value matching the type of E.
7133 llvm::APSInt Val = ECD->getInitVal();
7135 Val.setIsSigned(!ECD->getInitVal().isSigned());
7137 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7138 return Success(Val, E);
7144 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7146 static int EvaluateBuiltinClassifyType(const CallExpr *E,
7147 const LangOptions &LangOpts) {
7148 // The following enum mimics the values returned by GCC.
7149 // FIXME: Does GCC differ between lvalue and rvalue references here?
7150 enum gcc_type_class {
7152 void_type_class, integer_type_class, char_type_class,
7153 enumeral_type_class, boolean_type_class,
7154 pointer_type_class, reference_type_class, offset_type_class,
7155 real_type_class, complex_type_class,
7156 function_type_class, method_type_class,
7157 record_type_class, union_type_class,
7158 array_type_class, string_type_class,
7162 // If no argument was supplied, default to "no_type_class". This isn't
7163 // ideal, however it is what gcc does.
7164 if (E->getNumArgs() == 0)
7165 return no_type_class;
7167 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7168 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7170 switch (CanTy->getTypeClass()) {
7171 #define TYPE(ID, BASE)
7172 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7173 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7174 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7175 #include "clang/AST/TypeNodes.def"
7176 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7179 switch (BT->getKind()) {
7180 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7181 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7182 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7183 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7184 #include "clang/AST/BuiltinTypes.def"
7185 case BuiltinType::Void:
7186 return void_type_class;
7188 case BuiltinType::Bool:
7189 return boolean_type_class;
7191 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7192 case BuiltinType::UChar:
7193 case BuiltinType::UShort:
7194 case BuiltinType::UInt:
7195 case BuiltinType::ULong:
7196 case BuiltinType::ULongLong:
7197 case BuiltinType::UInt128:
7198 return integer_type_class;
7200 case BuiltinType::NullPtr:
7201 return pointer_type_class;
7203 case BuiltinType::WChar_U:
7204 case BuiltinType::Char16:
7205 case BuiltinType::Char32:
7206 case BuiltinType::ObjCId:
7207 case BuiltinType::ObjCClass:
7208 case BuiltinType::ObjCSel:
7209 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7210 case BuiltinType::Id:
7211 #include "clang/Basic/OpenCLImageTypes.def"
7212 case BuiltinType::OCLSampler:
7213 case BuiltinType::OCLEvent:
7214 case BuiltinType::OCLClkEvent:
7215 case BuiltinType::OCLQueue:
7216 case BuiltinType::OCLReserveID:
7217 case BuiltinType::Dependent:
7218 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7223 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7227 return pointer_type_class;
7230 case Type::MemberPointer:
7231 if (CanTy->isMemberDataPointerType())
7232 return offset_type_class;
7234 // We expect member pointers to be either data or function pointers,
7236 assert(CanTy->isMemberFunctionPointerType());
7237 return method_type_class;
7241 return complex_type_class;
7243 case Type::FunctionNoProto:
7244 case Type::FunctionProto:
7245 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7248 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7249 switch (RT->getDecl()->getTagKind()) {
7250 case TagTypeKind::TTK_Struct:
7251 case TagTypeKind::TTK_Class:
7252 case TagTypeKind::TTK_Interface:
7253 return record_type_class;
7255 case TagTypeKind::TTK_Enum:
7256 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7258 case TagTypeKind::TTK_Union:
7259 return union_type_class;
7262 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7264 case Type::ConstantArray:
7265 case Type::VariableArray:
7266 case Type::IncompleteArray:
7267 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7269 case Type::BlockPointer:
7270 case Type::LValueReference:
7271 case Type::RValueReference:
7273 case Type::ExtVector:
7275 case Type::DeducedTemplateSpecialization:
7276 case Type::ObjCObject:
7277 case Type::ObjCInterface:
7278 case Type::ObjCObjectPointer:
7281 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7284 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7287 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7288 /// __builtin_constant_p when applied to the given lvalue.
7290 /// An lvalue is only "constant" if it is a pointer or reference to the first
7291 /// character of a string literal.
7292 template<typename LValue>
7293 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7294 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7295 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7298 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7299 /// GCC as we can manage.
7300 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7301 QualType ArgType = Arg->getType();
7303 // __builtin_constant_p always has one operand. The rules which gcc follows
7304 // are not precisely documented, but are as follows:
7306 // - If the operand is of integral, floating, complex or enumeration type,
7307 // and can be folded to a known value of that type, it returns 1.
7308 // - If the operand and can be folded to a pointer to the first character
7309 // of a string literal (or such a pointer cast to an integral type), it
7312 // Otherwise, it returns 0.
7314 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7315 // its support for this does not currently work.
7316 if (ArgType->isIntegralOrEnumerationType()) {
7317 Expr::EvalResult Result;
7318 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7321 APValue &V = Result.Val;
7322 if (V.getKind() == APValue::Int)
7324 if (V.getKind() == APValue::LValue)
7325 return EvaluateBuiltinConstantPForLValue(V);
7326 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7327 return Arg->isEvaluatable(Ctx);
7328 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7330 Expr::EvalStatus Status;
7331 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7332 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7333 : EvaluatePointer(Arg, LV, Info)) &&
7334 !Status.HasSideEffects)
7335 return EvaluateBuiltinConstantPForLValue(LV);
7338 // Anything else isn't considered to be sufficiently constant.
7342 /// Retrieves the "underlying object type" of the given expression,
7343 /// as used by __builtin_object_size.
7344 static QualType getObjectType(APValue::LValueBase B) {
7345 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7346 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7347 return VD->getType();
7348 } else if (const Expr *E = B.get<const Expr*>()) {
7349 if (isa<CompoundLiteralExpr>(E))
7350 return E->getType();
7356 /// A more selective version of E->IgnoreParenCasts for
7357 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7358 /// to change the type of E.
7359 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7361 /// Always returns an RValue with a pointer representation.
7362 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7363 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7365 auto *NoParens = E->IgnoreParens();
7366 auto *Cast = dyn_cast<CastExpr>(NoParens);
7367 if (Cast == nullptr)
7370 // We only conservatively allow a few kinds of casts, because this code is
7371 // inherently a simple solution that seeks to support the common case.
7372 auto CastKind = Cast->getCastKind();
7373 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7374 CastKind != CK_AddressSpaceConversion)
7377 auto *SubExpr = Cast->getSubExpr();
7378 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7380 return ignorePointerCastsAndParens(SubExpr);
7383 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7384 /// record layout. e.g.
7385 /// struct { struct { int a, b; } fst, snd; } obj;
7391 /// obj.snd.b // yes
7393 /// Please note: this function is specialized for how __builtin_object_size
7394 /// views "objects".
7396 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7397 /// correct result, it will always return true.
7398 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7399 assert(!LVal.Designator.Invalid);
7401 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7402 const RecordDecl *Parent = FD->getParent();
7403 Invalid = Parent->isInvalidDecl();
7404 if (Invalid || Parent->isUnion())
7406 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7407 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7410 auto &Base = LVal.getLValueBase();
7411 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7412 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7414 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7416 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7417 for (auto *FD : IFD->chain()) {
7419 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7426 QualType BaseType = getType(Base);
7427 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7428 // If we don't know the array bound, conservatively assume we're looking at
7429 // the final array element.
7431 if (BaseType->isIncompleteArrayType())
7432 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7434 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7437 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7438 const auto &Entry = LVal.Designator.Entries[I];
7439 if (BaseType->isArrayType()) {
7440 // Because __builtin_object_size treats arrays as objects, we can ignore
7441 // the index iff this is the last array in the Designator.
7444 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7445 uint64_t Index = Entry.ArrayIndex;
7446 if (Index + 1 != CAT->getSize())
7448 BaseType = CAT->getElementType();
7449 } else if (BaseType->isAnyComplexType()) {
7450 const auto *CT = BaseType->castAs<ComplexType>();
7451 uint64_t Index = Entry.ArrayIndex;
7454 BaseType = CT->getElementType();
7455 } else if (auto *FD = getAsField(Entry)) {
7457 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7459 BaseType = FD->getType();
7461 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7468 /// Tests to see if the LValue has a user-specified designator (that isn't
7469 /// necessarily valid). Note that this always returns 'true' if the LValue has
7470 /// an unsized array as its first designator entry, because there's currently no
7471 /// way to tell if the user typed *foo or foo[0].
7472 static bool refersToCompleteObject(const LValue &LVal) {
7473 if (LVal.Designator.Invalid)
7476 if (!LVal.Designator.Entries.empty())
7477 return LVal.Designator.isMostDerivedAnUnsizedArray();
7479 if (!LVal.InvalidBase)
7482 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7484 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7485 return !E || !isa<MemberExpr>(E);
7488 /// Attempts to detect a user writing into a piece of memory that's impossible
7489 /// to figure out the size of by just using types.
7490 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7491 const SubobjectDesignator &Designator = LVal.Designator;
7493 // - Users can only write off of the end when we have an invalid base. Invalid
7494 // bases imply we don't know where the memory came from.
7495 // - We used to be a bit more aggressive here; we'd only be conservative if
7496 // the array at the end was flexible, or if it had 0 or 1 elements. This
7497 // broke some common standard library extensions (PR30346), but was
7498 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7499 // with some sort of whitelist. OTOH, it seems that GCC is always
7500 // conservative with the last element in structs (if it's an array), so our
7501 // current behavior is more compatible than a whitelisting approach would
7503 return LVal.InvalidBase &&
7504 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7505 Designator.MostDerivedIsArrayElement &&
7506 isDesignatorAtObjectEnd(Ctx, LVal);
7509 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7510 /// Fails if the conversion would cause loss of precision.
7511 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7512 CharUnits &Result) {
7513 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7514 if (Int.ugt(CharUnitsMax))
7516 Result = CharUnits::fromQuantity(Int.getZExtValue());
7520 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7521 /// determine how many bytes exist from the beginning of the object to either
7522 /// the end of the current subobject, or the end of the object itself, depending
7523 /// on what the LValue looks like + the value of Type.
7525 /// If this returns false, the value of Result is undefined.
7526 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7527 unsigned Type, const LValue &LVal,
7528 CharUnits &EndOffset) {
7529 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7531 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7532 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7534 return HandleSizeof(Info, ExprLoc, Ty, Result);
7537 // We want to evaluate the size of the entire object. This is a valid fallback
7538 // for when Type=1 and the designator is invalid, because we're asked for an
7540 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7541 // Type=3 wants a lower bound, so we can't fall back to this.
7542 if (Type == 3 && !DetermineForCompleteObject)
7545 llvm::APInt APEndOffset;
7546 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7547 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7548 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7550 if (LVal.InvalidBase)
7553 QualType BaseTy = getObjectType(LVal.getLValueBase());
7554 return CheckedHandleSizeof(BaseTy, EndOffset);
7557 // We want to evaluate the size of a subobject.
7558 const SubobjectDesignator &Designator = LVal.Designator;
7560 // The following is a moderately common idiom in C:
7562 // struct Foo { int a; char c[1]; };
7563 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7564 // strcpy(&F->c[0], Bar);
7566 // In order to not break too much legacy code, we need to support it.
7567 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7568 // If we can resolve this to an alloc_size call, we can hand that back,
7569 // because we know for certain how many bytes there are to write to.
7570 llvm::APInt APEndOffset;
7571 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7572 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7573 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7575 // If we cannot determine the size of the initial allocation, then we can't
7576 // given an accurate upper-bound. However, we are still able to give
7577 // conservative lower-bounds for Type=3.
7582 CharUnits BytesPerElem;
7583 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7586 // According to the GCC documentation, we want the size of the subobject
7587 // denoted by the pointer. But that's not quite right -- what we actually
7588 // want is the size of the immediately-enclosing array, if there is one.
7589 int64_t ElemsRemaining;
7590 if (Designator.MostDerivedIsArrayElement &&
7591 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7592 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7593 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7594 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7596 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7599 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7603 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7604 /// returns true and stores the result in @p Size.
7606 /// If @p WasError is non-null, this will report whether the failure to evaluate
7607 /// is to be treated as an Error in IntExprEvaluator.
7608 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7609 EvalInfo &Info, uint64_t &Size) {
7610 // Determine the denoted object.
7613 // The operand of __builtin_object_size is never evaluated for side-effects.
7614 // If there are any, but we can determine the pointed-to object anyway, then
7615 // ignore the side-effects.
7616 SpeculativeEvaluationRAII SpeculativeEval(Info);
7617 FoldOffsetRAII Fold(Info);
7619 if (E->isGLValue()) {
7620 // It's possible for us to be given GLValues if we're called via
7621 // Expr::tryEvaluateObjectSize.
7623 if (!EvaluateAsRValue(Info, E, RVal))
7625 LVal.setFrom(Info.Ctx, RVal);
7626 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7627 /*InvalidBaseOK=*/true))
7631 // If we point to before the start of the object, there are no accessible
7633 if (LVal.getLValueOffset().isNegative()) {
7638 CharUnits EndOffset;
7639 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7642 // If we've fallen outside of the end offset, just pretend there's nothing to
7643 // write to/read from.
7644 if (EndOffset <= LVal.getLValueOffset())
7647 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7651 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7652 if (unsigned BuiltinOp = E->getBuiltinCallee())
7653 return VisitBuiltinCallExpr(E, BuiltinOp);
7655 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7658 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7659 unsigned BuiltinOp) {
7660 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7662 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7664 case Builtin::BI__builtin_object_size: {
7665 // The type was checked when we built the expression.
7667 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7668 assert(Type <= 3 && "unexpected type");
7671 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7672 return Success(Size, E);
7674 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7675 return Success((Type & 2) ? 0 : -1, E);
7677 // Expression had no side effects, but we couldn't statically determine the
7678 // size of the referenced object.
7679 switch (Info.EvalMode) {
7680 case EvalInfo::EM_ConstantExpression:
7681 case EvalInfo::EM_PotentialConstantExpression:
7682 case EvalInfo::EM_ConstantFold:
7683 case EvalInfo::EM_EvaluateForOverflow:
7684 case EvalInfo::EM_IgnoreSideEffects:
7685 case EvalInfo::EM_OffsetFold:
7686 // Leave it to IR generation.
7688 case EvalInfo::EM_ConstantExpressionUnevaluated:
7689 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7690 // Reduce it to a constant now.
7691 return Success((Type & 2) ? 0 : -1, E);
7694 llvm_unreachable("unexpected EvalMode");
7697 case Builtin::BI__builtin_bswap16:
7698 case Builtin::BI__builtin_bswap32:
7699 case Builtin::BI__builtin_bswap64: {
7701 if (!EvaluateInteger(E->getArg(0), Val, Info))
7704 return Success(Val.byteSwap(), E);
7707 case Builtin::BI__builtin_classify_type:
7708 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7710 // FIXME: BI__builtin_clrsb
7711 // FIXME: BI__builtin_clrsbl
7712 // FIXME: BI__builtin_clrsbll
7714 case Builtin::BI__builtin_clz:
7715 case Builtin::BI__builtin_clzl:
7716 case Builtin::BI__builtin_clzll:
7717 case Builtin::BI__builtin_clzs: {
7719 if (!EvaluateInteger(E->getArg(0), Val, Info))
7724 return Success(Val.countLeadingZeros(), E);
7727 case Builtin::BI__builtin_constant_p:
7728 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7730 case Builtin::BI__builtin_ctz:
7731 case Builtin::BI__builtin_ctzl:
7732 case Builtin::BI__builtin_ctzll:
7733 case Builtin::BI__builtin_ctzs: {
7735 if (!EvaluateInteger(E->getArg(0), Val, Info))
7740 return Success(Val.countTrailingZeros(), E);
7743 case Builtin::BI__builtin_eh_return_data_regno: {
7744 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7745 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7746 return Success(Operand, E);
7749 case Builtin::BI__builtin_expect:
7750 return Visit(E->getArg(0));
7752 case Builtin::BI__builtin_ffs:
7753 case Builtin::BI__builtin_ffsl:
7754 case Builtin::BI__builtin_ffsll: {
7756 if (!EvaluateInteger(E->getArg(0), Val, Info))
7759 unsigned N = Val.countTrailingZeros();
7760 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7763 case Builtin::BI__builtin_fpclassify: {
7765 if (!EvaluateFloat(E->getArg(5), Val, Info))
7768 switch (Val.getCategory()) {
7769 case APFloat::fcNaN: Arg = 0; break;
7770 case APFloat::fcInfinity: Arg = 1; break;
7771 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7772 case APFloat::fcZero: Arg = 4; break;
7774 return Visit(E->getArg(Arg));
7777 case Builtin::BI__builtin_isinf_sign: {
7779 return EvaluateFloat(E->getArg(0), Val, Info) &&
7780 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7783 case Builtin::BI__builtin_isinf: {
7785 return EvaluateFloat(E->getArg(0), Val, Info) &&
7786 Success(Val.isInfinity() ? 1 : 0, E);
7789 case Builtin::BI__builtin_isfinite: {
7791 return EvaluateFloat(E->getArg(0), Val, Info) &&
7792 Success(Val.isFinite() ? 1 : 0, E);
7795 case Builtin::BI__builtin_isnan: {
7797 return EvaluateFloat(E->getArg(0), Val, Info) &&
7798 Success(Val.isNaN() ? 1 : 0, E);
7801 case Builtin::BI__builtin_isnormal: {
7803 return EvaluateFloat(E->getArg(0), Val, Info) &&
7804 Success(Val.isNormal() ? 1 : 0, E);
7807 case Builtin::BI__builtin_parity:
7808 case Builtin::BI__builtin_parityl:
7809 case Builtin::BI__builtin_parityll: {
7811 if (!EvaluateInteger(E->getArg(0), Val, Info))
7814 return Success(Val.countPopulation() % 2, E);
7817 case Builtin::BI__builtin_popcount:
7818 case Builtin::BI__builtin_popcountl:
7819 case Builtin::BI__builtin_popcountll: {
7821 if (!EvaluateInteger(E->getArg(0), Val, Info))
7824 return Success(Val.countPopulation(), E);
7827 case Builtin::BIstrlen:
7828 case Builtin::BIwcslen:
7829 // A call to strlen is not a constant expression.
7830 if (Info.getLangOpts().CPlusPlus11)
7831 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7832 << /*isConstexpr*/0 << /*isConstructor*/0
7833 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7835 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7837 case Builtin::BI__builtin_strlen:
7838 case Builtin::BI__builtin_wcslen: {
7839 // As an extension, we support __builtin_strlen() as a constant expression,
7840 // and support folding strlen() to a constant.
7842 if (!EvaluatePointer(E->getArg(0), String, Info))
7845 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7847 // Fast path: if it's a string literal, search the string value.
7848 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7849 String.getLValueBase().dyn_cast<const Expr *>())) {
7850 // The string literal may have embedded null characters. Find the first
7851 // one and truncate there.
7852 StringRef Str = S->getBytes();
7853 int64_t Off = String.Offset.getQuantity();
7854 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7855 S->getCharByteWidth() == 1 &&
7856 // FIXME: Add fast-path for wchar_t too.
7857 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7858 Str = Str.substr(Off);
7860 StringRef::size_type Pos = Str.find(0);
7861 if (Pos != StringRef::npos)
7862 Str = Str.substr(0, Pos);
7864 return Success(Str.size(), E);
7867 // Fall through to slow path to issue appropriate diagnostic.
7870 // Slow path: scan the bytes of the string looking for the terminating 0.
7871 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7873 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7877 return Success(Strlen, E);
7878 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7883 case Builtin::BIstrcmp:
7884 case Builtin::BIwcscmp:
7885 case Builtin::BIstrncmp:
7886 case Builtin::BIwcsncmp:
7887 case Builtin::BImemcmp:
7888 case Builtin::BIwmemcmp:
7889 // A call to strlen is not a constant expression.
7890 if (Info.getLangOpts().CPlusPlus11)
7891 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7892 << /*isConstexpr*/0 << /*isConstructor*/0
7893 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7895 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7897 case Builtin::BI__builtin_strcmp:
7898 case Builtin::BI__builtin_wcscmp:
7899 case Builtin::BI__builtin_strncmp:
7900 case Builtin::BI__builtin_wcsncmp:
7901 case Builtin::BI__builtin_memcmp:
7902 case Builtin::BI__builtin_wmemcmp: {
7903 LValue String1, String2;
7904 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7905 !EvaluatePointer(E->getArg(1), String2, Info))
7908 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7910 uint64_t MaxLength = uint64_t(-1);
7911 if (BuiltinOp != Builtin::BIstrcmp &&
7912 BuiltinOp != Builtin::BIwcscmp &&
7913 BuiltinOp != Builtin::BI__builtin_strcmp &&
7914 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7916 if (!EvaluateInteger(E->getArg(2), N, Info))
7918 MaxLength = N.getExtValue();
7920 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7921 BuiltinOp != Builtin::BIwmemcmp &&
7922 BuiltinOp != Builtin::BI__builtin_memcmp &&
7923 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7924 for (; MaxLength; --MaxLength) {
7925 APValue Char1, Char2;
7926 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7927 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7928 !Char1.isInt() || !Char2.isInt())
7930 if (Char1.getInt() != Char2.getInt())
7931 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7932 if (StopAtNull && !Char1.getInt())
7933 return Success(0, E);
7934 assert(!(StopAtNull && !Char2.getInt()));
7935 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7936 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7939 // We hit the strncmp / memcmp limit.
7940 return Success(0, E);
7943 case Builtin::BI__atomic_always_lock_free:
7944 case Builtin::BI__atomic_is_lock_free:
7945 case Builtin::BI__c11_atomic_is_lock_free: {
7947 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7950 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7951 // of two less than the maximum inline atomic width, we know it is
7952 // lock-free. If the size isn't a power of two, or greater than the
7953 // maximum alignment where we promote atomics, we know it is not lock-free
7954 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7955 // the answer can only be determined at runtime; for example, 16-byte
7956 // atomics have lock-free implementations on some, but not all,
7957 // x86-64 processors.
7959 // Check power-of-two.
7960 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7961 if (Size.isPowerOfTwo()) {
7962 // Check against inlining width.
7963 unsigned InlineWidthBits =
7964 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7965 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7966 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7967 Size == CharUnits::One() ||
7968 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7969 Expr::NPC_NeverValueDependent))
7970 // OK, we will inline appropriately-aligned operations of this size,
7971 // and _Atomic(T) is appropriately-aligned.
7972 return Success(1, E);
7974 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7975 castAs<PointerType>()->getPointeeType();
7976 if (!PointeeType->isIncompleteType() &&
7977 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7978 // OK, we will inline operations on this object.
7979 return Success(1, E);
7984 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7985 Success(0, E) : Error(E);
7987 case Builtin::BIomp_is_initial_device:
7988 // We can decide statically which value the runtime would return if called.
7989 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
7993 static bool HasSameBase(const LValue &A, const LValue &B) {
7994 if (!A.getLValueBase())
7995 return !B.getLValueBase();
7996 if (!B.getLValueBase())
7999 if (A.getLValueBase().getOpaqueValue() !=
8000 B.getLValueBase().getOpaqueValue()) {
8001 const Decl *ADecl = GetLValueBaseDecl(A);
8004 const Decl *BDecl = GetLValueBaseDecl(B);
8005 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
8009 return IsGlobalLValue(A.getLValueBase()) ||
8010 A.getLValueCallIndex() == B.getLValueCallIndex();
8013 /// \brief Determine whether this is a pointer past the end of the complete
8014 /// object referred to by the lvalue.
8015 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8017 // A null pointer can be viewed as being "past the end" but we don't
8018 // choose to look at it that way here.
8019 if (!LV.getLValueBase())
8022 // If the designator is valid and refers to a subobject, we're not pointing
8024 if (!LV.getLValueDesignator().Invalid &&
8025 !LV.getLValueDesignator().isOnePastTheEnd())
8028 // A pointer to an incomplete type might be past-the-end if the type's size is
8029 // zero. We cannot tell because the type is incomplete.
8030 QualType Ty = getType(LV.getLValueBase());
8031 if (Ty->isIncompleteType())
8034 // We're a past-the-end pointer if we point to the byte after the object,
8035 // no matter what our type or path is.
8036 auto Size = Ctx.getTypeSizeInChars(Ty);
8037 return LV.getLValueOffset() == Size;
8042 /// \brief Data recursive integer evaluator of certain binary operators.
8044 /// We use a data recursive algorithm for binary operators so that we are able
8045 /// to handle extreme cases of chained binary operators without causing stack
8047 class DataRecursiveIntBinOpEvaluator {
8052 EvalResult() : Failed(false) { }
8054 void swap(EvalResult &RHS) {
8056 Failed = RHS.Failed;
8063 EvalResult LHSResult; // meaningful only for binary operator expression.
8064 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8067 Job(Job &&) = default;
8069 void startSpeculativeEval(EvalInfo &Info) {
8070 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8074 SpeculativeEvaluationRAII SpecEvalRAII;
8077 SmallVector<Job, 16> Queue;
8079 IntExprEvaluator &IntEval;
8081 APValue &FinalResult;
8084 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8085 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8087 /// \brief True if \param E is a binary operator that we are going to handle
8088 /// data recursively.
8089 /// We handle binary operators that are comma, logical, or that have operands
8090 /// with integral or enumeration type.
8091 static bool shouldEnqueue(const BinaryOperator *E) {
8092 return E->getOpcode() == BO_Comma ||
8095 E->getType()->isIntegralOrEnumerationType() &&
8096 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8097 E->getRHS()->getType()->isIntegralOrEnumerationType());
8100 bool Traverse(const BinaryOperator *E) {
8102 EvalResult PrevResult;
8103 while (!Queue.empty())
8104 process(PrevResult);
8106 if (PrevResult.Failed) return false;
8108 FinalResult.swap(PrevResult.Val);
8113 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8114 return IntEval.Success(Value, E, Result);
8116 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8117 return IntEval.Success(Value, E, Result);
8119 bool Error(const Expr *E) {
8120 return IntEval.Error(E);
8122 bool Error(const Expr *E, diag::kind D) {
8123 return IntEval.Error(E, D);
8126 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8127 return Info.CCEDiag(E, D);
8130 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8131 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8132 bool &SuppressRHSDiags);
8134 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8135 const BinaryOperator *E, APValue &Result);
8137 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8138 Result.Failed = !Evaluate(Result.Val, Info, E);
8140 Result.Val = APValue();
8143 void process(EvalResult &Result);
8145 void enqueue(const Expr *E) {
8146 E = E->IgnoreParens();
8147 Queue.resize(Queue.size()+1);
8149 Queue.back().Kind = Job::AnyExprKind;
8155 bool DataRecursiveIntBinOpEvaluator::
8156 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8157 bool &SuppressRHSDiags) {
8158 if (E->getOpcode() == BO_Comma) {
8159 // Ignore LHS but note if we could not evaluate it.
8160 if (LHSResult.Failed)
8161 return Info.noteSideEffect();
8165 if (E->isLogicalOp()) {
8167 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8168 // We were able to evaluate the LHS, see if we can get away with not
8169 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8170 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8171 Success(LHSAsBool, E, LHSResult.Val);
8172 return false; // Ignore RHS
8175 LHSResult.Failed = true;
8177 // Since we weren't able to evaluate the left hand side, it
8178 // might have had side effects.
8179 if (!Info.noteSideEffect())
8182 // We can't evaluate the LHS; however, sometimes the result
8183 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8184 // Don't ignore RHS and suppress diagnostics from this arm.
8185 SuppressRHSDiags = true;
8191 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8192 E->getRHS()->getType()->isIntegralOrEnumerationType());
8194 if (LHSResult.Failed && !Info.noteFailure())
8195 return false; // Ignore RHS;
8200 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8202 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8203 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8205 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8206 CharUnits &Offset = LVal.getLValueOffset();
8207 uint64_t Offset64 = Offset.getQuantity();
8208 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8209 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8210 : Offset64 + Index64);
8213 bool DataRecursiveIntBinOpEvaluator::
8214 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8215 const BinaryOperator *E, APValue &Result) {
8216 if (E->getOpcode() == BO_Comma) {
8217 if (RHSResult.Failed)
8219 Result = RHSResult.Val;
8223 if (E->isLogicalOp()) {
8224 bool lhsResult, rhsResult;
8225 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8226 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8230 if (E->getOpcode() == BO_LOr)
8231 return Success(lhsResult || rhsResult, E, Result);
8233 return Success(lhsResult && rhsResult, E, Result);
8237 // We can't evaluate the LHS; however, sometimes the result
8238 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8239 if (rhsResult == (E->getOpcode() == BO_LOr))
8240 return Success(rhsResult, E, Result);
8247 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8248 E->getRHS()->getType()->isIntegralOrEnumerationType());
8250 if (LHSResult.Failed || RHSResult.Failed)
8253 const APValue &LHSVal = LHSResult.Val;
8254 const APValue &RHSVal = RHSResult.Val;
8256 // Handle cases like (unsigned long)&a + 4.
8257 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8259 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8263 // Handle cases like 4 + (unsigned long)&a
8264 if (E->getOpcode() == BO_Add &&
8265 RHSVal.isLValue() && LHSVal.isInt()) {
8267 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8271 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8272 // Handle (intptr_t)&&A - (intptr_t)&&B.
8273 if (!LHSVal.getLValueOffset().isZero() ||
8274 !RHSVal.getLValueOffset().isZero())
8276 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8277 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8278 if (!LHSExpr || !RHSExpr)
8280 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8281 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8282 if (!LHSAddrExpr || !RHSAddrExpr)
8284 // Make sure both labels come from the same function.
8285 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8286 RHSAddrExpr->getLabel()->getDeclContext())
8288 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8292 // All the remaining cases expect both operands to be an integer
8293 if (!LHSVal.isInt() || !RHSVal.isInt())
8296 // Set up the width and signedness manually, in case it can't be deduced
8297 // from the operation we're performing.
8298 // FIXME: Don't do this in the cases where we can deduce it.
8299 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8300 E->getType()->isUnsignedIntegerOrEnumerationType());
8301 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8302 RHSVal.getInt(), Value))
8304 return Success(Value, E, Result);
8307 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8308 Job &job = Queue.back();
8311 case Job::AnyExprKind: {
8312 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8313 if (shouldEnqueue(Bop)) {
8314 job.Kind = Job::BinOpKind;
8315 enqueue(Bop->getLHS());
8320 EvaluateExpr(job.E, Result);
8325 case Job::BinOpKind: {
8326 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8327 bool SuppressRHSDiags = false;
8328 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8332 if (SuppressRHSDiags)
8333 job.startSpeculativeEval(Info);
8334 job.LHSResult.swap(Result);
8335 job.Kind = Job::BinOpVisitedLHSKind;
8336 enqueue(Bop->getRHS());
8340 case Job::BinOpVisitedLHSKind: {
8341 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8344 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8350 llvm_unreachable("Invalid Job::Kind!");
8354 /// Used when we determine that we should fail, but can keep evaluating prior to
8355 /// noting that we had a failure.
8356 class DelayedNoteFailureRAII {
8361 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8362 : Info(Info), NoteFailure(NoteFailure) {}
8363 ~DelayedNoteFailureRAII() {
8365 bool ContinueAfterFailure = Info.noteFailure();
8366 (void)ContinueAfterFailure;
8367 assert(ContinueAfterFailure &&
8368 "Shouldn't have kept evaluating on failure.");
8374 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8375 // We don't call noteFailure immediately because the assignment happens after
8376 // we evaluate LHS and RHS.
8377 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8380 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8381 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8382 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8384 QualType LHSTy = E->getLHS()->getType();
8385 QualType RHSTy = E->getRHS()->getType();
8387 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8388 ComplexValue LHS, RHS;
8390 if (E->isAssignmentOp()) {
8392 EvaluateLValue(E->getLHS(), LV, Info);
8394 } else if (LHSTy->isRealFloatingType()) {
8395 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8397 LHS.makeComplexFloat();
8398 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8401 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8403 if (!LHSOK && !Info.noteFailure())
8406 if (E->getRHS()->getType()->isRealFloatingType()) {
8407 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8409 RHS.makeComplexFloat();
8410 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8411 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8414 if (LHS.isComplexFloat()) {
8415 APFloat::cmpResult CR_r =
8416 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8417 APFloat::cmpResult CR_i =
8418 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8420 if (E->getOpcode() == BO_EQ)
8421 return Success((CR_r == APFloat::cmpEqual &&
8422 CR_i == APFloat::cmpEqual), E);
8424 assert(E->getOpcode() == BO_NE &&
8425 "Invalid complex comparison.");
8426 return Success(((CR_r == APFloat::cmpGreaterThan ||
8427 CR_r == APFloat::cmpLessThan ||
8428 CR_r == APFloat::cmpUnordered) ||
8429 (CR_i == APFloat::cmpGreaterThan ||
8430 CR_i == APFloat::cmpLessThan ||
8431 CR_i == APFloat::cmpUnordered)), E);
8434 if (E->getOpcode() == BO_EQ)
8435 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8436 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8438 assert(E->getOpcode() == BO_NE &&
8439 "Invalid compex comparison.");
8440 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8441 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8446 if (LHSTy->isRealFloatingType() &&
8447 RHSTy->isRealFloatingType()) {
8448 APFloat RHS(0.0), LHS(0.0);
8450 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8451 if (!LHSOK && !Info.noteFailure())
8454 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8457 APFloat::cmpResult CR = LHS.compare(RHS);
8459 switch (E->getOpcode()) {
8461 llvm_unreachable("Invalid binary operator!");
8463 return Success(CR == APFloat::cmpLessThan, E);
8465 return Success(CR == APFloat::cmpGreaterThan, E);
8467 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8469 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8472 return Success(CR == APFloat::cmpEqual, E);
8474 return Success(CR == APFloat::cmpGreaterThan
8475 || CR == APFloat::cmpLessThan
8476 || CR == APFloat::cmpUnordered, E);
8480 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8481 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8482 LValue LHSValue, RHSValue;
8484 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8485 if (!LHSOK && !Info.noteFailure())
8488 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8491 // Reject differing bases from the normal codepath; we special-case
8492 // comparisons to null.
8493 if (!HasSameBase(LHSValue, RHSValue)) {
8494 if (E->getOpcode() == BO_Sub) {
8495 // Handle &&A - &&B.
8496 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8498 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8499 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8500 if (!LHSExpr || !RHSExpr)
8502 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8503 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8504 if (!LHSAddrExpr || !RHSAddrExpr)
8506 // Make sure both labels come from the same function.
8507 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8508 RHSAddrExpr->getLabel()->getDeclContext())
8510 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8512 // Inequalities and subtractions between unrelated pointers have
8513 // unspecified or undefined behavior.
8514 if (!E->isEqualityOp())
8516 // A constant address may compare equal to the address of a symbol.
8517 // The one exception is that address of an object cannot compare equal
8518 // to a null pointer constant.
8519 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8520 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8522 // It's implementation-defined whether distinct literals will have
8523 // distinct addresses. In clang, the result of such a comparison is
8524 // unspecified, so it is not a constant expression. However, we do know
8525 // that the address of a literal will be non-null.
8526 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8527 LHSValue.Base && RHSValue.Base)
8529 // We can't tell whether weak symbols will end up pointing to the same
8531 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8533 // We can't compare the address of the start of one object with the
8534 // past-the-end address of another object, per C++ DR1652.
8535 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8536 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8537 (RHSValue.Base && RHSValue.Offset.isZero() &&
8538 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8540 // We can't tell whether an object is at the same address as another
8541 // zero sized object.
8542 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8543 (LHSValue.Base && isZeroSized(RHSValue)))
8545 // Pointers with different bases cannot represent the same object.
8546 return Success(E->getOpcode() == BO_NE, E);
8549 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8550 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8552 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8553 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8555 if (E->getOpcode() == BO_Sub) {
8556 // C++11 [expr.add]p6:
8557 // Unless both pointers point to elements of the same array object, or
8558 // one past the last element of the array object, the behavior is
8560 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8561 !AreElementsOfSameArray(getType(LHSValue.Base),
8562 LHSDesignator, RHSDesignator))
8563 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8565 QualType Type = E->getLHS()->getType();
8566 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8568 CharUnits ElementSize;
8569 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8572 // As an extension, a type may have zero size (empty struct or union in
8573 // C, array of zero length). Pointer subtraction in such cases has
8574 // undefined behavior, so is not constant.
8575 if (ElementSize.isZero()) {
8576 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8581 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8582 // and produce incorrect results when it overflows. Such behavior
8583 // appears to be non-conforming, but is common, so perhaps we should
8584 // assume the standard intended for such cases to be undefined behavior
8585 // and check for them.
8587 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8588 // overflow in the final conversion to ptrdiff_t.
8590 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8592 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8594 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8595 APSInt TrueResult = (LHS - RHS) / ElemSize;
8596 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8598 if (Result.extend(65) != TrueResult &&
8599 !HandleOverflow(Info, E, TrueResult, E->getType()))
8601 return Success(Result, E);
8604 // C++11 [expr.rel]p3:
8605 // Pointers to void (after pointer conversions) can be compared, with a
8606 // result defined as follows: If both pointers represent the same
8607 // address or are both the null pointer value, the result is true if the
8608 // operator is <= or >= and false otherwise; otherwise the result is
8610 // We interpret this as applying to pointers to *cv* void.
8611 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8612 E->isRelationalOp())
8613 CCEDiag(E, diag::note_constexpr_void_comparison);
8615 // C++11 [expr.rel]p2:
8616 // - If two pointers point to non-static data members of the same object,
8617 // or to subobjects or array elements fo such members, recursively, the
8618 // pointer to the later declared member compares greater provided the
8619 // two members have the same access control and provided their class is
8622 // - Otherwise pointer comparisons are unspecified.
8623 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8624 E->isRelationalOp()) {
8627 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8628 RHSDesignator, WasArrayIndex);
8629 // At the point where the designators diverge, the comparison has a
8630 // specified value if:
8631 // - we are comparing array indices
8632 // - we are comparing fields of a union, or fields with the same access
8633 // Otherwise, the result is unspecified and thus the comparison is not a
8634 // constant expression.
8635 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8636 Mismatch < RHSDesignator.Entries.size()) {
8637 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8638 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8640 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8642 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8643 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8644 << RF->getParent() << RF;
8646 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8647 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8648 << LF->getParent() << LF;
8649 else if (!LF->getParent()->isUnion() &&
8650 LF->getAccess() != RF->getAccess())
8651 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8652 << LF << LF->getAccess() << RF << RF->getAccess()
8657 // The comparison here must be unsigned, and performed with the same
8658 // width as the pointer.
8659 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8660 uint64_t CompareLHS = LHSOffset.getQuantity();
8661 uint64_t CompareRHS = RHSOffset.getQuantity();
8662 assert(PtrSize <= 64 && "Unexpected pointer width");
8663 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8667 // If there is a base and this is a relational operator, we can only
8668 // compare pointers within the object in question; otherwise, the result
8669 // depends on where the object is located in memory.
8670 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8671 QualType BaseTy = getType(LHSValue.Base);
8672 if (BaseTy->isIncompleteType())
8674 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8675 uint64_t OffsetLimit = Size.getQuantity();
8676 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8680 switch (E->getOpcode()) {
8681 default: llvm_unreachable("missing comparison operator");
8682 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8683 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8684 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8685 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8686 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8687 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8692 if (LHSTy->isMemberPointerType()) {
8693 assert(E->isEqualityOp() && "unexpected member pointer operation");
8694 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8696 MemberPtr LHSValue, RHSValue;
8698 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8699 if (!LHSOK && !Info.noteFailure())
8702 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8705 // C++11 [expr.eq]p2:
8706 // If both operands are null, they compare equal. Otherwise if only one is
8707 // null, they compare unequal.
8708 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8709 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8710 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8713 // Otherwise if either is a pointer to a virtual member function, the
8714 // result is unspecified.
8715 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8716 if (MD->isVirtual())
8717 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8718 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8719 if (MD->isVirtual())
8720 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8722 // Otherwise they compare equal if and only if they would refer to the
8723 // same member of the same most derived object or the same subobject if
8724 // they were dereferenced with a hypothetical object of the associated
8726 bool Equal = LHSValue == RHSValue;
8727 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8730 if (LHSTy->isNullPtrType()) {
8731 assert(E->isComparisonOp() && "unexpected nullptr operation");
8732 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8733 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8734 // are compared, the result is true of the operator is <=, >= or ==, and
8736 BinaryOperator::Opcode Opcode = E->getOpcode();
8737 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8740 assert((!LHSTy->isIntegralOrEnumerationType() ||
8741 !RHSTy->isIntegralOrEnumerationType()) &&
8742 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8743 // We can't continue from here for non-integral types.
8744 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8747 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8748 /// a result as the expression's type.
8749 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8750 const UnaryExprOrTypeTraitExpr *E) {
8751 switch(E->getKind()) {
8752 case UETT_AlignOf: {
8753 if (E->isArgumentType())
8754 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8756 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8759 case UETT_VecStep: {
8760 QualType Ty = E->getTypeOfArgument();
8762 if (Ty->isVectorType()) {
8763 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8765 // The vec_step built-in functions that take a 3-component
8766 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8770 return Success(n, E);
8772 return Success(1, E);
8776 QualType SrcTy = E->getTypeOfArgument();
8777 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8778 // the result is the size of the referenced type."
8779 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8780 SrcTy = Ref->getPointeeType();
8783 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8785 return Success(Sizeof, E);
8787 case UETT_OpenMPRequiredSimdAlign:
8788 assert(E->isArgumentType());
8790 Info.Ctx.toCharUnitsFromBits(
8791 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8796 llvm_unreachable("unknown expr/type trait");
8799 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8801 unsigned n = OOE->getNumComponents();
8804 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8805 for (unsigned i = 0; i != n; ++i) {
8806 OffsetOfNode ON = OOE->getComponent(i);
8807 switch (ON.getKind()) {
8808 case OffsetOfNode::Array: {
8809 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8811 if (!EvaluateInteger(Idx, IdxResult, Info))
8813 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8816 CurrentType = AT->getElementType();
8817 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8818 Result += IdxResult.getSExtValue() * ElementSize;
8822 case OffsetOfNode::Field: {
8823 FieldDecl *MemberDecl = ON.getField();
8824 const RecordType *RT = CurrentType->getAs<RecordType>();
8827 RecordDecl *RD = RT->getDecl();
8828 if (RD->isInvalidDecl()) return false;
8829 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8830 unsigned i = MemberDecl->getFieldIndex();
8831 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8832 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8833 CurrentType = MemberDecl->getType().getNonReferenceType();
8837 case OffsetOfNode::Identifier:
8838 llvm_unreachable("dependent __builtin_offsetof");
8840 case OffsetOfNode::Base: {
8841 CXXBaseSpecifier *BaseSpec = ON.getBase();
8842 if (BaseSpec->isVirtual())
8845 // Find the layout of the class whose base we are looking into.
8846 const RecordType *RT = CurrentType->getAs<RecordType>();
8849 RecordDecl *RD = RT->getDecl();
8850 if (RD->isInvalidDecl()) return false;
8851 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8853 // Find the base class itself.
8854 CurrentType = BaseSpec->getType();
8855 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8859 // Add the offset to the base.
8860 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8865 return Success(Result, OOE);
8868 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8869 switch (E->getOpcode()) {
8871 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8875 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8876 // If so, we could clear the diagnostic ID.
8877 return Visit(E->getSubExpr());
8879 // The result is just the value.
8880 return Visit(E->getSubExpr());
8882 if (!Visit(E->getSubExpr()))
8884 if (!Result.isInt()) return Error(E);
8885 const APSInt &Value = Result.getInt();
8886 if (Value.isSigned() && Value.isMinSignedValue() &&
8887 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8890 return Success(-Value, E);
8893 if (!Visit(E->getSubExpr()))
8895 if (!Result.isInt()) return Error(E);
8896 return Success(~Result.getInt(), E);
8900 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8902 return Success(!bres, E);
8907 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8908 /// result type is integer.
8909 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8910 const Expr *SubExpr = E->getSubExpr();
8911 QualType DestType = E->getType();
8912 QualType SrcType = SubExpr->getType();
8914 switch (E->getCastKind()) {
8915 case CK_BaseToDerived:
8916 case CK_DerivedToBase:
8917 case CK_UncheckedDerivedToBase:
8920 case CK_ArrayToPointerDecay:
8921 case CK_FunctionToPointerDecay:
8922 case CK_NullToPointer:
8923 case CK_NullToMemberPointer:
8924 case CK_BaseToDerivedMemberPointer:
8925 case CK_DerivedToBaseMemberPointer:
8926 case CK_ReinterpretMemberPointer:
8927 case CK_ConstructorConversion:
8928 case CK_IntegralToPointer:
8930 case CK_VectorSplat:
8931 case CK_IntegralToFloating:
8932 case CK_FloatingCast:
8933 case CK_CPointerToObjCPointerCast:
8934 case CK_BlockPointerToObjCPointerCast:
8935 case CK_AnyPointerToBlockPointerCast:
8936 case CK_ObjCObjectLValueCast:
8937 case CK_FloatingRealToComplex:
8938 case CK_FloatingComplexToReal:
8939 case CK_FloatingComplexCast:
8940 case CK_FloatingComplexToIntegralComplex:
8941 case CK_IntegralRealToComplex:
8942 case CK_IntegralComplexCast:
8943 case CK_IntegralComplexToFloatingComplex:
8944 case CK_BuiltinFnToFnPtr:
8945 case CK_ZeroToOCLEvent:
8946 case CK_ZeroToOCLQueue:
8947 case CK_NonAtomicToAtomic:
8948 case CK_AddressSpaceConversion:
8949 case CK_IntToOCLSampler:
8950 llvm_unreachable("invalid cast kind for integral value");
8954 case CK_LValueBitCast:
8955 case CK_ARCProduceObject:
8956 case CK_ARCConsumeObject:
8957 case CK_ARCReclaimReturnedObject:
8958 case CK_ARCExtendBlockObject:
8959 case CK_CopyAndAutoreleaseBlockObject:
8962 case CK_UserDefinedConversion:
8963 case CK_LValueToRValue:
8964 case CK_AtomicToNonAtomic:
8966 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8968 case CK_MemberPointerToBoolean:
8969 case CK_PointerToBoolean:
8970 case CK_IntegralToBoolean:
8971 case CK_FloatingToBoolean:
8972 case CK_BooleanToSignedIntegral:
8973 case CK_FloatingComplexToBoolean:
8974 case CK_IntegralComplexToBoolean: {
8976 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8978 uint64_t IntResult = BoolResult;
8979 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8980 IntResult = (uint64_t)-1;
8981 return Success(IntResult, E);
8984 case CK_IntegralCast: {
8985 if (!Visit(SubExpr))
8988 if (!Result.isInt()) {
8989 // Allow casts of address-of-label differences if they are no-ops
8990 // or narrowing. (The narrowing case isn't actually guaranteed to
8991 // be constant-evaluatable except in some narrow cases which are hard
8992 // to detect here. We let it through on the assumption the user knows
8993 // what they are doing.)
8994 if (Result.isAddrLabelDiff())
8995 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8996 // Only allow casts of lvalues if they are lossless.
8997 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9000 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9001 Result.getInt()), E);
9004 case CK_PointerToIntegral: {
9005 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9008 if (!EvaluatePointer(SubExpr, LV, Info))
9011 if (LV.getLValueBase()) {
9012 // Only allow based lvalue casts if they are lossless.
9013 // FIXME: Allow a larger integer size than the pointer size, and allow
9014 // narrowing back down to pointer width in subsequent integral casts.
9015 // FIXME: Check integer type's active bits, not its type size.
9016 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9019 LV.Designator.setInvalid();
9020 LV.moveInto(Result);
9025 if (LV.isNullPointer())
9026 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9028 V = LV.getLValueOffset().getQuantity();
9030 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9031 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9034 case CK_IntegralComplexToReal: {
9036 if (!EvaluateComplex(SubExpr, C, Info))
9038 return Success(C.getComplexIntReal(), E);
9041 case CK_FloatingToIntegral: {
9043 if (!EvaluateFloat(SubExpr, F, Info))
9047 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9049 return Success(Value, E);
9053 llvm_unreachable("unknown cast resulting in integral value");
9056 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9057 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9059 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9061 if (!LV.isComplexInt())
9063 return Success(LV.getComplexIntReal(), E);
9066 return Visit(E->getSubExpr());
9069 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9070 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9072 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9074 if (!LV.isComplexInt())
9076 return Success(LV.getComplexIntImag(), E);
9079 VisitIgnoredValue(E->getSubExpr());
9080 return Success(0, E);
9083 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9084 return Success(E->getPackLength(), E);
9087 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9088 return Success(E->getValue(), E);
9091 //===----------------------------------------------------------------------===//
9093 //===----------------------------------------------------------------------===//
9096 class FloatExprEvaluator
9097 : public ExprEvaluatorBase<FloatExprEvaluator> {
9100 FloatExprEvaluator(EvalInfo &info, APFloat &result)
9101 : ExprEvaluatorBaseTy(info), Result(result) {}
9103 bool Success(const APValue &V, const Expr *e) {
9104 Result = V.getFloat();
9108 bool ZeroInitialization(const Expr *E) {
9109 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9113 bool VisitCallExpr(const CallExpr *E);
9115 bool VisitUnaryOperator(const UnaryOperator *E);
9116 bool VisitBinaryOperator(const BinaryOperator *E);
9117 bool VisitFloatingLiteral(const FloatingLiteral *E);
9118 bool VisitCastExpr(const CastExpr *E);
9120 bool VisitUnaryReal(const UnaryOperator *E);
9121 bool VisitUnaryImag(const UnaryOperator *E);
9123 // FIXME: Missing: array subscript of vector, member of vector
9125 } // end anonymous namespace
9127 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9128 assert(E->isRValue() && E->getType()->isRealFloatingType());
9129 return FloatExprEvaluator(Info, Result).Visit(E);
9132 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9136 llvm::APFloat &Result) {
9137 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9138 if (!S) return false;
9140 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9144 // Treat empty strings as if they were zero.
9145 if (S->getString().empty())
9146 fill = llvm::APInt(32, 0);
9147 else if (S->getString().getAsInteger(0, fill))
9150 if (Context.getTargetInfo().isNan2008()) {
9152 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9154 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9156 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9157 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9158 // a different encoding to what became a standard in 2008, and for pre-
9159 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9160 // sNaN. This is now known as "legacy NaN" encoding.
9162 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9164 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9170 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9171 switch (E->getBuiltinCallee()) {
9173 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9175 case Builtin::BI__builtin_huge_val:
9176 case Builtin::BI__builtin_huge_valf:
9177 case Builtin::BI__builtin_huge_vall:
9178 case Builtin::BI__builtin_inf:
9179 case Builtin::BI__builtin_inff:
9180 case Builtin::BI__builtin_infl: {
9181 const llvm::fltSemantics &Sem =
9182 Info.Ctx.getFloatTypeSemantics(E->getType());
9183 Result = llvm::APFloat::getInf(Sem);
9187 case Builtin::BI__builtin_nans:
9188 case Builtin::BI__builtin_nansf:
9189 case Builtin::BI__builtin_nansl:
9190 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9195 case Builtin::BI__builtin_nan:
9196 case Builtin::BI__builtin_nanf:
9197 case Builtin::BI__builtin_nanl:
9198 // If this is __builtin_nan() turn this into a nan, otherwise we
9199 // can't constant fold it.
9200 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9205 case Builtin::BI__builtin_fabs:
9206 case Builtin::BI__builtin_fabsf:
9207 case Builtin::BI__builtin_fabsl:
9208 if (!EvaluateFloat(E->getArg(0), Result, Info))
9211 if (Result.isNegative())
9212 Result.changeSign();
9215 // FIXME: Builtin::BI__builtin_powi
9216 // FIXME: Builtin::BI__builtin_powif
9217 // FIXME: Builtin::BI__builtin_powil
9219 case Builtin::BI__builtin_copysign:
9220 case Builtin::BI__builtin_copysignf:
9221 case Builtin::BI__builtin_copysignl: {
9223 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9224 !EvaluateFloat(E->getArg(1), RHS, Info))
9226 Result.copySign(RHS);
9232 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9233 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9235 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9237 Result = CV.FloatReal;
9241 return Visit(E->getSubExpr());
9244 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9245 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9247 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9249 Result = CV.FloatImag;
9253 VisitIgnoredValue(E->getSubExpr());
9254 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9255 Result = llvm::APFloat::getZero(Sem);
9259 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9260 switch (E->getOpcode()) {
9261 default: return Error(E);
9263 return EvaluateFloat(E->getSubExpr(), Result, Info);
9265 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9267 Result.changeSign();
9272 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9273 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9274 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9277 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9278 if (!LHSOK && !Info.noteFailure())
9280 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9281 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9284 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9285 Result = E->getValue();
9289 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9290 const Expr* SubExpr = E->getSubExpr();
9292 switch (E->getCastKind()) {
9294 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9296 case CK_IntegralToFloating: {
9298 return EvaluateInteger(SubExpr, IntResult, Info) &&
9299 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9300 E->getType(), Result);
9303 case CK_FloatingCast: {
9304 if (!Visit(SubExpr))
9306 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9310 case CK_FloatingComplexToReal: {
9312 if (!EvaluateComplex(SubExpr, V, Info))
9314 Result = V.getComplexFloatReal();
9320 //===----------------------------------------------------------------------===//
9321 // Complex Evaluation (for float and integer)
9322 //===----------------------------------------------------------------------===//
9325 class ComplexExprEvaluator
9326 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9327 ComplexValue &Result;
9330 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9331 : ExprEvaluatorBaseTy(info), Result(Result) {}
9333 bool Success(const APValue &V, const Expr *e) {
9338 bool ZeroInitialization(const Expr *E);
9340 //===--------------------------------------------------------------------===//
9342 //===--------------------------------------------------------------------===//
9344 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9345 bool VisitCastExpr(const CastExpr *E);
9346 bool VisitBinaryOperator(const BinaryOperator *E);
9347 bool VisitUnaryOperator(const UnaryOperator *E);
9348 bool VisitInitListExpr(const InitListExpr *E);
9350 } // end anonymous namespace
9352 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9354 assert(E->isRValue() && E->getType()->isAnyComplexType());
9355 return ComplexExprEvaluator(Info, Result).Visit(E);
9358 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9359 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9360 if (ElemTy->isRealFloatingType()) {
9361 Result.makeComplexFloat();
9362 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9363 Result.FloatReal = Zero;
9364 Result.FloatImag = Zero;
9366 Result.makeComplexInt();
9367 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9368 Result.IntReal = Zero;
9369 Result.IntImag = Zero;
9374 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9375 const Expr* SubExpr = E->getSubExpr();
9377 if (SubExpr->getType()->isRealFloatingType()) {
9378 Result.makeComplexFloat();
9379 APFloat &Imag = Result.FloatImag;
9380 if (!EvaluateFloat(SubExpr, Imag, Info))
9383 Result.FloatReal = APFloat(Imag.getSemantics());
9386 assert(SubExpr->getType()->isIntegerType() &&
9387 "Unexpected imaginary literal.");
9389 Result.makeComplexInt();
9390 APSInt &Imag = Result.IntImag;
9391 if (!EvaluateInteger(SubExpr, Imag, Info))
9394 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9399 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9401 switch (E->getCastKind()) {
9403 case CK_BaseToDerived:
9404 case CK_DerivedToBase:
9405 case CK_UncheckedDerivedToBase:
9408 case CK_ArrayToPointerDecay:
9409 case CK_FunctionToPointerDecay:
9410 case CK_NullToPointer:
9411 case CK_NullToMemberPointer:
9412 case CK_BaseToDerivedMemberPointer:
9413 case CK_DerivedToBaseMemberPointer:
9414 case CK_MemberPointerToBoolean:
9415 case CK_ReinterpretMemberPointer:
9416 case CK_ConstructorConversion:
9417 case CK_IntegralToPointer:
9418 case CK_PointerToIntegral:
9419 case CK_PointerToBoolean:
9421 case CK_VectorSplat:
9422 case CK_IntegralCast:
9423 case CK_BooleanToSignedIntegral:
9424 case CK_IntegralToBoolean:
9425 case CK_IntegralToFloating:
9426 case CK_FloatingToIntegral:
9427 case CK_FloatingToBoolean:
9428 case CK_FloatingCast:
9429 case CK_CPointerToObjCPointerCast:
9430 case CK_BlockPointerToObjCPointerCast:
9431 case CK_AnyPointerToBlockPointerCast:
9432 case CK_ObjCObjectLValueCast:
9433 case CK_FloatingComplexToReal:
9434 case CK_FloatingComplexToBoolean:
9435 case CK_IntegralComplexToReal:
9436 case CK_IntegralComplexToBoolean:
9437 case CK_ARCProduceObject:
9438 case CK_ARCConsumeObject:
9439 case CK_ARCReclaimReturnedObject:
9440 case CK_ARCExtendBlockObject:
9441 case CK_CopyAndAutoreleaseBlockObject:
9442 case CK_BuiltinFnToFnPtr:
9443 case CK_ZeroToOCLEvent:
9444 case CK_ZeroToOCLQueue:
9445 case CK_NonAtomicToAtomic:
9446 case CK_AddressSpaceConversion:
9447 case CK_IntToOCLSampler:
9448 llvm_unreachable("invalid cast kind for complex value");
9450 case CK_LValueToRValue:
9451 case CK_AtomicToNonAtomic:
9453 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9456 case CK_LValueBitCast:
9457 case CK_UserDefinedConversion:
9460 case CK_FloatingRealToComplex: {
9461 APFloat &Real = Result.FloatReal;
9462 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9465 Result.makeComplexFloat();
9466 Result.FloatImag = APFloat(Real.getSemantics());
9470 case CK_FloatingComplexCast: {
9471 if (!Visit(E->getSubExpr()))
9474 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9476 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9478 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9479 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9482 case CK_FloatingComplexToIntegralComplex: {
9483 if (!Visit(E->getSubExpr()))
9486 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9488 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9489 Result.makeComplexInt();
9490 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9491 To, Result.IntReal) &&
9492 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9493 To, Result.IntImag);
9496 case CK_IntegralRealToComplex: {
9497 APSInt &Real = Result.IntReal;
9498 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9501 Result.makeComplexInt();
9502 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9506 case CK_IntegralComplexCast: {
9507 if (!Visit(E->getSubExpr()))
9510 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9512 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9514 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9515 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9519 case CK_IntegralComplexToFloatingComplex: {
9520 if (!Visit(E->getSubExpr()))
9523 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9525 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9526 Result.makeComplexFloat();
9527 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9528 To, Result.FloatReal) &&
9529 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9530 To, Result.FloatImag);
9534 llvm_unreachable("unknown cast resulting in complex value");
9537 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9538 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9539 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9541 // Track whether the LHS or RHS is real at the type system level. When this is
9542 // the case we can simplify our evaluation strategy.
9543 bool LHSReal = false, RHSReal = false;
9546 if (E->getLHS()->getType()->isRealFloatingType()) {
9548 APFloat &Real = Result.FloatReal;
9549 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9551 Result.makeComplexFloat();
9552 Result.FloatImag = APFloat(Real.getSemantics());
9555 LHSOK = Visit(E->getLHS());
9557 if (!LHSOK && !Info.noteFailure())
9561 if (E->getRHS()->getType()->isRealFloatingType()) {
9563 APFloat &Real = RHS.FloatReal;
9564 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9566 RHS.makeComplexFloat();
9567 RHS.FloatImag = APFloat(Real.getSemantics());
9568 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9571 assert(!(LHSReal && RHSReal) &&
9572 "Cannot have both operands of a complex operation be real.");
9573 switch (E->getOpcode()) {
9574 default: return Error(E);
9576 if (Result.isComplexFloat()) {
9577 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9578 APFloat::rmNearestTiesToEven);
9580 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9582 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9583 APFloat::rmNearestTiesToEven);
9585 Result.getComplexIntReal() += RHS.getComplexIntReal();
9586 Result.getComplexIntImag() += RHS.getComplexIntImag();
9590 if (Result.isComplexFloat()) {
9591 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9592 APFloat::rmNearestTiesToEven);
9594 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9595 Result.getComplexFloatImag().changeSign();
9596 } else if (!RHSReal) {
9597 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9598 APFloat::rmNearestTiesToEven);
9601 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9602 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9606 if (Result.isComplexFloat()) {
9607 // This is an implementation of complex multiplication according to the
9608 // constraints laid out in C11 Annex G. The implemention uses the
9609 // following naming scheme:
9610 // (a + ib) * (c + id)
9611 ComplexValue LHS = Result;
9612 APFloat &A = LHS.getComplexFloatReal();
9613 APFloat &B = LHS.getComplexFloatImag();
9614 APFloat &C = RHS.getComplexFloatReal();
9615 APFloat &D = RHS.getComplexFloatImag();
9616 APFloat &ResR = Result.getComplexFloatReal();
9617 APFloat &ResI = Result.getComplexFloatImag();
9619 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9622 } else if (RHSReal) {
9626 // In the fully general case, we need to handle NaNs and infinities
9634 if (ResR.isNaN() && ResI.isNaN()) {
9635 bool Recalc = false;
9636 if (A.isInfinity() || B.isInfinity()) {
9637 A = APFloat::copySign(
9638 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9639 B = APFloat::copySign(
9640 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9642 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9644 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9647 if (C.isInfinity() || D.isInfinity()) {
9648 C = APFloat::copySign(
9649 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9650 D = APFloat::copySign(
9651 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9653 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9655 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9658 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9659 AD.isInfinity() || BC.isInfinity())) {
9661 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9663 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9665 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9667 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9671 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9672 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9677 ComplexValue LHS = Result;
9678 Result.getComplexIntReal() =
9679 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9680 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9681 Result.getComplexIntImag() =
9682 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9683 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9687 if (Result.isComplexFloat()) {
9688 // This is an implementation of complex division according to the
9689 // constraints laid out in C11 Annex G. The implemention uses the
9690 // following naming scheme:
9691 // (a + ib) / (c + id)
9692 ComplexValue LHS = Result;
9693 APFloat &A = LHS.getComplexFloatReal();
9694 APFloat &B = LHS.getComplexFloatImag();
9695 APFloat &C = RHS.getComplexFloatReal();
9696 APFloat &D = RHS.getComplexFloatImag();
9697 APFloat &ResR = Result.getComplexFloatReal();
9698 APFloat &ResI = Result.getComplexFloatImag();
9704 // No real optimizations we can do here, stub out with zero.
9705 B = APFloat::getZero(A.getSemantics());
9708 APFloat MaxCD = maxnum(abs(C), abs(D));
9709 if (MaxCD.isFinite()) {
9710 DenomLogB = ilogb(MaxCD);
9711 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9712 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9714 APFloat Denom = C * C + D * D;
9715 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9716 APFloat::rmNearestTiesToEven);
9717 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9718 APFloat::rmNearestTiesToEven);
9719 if (ResR.isNaN() && ResI.isNaN()) {
9720 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9721 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9722 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9723 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9725 A = APFloat::copySign(
9726 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9727 B = APFloat::copySign(
9728 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9729 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9730 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9731 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9732 C = APFloat::copySign(
9733 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9734 D = APFloat::copySign(
9735 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9736 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9737 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9742 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9743 return Error(E, diag::note_expr_divide_by_zero);
9745 ComplexValue LHS = Result;
9746 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9747 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9748 Result.getComplexIntReal() =
9749 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9750 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9751 Result.getComplexIntImag() =
9752 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9753 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9761 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9762 // Get the operand value into 'Result'.
9763 if (!Visit(E->getSubExpr()))
9766 switch (E->getOpcode()) {
9772 // The result is always just the subexpr.
9775 if (Result.isComplexFloat()) {
9776 Result.getComplexFloatReal().changeSign();
9777 Result.getComplexFloatImag().changeSign();
9780 Result.getComplexIntReal() = -Result.getComplexIntReal();
9781 Result.getComplexIntImag() = -Result.getComplexIntImag();
9785 if (Result.isComplexFloat())
9786 Result.getComplexFloatImag().changeSign();
9788 Result.getComplexIntImag() = -Result.getComplexIntImag();
9793 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9794 if (E->getNumInits() == 2) {
9795 if (E->getType()->isComplexType()) {
9796 Result.makeComplexFloat();
9797 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9799 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9802 Result.makeComplexInt();
9803 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9805 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9810 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9813 //===----------------------------------------------------------------------===//
9814 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9815 // implicit conversion.
9816 //===----------------------------------------------------------------------===//
9819 class AtomicExprEvaluator :
9820 public ExprEvaluatorBase<AtomicExprEvaluator> {
9824 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9825 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9827 bool Success(const APValue &V, const Expr *E) {
9832 bool ZeroInitialization(const Expr *E) {
9833 ImplicitValueInitExpr VIE(
9834 E->getType()->castAs<AtomicType>()->getValueType());
9835 // For atomic-qualified class (and array) types in C++, initialize the
9836 // _Atomic-wrapped subobject directly, in-place.
9837 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9838 : Evaluate(Result, Info, &VIE);
9841 bool VisitCastExpr(const CastExpr *E) {
9842 switch (E->getCastKind()) {
9844 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9845 case CK_NonAtomicToAtomic:
9846 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9847 : Evaluate(Result, Info, E->getSubExpr());
9851 } // end anonymous namespace
9853 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9855 assert(E->isRValue() && E->getType()->isAtomicType());
9856 return AtomicExprEvaluator(Info, This, Result).Visit(E);
9859 //===----------------------------------------------------------------------===//
9860 // Void expression evaluation, primarily for a cast to void on the LHS of a
9862 //===----------------------------------------------------------------------===//
9865 class VoidExprEvaluator
9866 : public ExprEvaluatorBase<VoidExprEvaluator> {
9868 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9870 bool Success(const APValue &V, const Expr *e) { return true; }
9872 bool ZeroInitialization(const Expr *E) { return true; }
9874 bool VisitCastExpr(const CastExpr *E) {
9875 switch (E->getCastKind()) {
9877 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9879 VisitIgnoredValue(E->getSubExpr());
9884 bool VisitCallExpr(const CallExpr *E) {
9885 switch (E->getBuiltinCallee()) {
9887 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9888 case Builtin::BI__assume:
9889 case Builtin::BI__builtin_assume:
9890 // The argument is not evaluated!
9895 } // end anonymous namespace
9897 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9898 assert(E->isRValue() && E->getType()->isVoidType());
9899 return VoidExprEvaluator(Info).Visit(E);
9902 //===----------------------------------------------------------------------===//
9903 // Top level Expr::EvaluateAsRValue method.
9904 //===----------------------------------------------------------------------===//
9906 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9907 // In C, function designators are not lvalues, but we evaluate them as if they
9909 QualType T = E->getType();
9910 if (E->isGLValue() || T->isFunctionType()) {
9912 if (!EvaluateLValue(E, LV, Info))
9914 LV.moveInto(Result);
9915 } else if (T->isVectorType()) {
9916 if (!EvaluateVector(E, Result, Info))
9918 } else if (T->isIntegralOrEnumerationType()) {
9919 if (!IntExprEvaluator(Info, Result).Visit(E))
9921 } else if (T->hasPointerRepresentation()) {
9923 if (!EvaluatePointer(E, LV, Info))
9925 LV.moveInto(Result);
9926 } else if (T->isRealFloatingType()) {
9927 llvm::APFloat F(0.0);
9928 if (!EvaluateFloat(E, F, Info))
9930 Result = APValue(F);
9931 } else if (T->isAnyComplexType()) {
9933 if (!EvaluateComplex(E, C, Info))
9936 } else if (T->isMemberPointerType()) {
9938 if (!EvaluateMemberPointer(E, P, Info))
9942 } else if (T->isArrayType()) {
9944 LV.set(E, Info.CurrentCall->Index);
9945 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9946 if (!EvaluateArray(E, LV, Value, Info))
9949 } else if (T->isRecordType()) {
9951 LV.set(E, Info.CurrentCall->Index);
9952 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9953 if (!EvaluateRecord(E, LV, Value, Info))
9956 } else if (T->isVoidType()) {
9957 if (!Info.getLangOpts().CPlusPlus11)
9958 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9960 if (!EvaluateVoid(E, Info))
9962 } else if (T->isAtomicType()) {
9963 QualType Unqual = T.getAtomicUnqualifiedType();
9964 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9966 LV.set(E, Info.CurrentCall->Index);
9967 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9968 if (!EvaluateAtomic(E, &LV, Value, Info))
9971 if (!EvaluateAtomic(E, nullptr, Result, Info))
9974 } else if (Info.getLangOpts().CPlusPlus11) {
9975 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9978 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9985 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9986 /// cases, the in-place evaluation is essential, since later initializers for
9987 /// an object can indirectly refer to subobjects which were initialized earlier.
9988 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9989 const Expr *E, bool AllowNonLiteralTypes) {
9990 assert(!E->isValueDependent());
9992 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9995 if (E->isRValue()) {
9996 // Evaluate arrays and record types in-place, so that later initializers can
9997 // refer to earlier-initialized members of the object.
9998 QualType T = E->getType();
9999 if (T->isArrayType())
10000 return EvaluateArray(E, This, Result, Info);
10001 else if (T->isRecordType())
10002 return EvaluateRecord(E, This, Result, Info);
10003 else if (T->isAtomicType()) {
10004 QualType Unqual = T.getAtomicUnqualifiedType();
10005 if (Unqual->isArrayType() || Unqual->isRecordType())
10006 return EvaluateAtomic(E, &This, Result, Info);
10010 // For any other type, in-place evaluation is unimportant.
10011 return Evaluate(Result, Info, E);
10014 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10015 /// lvalue-to-rvalue cast if it is an lvalue.
10016 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10017 if (E->getType().isNull())
10020 if (!CheckLiteralType(Info, E))
10023 if (!::Evaluate(Result, Info, E))
10026 if (E->isGLValue()) {
10028 LV.setFrom(Info.Ctx, Result);
10029 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10033 // Check this core constant expression is a constant expression.
10034 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10037 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10038 const ASTContext &Ctx, bool &IsConst) {
10039 // Fast-path evaluations of integer literals, since we sometimes see files
10040 // containing vast quantities of these.
10041 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10042 Result.Val = APValue(APSInt(L->getValue(),
10043 L->getType()->isUnsignedIntegerType()));
10048 // This case should be rare, but we need to check it before we check on
10050 if (Exp->getType().isNull()) {
10055 // FIXME: Evaluating values of large array and record types can cause
10056 // performance problems. Only do so in C++11 for now.
10057 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10058 Exp->getType()->isRecordType()) &&
10059 !Ctx.getLangOpts().CPlusPlus11) {
10067 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10068 /// any crazy technique (that has nothing to do with language standards) that
10069 /// we want to. If this function returns true, it returns the folded constant
10070 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10071 /// will be applied to the result.
10072 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
10074 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
10077 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10078 return ::EvaluateAsRValue(Info, this, Result.Val);
10081 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10082 const ASTContext &Ctx) const {
10083 EvalResult Scratch;
10084 return EvaluateAsRValue(Scratch, Ctx) &&
10085 HandleConversionToBool(Scratch.Val, Result);
10088 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10089 Expr::SideEffectsKind SEK) {
10090 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10091 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10094 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10095 SideEffectsKind AllowSideEffects) const {
10096 if (!getType()->isIntegralOrEnumerationType())
10099 EvalResult ExprResult;
10100 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10101 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10104 Result = ExprResult.Val.getInt();
10108 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10109 SideEffectsKind AllowSideEffects) const {
10110 if (!getType()->isRealFloatingType())
10113 EvalResult ExprResult;
10114 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10115 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10118 Result = ExprResult.Val.getFloat();
10122 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10123 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10126 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10127 !CheckLValueConstantExpression(Info, getExprLoc(),
10128 Ctx.getLValueReferenceType(getType()), LV))
10131 LV.moveInto(Result.Val);
10135 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10137 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10138 // FIXME: Evaluating initializers for large array and record types can cause
10139 // performance problems. Only do so in C++11 for now.
10140 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10141 !Ctx.getLangOpts().CPlusPlus11)
10144 Expr::EvalStatus EStatus;
10145 EStatus.Diag = &Notes;
10147 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10148 ? EvalInfo::EM_ConstantExpression
10149 : EvalInfo::EM_ConstantFold);
10150 InitInfo.setEvaluatingDecl(VD, Value);
10155 // C++11 [basic.start.init]p2:
10156 // Variables with static storage duration or thread storage duration shall be
10157 // zero-initialized before any other initialization takes place.
10158 // This behavior is not present in C.
10159 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10160 !VD->getType()->isReferenceType()) {
10161 ImplicitValueInitExpr VIE(VD->getType());
10162 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10163 /*AllowNonLiteralTypes=*/true))
10167 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10168 /*AllowNonLiteralTypes=*/true) ||
10169 EStatus.HasSideEffects)
10172 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10176 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10177 /// constant folded, but discard the result.
10178 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10180 return EvaluateAsRValue(Result, Ctx) &&
10181 !hasUnacceptableSideEffect(Result, SEK);
10184 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10185 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10186 EvalResult EvalResult;
10187 EvalResult.Diag = Diag;
10188 bool Result = EvaluateAsRValue(EvalResult, Ctx);
10190 assert(Result && "Could not evaluate expression");
10191 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10193 return EvalResult.Val.getInt();
10196 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10198 EvalResult EvalResult;
10199 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10200 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10201 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10205 bool Expr::EvalResult::isGlobalLValue() const {
10206 assert(Val.isLValue());
10207 return IsGlobalLValue(Val.getLValueBase());
10211 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10212 /// an integer constant expression.
10214 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10217 // CheckICE - This function does the fundamental ICE checking: the returned
10218 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10219 // and a (possibly null) SourceLocation indicating the location of the problem.
10221 // Note that to reduce code duplication, this helper does no evaluation
10222 // itself; the caller checks whether the expression is evaluatable, and
10223 // in the rare cases where CheckICE actually cares about the evaluated
10224 // value, it calls into Evaluate.
10229 /// This expression is an ICE.
10231 /// This expression is not an ICE, but if it isn't evaluated, it's
10232 /// a legal subexpression for an ICE. This return value is used to handle
10233 /// the comma operator in C99 mode, and non-constant subexpressions.
10234 IK_ICEIfUnevaluated,
10235 /// This expression is not an ICE, and is not a legal subexpression for one.
10241 SourceLocation Loc;
10243 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10248 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10250 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10252 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10253 Expr::EvalResult EVResult;
10254 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10255 !EVResult.Val.isInt())
10256 return ICEDiag(IK_NotICE, E->getLocStart());
10261 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10262 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10263 if (!E->getType()->isIntegralOrEnumerationType())
10264 return ICEDiag(IK_NotICE, E->getLocStart());
10266 switch (E->getStmtClass()) {
10267 #define ABSTRACT_STMT(Node)
10268 #define STMT(Node, Base) case Expr::Node##Class:
10269 #define EXPR(Node, Base)
10270 #include "clang/AST/StmtNodes.inc"
10271 case Expr::PredefinedExprClass:
10272 case Expr::FloatingLiteralClass:
10273 case Expr::ImaginaryLiteralClass:
10274 case Expr::StringLiteralClass:
10275 case Expr::ArraySubscriptExprClass:
10276 case Expr::OMPArraySectionExprClass:
10277 case Expr::MemberExprClass:
10278 case Expr::CompoundAssignOperatorClass:
10279 case Expr::CompoundLiteralExprClass:
10280 case Expr::ExtVectorElementExprClass:
10281 case Expr::DesignatedInitExprClass:
10282 case Expr::ArrayInitLoopExprClass:
10283 case Expr::ArrayInitIndexExprClass:
10284 case Expr::NoInitExprClass:
10285 case Expr::DesignatedInitUpdateExprClass:
10286 case Expr::ImplicitValueInitExprClass:
10287 case Expr::ParenListExprClass:
10288 case Expr::VAArgExprClass:
10289 case Expr::AddrLabelExprClass:
10290 case Expr::StmtExprClass:
10291 case Expr::CXXMemberCallExprClass:
10292 case Expr::CUDAKernelCallExprClass:
10293 case Expr::CXXDynamicCastExprClass:
10294 case Expr::CXXTypeidExprClass:
10295 case Expr::CXXUuidofExprClass:
10296 case Expr::MSPropertyRefExprClass:
10297 case Expr::MSPropertySubscriptExprClass:
10298 case Expr::CXXNullPtrLiteralExprClass:
10299 case Expr::UserDefinedLiteralClass:
10300 case Expr::CXXThisExprClass:
10301 case Expr::CXXThrowExprClass:
10302 case Expr::CXXNewExprClass:
10303 case Expr::CXXDeleteExprClass:
10304 case Expr::CXXPseudoDestructorExprClass:
10305 case Expr::UnresolvedLookupExprClass:
10306 case Expr::TypoExprClass:
10307 case Expr::DependentScopeDeclRefExprClass:
10308 case Expr::CXXConstructExprClass:
10309 case Expr::CXXInheritedCtorInitExprClass:
10310 case Expr::CXXStdInitializerListExprClass:
10311 case Expr::CXXBindTemporaryExprClass:
10312 case Expr::ExprWithCleanupsClass:
10313 case Expr::CXXTemporaryObjectExprClass:
10314 case Expr::CXXUnresolvedConstructExprClass:
10315 case Expr::CXXDependentScopeMemberExprClass:
10316 case Expr::UnresolvedMemberExprClass:
10317 case Expr::ObjCStringLiteralClass:
10318 case Expr::ObjCBoxedExprClass:
10319 case Expr::ObjCArrayLiteralClass:
10320 case Expr::ObjCDictionaryLiteralClass:
10321 case Expr::ObjCEncodeExprClass:
10322 case Expr::ObjCMessageExprClass:
10323 case Expr::ObjCSelectorExprClass:
10324 case Expr::ObjCProtocolExprClass:
10325 case Expr::ObjCIvarRefExprClass:
10326 case Expr::ObjCPropertyRefExprClass:
10327 case Expr::ObjCSubscriptRefExprClass:
10328 case Expr::ObjCIsaExprClass:
10329 case Expr::ObjCAvailabilityCheckExprClass:
10330 case Expr::ShuffleVectorExprClass:
10331 case Expr::ConvertVectorExprClass:
10332 case Expr::BlockExprClass:
10333 case Expr::NoStmtClass:
10334 case Expr::OpaqueValueExprClass:
10335 case Expr::PackExpansionExprClass:
10336 case Expr::SubstNonTypeTemplateParmPackExprClass:
10337 case Expr::FunctionParmPackExprClass:
10338 case Expr::AsTypeExprClass:
10339 case Expr::ObjCIndirectCopyRestoreExprClass:
10340 case Expr::MaterializeTemporaryExprClass:
10341 case Expr::PseudoObjectExprClass:
10342 case Expr::AtomicExprClass:
10343 case Expr::LambdaExprClass:
10344 case Expr::CXXFoldExprClass:
10345 case Expr::CoawaitExprClass:
10346 case Expr::DependentCoawaitExprClass:
10347 case Expr::CoyieldExprClass:
10348 return ICEDiag(IK_NotICE, E->getLocStart());
10350 case Expr::InitListExprClass: {
10351 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10352 // form "T x = { a };" is equivalent to "T x = a;".
10353 // Unless we're initializing a reference, T is a scalar as it is known to be
10354 // of integral or enumeration type.
10356 if (cast<InitListExpr>(E)->getNumInits() == 1)
10357 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10358 return ICEDiag(IK_NotICE, E->getLocStart());
10361 case Expr::SizeOfPackExprClass:
10362 case Expr::GNUNullExprClass:
10363 // GCC considers the GNU __null value to be an integral constant expression.
10366 case Expr::SubstNonTypeTemplateParmExprClass:
10368 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10370 case Expr::ParenExprClass:
10371 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10372 case Expr::GenericSelectionExprClass:
10373 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10374 case Expr::IntegerLiteralClass:
10375 case Expr::CharacterLiteralClass:
10376 case Expr::ObjCBoolLiteralExprClass:
10377 case Expr::CXXBoolLiteralExprClass:
10378 case Expr::CXXScalarValueInitExprClass:
10379 case Expr::TypeTraitExprClass:
10380 case Expr::ArrayTypeTraitExprClass:
10381 case Expr::ExpressionTraitExprClass:
10382 case Expr::CXXNoexceptExprClass:
10384 case Expr::CallExprClass:
10385 case Expr::CXXOperatorCallExprClass: {
10386 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10387 // constant expressions, but they can never be ICEs because an ICE cannot
10388 // contain an operand of (pointer to) function type.
10389 const CallExpr *CE = cast<CallExpr>(E);
10390 if (CE->getBuiltinCallee())
10391 return CheckEvalInICE(E, Ctx);
10392 return ICEDiag(IK_NotICE, E->getLocStart());
10394 case Expr::DeclRefExprClass: {
10395 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10397 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10398 if (Ctx.getLangOpts().CPlusPlus &&
10399 D && IsConstNonVolatile(D->getType())) {
10400 // Parameter variables are never constants. Without this check,
10401 // getAnyInitializer() can find a default argument, which leads
10403 if (isa<ParmVarDecl>(D))
10404 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10407 // A variable of non-volatile const-qualified integral or enumeration
10408 // type initialized by an ICE can be used in ICEs.
10409 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10410 if (!Dcl->getType()->isIntegralOrEnumerationType())
10411 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10414 // Look for a declaration of this variable that has an initializer, and
10415 // check whether it is an ICE.
10416 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10419 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10422 return ICEDiag(IK_NotICE, E->getLocStart());
10424 case Expr::UnaryOperatorClass: {
10425 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10426 switch (Exp->getOpcode()) {
10434 // C99 6.6/3 allows increment and decrement within unevaluated
10435 // subexpressions of constant expressions, but they can never be ICEs
10436 // because an ICE cannot contain an lvalue operand.
10437 return ICEDiag(IK_NotICE, E->getLocStart());
10445 return CheckICE(Exp->getSubExpr(), Ctx);
10448 // OffsetOf falls through here.
10451 case Expr::OffsetOfExprClass: {
10452 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10453 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10454 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10455 // compliance: we should warn earlier for offsetof expressions with
10456 // array subscripts that aren't ICEs, and if the array subscripts
10457 // are ICEs, the value of the offsetof must be an integer constant.
10458 return CheckEvalInICE(E, Ctx);
10460 case Expr::UnaryExprOrTypeTraitExprClass: {
10461 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10462 if ((Exp->getKind() == UETT_SizeOf) &&
10463 Exp->getTypeOfArgument()->isVariableArrayType())
10464 return ICEDiag(IK_NotICE, E->getLocStart());
10467 case Expr::BinaryOperatorClass: {
10468 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10469 switch (Exp->getOpcode()) {
10483 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
10484 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10485 // constant expressions, but they can never be ICEs because an ICE cannot
10486 // contain an lvalue operand.
10487 return ICEDiag(IK_NotICE, E->getLocStart());
10506 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10507 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10508 if (Exp->getOpcode() == BO_Div ||
10509 Exp->getOpcode() == BO_Rem) {
10510 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10511 // we don't evaluate one.
10512 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10513 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10515 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10516 if (REval.isSigned() && REval.isAllOnesValue()) {
10517 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10518 if (LEval.isMinSignedValue())
10519 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10523 if (Exp->getOpcode() == BO_Comma) {
10524 if (Ctx.getLangOpts().C99) {
10525 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10526 // if it isn't evaluated.
10527 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10528 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10530 // In both C89 and C++, commas in ICEs are illegal.
10531 return ICEDiag(IK_NotICE, E->getLocStart());
10534 return Worst(LHSResult, RHSResult);
10538 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10539 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10540 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10541 // Rare case where the RHS has a comma "side-effect"; we need
10542 // to actually check the condition to see whether the side
10543 // with the comma is evaluated.
10544 if ((Exp->getOpcode() == BO_LAnd) !=
10545 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10550 return Worst(LHSResult, RHSResult);
10555 case Expr::ImplicitCastExprClass:
10556 case Expr::CStyleCastExprClass:
10557 case Expr::CXXFunctionalCastExprClass:
10558 case Expr::CXXStaticCastExprClass:
10559 case Expr::CXXReinterpretCastExprClass:
10560 case Expr::CXXConstCastExprClass:
10561 case Expr::ObjCBridgedCastExprClass: {
10562 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10563 if (isa<ExplicitCastExpr>(E)) {
10564 if (const FloatingLiteral *FL
10565 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10566 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10567 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10568 APSInt IgnoredVal(DestWidth, !DestSigned);
10570 // If the value does not fit in the destination type, the behavior is
10571 // undefined, so we are not required to treat it as a constant
10573 if (FL->getValue().convertToInteger(IgnoredVal,
10574 llvm::APFloat::rmTowardZero,
10575 &Ignored) & APFloat::opInvalidOp)
10576 return ICEDiag(IK_NotICE, E->getLocStart());
10580 switch (cast<CastExpr>(E)->getCastKind()) {
10581 case CK_LValueToRValue:
10582 case CK_AtomicToNonAtomic:
10583 case CK_NonAtomicToAtomic:
10585 case CK_IntegralToBoolean:
10586 case CK_IntegralCast:
10587 return CheckICE(SubExpr, Ctx);
10589 return ICEDiag(IK_NotICE, E->getLocStart());
10592 case Expr::BinaryConditionalOperatorClass: {
10593 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10594 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10595 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10596 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10597 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10598 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10599 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10600 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10601 return FalseResult;
10603 case Expr::ConditionalOperatorClass: {
10604 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10605 // If the condition (ignoring parens) is a __builtin_constant_p call,
10606 // then only the true side is actually considered in an integer constant
10607 // expression, and it is fully evaluated. This is an important GNU
10608 // extension. See GCC PR38377 for discussion.
10609 if (const CallExpr *CallCE
10610 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10611 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10612 return CheckEvalInICE(E, Ctx);
10613 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10614 if (CondResult.Kind == IK_NotICE)
10617 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10618 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10620 if (TrueResult.Kind == IK_NotICE)
10622 if (FalseResult.Kind == IK_NotICE)
10623 return FalseResult;
10624 if (CondResult.Kind == IK_ICEIfUnevaluated)
10626 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10628 // Rare case where the diagnostics depend on which side is evaluated
10629 // Note that if we get here, CondResult is 0, and at least one of
10630 // TrueResult and FalseResult is non-zero.
10631 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10632 return FalseResult;
10635 case Expr::CXXDefaultArgExprClass:
10636 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10637 case Expr::CXXDefaultInitExprClass:
10638 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10639 case Expr::ChooseExprClass: {
10640 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10644 llvm_unreachable("Invalid StmtClass!");
10647 /// Evaluate an expression as a C++11 integral constant expression.
10648 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10650 llvm::APSInt *Value,
10651 SourceLocation *Loc) {
10652 if (!E->getType()->isIntegralOrEnumerationType()) {
10653 if (Loc) *Loc = E->getExprLoc();
10658 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10661 if (!Result.isInt()) {
10662 if (Loc) *Loc = E->getExprLoc();
10666 if (Value) *Value = Result.getInt();
10670 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10671 SourceLocation *Loc) const {
10672 if (Ctx.getLangOpts().CPlusPlus11)
10673 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10675 ICEDiag D = CheckICE(this, Ctx);
10676 if (D.Kind != IK_ICE) {
10677 if (Loc) *Loc = D.Loc;
10683 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10684 SourceLocation *Loc, bool isEvaluated) const {
10685 if (Ctx.getLangOpts().CPlusPlus11)
10686 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10688 if (!isIntegerConstantExpr(Ctx, Loc))
10690 // The only possible side-effects here are due to UB discovered in the
10691 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10692 // required to treat the expression as an ICE, so we produce the folded
10694 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10695 llvm_unreachable("ICE cannot be evaluated!");
10699 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10700 return CheckICE(this, Ctx).Kind == IK_ICE;
10703 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10704 SourceLocation *Loc) const {
10705 // We support this checking in C++98 mode in order to diagnose compatibility
10707 assert(Ctx.getLangOpts().CPlusPlus);
10709 // Build evaluation settings.
10710 Expr::EvalStatus Status;
10711 SmallVector<PartialDiagnosticAt, 8> Diags;
10712 Status.Diag = &Diags;
10713 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10716 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10718 if (!Diags.empty()) {
10719 IsConstExpr = false;
10720 if (Loc) *Loc = Diags[0].first;
10721 } else if (!IsConstExpr) {
10722 // FIXME: This shouldn't happen.
10723 if (Loc) *Loc = getExprLoc();
10726 return IsConstExpr;
10729 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10730 const FunctionDecl *Callee,
10731 ArrayRef<const Expr*> Args,
10732 const Expr *This) const {
10733 Expr::EvalStatus Status;
10734 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10737 const LValue *ThisPtr = nullptr;
10740 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10741 assert(MD && "Don't provide `this` for non-methods.");
10742 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10744 if (EvaluateObjectArgument(Info, This, ThisVal))
10745 ThisPtr = &ThisVal;
10746 if (Info.EvalStatus.HasSideEffects)
10750 ArgVector ArgValues(Args.size());
10751 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10753 if ((*I)->isValueDependent() ||
10754 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10755 // If evaluation fails, throw away the argument entirely.
10756 ArgValues[I - Args.begin()] = APValue();
10757 if (Info.EvalStatus.HasSideEffects)
10761 // Build fake call to Callee.
10762 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10764 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10767 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10769 PartialDiagnosticAt> &Diags) {
10770 // FIXME: It would be useful to check constexpr function templates, but at the
10771 // moment the constant expression evaluator cannot cope with the non-rigorous
10772 // ASTs which we build for dependent expressions.
10773 if (FD->isDependentContext())
10776 Expr::EvalStatus Status;
10777 Status.Diag = &Diags;
10779 EvalInfo Info(FD->getASTContext(), Status,
10780 EvalInfo::EM_PotentialConstantExpression);
10782 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10783 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10785 // Fabricate an arbitrary expression on the stack and pretend that it
10786 // is a temporary being used as the 'this' pointer.
10788 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10789 This.set(&VIE, Info.CurrentCall->Index);
10791 ArrayRef<const Expr*> Args;
10794 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10795 // Evaluate the call as a constant initializer, to allow the construction
10796 // of objects of non-literal types.
10797 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10798 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10800 SourceLocation Loc = FD->getLocation();
10801 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10802 Args, FD->getBody(), Info, Scratch, nullptr);
10805 return Diags.empty();
10808 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10809 const FunctionDecl *FD,
10811 PartialDiagnosticAt> &Diags) {
10812 Expr::EvalStatus Status;
10813 Status.Diag = &Diags;
10815 EvalInfo Info(FD->getASTContext(), Status,
10816 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10818 // Fabricate a call stack frame to give the arguments a plausible cover story.
10819 ArrayRef<const Expr*> Args;
10820 ArgVector ArgValues(0);
10821 bool Success = EvaluateArgs(Args, ArgValues, Info);
10824 "Failed to set up arguments for potential constant evaluation");
10825 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10827 APValue ResultScratch;
10828 Evaluate(ResultScratch, Info, E);
10829 return Diags.empty();
10832 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10833 unsigned Type) const {
10834 if (!getType()->isPointerType())
10837 Expr::EvalStatus Status;
10838 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10839 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);