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. Using the type of
67 // the most recent declaration isn't clearly correct in general. Eg:
69 // extern int arr[]; void f() { extern int arr[3]; };
70 // constexpr int *p = &arr[1]; // valid?
71 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
73 const Expr *Base = B.get<const Expr*>();
75 // For a materialized temporary, the type of the temporary we materialized
76 // may not be the type of the expression.
77 if (const MaterializeTemporaryExpr *MTE =
78 dyn_cast<MaterializeTemporaryExpr>(Base)) {
79 SmallVector<const Expr *, 2> CommaLHSs;
80 SmallVector<SubobjectAdjustment, 2> Adjustments;
81 const Expr *Temp = MTE->GetTemporaryExpr();
82 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
84 // Keep any cv-qualifiers from the reference if we generated a temporary
85 // for it directly. Otherwise use the type after adjustment.
86 if (!Adjustments.empty())
87 return Inner->getType();
90 return Base->getType();
93 /// Get an LValue path entry, which is known to not be an array index, as a
94 /// field or base class.
96 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
97 APValue::BaseOrMemberType Value;
98 Value.setFromOpaqueValue(E.BaseOrMember);
102 /// Get an LValue path entry, which is known to not be an array index, as a
103 /// field declaration.
104 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
105 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
107 /// Get an LValue path entry, which is known to not be an array index, as a
108 /// base class declaration.
109 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
110 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
112 /// Determine whether this LValue path entry for a base class names a virtual
114 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
115 return getAsBaseOrMember(E).getInt();
118 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
119 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
120 const FunctionDecl *Callee = CE->getDirectCallee();
121 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. Ignore it.
135 if (const auto *Cast = dyn_cast<CastExpr>(E))
136 E = Cast->getSubExpr()->IgnoreParens();
138 if (const auto *CE = dyn_cast<CallExpr>(E))
139 return getAllocSizeAttr(CE) ? CE : nullptr;
143 /// Determines whether or not the given Base contains a call to a function
144 /// with the alloc_size attribute.
145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
146 const auto *E = Base.dyn_cast<const Expr *>();
147 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150 /// The bound to claim that an array of unknown bound has.
151 /// The value in MostDerivedArraySize is undefined in this case. So, set it
152 /// to an arbitrary value that's likely to loudly break things if it's used.
153 static const uint64_t AssumedSizeForUnsizedArray =
154 std::numeric_limits<uint64_t>::max() / 2;
156 /// Determines if an LValue with the given LValueBase will have an unsized
157 /// array in its designator.
158 /// Find the path length and type of the most-derived subobject in the given
159 /// path, and find the size of the containing array, if any.
161 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
162 ArrayRef<APValue::LValuePathEntry> Path,
163 uint64_t &ArraySize, QualType &Type, bool &IsArray,
164 bool &FirstEntryIsUnsizedArray) {
165 // This only accepts LValueBases from APValues, and APValues don't support
166 // arrays that lack size info.
167 assert(!isBaseAnAllocSizeCall(Base) &&
168 "Unsized arrays shouldn't appear here");
169 unsigned MostDerivedLength = 0;
170 Type = getType(Base);
172 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
173 if (Type->isArrayType()) {
174 const ArrayType *AT = Ctx.getAsArrayType(Type);
175 Type = AT->getElementType();
176 MostDerivedLength = I + 1;
179 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
180 ArraySize = CAT->getSize().getZExtValue();
182 assert(I == 0 && "unexpected unsized array designator");
183 FirstEntryIsUnsizedArray = true;
184 ArraySize = AssumedSizeForUnsizedArray;
186 } else if (Type->isAnyComplexType()) {
187 const ComplexType *CT = Type->castAs<ComplexType>();
188 Type = CT->getElementType();
190 MostDerivedLength = I + 1;
192 } else if (const FieldDecl *FD = getAsField(Path[I])) {
193 Type = FD->getType();
195 MostDerivedLength = I + 1;
198 // Path[I] describes a base class.
203 return MostDerivedLength;
206 // The order of this enum is important for diagnostics.
207 enum CheckSubobjectKind {
208 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
209 CSK_This, CSK_Real, CSK_Imag
212 /// A path from a glvalue to a subobject of that glvalue.
213 struct SubobjectDesignator {
214 /// True if the subobject was named in a manner not supported by C++11. Such
215 /// lvalues can still be folded, but they are not core constant expressions
216 /// and we cannot perform lvalue-to-rvalue conversions on them.
217 unsigned Invalid : 1;
219 /// Is this a pointer one past the end of an object?
220 unsigned IsOnePastTheEnd : 1;
222 /// Indicator of whether the first entry is an unsized array.
223 unsigned FirstEntryIsAnUnsizedArray : 1;
225 /// Indicator of whether the most-derived object is an array element.
226 unsigned MostDerivedIsArrayElement : 1;
228 /// The length of the path to the most-derived object of which this is a
230 unsigned MostDerivedPathLength : 28;
232 /// The size of the array of which the most-derived object is an element.
233 /// This will always be 0 if the most-derived object is not an array
234 /// element. 0 is not an indicator of whether or not the most-derived object
235 /// is an array, however, because 0-length arrays are allowed.
237 /// If the current array is an unsized array, the value of this is
239 uint64_t MostDerivedArraySize;
241 /// The type of the most derived object referred to by this address.
242 QualType MostDerivedType;
244 typedef APValue::LValuePathEntry PathEntry;
246 /// The entries on the path from the glvalue to the designated subobject.
247 SmallVector<PathEntry, 8> Entries;
249 SubobjectDesignator() : Invalid(true) {}
251 explicit SubobjectDesignator(QualType T)
252 : Invalid(false), IsOnePastTheEnd(false),
253 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
254 MostDerivedPathLength(0), MostDerivedArraySize(0),
255 MostDerivedType(T) {}
257 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
258 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
259 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
260 MostDerivedPathLength(0), MostDerivedArraySize(0) {
261 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
263 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
264 ArrayRef<PathEntry> VEntries = V.getLValuePath();
265 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
266 if (V.getLValueBase()) {
267 bool IsArray = false;
268 bool FirstIsUnsizedArray = false;
269 MostDerivedPathLength = findMostDerivedSubobject(
270 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
271 MostDerivedType, IsArray, FirstIsUnsizedArray);
272 MostDerivedIsArrayElement = IsArray;
273 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
283 /// Determine whether the most derived subobject is an array without a
285 bool isMostDerivedAnUnsizedArray() const {
286 assert(!Invalid && "Calling this makes no sense on invalid designators");
287 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
290 /// Determine what the most derived array's size is. Results in an assertion
291 /// failure if the most derived array lacks a size.
292 uint64_t getMostDerivedArraySize() const {
293 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
294 return MostDerivedArraySize;
297 /// Determine whether this is a one-past-the-end pointer.
298 bool isOnePastTheEnd() const {
302 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
303 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
308 /// Check that this refers to a valid subobject.
309 bool isValidSubobject() const {
312 return !isOnePastTheEnd();
314 /// Check that this refers to a valid subobject, and if not, produce a
315 /// relevant diagnostic and set the designator as invalid.
316 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
318 /// Update this designator to refer to the first element within this array.
319 void addArrayUnchecked(const ConstantArrayType *CAT) {
321 Entry.ArrayIndex = 0;
322 Entries.push_back(Entry);
324 // This is a most-derived object.
325 MostDerivedType = CAT->getElementType();
326 MostDerivedIsArrayElement = true;
327 MostDerivedArraySize = CAT->getSize().getZExtValue();
328 MostDerivedPathLength = Entries.size();
330 /// Update this designator to refer to the first element within the array of
331 /// elements of type T. This is an array of unknown size.
332 void addUnsizedArrayUnchecked(QualType ElemTy) {
334 Entry.ArrayIndex = 0;
335 Entries.push_back(Entry);
337 MostDerivedType = ElemTy;
338 MostDerivedIsArrayElement = true;
339 // The value in MostDerivedArraySize is undefined in this case. So, set it
340 // to an arbitrary value that's likely to loudly break things if it's
342 MostDerivedArraySize = AssumedSizeForUnsizedArray;
343 MostDerivedPathLength = Entries.size();
345 /// Update this designator to refer to the given base or member of this
347 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
349 APValue::BaseOrMemberType Value(D, Virtual);
350 Entry.BaseOrMember = Value.getOpaqueValue();
351 Entries.push_back(Entry);
353 // If this isn't a base class, it's a new most-derived object.
354 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
355 MostDerivedType = FD->getType();
356 MostDerivedIsArrayElement = false;
357 MostDerivedArraySize = 0;
358 MostDerivedPathLength = Entries.size();
361 /// Update this designator to refer to the given complex component.
362 void addComplexUnchecked(QualType EltTy, bool Imag) {
364 Entry.ArrayIndex = Imag;
365 Entries.push_back(Entry);
367 // This is technically a most-derived object, though in practice this
368 // is unlikely to matter.
369 MostDerivedType = EltTy;
370 MostDerivedIsArrayElement = true;
371 MostDerivedArraySize = 2;
372 MostDerivedPathLength = Entries.size();
374 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
375 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
377 /// Add N to the address of this subobject.
378 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
379 if (Invalid || !N) return;
380 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
381 if (isMostDerivedAnUnsizedArray()) {
382 diagnoseUnsizedArrayPointerArithmetic(Info, E);
383 // Can't verify -- trust that the user is doing the right thing (or if
384 // not, trust that the caller will catch the bad behavior).
385 // FIXME: Should we reject if this overflows, at least?
386 Entries.back().ArrayIndex += TruncatedN;
390 // [expr.add]p4: For the purposes of these operators, a pointer to a
391 // nonarray object behaves the same as a pointer to the first element of
392 // an array of length one with the type of the object as its element type.
393 bool IsArray = MostDerivedPathLength == Entries.size() &&
394 MostDerivedIsArrayElement;
395 uint64_t ArrayIndex =
396 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
398 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
400 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
401 // Calculate the actual index in a wide enough type, so we can include
403 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
404 (llvm::APInt&)N += ArrayIndex;
405 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
406 diagnosePointerArithmetic(Info, E, N);
411 ArrayIndex += TruncatedN;
412 assert(ArrayIndex <= ArraySize &&
413 "bounds check succeeded for out-of-bounds index");
416 Entries.back().ArrayIndex = ArrayIndex;
418 IsOnePastTheEnd = (ArrayIndex != 0);
422 /// A stack frame in the constexpr call stack.
423 struct CallStackFrame {
426 /// Parent - The caller of this stack frame.
427 CallStackFrame *Caller;
429 /// Callee - The function which was called.
430 const FunctionDecl *Callee;
432 /// This - The binding for the this pointer in this call, if any.
435 /// Arguments - Parameter bindings for this function call, indexed by
436 /// parameters' function scope indices.
439 // Note that we intentionally use std::map here so that references to
440 // values are stable.
441 typedef std::map<const void*, APValue> MapTy;
442 typedef MapTy::const_iterator temp_iterator;
443 /// Temporaries - Temporary lvalues materialized within this stack frame.
446 /// CallLoc - The location of the call expression for this call.
447 SourceLocation CallLoc;
449 /// Index - The call index of this call.
452 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
453 // on the overall stack usage of deeply-recursing constexpr evaluataions.
454 // (We should cache this map rather than recomputing it repeatedly.)
455 // But let's try this and see how it goes; we can look into caching the map
456 // as a later change.
458 /// LambdaCaptureFields - Mapping from captured variables/this to
459 /// corresponding data members in the closure class.
460 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
461 FieldDecl *LambdaThisCaptureField;
463 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
464 const FunctionDecl *Callee, const LValue *This,
468 APValue *getTemporary(const void *Key) {
469 MapTy::iterator I = Temporaries.find(Key);
470 return I == Temporaries.end() ? nullptr : &I->second;
472 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
475 /// Temporarily override 'this'.
476 class ThisOverrideRAII {
478 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
479 : Frame(Frame), OldThis(Frame.This) {
481 Frame.This = NewThis;
483 ~ThisOverrideRAII() {
484 Frame.This = OldThis;
487 CallStackFrame &Frame;
488 const LValue *OldThis;
491 /// A partial diagnostic which we might know in advance that we are not going
493 class OptionalDiagnostic {
494 PartialDiagnostic *Diag;
497 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
501 OptionalDiagnostic &operator<<(const T &v) {
507 OptionalDiagnostic &operator<<(const APSInt &I) {
509 SmallVector<char, 32> Buffer;
511 *Diag << StringRef(Buffer.data(), Buffer.size());
516 OptionalDiagnostic &operator<<(const APFloat &F) {
518 // FIXME: Force the precision of the source value down so we don't
519 // print digits which are usually useless (we don't really care here if
520 // we truncate a digit by accident in edge cases). Ideally,
521 // APFloat::toString would automatically print the shortest
522 // representation which rounds to the correct value, but it's a bit
523 // tricky to implement.
525 llvm::APFloat::semanticsPrecision(F.getSemantics());
526 precision = (precision * 59 + 195) / 196;
527 SmallVector<char, 32> Buffer;
528 F.toString(Buffer, precision);
529 *Diag << StringRef(Buffer.data(), Buffer.size());
535 /// A cleanup, and a flag indicating whether it is lifetime-extended.
537 llvm::PointerIntPair<APValue*, 1, bool> Value;
540 Cleanup(APValue *Val, bool IsLifetimeExtended)
541 : Value(Val, IsLifetimeExtended) {}
543 bool isLifetimeExtended() const { return Value.getInt(); }
545 *Value.getPointer() = APValue();
549 /// EvalInfo - This is a private struct used by the evaluator to capture
550 /// information about a subexpression as it is folded. It retains information
551 /// about the AST context, but also maintains information about the folded
554 /// If an expression could be evaluated, it is still possible it is not a C
555 /// "integer constant expression" or constant expression. If not, this struct
556 /// captures information about how and why not.
558 /// One bit of information passed *into* the request for constant folding
559 /// indicates whether the subexpression is "evaluated" or not according to C
560 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
561 /// evaluate the expression regardless of what the RHS is, but C only allows
562 /// certain things in certain situations.
566 /// EvalStatus - Contains information about the evaluation.
567 Expr::EvalStatus &EvalStatus;
569 /// CurrentCall - The top of the constexpr call stack.
570 CallStackFrame *CurrentCall;
572 /// CallStackDepth - The number of calls in the call stack right now.
573 unsigned CallStackDepth;
575 /// NextCallIndex - The next call index to assign.
576 unsigned NextCallIndex;
578 /// StepsLeft - The remaining number of evaluation steps we're permitted
579 /// to perform. This is essentially a limit for the number of statements
580 /// we will evaluate.
583 /// BottomFrame - The frame in which evaluation started. This must be
584 /// initialized after CurrentCall and CallStackDepth.
585 CallStackFrame BottomFrame;
587 /// A stack of values whose lifetimes end at the end of some surrounding
588 /// evaluation frame.
589 llvm::SmallVector<Cleanup, 16> CleanupStack;
591 /// EvaluatingDecl - This is the declaration whose initializer is being
592 /// evaluated, if any.
593 APValue::LValueBase EvaluatingDecl;
595 /// EvaluatingDeclValue - This is the value being constructed for the
596 /// declaration whose initializer is being evaluated, if any.
597 APValue *EvaluatingDeclValue;
599 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
600 /// the call index that that lvalue was allocated in.
601 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
603 /// EvaluatingConstructors - Set of objects that are currently being
605 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
607 struct EvaluatingConstructorRAII {
609 EvaluatingObject Object;
611 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
612 : EI(EI), Object(Object) {
613 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
615 ~EvaluatingConstructorRAII() {
616 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
620 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
621 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
624 /// The current array initialization index, if we're performing array
626 uint64_t ArrayInitIndex = -1;
628 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
629 /// notes attached to it will also be stored, otherwise they will not be.
630 bool HasActiveDiagnostic;
632 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
633 /// fold (not just why it's not strictly a constant expression)?
634 bool HasFoldFailureDiagnostic;
636 /// \brief Whether or not we're currently speculatively evaluating.
637 bool IsSpeculativelyEvaluating;
639 enum EvaluationMode {
640 /// Evaluate as a constant expression. Stop if we find that the expression
641 /// is not a constant expression.
642 EM_ConstantExpression,
644 /// Evaluate as a potential constant expression. Keep going if we hit a
645 /// construct that we can't evaluate yet (because we don't yet know the
646 /// value of something) but stop if we hit something that could never be
647 /// a constant expression.
648 EM_PotentialConstantExpression,
650 /// Fold the expression to a constant. Stop if we hit a side-effect that
654 /// Evaluate the expression looking for integer overflow and similar
655 /// issues. Don't worry about side-effects, and try to visit all
657 EM_EvaluateForOverflow,
659 /// Evaluate in any way we know how. Don't worry about side-effects that
660 /// can't be modeled.
661 EM_IgnoreSideEffects,
663 /// Evaluate as a constant expression. Stop if we find that the expression
664 /// is not a constant expression. Some expressions can be retried in the
665 /// optimizer if we don't constant fold them here, but in an unevaluated
666 /// context we try to fold them immediately since the optimizer never
667 /// gets a chance to look at it.
668 EM_ConstantExpressionUnevaluated,
670 /// Evaluate as a potential constant expression. Keep going if we hit a
671 /// construct that we can't evaluate yet (because we don't yet know the
672 /// value of something) but stop if we hit something that could never be
673 /// a constant expression. Some expressions can be retried in the
674 /// optimizer if we don't constant fold them here, but in an unevaluated
675 /// context we try to fold them immediately since the optimizer never
676 /// gets a chance to look at it.
677 EM_PotentialConstantExpressionUnevaluated,
679 /// Evaluate as a constant expression. In certain scenarios, if:
680 /// - we find a MemberExpr with a base that can't be evaluated, or
681 /// - we find a variable initialized with a call to a function that has
682 /// the alloc_size attribute on it
683 /// then we may consider evaluation to have succeeded.
685 /// In either case, the LValue returned shall have an invalid base; in the
686 /// former, the base will be the invalid MemberExpr, in the latter, the
687 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
692 /// Are we checking whether the expression is a potential constant
694 bool checkingPotentialConstantExpression() const {
695 return EvalMode == EM_PotentialConstantExpression ||
696 EvalMode == EM_PotentialConstantExpressionUnevaluated;
699 /// Are we checking an expression for overflow?
700 // FIXME: We should check for any kind of undefined or suspicious behavior
701 // in such constructs, not just overflow.
702 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
704 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
705 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
706 CallStackDepth(0), NextCallIndex(1),
707 StepsLeft(getLangOpts().ConstexprStepLimit),
708 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
709 EvaluatingDecl((const ValueDecl *)nullptr),
710 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
711 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
714 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
715 EvaluatingDecl = Base;
716 EvaluatingDeclValue = &Value;
717 EvaluatingConstructors.insert({Base, 0});
720 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
722 bool CheckCallLimit(SourceLocation Loc) {
723 // Don't perform any constexpr calls (other than the call we're checking)
724 // when checking a potential constant expression.
725 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
727 if (NextCallIndex == 0) {
728 // NextCallIndex has wrapped around.
729 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
732 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
734 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
735 << getLangOpts().ConstexprCallDepth;
739 CallStackFrame *getCallFrame(unsigned CallIndex) {
740 assert(CallIndex && "no call index in getCallFrame");
741 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
742 // be null in this loop.
743 CallStackFrame *Frame = CurrentCall;
744 while (Frame->Index > CallIndex)
745 Frame = Frame->Caller;
746 return (Frame->Index == CallIndex) ? Frame : nullptr;
749 bool nextStep(const Stmt *S) {
751 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
759 /// Add a diagnostic to the diagnostics list.
760 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
761 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
762 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
763 return EvalStatus.Diag->back().second;
766 /// Add notes containing a call stack to the current point of evaluation.
767 void addCallStack(unsigned Limit);
770 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
771 unsigned ExtraNotes, bool IsCCEDiag) {
773 if (EvalStatus.Diag) {
774 // If we have a prior diagnostic, it will be noting that the expression
775 // isn't a constant expression. This diagnostic is more important,
776 // unless we require this evaluation to produce a constant expression.
778 // FIXME: We might want to show both diagnostics to the user in
779 // EM_ConstantFold mode.
780 if (!EvalStatus.Diag->empty()) {
782 case EM_ConstantFold:
783 case EM_IgnoreSideEffects:
784 case EM_EvaluateForOverflow:
785 if (!HasFoldFailureDiagnostic)
787 // We've already failed to fold something. Keep that diagnostic.
789 case EM_ConstantExpression:
790 case EM_PotentialConstantExpression:
791 case EM_ConstantExpressionUnevaluated:
792 case EM_PotentialConstantExpressionUnevaluated:
794 HasActiveDiagnostic = false;
795 return OptionalDiagnostic();
799 unsigned CallStackNotes = CallStackDepth - 1;
800 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
802 CallStackNotes = std::min(CallStackNotes, Limit + 1);
803 if (checkingPotentialConstantExpression())
806 HasActiveDiagnostic = true;
807 HasFoldFailureDiagnostic = !IsCCEDiag;
808 EvalStatus.Diag->clear();
809 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
810 addDiag(Loc, DiagId);
811 if (!checkingPotentialConstantExpression())
813 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
815 HasActiveDiagnostic = false;
816 return OptionalDiagnostic();
819 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
821 FFDiag(SourceLocation Loc,
822 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
823 unsigned ExtraNotes = 0) {
824 return Diag(Loc, DiagId, ExtraNotes, false);
827 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
828 = diag::note_invalid_subexpr_in_const_expr,
829 unsigned ExtraNotes = 0) {
831 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
832 HasActiveDiagnostic = false;
833 return OptionalDiagnostic();
836 /// Diagnose that the evaluation does not produce a C++11 core constant
839 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
840 /// EM_PotentialConstantExpression mode and we produce one of these.
841 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
842 = diag::note_invalid_subexpr_in_const_expr,
843 unsigned ExtraNotes = 0) {
844 // Don't override a previous diagnostic. Don't bother collecting
845 // diagnostics if we're evaluating for overflow.
846 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
847 HasActiveDiagnostic = false;
848 return OptionalDiagnostic();
850 return Diag(Loc, DiagId, ExtraNotes, true);
852 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
853 = diag::note_invalid_subexpr_in_const_expr,
854 unsigned ExtraNotes = 0) {
855 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
857 /// Add a note to a prior diagnostic.
858 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
859 if (!HasActiveDiagnostic)
860 return OptionalDiagnostic();
861 return OptionalDiagnostic(&addDiag(Loc, DiagId));
864 /// Add a stack of notes to a prior diagnostic.
865 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
866 if (HasActiveDiagnostic) {
867 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
868 Diags.begin(), Diags.end());
872 /// Should we continue evaluation after encountering a side-effect that we
874 bool keepEvaluatingAfterSideEffect() {
876 case EM_PotentialConstantExpression:
877 case EM_PotentialConstantExpressionUnevaluated:
878 case EM_EvaluateForOverflow:
879 case EM_IgnoreSideEffects:
882 case EM_ConstantExpression:
883 case EM_ConstantExpressionUnevaluated:
884 case EM_ConstantFold:
888 llvm_unreachable("Missed EvalMode case");
891 /// Note that we have had a side-effect, and determine whether we should
893 bool noteSideEffect() {
894 EvalStatus.HasSideEffects = true;
895 return keepEvaluatingAfterSideEffect();
898 /// Should we continue evaluation after encountering undefined behavior?
899 bool keepEvaluatingAfterUndefinedBehavior() {
901 case EM_EvaluateForOverflow:
902 case EM_IgnoreSideEffects:
903 case EM_ConstantFold:
907 case EM_PotentialConstantExpression:
908 case EM_PotentialConstantExpressionUnevaluated:
909 case EM_ConstantExpression:
910 case EM_ConstantExpressionUnevaluated:
913 llvm_unreachable("Missed EvalMode case");
916 /// Note that we hit something that was technically undefined behavior, but
917 /// that we can evaluate past it (such as signed overflow or floating-point
918 /// division by zero.)
919 bool noteUndefinedBehavior() {
920 EvalStatus.HasUndefinedBehavior = true;
921 return keepEvaluatingAfterUndefinedBehavior();
924 /// Should we continue evaluation as much as possible after encountering a
925 /// construct which can't be reduced to a value?
926 bool keepEvaluatingAfterFailure() {
931 case EM_PotentialConstantExpression:
932 case EM_PotentialConstantExpressionUnevaluated:
933 case EM_EvaluateForOverflow:
936 case EM_ConstantExpression:
937 case EM_ConstantExpressionUnevaluated:
938 case EM_ConstantFold:
939 case EM_IgnoreSideEffects:
943 llvm_unreachable("Missed EvalMode case");
946 /// Notes that we failed to evaluate an expression that other expressions
947 /// directly depend on, and determine if we should keep evaluating. This
948 /// should only be called if we actually intend to keep evaluating.
950 /// Call noteSideEffect() instead if we may be able to ignore the value that
951 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
953 /// (Foo(), 1) // use noteSideEffect
954 /// (Foo() || true) // use noteSideEffect
955 /// Foo() + 1 // use noteFailure
956 LLVM_NODISCARD bool noteFailure() {
957 // Failure when evaluating some expression often means there is some
958 // subexpression whose evaluation was skipped. Therefore, (because we
959 // don't track whether we skipped an expression when unwinding after an
960 // evaluation failure) every evaluation failure that bubbles up from a
961 // subexpression implies that a side-effect has potentially happened. We
962 // skip setting the HasSideEffects flag to true until we decide to
963 // continue evaluating after that point, which happens here.
964 bool KeepGoing = keepEvaluatingAfterFailure();
965 EvalStatus.HasSideEffects |= KeepGoing;
969 class ArrayInitLoopIndex {
974 ArrayInitLoopIndex(EvalInfo &Info)
975 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
976 Info.ArrayInitIndex = 0;
978 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
980 operator uint64_t&() { return Info.ArrayInitIndex; }
984 /// Object used to treat all foldable expressions as constant expressions.
985 struct FoldConstant {
988 bool HadNoPriorDiags;
989 EvalInfo::EvaluationMode OldMode;
991 explicit FoldConstant(EvalInfo &Info, bool Enabled)
994 HadNoPriorDiags(Info.EvalStatus.Diag &&
995 Info.EvalStatus.Diag->empty() &&
996 !Info.EvalStatus.HasSideEffects),
997 OldMode(Info.EvalMode) {
999 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1000 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1001 Info.EvalMode = EvalInfo::EM_ConstantFold;
1003 void keepDiagnostics() { Enabled = false; }
1005 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1006 !Info.EvalStatus.HasSideEffects)
1007 Info.EvalStatus.Diag->clear();
1008 Info.EvalMode = OldMode;
1012 /// RAII object used to treat the current evaluation as the correct pointer
1013 /// offset fold for the current EvalMode
1014 struct FoldOffsetRAII {
1016 EvalInfo::EvaluationMode OldMode;
1017 explicit FoldOffsetRAII(EvalInfo &Info)
1018 : Info(Info), OldMode(Info.EvalMode) {
1019 if (!Info.checkingPotentialConstantExpression())
1020 Info.EvalMode = EvalInfo::EM_OffsetFold;
1023 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1026 /// RAII object used to optionally suppress diagnostics and side-effects from
1027 /// a speculative evaluation.
1028 class SpeculativeEvaluationRAII {
1029 EvalInfo *Info = nullptr;
1030 Expr::EvalStatus OldStatus;
1031 bool OldIsSpeculativelyEvaluating;
1033 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1035 OldStatus = Other.OldStatus;
1036 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1037 Other.Info = nullptr;
1040 void maybeRestoreState() {
1044 Info->EvalStatus = OldStatus;
1045 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1049 SpeculativeEvaluationRAII() = default;
1051 SpeculativeEvaluationRAII(
1052 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1053 : Info(&Info), OldStatus(Info.EvalStatus),
1054 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1055 Info.EvalStatus.Diag = NewDiag;
1056 Info.IsSpeculativelyEvaluating = true;
1059 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1060 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1061 moveFromAndCancel(std::move(Other));
1064 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1065 maybeRestoreState();
1066 moveFromAndCancel(std::move(Other));
1070 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1073 /// RAII object wrapping a full-expression or block scope, and handling
1074 /// the ending of the lifetime of temporaries created within it.
1075 template<bool IsFullExpression>
1078 unsigned OldStackSize;
1080 ScopeRAII(EvalInfo &Info)
1081 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1083 // Body moved to a static method to encourage the compiler to inline away
1084 // instances of this class.
1085 cleanup(Info, OldStackSize);
1088 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1089 unsigned NewEnd = OldStackSize;
1090 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1092 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1093 // Full-expression cleanup of a lifetime-extended temporary: nothing
1094 // to do, just move this cleanup to the right place in the stack.
1095 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1098 // End the lifetime of the object.
1099 Info.CleanupStack[I].endLifetime();
1102 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1103 Info.CleanupStack.end());
1106 typedef ScopeRAII<false> BlockScopeRAII;
1107 typedef ScopeRAII<true> FullExpressionRAII;
1110 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1111 CheckSubobjectKind CSK) {
1114 if (isOnePastTheEnd()) {
1115 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1120 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1121 // must actually be at least one array element; even a VLA cannot have a
1122 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1126 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1128 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1129 // Do not set the designator as invalid: we can represent this situation,
1130 // and correct handling of __builtin_object_size requires us to do so.
1133 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1136 // If we're complaining, we must be able to statically determine the size of
1137 // the most derived array.
1138 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1139 Info.CCEDiag(E, diag::note_constexpr_array_index)
1141 << static_cast<unsigned>(getMostDerivedArraySize());
1143 Info.CCEDiag(E, diag::note_constexpr_array_index)
1144 << N << /*non-array*/ 1;
1148 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1149 const FunctionDecl *Callee, const LValue *This,
1151 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1152 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1153 Info.CurrentCall = this;
1154 ++Info.CallStackDepth;
1157 CallStackFrame::~CallStackFrame() {
1158 assert(Info.CurrentCall == this && "calls retired out of order");
1159 --Info.CallStackDepth;
1160 Info.CurrentCall = Caller;
1163 APValue &CallStackFrame::createTemporary(const void *Key,
1164 bool IsLifetimeExtended) {
1165 APValue &Result = Temporaries[Key];
1166 assert(Result.isUninit() && "temporary created multiple times");
1167 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1171 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1173 void EvalInfo::addCallStack(unsigned Limit) {
1174 // Determine which calls to skip, if any.
1175 unsigned ActiveCalls = CallStackDepth - 1;
1176 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1177 if (Limit && Limit < ActiveCalls) {
1178 SkipStart = Limit / 2 + Limit % 2;
1179 SkipEnd = ActiveCalls - Limit / 2;
1182 // Walk the call stack and add the diagnostics.
1183 unsigned CallIdx = 0;
1184 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1185 Frame = Frame->Caller, ++CallIdx) {
1187 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1188 if (CallIdx == SkipStart) {
1189 // Note that we're skipping calls.
1190 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1191 << unsigned(ActiveCalls - Limit);
1196 // Use a different note for an inheriting constructor, because from the
1197 // user's perspective it's not really a function at all.
1198 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1199 if (CD->isInheritingConstructor()) {
1200 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1206 SmallVector<char, 128> Buffer;
1207 llvm::raw_svector_ostream Out(Buffer);
1208 describeCall(Frame, Out);
1209 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1214 struct ComplexValue {
1219 APSInt IntReal, IntImag;
1220 APFloat FloatReal, FloatImag;
1222 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1224 void makeComplexFloat() { IsInt = false; }
1225 bool isComplexFloat() const { return !IsInt; }
1226 APFloat &getComplexFloatReal() { return FloatReal; }
1227 APFloat &getComplexFloatImag() { return FloatImag; }
1229 void makeComplexInt() { IsInt = true; }
1230 bool isComplexInt() const { return IsInt; }
1231 APSInt &getComplexIntReal() { return IntReal; }
1232 APSInt &getComplexIntImag() { return IntImag; }
1234 void moveInto(APValue &v) const {
1235 if (isComplexFloat())
1236 v = APValue(FloatReal, FloatImag);
1238 v = APValue(IntReal, IntImag);
1240 void setFrom(const APValue &v) {
1241 assert(v.isComplexFloat() || v.isComplexInt());
1242 if (v.isComplexFloat()) {
1244 FloatReal = v.getComplexFloatReal();
1245 FloatImag = v.getComplexFloatImag();
1248 IntReal = v.getComplexIntReal();
1249 IntImag = v.getComplexIntImag();
1255 APValue::LValueBase Base;
1257 unsigned InvalidBase : 1;
1258 unsigned CallIndex : 31;
1259 SubobjectDesignator Designator;
1262 const APValue::LValueBase getLValueBase() const { return Base; }
1263 CharUnits &getLValueOffset() { return Offset; }
1264 const CharUnits &getLValueOffset() const { return Offset; }
1265 unsigned getLValueCallIndex() const { return CallIndex; }
1266 SubobjectDesignator &getLValueDesignator() { return Designator; }
1267 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1268 bool isNullPointer() const { return IsNullPtr;}
1270 void moveInto(APValue &V) const {
1271 if (Designator.Invalid)
1272 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1275 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1276 V = APValue(Base, Offset, Designator.Entries,
1277 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1280 void setFrom(ASTContext &Ctx, const APValue &V) {
1281 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1282 Base = V.getLValueBase();
1283 Offset = V.getLValueOffset();
1284 InvalidBase = false;
1285 CallIndex = V.getLValueCallIndex();
1286 Designator = SubobjectDesignator(Ctx, V);
1287 IsNullPtr = V.isNullPointer();
1290 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1292 // We only allow a few types of invalid bases. Enforce that here.
1294 const auto *E = B.get<const Expr *>();
1295 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1296 "Unexpected type of invalid base");
1301 Offset = CharUnits::fromQuantity(0);
1302 InvalidBase = BInvalid;
1304 Designator = SubobjectDesignator(getType(B));
1308 void setNull(QualType PointerTy, uint64_t TargetVal) {
1309 Base = (Expr *)nullptr;
1310 Offset = CharUnits::fromQuantity(TargetVal);
1311 InvalidBase = false;
1313 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1317 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1321 // Check that this LValue is not based on a null pointer. If it is, produce
1322 // a diagnostic and mark the designator as invalid.
1323 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1324 CheckSubobjectKind CSK) {
1325 if (Designator.Invalid)
1328 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1330 Designator.setInvalid();
1336 // Check this LValue refers to an object. If not, set the designator to be
1337 // invalid and emit a diagnostic.
1338 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1339 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1340 Designator.checkSubobject(Info, E, CSK);
1343 void addDecl(EvalInfo &Info, const Expr *E,
1344 const Decl *D, bool Virtual = false) {
1345 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1346 Designator.addDeclUnchecked(D, Virtual);
1348 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1349 if (!Designator.Entries.empty()) {
1350 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1351 Designator.setInvalid();
1354 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1355 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1356 Designator.FirstEntryIsAnUnsizedArray = true;
1357 Designator.addUnsizedArrayUnchecked(ElemTy);
1360 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1361 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1362 Designator.addArrayUnchecked(CAT);
1364 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1365 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1366 Designator.addComplexUnchecked(EltTy, Imag);
1368 void clearIsNullPointer() {
1371 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1372 const APSInt &Index, CharUnits ElementSize) {
1373 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1374 // but we're not required to diagnose it and it's valid in C++.)
1378 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1379 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1381 uint64_t Offset64 = Offset.getQuantity();
1382 uint64_t ElemSize64 = ElementSize.getQuantity();
1383 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1384 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1386 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1387 Designator.adjustIndex(Info, E, Index);
1388 clearIsNullPointer();
1390 void adjustOffset(CharUnits N) {
1392 if (N.getQuantity())
1393 clearIsNullPointer();
1399 explicit MemberPtr(const ValueDecl *Decl) :
1400 DeclAndIsDerivedMember(Decl, false), Path() {}
1402 /// The member or (direct or indirect) field referred to by this member
1403 /// pointer, or 0 if this is a null member pointer.
1404 const ValueDecl *getDecl() const {
1405 return DeclAndIsDerivedMember.getPointer();
1407 /// Is this actually a member of some type derived from the relevant class?
1408 bool isDerivedMember() const {
1409 return DeclAndIsDerivedMember.getInt();
1411 /// Get the class which the declaration actually lives in.
1412 const CXXRecordDecl *getContainingRecord() const {
1413 return cast<CXXRecordDecl>(
1414 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1417 void moveInto(APValue &V) const {
1418 V = APValue(getDecl(), isDerivedMember(), Path);
1420 void setFrom(const APValue &V) {
1421 assert(V.isMemberPointer());
1422 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1423 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1425 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1426 Path.insert(Path.end(), P.begin(), P.end());
1429 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1430 /// whether the member is a member of some class derived from the class type
1431 /// of the member pointer.
1432 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1433 /// Path - The path of base/derived classes from the member declaration's
1434 /// class (exclusive) to the class type of the member pointer (inclusive).
1435 SmallVector<const CXXRecordDecl*, 4> Path;
1437 /// Perform a cast towards the class of the Decl (either up or down the
1439 bool castBack(const CXXRecordDecl *Class) {
1440 assert(!Path.empty());
1441 const CXXRecordDecl *Expected;
1442 if (Path.size() >= 2)
1443 Expected = Path[Path.size() - 2];
1445 Expected = getContainingRecord();
1446 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1447 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1448 // if B does not contain the original member and is not a base or
1449 // derived class of the class containing the original member, the result
1450 // of the cast is undefined.
1451 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1452 // (D::*). We consider that to be a language defect.
1458 /// Perform a base-to-derived member pointer cast.
1459 bool castToDerived(const CXXRecordDecl *Derived) {
1462 if (!isDerivedMember()) {
1463 Path.push_back(Derived);
1466 if (!castBack(Derived))
1469 DeclAndIsDerivedMember.setInt(false);
1472 /// Perform a derived-to-base member pointer cast.
1473 bool castToBase(const CXXRecordDecl *Base) {
1477 DeclAndIsDerivedMember.setInt(true);
1478 if (isDerivedMember()) {
1479 Path.push_back(Base);
1482 return castBack(Base);
1486 /// Compare two member pointers, which are assumed to be of the same type.
1487 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1488 if (!LHS.getDecl() || !RHS.getDecl())
1489 return !LHS.getDecl() && !RHS.getDecl();
1490 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1492 return LHS.Path == RHS.Path;
1496 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1497 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1498 const LValue &This, const Expr *E,
1499 bool AllowNonLiteralTypes = false);
1500 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1501 bool InvalidBaseOK = false);
1502 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1503 bool InvalidBaseOK = false);
1504 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1506 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1507 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1508 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1510 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1511 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1512 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1514 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1516 //===----------------------------------------------------------------------===//
1518 //===----------------------------------------------------------------------===//
1520 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1521 /// preserving its value (by extending by up to one bit as needed).
1522 static void negateAsSigned(APSInt &Int) {
1523 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1524 Int = Int.extend(Int.getBitWidth() + 1);
1525 Int.setIsSigned(true);
1530 /// Produce a string describing the given constexpr call.
1531 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1532 unsigned ArgIndex = 0;
1533 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1534 !isa<CXXConstructorDecl>(Frame->Callee) &&
1535 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1538 Out << *Frame->Callee << '(';
1540 if (Frame->This && IsMemberCall) {
1542 Frame->This->moveInto(Val);
1543 Val.printPretty(Out, Frame->Info.Ctx,
1544 Frame->This->Designator.MostDerivedType);
1545 // FIXME: Add parens around Val if needed.
1546 Out << "->" << *Frame->Callee << '(';
1547 IsMemberCall = false;
1550 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1551 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1552 if (ArgIndex > (unsigned)IsMemberCall)
1555 const ParmVarDecl *Param = *I;
1556 const APValue &Arg = Frame->Arguments[ArgIndex];
1557 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1559 if (ArgIndex == 0 && IsMemberCall)
1560 Out << "->" << *Frame->Callee << '(';
1566 /// Evaluate an expression to see if it had side-effects, and discard its
1568 /// \return \c true if the caller should keep evaluating.
1569 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1571 if (!Evaluate(Scratch, Info, E))
1572 // We don't need the value, but we might have skipped a side effect here.
1573 return Info.noteSideEffect();
1577 /// Should this call expression be treated as a string literal?
1578 static bool IsStringLiteralCall(const CallExpr *E) {
1579 unsigned Builtin = E->getBuiltinCallee();
1580 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1581 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1584 static bool IsGlobalLValue(APValue::LValueBase B) {
1585 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1586 // constant expression of pointer type that evaluates to...
1588 // ... a null pointer value, or a prvalue core constant expression of type
1590 if (!B) return true;
1592 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1593 // ... the address of an object with static storage duration,
1594 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1595 return VD->hasGlobalStorage();
1596 // ... the address of a function,
1597 return isa<FunctionDecl>(D);
1600 const Expr *E = B.get<const Expr*>();
1601 switch (E->getStmtClass()) {
1604 case Expr::CompoundLiteralExprClass: {
1605 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1606 return CLE->isFileScope() && CLE->isLValue();
1608 case Expr::MaterializeTemporaryExprClass:
1609 // A materialized temporary might have been lifetime-extended to static
1610 // storage duration.
1611 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1612 // A string literal has static storage duration.
1613 case Expr::StringLiteralClass:
1614 case Expr::PredefinedExprClass:
1615 case Expr::ObjCStringLiteralClass:
1616 case Expr::ObjCEncodeExprClass:
1617 case Expr::CXXTypeidExprClass:
1618 case Expr::CXXUuidofExprClass:
1620 case Expr::CallExprClass:
1621 return IsStringLiteralCall(cast<CallExpr>(E));
1622 // For GCC compatibility, &&label has static storage duration.
1623 case Expr::AddrLabelExprClass:
1625 // A Block literal expression may be used as the initialization value for
1626 // Block variables at global or local static scope.
1627 case Expr::BlockExprClass:
1628 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1629 case Expr::ImplicitValueInitExprClass:
1631 // We can never form an lvalue with an implicit value initialization as its
1632 // base through expression evaluation, so these only appear in one case: the
1633 // implicit variable declaration we invent when checking whether a constexpr
1634 // constructor can produce a constant expression. We must assume that such
1635 // an expression might be a global lvalue.
1640 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1641 assert(Base && "no location for a null lvalue");
1642 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1644 Info.Note(VD->getLocation(), diag::note_declared_at);
1646 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1647 diag::note_constexpr_temporary_here);
1650 /// Check that this reference or pointer core constant expression is a valid
1651 /// value for an address or reference constant expression. Return true if we
1652 /// can fold this expression, whether or not it's a constant expression.
1653 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1654 QualType Type, const LValue &LVal) {
1655 bool IsReferenceType = Type->isReferenceType();
1657 APValue::LValueBase Base = LVal.getLValueBase();
1658 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1660 // Check that the object is a global. Note that the fake 'this' object we
1661 // manufacture when checking potential constant expressions is conservatively
1662 // assumed to be global here.
1663 if (!IsGlobalLValue(Base)) {
1664 if (Info.getLangOpts().CPlusPlus11) {
1665 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1666 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1667 << IsReferenceType << !Designator.Entries.empty()
1669 NoteLValueLocation(Info, Base);
1673 // Don't allow references to temporaries to escape.
1676 assert((Info.checkingPotentialConstantExpression() ||
1677 LVal.getLValueCallIndex() == 0) &&
1678 "have call index for global lvalue");
1680 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1681 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1682 // Check if this is a thread-local variable.
1683 if (Var->getTLSKind())
1686 // A dllimport variable never acts like a constant.
1687 if (Var->hasAttr<DLLImportAttr>())
1690 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1691 // __declspec(dllimport) must be handled very carefully:
1692 // We must never initialize an expression with the thunk in C++.
1693 // Doing otherwise would allow the same id-expression to yield
1694 // different addresses for the same function in different translation
1695 // units. However, this means that we must dynamically initialize the
1696 // expression with the contents of the import address table at runtime.
1698 // The C language has no notion of ODR; furthermore, it has no notion of
1699 // dynamic initialization. This means that we are permitted to
1700 // perform initialization with the address of the thunk.
1701 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1706 // Allow address constant expressions to be past-the-end pointers. This is
1707 // an extension: the standard requires them to point to an object.
1708 if (!IsReferenceType)
1711 // A reference constant expression must refer to an object.
1713 // FIXME: diagnostic
1718 // Does this refer one past the end of some object?
1719 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1720 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1721 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1722 << !Designator.Entries.empty() << !!VD << VD;
1723 NoteLValueLocation(Info, Base);
1729 /// Member pointers are constant expressions unless they point to a
1730 /// non-virtual dllimport member function.
1731 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1734 const APValue &Value) {
1735 const ValueDecl *Member = Value.getMemberPointerDecl();
1736 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1739 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1742 /// Check that this core constant expression is of literal type, and if not,
1743 /// produce an appropriate diagnostic.
1744 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1745 const LValue *This = nullptr) {
1746 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1749 // C++1y: A constant initializer for an object o [...] may also invoke
1750 // constexpr constructors for o and its subobjects even if those objects
1751 // are of non-literal class types.
1753 // C++11 missed this detail for aggregates, so classes like this:
1754 // struct foo_t { union { int i; volatile int j; } u; };
1755 // are not (obviously) initializable like so:
1756 // __attribute__((__require_constant_initialization__))
1757 // static const foo_t x = {{0}};
1758 // because "i" is a subobject with non-literal initialization (due to the
1759 // volatile member of the union). See:
1760 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1761 // Therefore, we use the C++1y behavior.
1762 if (This && Info.EvaluatingDecl == This->getLValueBase())
1765 // Prvalue constant expressions must be of literal types.
1766 if (Info.getLangOpts().CPlusPlus11)
1767 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1774 /// Check that this core constant expression value is a valid value for a
1775 /// constant expression. If not, report an appropriate diagnostic. Does not
1776 /// check that the expression is of literal type.
1777 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1778 QualType Type, const APValue &Value) {
1779 if (Value.isUninit()) {
1780 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1785 // We allow _Atomic(T) to be initialized from anything that T can be
1786 // initialized from.
1787 if (const AtomicType *AT = Type->getAs<AtomicType>())
1788 Type = AT->getValueType();
1790 // Core issue 1454: For a literal constant expression of array or class type,
1791 // each subobject of its value shall have been initialized by a constant
1793 if (Value.isArray()) {
1794 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1795 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1796 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1797 Value.getArrayInitializedElt(I)))
1800 if (!Value.hasArrayFiller())
1802 return CheckConstantExpression(Info, DiagLoc, EltTy,
1803 Value.getArrayFiller());
1805 if (Value.isUnion() && Value.getUnionField()) {
1806 return CheckConstantExpression(Info, DiagLoc,
1807 Value.getUnionField()->getType(),
1808 Value.getUnionValue());
1810 if (Value.isStruct()) {
1811 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1812 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1813 unsigned BaseIndex = 0;
1814 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1815 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1816 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1817 Value.getStructBase(BaseIndex)))
1821 for (const auto *I : RD->fields()) {
1822 if (I->isUnnamedBitfield())
1825 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1826 Value.getStructField(I->getFieldIndex())))
1831 if (Value.isLValue()) {
1833 LVal.setFrom(Info.Ctx, Value);
1834 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1837 if (Value.isMemberPointer())
1838 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1840 // Everything else is fine.
1844 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1845 return LVal.Base.dyn_cast<const ValueDecl*>();
1848 static bool IsLiteralLValue(const LValue &Value) {
1849 if (Value.CallIndex)
1851 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1852 return E && !isa<MaterializeTemporaryExpr>(E);
1855 static bool IsWeakLValue(const LValue &Value) {
1856 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1857 return Decl && Decl->isWeak();
1860 static bool isZeroSized(const LValue &Value) {
1861 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1862 if (Decl && isa<VarDecl>(Decl)) {
1863 QualType Ty = Decl->getType();
1864 if (Ty->isArrayType())
1865 return Ty->isIncompleteType() ||
1866 Decl->getASTContext().getTypeSize(Ty) == 0;
1871 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1872 // A null base expression indicates a null pointer. These are always
1873 // evaluatable, and they are false unless the offset is zero.
1874 if (!Value.getLValueBase()) {
1875 Result = !Value.getLValueOffset().isZero();
1879 // We have a non-null base. These are generally known to be true, but if it's
1880 // a weak declaration it can be null at runtime.
1882 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1883 return !Decl || !Decl->isWeak();
1886 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1887 switch (Val.getKind()) {
1888 case APValue::Uninitialized:
1891 Result = Val.getInt().getBoolValue();
1893 case APValue::Float:
1894 Result = !Val.getFloat().isZero();
1896 case APValue::ComplexInt:
1897 Result = Val.getComplexIntReal().getBoolValue() ||
1898 Val.getComplexIntImag().getBoolValue();
1900 case APValue::ComplexFloat:
1901 Result = !Val.getComplexFloatReal().isZero() ||
1902 !Val.getComplexFloatImag().isZero();
1904 case APValue::LValue:
1905 return EvalPointerValueAsBool(Val, Result);
1906 case APValue::MemberPointer:
1907 Result = Val.getMemberPointerDecl();
1909 case APValue::Vector:
1910 case APValue::Array:
1911 case APValue::Struct:
1912 case APValue::Union:
1913 case APValue::AddrLabelDiff:
1917 llvm_unreachable("unknown APValue kind");
1920 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1922 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1924 if (!Evaluate(Val, Info, E))
1926 return HandleConversionToBool(Val, Result);
1929 template<typename T>
1930 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1931 const T &SrcValue, QualType DestType) {
1932 Info.CCEDiag(E, diag::note_constexpr_overflow)
1933 << SrcValue << DestType;
1934 return Info.noteUndefinedBehavior();
1937 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1938 QualType SrcType, const APFloat &Value,
1939 QualType DestType, APSInt &Result) {
1940 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1941 // Determine whether we are converting to unsigned or signed.
1942 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1944 Result = APSInt(DestWidth, !DestSigned);
1946 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1947 & APFloat::opInvalidOp)
1948 return HandleOverflow(Info, E, Value, DestType);
1952 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1953 QualType SrcType, QualType DestType,
1955 APFloat Value = Result;
1957 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1958 APFloat::rmNearestTiesToEven, &ignored)
1959 & APFloat::opOverflow)
1960 return HandleOverflow(Info, E, Value, DestType);
1964 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1965 QualType DestType, QualType SrcType,
1966 const APSInt &Value) {
1967 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1968 APSInt Result = Value;
1969 // Figure out if this is a truncate, extend or noop cast.
1970 // If the input is signed, do a sign extend, noop, or truncate.
1971 Result = Result.extOrTrunc(DestWidth);
1972 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1976 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1977 QualType SrcType, const APSInt &Value,
1978 QualType DestType, APFloat &Result) {
1979 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1980 if (Result.convertFromAPInt(Value, Value.isSigned(),
1981 APFloat::rmNearestTiesToEven)
1982 & APFloat::opOverflow)
1983 return HandleOverflow(Info, E, Value, DestType);
1987 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1988 APValue &Value, const FieldDecl *FD) {
1989 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1991 if (!Value.isInt()) {
1992 // Trying to store a pointer-cast-to-integer into a bitfield.
1993 // FIXME: In this case, we should provide the diagnostic for casting
1994 // a pointer to an integer.
1995 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2000 APSInt &Int = Value.getInt();
2001 unsigned OldBitWidth = Int.getBitWidth();
2002 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2003 if (NewBitWidth < OldBitWidth)
2004 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2008 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2011 if (!Evaluate(SVal, Info, E))
2014 Res = SVal.getInt();
2017 if (SVal.isFloat()) {
2018 Res = SVal.getFloat().bitcastToAPInt();
2021 if (SVal.isVector()) {
2022 QualType VecTy = E->getType();
2023 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2024 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2025 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2026 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2027 Res = llvm::APInt::getNullValue(VecSize);
2028 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2029 APValue &Elt = SVal.getVectorElt(i);
2030 llvm::APInt EltAsInt;
2032 EltAsInt = Elt.getInt();
2033 } else if (Elt.isFloat()) {
2034 EltAsInt = Elt.getFloat().bitcastToAPInt();
2036 // Don't try to handle vectors of anything other than int or float
2037 // (not sure if it's possible to hit this case).
2038 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2041 unsigned BaseEltSize = EltAsInt.getBitWidth();
2043 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2045 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2049 // Give up if the input isn't an int, float, or vector. For example, we
2050 // reject "(v4i16)(intptr_t)&a".
2051 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2055 /// Perform the given integer operation, which is known to need at most BitWidth
2056 /// bits, and check for overflow in the original type (if that type was not an
2058 template<typename Operation>
2059 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2060 const APSInt &LHS, const APSInt &RHS,
2061 unsigned BitWidth, Operation Op,
2063 if (LHS.isUnsigned()) {
2064 Result = Op(LHS, RHS);
2068 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2069 Result = Value.trunc(LHS.getBitWidth());
2070 if (Result.extend(BitWidth) != Value) {
2071 if (Info.checkingForOverflow())
2072 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2073 diag::warn_integer_constant_overflow)
2074 << Result.toString(10) << E->getType();
2076 return HandleOverflow(Info, E, Value, E->getType());
2081 /// Perform the given binary integer operation.
2082 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2083 BinaryOperatorKind Opcode, APSInt RHS,
2090 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2091 std::multiplies<APSInt>(), Result);
2093 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2094 std::plus<APSInt>(), Result);
2096 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2097 std::minus<APSInt>(), Result);
2098 case BO_And: Result = LHS & RHS; return true;
2099 case BO_Xor: Result = LHS ^ RHS; return true;
2100 case BO_Or: Result = LHS | RHS; return true;
2104 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2107 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2108 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2109 // this operation and gives the two's complement result.
2110 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2111 LHS.isSigned() && LHS.isMinSignedValue())
2112 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2116 if (Info.getLangOpts().OpenCL)
2117 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2118 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2119 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2121 else if (RHS.isSigned() && RHS.isNegative()) {
2122 // During constant-folding, a negative shift is an opposite shift. Such
2123 // a shift is not a constant expression.
2124 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2129 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2130 // the shifted type.
2131 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2133 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2134 << RHS << E->getType() << LHS.getBitWidth();
2135 } else if (LHS.isSigned()) {
2136 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2137 // operand, and must not overflow the corresponding unsigned type.
2138 if (LHS.isNegative())
2139 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2140 else if (LHS.countLeadingZeros() < SA)
2141 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2147 if (Info.getLangOpts().OpenCL)
2148 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2149 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2150 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2152 else if (RHS.isSigned() && RHS.isNegative()) {
2153 // During constant-folding, a negative shift is an opposite shift. Such a
2154 // shift is not a constant expression.
2155 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2160 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2162 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2164 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2165 << RHS << E->getType() << LHS.getBitWidth();
2170 case BO_LT: Result = LHS < RHS; return true;
2171 case BO_GT: Result = LHS > RHS; return true;
2172 case BO_LE: Result = LHS <= RHS; return true;
2173 case BO_GE: Result = LHS >= RHS; return true;
2174 case BO_EQ: Result = LHS == RHS; return true;
2175 case BO_NE: Result = LHS != RHS; return true;
2179 /// Perform the given binary floating-point operation, in-place, on LHS.
2180 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2181 APFloat &LHS, BinaryOperatorKind Opcode,
2182 const APFloat &RHS) {
2188 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2191 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2194 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2197 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2201 if (LHS.isInfinity() || LHS.isNaN()) {
2202 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2203 return Info.noteUndefinedBehavior();
2208 /// Cast an lvalue referring to a base subobject to a derived class, by
2209 /// truncating the lvalue's path to the given length.
2210 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2211 const RecordDecl *TruncatedType,
2212 unsigned TruncatedElements) {
2213 SubobjectDesignator &D = Result.Designator;
2215 // Check we actually point to a derived class object.
2216 if (TruncatedElements == D.Entries.size())
2218 assert(TruncatedElements >= D.MostDerivedPathLength &&
2219 "not casting to a derived class");
2220 if (!Result.checkSubobject(Info, E, CSK_Derived))
2223 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2224 const RecordDecl *RD = TruncatedType;
2225 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2226 if (RD->isInvalidDecl()) return false;
2227 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2228 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2229 if (isVirtualBaseClass(D.Entries[I]))
2230 Result.Offset -= Layout.getVBaseClassOffset(Base);
2232 Result.Offset -= Layout.getBaseClassOffset(Base);
2235 D.Entries.resize(TruncatedElements);
2239 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2240 const CXXRecordDecl *Derived,
2241 const CXXRecordDecl *Base,
2242 const ASTRecordLayout *RL = nullptr) {
2244 if (Derived->isInvalidDecl()) return false;
2245 RL = &Info.Ctx.getASTRecordLayout(Derived);
2248 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2249 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2253 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2254 const CXXRecordDecl *DerivedDecl,
2255 const CXXBaseSpecifier *Base) {
2256 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2258 if (!Base->isVirtual())
2259 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2261 SubobjectDesignator &D = Obj.Designator;
2265 // Extract most-derived object and corresponding type.
2266 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2267 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2270 // Find the virtual base class.
2271 if (DerivedDecl->isInvalidDecl()) return false;
2272 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2273 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2274 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2278 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2279 QualType Type, LValue &Result) {
2280 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2281 PathE = E->path_end();
2282 PathI != PathE; ++PathI) {
2283 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2286 Type = (*PathI)->getType();
2291 /// Update LVal to refer to the given field, which must be a member of the type
2292 /// currently described by LVal.
2293 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2294 const FieldDecl *FD,
2295 const ASTRecordLayout *RL = nullptr) {
2297 if (FD->getParent()->isInvalidDecl()) return false;
2298 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2301 unsigned I = FD->getFieldIndex();
2302 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2303 LVal.addDecl(Info, E, FD);
2307 /// Update LVal to refer to the given indirect field.
2308 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2310 const IndirectFieldDecl *IFD) {
2311 for (const auto *C : IFD->chain())
2312 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2317 /// Get the size of the given type in char units.
2318 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2319 QualType Type, CharUnits &Size) {
2320 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2322 if (Type->isVoidType() || Type->isFunctionType()) {
2323 Size = CharUnits::One();
2327 if (Type->isDependentType()) {
2332 if (!Type->isConstantSizeType()) {
2333 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2334 // FIXME: Better diagnostic.
2339 Size = Info.Ctx.getTypeSizeInChars(Type);
2343 /// Update a pointer value to model pointer arithmetic.
2344 /// \param Info - Information about the ongoing evaluation.
2345 /// \param E - The expression being evaluated, for diagnostic purposes.
2346 /// \param LVal - The pointer value to be updated.
2347 /// \param EltTy - The pointee type represented by LVal.
2348 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2349 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2350 LValue &LVal, QualType EltTy,
2351 APSInt Adjustment) {
2352 CharUnits SizeOfPointee;
2353 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2356 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2360 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2361 LValue &LVal, QualType EltTy,
2362 int64_t Adjustment) {
2363 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2364 APSInt::get(Adjustment));
2367 /// Update an lvalue to refer to a component of a complex number.
2368 /// \param Info - Information about the ongoing evaluation.
2369 /// \param LVal - The lvalue to be updated.
2370 /// \param EltTy - The complex number's component type.
2371 /// \param Imag - False for the real component, true for the imaginary.
2372 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2373 LValue &LVal, QualType EltTy,
2376 CharUnits SizeOfComponent;
2377 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2379 LVal.Offset += SizeOfComponent;
2381 LVal.addComplex(Info, E, EltTy, Imag);
2385 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2386 QualType Type, const LValue &LVal,
2389 /// Try to evaluate the initializer for a variable declaration.
2391 /// \param Info Information about the ongoing evaluation.
2392 /// \param E An expression to be used when printing diagnostics.
2393 /// \param VD The variable whose initializer should be obtained.
2394 /// \param Frame The frame in which the variable was created. Must be null
2395 /// if this variable is not local to the evaluation.
2396 /// \param Result Filled in with a pointer to the value of the variable.
2397 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2398 const VarDecl *VD, CallStackFrame *Frame,
2401 // If this is a parameter to an active constexpr function call, perform
2402 // argument substitution.
2403 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2404 // Assume arguments of a potential constant expression are unknown
2405 // constant expressions.
2406 if (Info.checkingPotentialConstantExpression())
2408 if (!Frame || !Frame->Arguments) {
2409 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2412 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2416 // If this is a local variable, dig out its value.
2418 Result = Frame->getTemporary(VD);
2420 // Assume variables referenced within a lambda's call operator that were
2421 // not declared within the call operator are captures and during checking
2422 // of a potential constant expression, assume they are unknown constant
2424 assert(isLambdaCallOperator(Frame->Callee) &&
2425 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2426 "missing value for local variable");
2427 if (Info.checkingPotentialConstantExpression())
2429 // FIXME: implement capture evaluation during constant expr evaluation.
2430 Info.FFDiag(E->getLocStart(),
2431 diag::note_unimplemented_constexpr_lambda_feature_ast)
2432 << "captures not currently allowed";
2438 // Dig out the initializer, and use the declaration which it's attached to.
2439 const Expr *Init = VD->getAnyInitializer(VD);
2440 if (!Init || Init->isValueDependent()) {
2441 // If we're checking a potential constant expression, the variable could be
2442 // initialized later.
2443 if (!Info.checkingPotentialConstantExpression())
2444 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2448 // If we're currently evaluating the initializer of this declaration, use that
2450 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2451 Result = Info.EvaluatingDeclValue;
2455 // Never evaluate the initializer of a weak variable. We can't be sure that
2456 // this is the definition which will be used.
2458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2462 // Check that we can fold the initializer. In C++, we will have already done
2463 // this in the cases where it matters for conformance.
2464 SmallVector<PartialDiagnosticAt, 8> Notes;
2465 if (!VD->evaluateValue(Notes)) {
2466 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2467 Notes.size() + 1) << VD;
2468 Info.Note(VD->getLocation(), diag::note_declared_at);
2469 Info.addNotes(Notes);
2471 } else if (!VD->checkInitIsICE()) {
2472 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2473 Notes.size() + 1) << VD;
2474 Info.Note(VD->getLocation(), diag::note_declared_at);
2475 Info.addNotes(Notes);
2478 Result = VD->getEvaluatedValue();
2482 static bool IsConstNonVolatile(QualType T) {
2483 Qualifiers Quals = T.getQualifiers();
2484 return Quals.hasConst() && !Quals.hasVolatile();
2487 /// Get the base index of the given base class within an APValue representing
2488 /// the given derived class.
2489 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2490 const CXXRecordDecl *Base) {
2491 Base = Base->getCanonicalDecl();
2493 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2494 E = Derived->bases_end(); I != E; ++I, ++Index) {
2495 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2499 llvm_unreachable("base class missing from derived class's bases list");
2502 /// Extract the value of a character from a string literal.
2503 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2505 // FIXME: Support MakeStringConstant
2506 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2508 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2509 assert(Index <= Str.size() && "Index too large");
2510 return APSInt::getUnsigned(Str.c_str()[Index]);
2513 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2514 Lit = PE->getFunctionName();
2515 const StringLiteral *S = cast<StringLiteral>(Lit);
2516 const ConstantArrayType *CAT =
2517 Info.Ctx.getAsConstantArrayType(S->getType());
2518 assert(CAT && "string literal isn't an array");
2519 QualType CharType = CAT->getElementType();
2520 assert(CharType->isIntegerType() && "unexpected character type");
2522 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2523 CharType->isUnsignedIntegerType());
2524 if (Index < S->getLength())
2525 Value = S->getCodeUnit(Index);
2529 // Expand a string literal into an array of characters.
2530 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2532 const StringLiteral *S = cast<StringLiteral>(Lit);
2533 const ConstantArrayType *CAT =
2534 Info.Ctx.getAsConstantArrayType(S->getType());
2535 assert(CAT && "string literal isn't an array");
2536 QualType CharType = CAT->getElementType();
2537 assert(CharType->isIntegerType() && "unexpected character type");
2539 unsigned Elts = CAT->getSize().getZExtValue();
2540 Result = APValue(APValue::UninitArray(),
2541 std::min(S->getLength(), Elts), Elts);
2542 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2543 CharType->isUnsignedIntegerType());
2544 if (Result.hasArrayFiller())
2545 Result.getArrayFiller() = APValue(Value);
2546 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2547 Value = S->getCodeUnit(I);
2548 Result.getArrayInitializedElt(I) = APValue(Value);
2552 // Expand an array so that it has more than Index filled elements.
2553 static void expandArray(APValue &Array, unsigned Index) {
2554 unsigned Size = Array.getArraySize();
2555 assert(Index < Size);
2557 // Always at least double the number of elements for which we store a value.
2558 unsigned OldElts = Array.getArrayInitializedElts();
2559 unsigned NewElts = std::max(Index+1, OldElts * 2);
2560 NewElts = std::min(Size, std::max(NewElts, 8u));
2562 // Copy the data across.
2563 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2564 for (unsigned I = 0; I != OldElts; ++I)
2565 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2566 for (unsigned I = OldElts; I != NewElts; ++I)
2567 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2568 if (NewValue.hasArrayFiller())
2569 NewValue.getArrayFiller() = Array.getArrayFiller();
2570 Array.swap(NewValue);
2573 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2574 /// conversion. If it's of class type, we may assume that the copy operation
2575 /// is trivial. Note that this is never true for a union type with fields
2576 /// (because the copy always "reads" the active member) and always true for
2577 /// a non-class type.
2578 static bool isReadByLvalueToRvalueConversion(QualType T) {
2579 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2580 if (!RD || (RD->isUnion() && !RD->field_empty()))
2585 for (auto *Field : RD->fields())
2586 if (isReadByLvalueToRvalueConversion(Field->getType()))
2589 for (auto &BaseSpec : RD->bases())
2590 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2596 /// Diagnose an attempt to read from any unreadable field within the specified
2597 /// type, which might be a class type.
2598 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2600 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2604 if (!RD->hasMutableFields())
2607 for (auto *Field : RD->fields()) {
2608 // If we're actually going to read this field in some way, then it can't
2609 // be mutable. If we're in a union, then assigning to a mutable field
2610 // (even an empty one) can change the active member, so that's not OK.
2611 // FIXME: Add core issue number for the union case.
2612 if (Field->isMutable() &&
2613 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2614 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2615 Info.Note(Field->getLocation(), diag::note_declared_at);
2619 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2623 for (auto &BaseSpec : RD->bases())
2624 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2627 // All mutable fields were empty, and thus not actually read.
2631 /// Kinds of access we can perform on an object, for diagnostics.
2640 /// A handle to a complete object (an object that is not a subobject of
2641 /// another object).
2642 struct CompleteObject {
2643 /// The value of the complete object.
2645 /// The type of the complete object.
2648 CompleteObject() : Value(nullptr) {}
2649 CompleteObject(APValue *Value, QualType Type)
2650 : Value(Value), Type(Type) {
2651 assert(Value && "missing value for complete object");
2654 explicit operator bool() const { return Value; }
2656 } // end anonymous namespace
2658 /// Find the designated sub-object of an rvalue.
2659 template<typename SubobjectHandler>
2660 typename SubobjectHandler::result_type
2661 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2662 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2664 // A diagnostic will have already been produced.
2665 return handler.failed();
2666 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2667 if (Info.getLangOpts().CPlusPlus11)
2668 Info.FFDiag(E, Sub.isOnePastTheEnd()
2669 ? diag::note_constexpr_access_past_end
2670 : diag::note_constexpr_access_unsized_array)
2671 << handler.AccessKind;
2674 return handler.failed();
2677 APValue *O = Obj.Value;
2678 QualType ObjType = Obj.Type;
2679 const FieldDecl *LastField = nullptr;
2681 // Walk the designator's path to find the subobject.
2682 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2683 if (O->isUninit()) {
2684 if (!Info.checkingPotentialConstantExpression())
2685 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2686 return handler.failed();
2690 // If we are reading an object of class type, there may still be more
2691 // things we need to check: if there are any mutable subobjects, we
2692 // cannot perform this read. (This only happens when performing a trivial
2693 // copy or assignment.)
2694 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2695 diagnoseUnreadableFields(Info, E, ObjType))
2696 return handler.failed();
2698 if (!handler.found(*O, ObjType))
2701 // If we modified a bit-field, truncate it to the right width.
2702 if (handler.AccessKind != AK_Read &&
2703 LastField && LastField->isBitField() &&
2704 !truncateBitfieldValue(Info, E, *O, LastField))
2710 LastField = nullptr;
2711 if (ObjType->isArrayType()) {
2712 // Next subobject is an array element.
2713 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2714 assert(CAT && "vla in literal type?");
2715 uint64_t Index = Sub.Entries[I].ArrayIndex;
2716 if (CAT->getSize().ule(Index)) {
2717 // Note, it should not be possible to form a pointer with a valid
2718 // designator which points more than one past the end of the array.
2719 if (Info.getLangOpts().CPlusPlus11)
2720 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2721 << handler.AccessKind;
2724 return handler.failed();
2727 ObjType = CAT->getElementType();
2729 // An array object is represented as either an Array APValue or as an
2730 // LValue which refers to a string literal.
2731 if (O->isLValue()) {
2732 assert(I == N - 1 && "extracting subobject of character?");
2733 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2734 if (handler.AccessKind != AK_Read)
2735 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2738 return handler.foundString(*O, ObjType, Index);
2741 if (O->getArrayInitializedElts() > Index)
2742 O = &O->getArrayInitializedElt(Index);
2743 else if (handler.AccessKind != AK_Read) {
2744 expandArray(*O, Index);
2745 O = &O->getArrayInitializedElt(Index);
2747 O = &O->getArrayFiller();
2748 } else if (ObjType->isAnyComplexType()) {
2749 // Next subobject is a complex number.
2750 uint64_t Index = Sub.Entries[I].ArrayIndex;
2752 if (Info.getLangOpts().CPlusPlus11)
2753 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2754 << handler.AccessKind;
2757 return handler.failed();
2760 bool WasConstQualified = ObjType.isConstQualified();
2761 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2762 if (WasConstQualified)
2765 assert(I == N - 1 && "extracting subobject of scalar?");
2766 if (O->isComplexInt()) {
2767 return handler.found(Index ? O->getComplexIntImag()
2768 : O->getComplexIntReal(), ObjType);
2770 assert(O->isComplexFloat());
2771 return handler.found(Index ? O->getComplexFloatImag()
2772 : O->getComplexFloatReal(), ObjType);
2774 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2775 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2776 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2778 Info.Note(Field->getLocation(), diag::note_declared_at);
2779 return handler.failed();
2782 // Next subobject is a class, struct or union field.
2783 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2784 if (RD->isUnion()) {
2785 const FieldDecl *UnionField = O->getUnionField();
2787 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2788 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2789 << handler.AccessKind << Field << !UnionField << UnionField;
2790 return handler.failed();
2792 O = &O->getUnionValue();
2794 O = &O->getStructField(Field->getFieldIndex());
2796 bool WasConstQualified = ObjType.isConstQualified();
2797 ObjType = Field->getType();
2798 if (WasConstQualified && !Field->isMutable())
2801 if (ObjType.isVolatileQualified()) {
2802 if (Info.getLangOpts().CPlusPlus) {
2803 // FIXME: Include a description of the path to the volatile subobject.
2804 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2805 << handler.AccessKind << 2 << Field;
2806 Info.Note(Field->getLocation(), diag::note_declared_at);
2808 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2810 return handler.failed();
2815 // Next subobject is a base class.
2816 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2817 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2818 O = &O->getStructBase(getBaseIndex(Derived, Base));
2820 bool WasConstQualified = ObjType.isConstQualified();
2821 ObjType = Info.Ctx.getRecordType(Base);
2822 if (WasConstQualified)
2829 struct ExtractSubobjectHandler {
2833 static const AccessKinds AccessKind = AK_Read;
2835 typedef bool result_type;
2836 bool failed() { return false; }
2837 bool found(APValue &Subobj, QualType SubobjType) {
2841 bool found(APSInt &Value, QualType SubobjType) {
2842 Result = APValue(Value);
2845 bool found(APFloat &Value, QualType SubobjType) {
2846 Result = APValue(Value);
2849 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2850 Result = APValue(extractStringLiteralCharacter(
2851 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2855 } // end anonymous namespace
2857 const AccessKinds ExtractSubobjectHandler::AccessKind;
2859 /// Extract the designated sub-object of an rvalue.
2860 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2861 const CompleteObject &Obj,
2862 const SubobjectDesignator &Sub,
2864 ExtractSubobjectHandler Handler = { Info, Result };
2865 return findSubobject(Info, E, Obj, Sub, Handler);
2869 struct ModifySubobjectHandler {
2874 typedef bool result_type;
2875 static const AccessKinds AccessKind = AK_Assign;
2877 bool checkConst(QualType QT) {
2878 // Assigning to a const object has undefined behavior.
2879 if (QT.isConstQualified()) {
2880 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2886 bool failed() { return false; }
2887 bool found(APValue &Subobj, QualType SubobjType) {
2888 if (!checkConst(SubobjType))
2890 // We've been given ownership of NewVal, so just swap it in.
2891 Subobj.swap(NewVal);
2894 bool found(APSInt &Value, QualType SubobjType) {
2895 if (!checkConst(SubobjType))
2897 if (!NewVal.isInt()) {
2898 // Maybe trying to write a cast pointer value into a complex?
2902 Value = NewVal.getInt();
2905 bool found(APFloat &Value, QualType SubobjType) {
2906 if (!checkConst(SubobjType))
2908 Value = NewVal.getFloat();
2911 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2912 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2915 } // end anonymous namespace
2917 const AccessKinds ModifySubobjectHandler::AccessKind;
2919 /// Update the designated sub-object of an rvalue to the given value.
2920 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2921 const CompleteObject &Obj,
2922 const SubobjectDesignator &Sub,
2924 ModifySubobjectHandler Handler = { Info, NewVal, E };
2925 return findSubobject(Info, E, Obj, Sub, Handler);
2928 /// Find the position where two subobject designators diverge, or equivalently
2929 /// the length of the common initial subsequence.
2930 static unsigned FindDesignatorMismatch(QualType ObjType,
2931 const SubobjectDesignator &A,
2932 const SubobjectDesignator &B,
2933 bool &WasArrayIndex) {
2934 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2935 for (/**/; I != N; ++I) {
2936 if (!ObjType.isNull() &&
2937 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2938 // Next subobject is an array element.
2939 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2940 WasArrayIndex = true;
2943 if (ObjType->isAnyComplexType())
2944 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2946 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2948 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2949 WasArrayIndex = false;
2952 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2953 // Next subobject is a field.
2954 ObjType = FD->getType();
2956 // Next subobject is a base class.
2957 ObjType = QualType();
2960 WasArrayIndex = false;
2964 /// Determine whether the given subobject designators refer to elements of the
2965 /// same array object.
2966 static bool AreElementsOfSameArray(QualType ObjType,
2967 const SubobjectDesignator &A,
2968 const SubobjectDesignator &B) {
2969 if (A.Entries.size() != B.Entries.size())
2972 bool IsArray = A.MostDerivedIsArrayElement;
2973 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2974 // A is a subobject of the array element.
2977 // If A (and B) designates an array element, the last entry will be the array
2978 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2979 // of length 1' case, and the entire path must match.
2981 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2982 return CommonLength >= A.Entries.size() - IsArray;
2985 /// Find the complete object to which an LValue refers.
2986 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2987 AccessKinds AK, const LValue &LVal,
2988 QualType LValType) {
2990 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2991 return CompleteObject();
2994 CallStackFrame *Frame = nullptr;
2995 if (LVal.CallIndex) {
2996 Frame = Info.getCallFrame(LVal.CallIndex);
2998 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2999 << AK << LVal.Base.is<const ValueDecl*>();
3000 NoteLValueLocation(Info, LVal.Base);
3001 return CompleteObject();
3005 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3006 // is not a constant expression (even if the object is non-volatile). We also
3007 // apply this rule to C++98, in order to conform to the expected 'volatile'
3009 if (LValType.isVolatileQualified()) {
3010 if (Info.getLangOpts().CPlusPlus)
3011 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3015 return CompleteObject();
3018 // Compute value storage location and type of base object.
3019 APValue *BaseVal = nullptr;
3020 QualType BaseType = getType(LVal.Base);
3022 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3023 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3024 // In C++11, constexpr, non-volatile variables initialized with constant
3025 // expressions are constant expressions too. Inside constexpr functions,
3026 // parameters are constant expressions even if they're non-const.
3027 // In C++1y, objects local to a constant expression (those with a Frame) are
3028 // both readable and writable inside constant expressions.
3029 // In C, such things can also be folded, although they are not ICEs.
3030 const VarDecl *VD = dyn_cast<VarDecl>(D);
3032 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3035 if (!VD || VD->isInvalidDecl()) {
3037 return CompleteObject();
3040 // Accesses of volatile-qualified objects are not allowed.
3041 if (BaseType.isVolatileQualified()) {
3042 if (Info.getLangOpts().CPlusPlus) {
3043 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3045 Info.Note(VD->getLocation(), diag::note_declared_at);
3049 return CompleteObject();
3052 // Unless we're looking at a local variable or argument in a constexpr call,
3053 // the variable we're reading must be const.
3055 if (Info.getLangOpts().CPlusPlus14 &&
3056 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3057 // OK, we can read and modify an object if we're in the process of
3058 // evaluating its initializer, because its lifetime began in this
3060 } else if (AK != AK_Read) {
3061 // All the remaining cases only permit reading.
3062 Info.FFDiag(E, diag::note_constexpr_modify_global);
3063 return CompleteObject();
3064 } else if (VD->isConstexpr()) {
3065 // OK, we can read this variable.
3066 } else if (BaseType->isIntegralOrEnumerationType()) {
3067 // In OpenCL if a variable is in constant address space it is a const value.
3068 if (!(BaseType.isConstQualified() ||
3069 (Info.getLangOpts().OpenCL &&
3070 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3071 if (Info.getLangOpts().CPlusPlus) {
3072 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3073 Info.Note(VD->getLocation(), diag::note_declared_at);
3077 return CompleteObject();
3079 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3080 // We support folding of const floating-point types, in order to make
3081 // static const data members of such types (supported as an extension)
3083 if (Info.getLangOpts().CPlusPlus11) {
3084 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3085 Info.Note(VD->getLocation(), diag::note_declared_at);
3089 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3090 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3091 // Keep evaluating to see what we can do.
3093 // FIXME: Allow folding of values of any literal type in all languages.
3094 if (Info.checkingPotentialConstantExpression() &&
3095 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3096 // The definition of this variable could be constexpr. We can't
3097 // access it right now, but may be able to in future.
3098 } else if (Info.getLangOpts().CPlusPlus11) {
3099 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3100 Info.Note(VD->getLocation(), diag::note_declared_at);
3104 return CompleteObject();
3108 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3109 return CompleteObject();
3111 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3114 if (const MaterializeTemporaryExpr *MTE =
3115 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3116 assert(MTE->getStorageDuration() == SD_Static &&
3117 "should have a frame for a non-global materialized temporary");
3119 // Per C++1y [expr.const]p2:
3120 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3121 // - a [...] glvalue of integral or enumeration type that refers to
3122 // a non-volatile const object [...]
3124 // - a [...] glvalue of literal type that refers to a non-volatile
3125 // object whose lifetime began within the evaluation of e.
3127 // C++11 misses the 'began within the evaluation of e' check and
3128 // instead allows all temporaries, including things like:
3131 // constexpr int k = r;
3132 // Therefore we use the C++1y rules in C++11 too.
3133 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3134 const ValueDecl *ED = MTE->getExtendingDecl();
3135 if (!(BaseType.isConstQualified() &&
3136 BaseType->isIntegralOrEnumerationType()) &&
3137 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3138 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3139 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3140 return CompleteObject();
3143 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3144 assert(BaseVal && "got reference to unevaluated temporary");
3147 return CompleteObject();
3150 BaseVal = Frame->getTemporary(Base);
3151 assert(BaseVal && "missing value for temporary");
3154 // Volatile temporary objects cannot be accessed in constant expressions.
3155 if (BaseType.isVolatileQualified()) {
3156 if (Info.getLangOpts().CPlusPlus) {
3157 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3159 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3163 return CompleteObject();
3167 // During the construction of an object, it is not yet 'const'.
3168 // FIXME: This doesn't do quite the right thing for const subobjects of the
3169 // object under construction.
3170 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
3171 BaseType = Info.Ctx.getCanonicalType(BaseType);
3172 BaseType.removeLocalConst();
3175 // In C++1y, we can't safely access any mutable state when we might be
3176 // evaluating after an unmodeled side effect.
3178 // FIXME: Not all local state is mutable. Allow local constant subobjects
3179 // to be read here (but take care with 'mutable' fields).
3180 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3181 Info.EvalStatus.HasSideEffects) ||
3182 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3183 return CompleteObject();
3185 return CompleteObject(BaseVal, BaseType);
3188 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3189 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3190 /// glvalue referred to by an entity of reference type.
3192 /// \param Info - Information about the ongoing evaluation.
3193 /// \param Conv - The expression for which we are performing the conversion.
3194 /// Used for diagnostics.
3195 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3196 /// case of a non-class type).
3197 /// \param LVal - The glvalue on which we are attempting to perform this action.
3198 /// \param RVal - The produced value will be placed here.
3199 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3201 const LValue &LVal, APValue &RVal) {
3202 if (LVal.Designator.Invalid)
3205 // Check for special cases where there is no existing APValue to look at.
3206 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3207 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3208 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3209 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3210 // initializer until now for such expressions. Such an expression can't be
3211 // an ICE in C, so this only matters for fold.
3212 if (Type.isVolatileQualified()) {
3217 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3219 CompleteObject LitObj(&Lit, Base->getType());
3220 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3221 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3222 // We represent a string literal array as an lvalue pointing at the
3223 // corresponding expression, rather than building an array of chars.
3224 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3225 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3226 CompleteObject StrObj(&Str, Base->getType());
3227 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3231 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3232 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3235 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3236 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3237 QualType LValType, APValue &Val) {
3238 if (LVal.Designator.Invalid)
3241 if (!Info.getLangOpts().CPlusPlus14) {
3246 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3247 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3250 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3251 return T->isSignedIntegerType() &&
3252 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3256 struct CompoundAssignSubobjectHandler {
3259 QualType PromotedLHSType;
3260 BinaryOperatorKind Opcode;
3263 static const AccessKinds AccessKind = AK_Assign;
3265 typedef bool result_type;
3267 bool checkConst(QualType QT) {
3268 // Assigning to a const object has undefined behavior.
3269 if (QT.isConstQualified()) {
3270 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3276 bool failed() { return false; }
3277 bool found(APValue &Subobj, QualType SubobjType) {
3278 switch (Subobj.getKind()) {
3280 return found(Subobj.getInt(), SubobjType);
3281 case APValue::Float:
3282 return found(Subobj.getFloat(), SubobjType);
3283 case APValue::ComplexInt:
3284 case APValue::ComplexFloat:
3285 // FIXME: Implement complex compound assignment.
3288 case APValue::LValue:
3289 return foundPointer(Subobj, SubobjType);
3291 // FIXME: can this happen?
3296 bool found(APSInt &Value, QualType SubobjType) {
3297 if (!checkConst(SubobjType))
3300 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3301 // We don't support compound assignment on integer-cast-to-pointer
3307 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3309 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3311 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3314 bool found(APFloat &Value, QualType SubobjType) {
3315 return checkConst(SubobjType) &&
3316 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3318 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3319 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3321 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3322 if (!checkConst(SubobjType))
3325 QualType PointeeType;
3326 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3327 PointeeType = PT->getPointeeType();
3329 if (PointeeType.isNull() || !RHS.isInt() ||
3330 (Opcode != BO_Add && Opcode != BO_Sub)) {
3335 APSInt Offset = RHS.getInt();
3336 if (Opcode == BO_Sub)
3337 negateAsSigned(Offset);
3340 LVal.setFrom(Info.Ctx, Subobj);
3341 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3343 LVal.moveInto(Subobj);
3346 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3347 llvm_unreachable("shouldn't encounter string elements here");
3350 } // end anonymous namespace
3352 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3354 /// Perform a compound assignment of LVal <op>= RVal.
3355 static bool handleCompoundAssignment(
3356 EvalInfo &Info, const Expr *E,
3357 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3358 BinaryOperatorKind Opcode, const APValue &RVal) {
3359 if (LVal.Designator.Invalid)
3362 if (!Info.getLangOpts().CPlusPlus14) {
3367 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3368 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3370 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3374 struct IncDecSubobjectHandler {
3377 AccessKinds AccessKind;
3380 typedef bool result_type;
3382 bool checkConst(QualType QT) {
3383 // Assigning to a const object has undefined behavior.
3384 if (QT.isConstQualified()) {
3385 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3391 bool failed() { return false; }
3392 bool found(APValue &Subobj, QualType SubobjType) {
3393 // Stash the old value. Also clear Old, so we don't clobber it later
3394 // if we're post-incrementing a complex.
3400 switch (Subobj.getKind()) {
3402 return found(Subobj.getInt(), SubobjType);
3403 case APValue::Float:
3404 return found(Subobj.getFloat(), SubobjType);
3405 case APValue::ComplexInt:
3406 return found(Subobj.getComplexIntReal(),
3407 SubobjType->castAs<ComplexType>()->getElementType()
3408 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3409 case APValue::ComplexFloat:
3410 return found(Subobj.getComplexFloatReal(),
3411 SubobjType->castAs<ComplexType>()->getElementType()
3412 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3413 case APValue::LValue:
3414 return foundPointer(Subobj, SubobjType);
3416 // FIXME: can this happen?
3421 bool found(APSInt &Value, QualType SubobjType) {
3422 if (!checkConst(SubobjType))
3425 if (!SubobjType->isIntegerType()) {
3426 // We don't support increment / decrement on integer-cast-to-pointer
3432 if (Old) *Old = APValue(Value);
3434 // bool arithmetic promotes to int, and the conversion back to bool
3435 // doesn't reduce mod 2^n, so special-case it.
3436 if (SubobjType->isBooleanType()) {
3437 if (AccessKind == AK_Increment)
3444 bool WasNegative = Value.isNegative();
3445 if (AccessKind == AK_Increment) {
3448 if (!WasNegative && Value.isNegative() &&
3449 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3450 APSInt ActualValue(Value, /*IsUnsigned*/true);
3451 return HandleOverflow(Info, E, ActualValue, SubobjType);
3456 if (WasNegative && !Value.isNegative() &&
3457 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3458 unsigned BitWidth = Value.getBitWidth();
3459 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3460 ActualValue.setBit(BitWidth);
3461 return HandleOverflow(Info, E, ActualValue, SubobjType);
3466 bool found(APFloat &Value, QualType SubobjType) {
3467 if (!checkConst(SubobjType))
3470 if (Old) *Old = APValue(Value);
3472 APFloat One(Value.getSemantics(), 1);
3473 if (AccessKind == AK_Increment)
3474 Value.add(One, APFloat::rmNearestTiesToEven);
3476 Value.subtract(One, APFloat::rmNearestTiesToEven);
3479 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3480 if (!checkConst(SubobjType))
3483 QualType PointeeType;
3484 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3485 PointeeType = PT->getPointeeType();
3492 LVal.setFrom(Info.Ctx, Subobj);
3493 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3494 AccessKind == AK_Increment ? 1 : -1))
3496 LVal.moveInto(Subobj);
3499 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3500 llvm_unreachable("shouldn't encounter string elements here");
3503 } // end anonymous namespace
3505 /// Perform an increment or decrement on LVal.
3506 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3507 QualType LValType, bool IsIncrement, APValue *Old) {
3508 if (LVal.Designator.Invalid)
3511 if (!Info.getLangOpts().CPlusPlus14) {
3516 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3517 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3518 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3519 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3522 /// Build an lvalue for the object argument of a member function call.
3523 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3525 if (Object->getType()->isPointerType())
3526 return EvaluatePointer(Object, This, Info);
3528 if (Object->isGLValue())
3529 return EvaluateLValue(Object, This, Info);
3531 if (Object->getType()->isLiteralType(Info.Ctx))
3532 return EvaluateTemporary(Object, This, Info);
3534 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3538 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3539 /// lvalue referring to the result.
3541 /// \param Info - Information about the ongoing evaluation.
3542 /// \param LV - An lvalue referring to the base of the member pointer.
3543 /// \param RHS - The member pointer expression.
3544 /// \param IncludeMember - Specifies whether the member itself is included in
3545 /// the resulting LValue subobject designator. This is not possible when
3546 /// creating a bound member function.
3547 /// \return The field or method declaration to which the member pointer refers,
3548 /// or 0 if evaluation fails.
3549 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3553 bool IncludeMember = true) {
3555 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3558 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3559 // member value, the behavior is undefined.
3560 if (!MemPtr.getDecl()) {
3561 // FIXME: Specific diagnostic.
3566 if (MemPtr.isDerivedMember()) {
3567 // This is a member of some derived class. Truncate LV appropriately.
3568 // The end of the derived-to-base path for the base object must match the
3569 // derived-to-base path for the member pointer.
3570 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3571 LV.Designator.Entries.size()) {
3575 unsigned PathLengthToMember =
3576 LV.Designator.Entries.size() - MemPtr.Path.size();
3577 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3578 const CXXRecordDecl *LVDecl = getAsBaseClass(
3579 LV.Designator.Entries[PathLengthToMember + I]);
3580 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3581 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3587 // Truncate the lvalue to the appropriate derived class.
3588 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3589 PathLengthToMember))
3591 } else if (!MemPtr.Path.empty()) {
3592 // Extend the LValue path with the member pointer's path.
3593 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3594 MemPtr.Path.size() + IncludeMember);
3596 // Walk down to the appropriate base class.
3597 if (const PointerType *PT = LVType->getAs<PointerType>())
3598 LVType = PT->getPointeeType();
3599 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3600 assert(RD && "member pointer access on non-class-type expression");
3601 // The first class in the path is that of the lvalue.
3602 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3603 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3604 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3608 // Finally cast to the class containing the member.
3609 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3610 MemPtr.getContainingRecord()))
3614 // Add the member. Note that we cannot build bound member functions here.
3615 if (IncludeMember) {
3616 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3617 if (!HandleLValueMember(Info, RHS, LV, FD))
3619 } else if (const IndirectFieldDecl *IFD =
3620 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3621 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3624 llvm_unreachable("can't construct reference to bound member function");
3628 return MemPtr.getDecl();
3631 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3632 const BinaryOperator *BO,
3634 bool IncludeMember = true) {
3635 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3637 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3638 if (Info.noteFailure()) {
3640 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3645 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3646 BO->getRHS(), IncludeMember);
3649 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3650 /// the provided lvalue, which currently refers to the base object.
3651 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3653 SubobjectDesignator &D = Result.Designator;
3654 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3657 QualType TargetQT = E->getType();
3658 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3659 TargetQT = PT->getPointeeType();
3661 // Check this cast lands within the final derived-to-base subobject path.
3662 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3663 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3664 << D.MostDerivedType << TargetQT;
3668 // Check the type of the final cast. We don't need to check the path,
3669 // since a cast can only be formed if the path is unique.
3670 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3671 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3672 const CXXRecordDecl *FinalType;
3673 if (NewEntriesSize == D.MostDerivedPathLength)
3674 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3676 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3677 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3678 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3679 << D.MostDerivedType << TargetQT;
3683 // Truncate the lvalue to the appropriate derived class.
3684 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3688 enum EvalStmtResult {
3689 /// Evaluation failed.
3691 /// Hit a 'return' statement.
3693 /// Evaluation succeeded.
3695 /// Hit a 'continue' statement.
3697 /// Hit a 'break' statement.
3699 /// Still scanning for 'case' or 'default' statement.
3704 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3705 // We don't need to evaluate the initializer for a static local.
3706 if (!VD->hasLocalStorage())
3710 Result.set(VD, Info.CurrentCall->Index);
3711 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3713 const Expr *InitE = VD->getInit();
3715 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3716 << false << VD->getType();
3721 if (InitE->isValueDependent())
3724 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3725 // Wipe out any partially-computed value, to allow tracking that this
3726 // evaluation failed.
3734 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3737 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3738 OK &= EvaluateVarDecl(Info, VD);
3740 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3741 for (auto *BD : DD->bindings())
3742 if (auto *VD = BD->getHoldingVar())
3743 OK &= EvaluateDecl(Info, VD);
3749 /// Evaluate a condition (either a variable declaration or an expression).
3750 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3751 const Expr *Cond, bool &Result) {
3752 FullExpressionRAII Scope(Info);
3753 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3755 return EvaluateAsBooleanCondition(Cond, Result, Info);
3759 /// \brief A location where the result (returned value) of evaluating a
3760 /// statement should be stored.
3762 /// The APValue that should be filled in with the returned value.
3764 /// The location containing the result, if any (used to support RVO).
3769 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3771 const SwitchCase *SC = nullptr);
3773 /// Evaluate the body of a loop, and translate the result as appropriate.
3774 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3776 const SwitchCase *Case = nullptr) {
3777 BlockScopeRAII Scope(Info);
3778 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3780 return ESR_Succeeded;
3783 return ESR_Continue;
3786 case ESR_CaseNotFound:
3789 llvm_unreachable("Invalid EvalStmtResult!");
3792 /// Evaluate a switch statement.
3793 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3794 const SwitchStmt *SS) {
3795 BlockScopeRAII Scope(Info);
3797 // Evaluate the switch condition.
3800 FullExpressionRAII Scope(Info);
3801 if (const Stmt *Init = SS->getInit()) {
3802 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3803 if (ESR != ESR_Succeeded)
3806 if (SS->getConditionVariable() &&
3807 !EvaluateDecl(Info, SS->getConditionVariable()))
3809 if (!EvaluateInteger(SS->getCond(), Value, Info))
3813 // Find the switch case corresponding to the value of the condition.
3814 // FIXME: Cache this lookup.
3815 const SwitchCase *Found = nullptr;
3816 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3817 SC = SC->getNextSwitchCase()) {
3818 if (isa<DefaultStmt>(SC)) {
3823 const CaseStmt *CS = cast<CaseStmt>(SC);
3824 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3825 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3827 if (LHS <= Value && Value <= RHS) {
3834 return ESR_Succeeded;
3836 // Search the switch body for the switch case and evaluate it from there.
3837 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3839 return ESR_Succeeded;
3845 case ESR_CaseNotFound:
3846 // This can only happen if the switch case is nested within a statement
3847 // expression. We have no intention of supporting that.
3848 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3851 llvm_unreachable("Invalid EvalStmtResult!");
3854 // Evaluate a statement.
3855 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3856 const Stmt *S, const SwitchCase *Case) {
3857 if (!Info.nextStep(S))
3860 // If we're hunting down a 'case' or 'default' label, recurse through
3861 // substatements until we hit the label.
3863 // FIXME: We don't start the lifetime of objects whose initialization we
3864 // jump over. However, such objects must be of class type with a trivial
3865 // default constructor that initialize all subobjects, so must be empty,
3866 // so this almost never matters.
3867 switch (S->getStmtClass()) {
3868 case Stmt::CompoundStmtClass:
3869 // FIXME: Precompute which substatement of a compound statement we
3870 // would jump to, and go straight there rather than performing a
3871 // linear scan each time.
3872 case Stmt::LabelStmtClass:
3873 case Stmt::AttributedStmtClass:
3874 case Stmt::DoStmtClass:
3877 case Stmt::CaseStmtClass:
3878 case Stmt::DefaultStmtClass:
3883 case Stmt::IfStmtClass: {
3884 // FIXME: Precompute which side of an 'if' we would jump to, and go
3885 // straight there rather than scanning both sides.
3886 const IfStmt *IS = cast<IfStmt>(S);
3888 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3889 // preceded by our switch label.
3890 BlockScopeRAII Scope(Info);
3892 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3893 if (ESR != ESR_CaseNotFound || !IS->getElse())
3895 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3898 case Stmt::WhileStmtClass: {
3899 EvalStmtResult ESR =
3900 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3901 if (ESR != ESR_Continue)
3906 case Stmt::ForStmtClass: {
3907 const ForStmt *FS = cast<ForStmt>(S);
3908 EvalStmtResult ESR =
3909 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3910 if (ESR != ESR_Continue)
3913 FullExpressionRAII IncScope(Info);
3914 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3920 case Stmt::DeclStmtClass:
3921 // FIXME: If the variable has initialization that can't be jumped over,
3922 // bail out of any immediately-surrounding compound-statement too.
3924 return ESR_CaseNotFound;
3928 switch (S->getStmtClass()) {
3930 if (const Expr *E = dyn_cast<Expr>(S)) {
3931 // Don't bother evaluating beyond an expression-statement which couldn't
3933 FullExpressionRAII Scope(Info);
3934 if (!EvaluateIgnoredValue(Info, E))
3936 return ESR_Succeeded;
3939 Info.FFDiag(S->getLocStart());
3942 case Stmt::NullStmtClass:
3943 return ESR_Succeeded;
3945 case Stmt::DeclStmtClass: {
3946 const DeclStmt *DS = cast<DeclStmt>(S);
3947 for (const auto *DclIt : DS->decls()) {
3948 // Each declaration initialization is its own full-expression.
3949 // FIXME: This isn't quite right; if we're performing aggregate
3950 // initialization, each braced subexpression is its own full-expression.
3951 FullExpressionRAII Scope(Info);
3952 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3955 return ESR_Succeeded;
3958 case Stmt::ReturnStmtClass: {
3959 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3960 FullExpressionRAII Scope(Info);
3963 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3964 : Evaluate(Result.Value, Info, RetExpr)))
3966 return ESR_Returned;
3969 case Stmt::CompoundStmtClass: {
3970 BlockScopeRAII Scope(Info);
3972 const CompoundStmt *CS = cast<CompoundStmt>(S);
3973 for (const auto *BI : CS->body()) {
3974 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3975 if (ESR == ESR_Succeeded)
3977 else if (ESR != ESR_CaseNotFound)
3980 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3983 case Stmt::IfStmtClass: {
3984 const IfStmt *IS = cast<IfStmt>(S);
3986 // Evaluate the condition, as either a var decl or as an expression.
3987 BlockScopeRAII Scope(Info);
3988 if (const Stmt *Init = IS->getInit()) {
3989 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3990 if (ESR != ESR_Succeeded)
3994 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3997 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3998 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3999 if (ESR != ESR_Succeeded)
4002 return ESR_Succeeded;
4005 case Stmt::WhileStmtClass: {
4006 const WhileStmt *WS = cast<WhileStmt>(S);
4008 BlockScopeRAII Scope(Info);
4010 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4016 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4017 if (ESR != ESR_Continue)
4020 return ESR_Succeeded;
4023 case Stmt::DoStmtClass: {
4024 const DoStmt *DS = cast<DoStmt>(S);
4027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4028 if (ESR != ESR_Continue)
4032 FullExpressionRAII CondScope(Info);
4033 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4036 return ESR_Succeeded;
4039 case Stmt::ForStmtClass: {
4040 const ForStmt *FS = cast<ForStmt>(S);
4041 BlockScopeRAII Scope(Info);
4042 if (FS->getInit()) {
4043 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4044 if (ESR != ESR_Succeeded)
4048 BlockScopeRAII Scope(Info);
4049 bool Continue = true;
4050 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4051 FS->getCond(), Continue))
4056 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4057 if (ESR != ESR_Continue)
4061 FullExpressionRAII IncScope(Info);
4062 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4066 return ESR_Succeeded;
4069 case Stmt::CXXForRangeStmtClass: {
4070 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4071 BlockScopeRAII Scope(Info);
4073 // Initialize the __range variable.
4074 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4075 if (ESR != ESR_Succeeded)
4078 // Create the __begin and __end iterators.
4079 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4080 if (ESR != ESR_Succeeded)
4082 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4083 if (ESR != ESR_Succeeded)
4087 // Condition: __begin != __end.
4089 bool Continue = true;
4090 FullExpressionRAII CondExpr(Info);
4091 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4097 // User's variable declaration, initialized by *__begin.
4098 BlockScopeRAII InnerScope(Info);
4099 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4100 if (ESR != ESR_Succeeded)
4104 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4105 if (ESR != ESR_Continue)
4108 // Increment: ++__begin
4109 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4113 return ESR_Succeeded;
4116 case Stmt::SwitchStmtClass:
4117 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4119 case Stmt::ContinueStmtClass:
4120 return ESR_Continue;
4122 case Stmt::BreakStmtClass:
4125 case Stmt::LabelStmtClass:
4126 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4128 case Stmt::AttributedStmtClass:
4129 // As a general principle, C++11 attributes can be ignored without
4130 // any semantic impact.
4131 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4134 case Stmt::CaseStmtClass:
4135 case Stmt::DefaultStmtClass:
4136 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4140 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4141 /// default constructor. If so, we'll fold it whether or not it's marked as
4142 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4143 /// so we need special handling.
4144 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4145 const CXXConstructorDecl *CD,
4146 bool IsValueInitialization) {
4147 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4150 // Value-initialization does not call a trivial default constructor, so such a
4151 // call is a core constant expression whether or not the constructor is
4153 if (!CD->isConstexpr() && !IsValueInitialization) {
4154 if (Info.getLangOpts().CPlusPlus11) {
4155 // FIXME: If DiagDecl is an implicitly-declared special member function,
4156 // we should be much more explicit about why it's not constexpr.
4157 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4158 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4159 Info.Note(CD->getLocation(), diag::note_declared_at);
4161 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4167 /// CheckConstexprFunction - Check that a function can be called in a constant
4169 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4170 const FunctionDecl *Declaration,
4171 const FunctionDecl *Definition,
4173 // Potential constant expressions can contain calls to declared, but not yet
4174 // defined, constexpr functions.
4175 if (Info.checkingPotentialConstantExpression() && !Definition &&
4176 Declaration->isConstexpr())
4179 // Bail out with no diagnostic if the function declaration itself is invalid.
4180 // We will have produced a relevant diagnostic while parsing it.
4181 if (Declaration->isInvalidDecl())
4184 // Can we evaluate this function call?
4185 if (Definition && Definition->isConstexpr() &&
4186 !Definition->isInvalidDecl() && Body)
4189 if (Info.getLangOpts().CPlusPlus11) {
4190 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4192 // If this function is not constexpr because it is an inherited
4193 // non-constexpr constructor, diagnose that directly.
4194 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4195 if (CD && CD->isInheritingConstructor()) {
4196 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4197 if (!Inherited->isConstexpr())
4198 DiagDecl = CD = Inherited;
4201 // FIXME: If DiagDecl is an implicitly-declared special member function
4202 // or an inheriting constructor, we should be much more explicit about why
4203 // it's not constexpr.
4204 if (CD && CD->isInheritingConstructor())
4205 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4206 << CD->getInheritedConstructor().getConstructor()->getParent();
4208 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4209 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4210 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4212 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4217 /// Determine if a class has any fields that might need to be copied by a
4218 /// trivial copy or move operation.
4219 static bool hasFields(const CXXRecordDecl *RD) {
4220 if (!RD || RD->isEmpty())
4222 for (auto *FD : RD->fields()) {
4223 if (FD->isUnnamedBitfield())
4227 for (auto &Base : RD->bases())
4228 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4234 typedef SmallVector<APValue, 8> ArgVector;
4237 /// EvaluateArgs - Evaluate the arguments to a function call.
4238 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4240 bool Success = true;
4241 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4243 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4244 // If we're checking for a potential constant expression, evaluate all
4245 // initializers even if some of them fail.
4246 if (!Info.noteFailure())
4254 /// Evaluate a function call.
4255 static bool HandleFunctionCall(SourceLocation CallLoc,
4256 const FunctionDecl *Callee, const LValue *This,
4257 ArrayRef<const Expr*> Args, const Stmt *Body,
4258 EvalInfo &Info, APValue &Result,
4259 const LValue *ResultSlot) {
4260 ArgVector ArgValues(Args.size());
4261 if (!EvaluateArgs(Args, ArgValues, Info))
4264 if (!Info.CheckCallLimit(CallLoc))
4267 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4269 // For a trivial copy or move assignment, perform an APValue copy. This is
4270 // essential for unions, where the operations performed by the assignment
4271 // operator cannot be represented as statements.
4273 // Skip this for non-union classes with no fields; in that case, the defaulted
4274 // copy/move does not actually read the object.
4275 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4276 if (MD && MD->isDefaulted() &&
4277 (MD->getParent()->isUnion() ||
4278 (MD->isTrivial() && hasFields(MD->getParent())))) {
4280 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4282 RHS.setFrom(Info.Ctx, ArgValues[0]);
4284 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4287 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4290 This->moveInto(Result);
4292 } else if (MD && isLambdaCallOperator(MD)) {
4293 // We're in a lambda; determine the lambda capture field maps.
4294 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4295 Frame.LambdaThisCaptureField);
4298 StmtResult Ret = {Result, ResultSlot};
4299 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4300 if (ESR == ESR_Succeeded) {
4301 if (Callee->getReturnType()->isVoidType())
4303 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4305 return ESR == ESR_Returned;
4308 /// Evaluate a constructor call.
4309 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4311 const CXXConstructorDecl *Definition,
4312 EvalInfo &Info, APValue &Result) {
4313 SourceLocation CallLoc = E->getExprLoc();
4314 if (!Info.CheckCallLimit(CallLoc))
4317 const CXXRecordDecl *RD = Definition->getParent();
4318 if (RD->getNumVBases()) {
4319 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4323 EvalInfo::EvaluatingConstructorRAII EvalObj(
4324 Info, {This.getLValueBase(), This.CallIndex});
4325 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4327 // FIXME: Creating an APValue just to hold a nonexistent return value is
4330 StmtResult Ret = {RetVal, nullptr};
4332 // If it's a delegating constructor, delegate.
4333 if (Definition->isDelegatingConstructor()) {
4334 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4336 FullExpressionRAII InitScope(Info);
4337 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4340 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4343 // For a trivial copy or move constructor, perform an APValue copy. This is
4344 // essential for unions (or classes with anonymous union members), where the
4345 // operations performed by the constructor cannot be represented by
4346 // ctor-initializers.
4348 // Skip this for empty non-union classes; we should not perform an
4349 // lvalue-to-rvalue conversion on them because their copy constructor does not
4350 // actually read them.
4351 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4352 (Definition->getParent()->isUnion() ||
4353 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4355 RHS.setFrom(Info.Ctx, ArgValues[0]);
4356 return handleLValueToRValueConversion(
4357 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4361 // Reserve space for the struct members.
4362 if (!RD->isUnion() && Result.isUninit())
4363 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4364 std::distance(RD->field_begin(), RD->field_end()));
4366 if (RD->isInvalidDecl()) return false;
4367 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4369 // A scope for temporaries lifetime-extended by reference members.
4370 BlockScopeRAII LifetimeExtendedScope(Info);
4372 bool Success = true;
4373 unsigned BasesSeen = 0;
4375 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4377 for (const auto *I : Definition->inits()) {
4378 LValue Subobject = This;
4379 APValue *Value = &Result;
4381 // Determine the subobject to initialize.
4382 FieldDecl *FD = nullptr;
4383 if (I->isBaseInitializer()) {
4384 QualType BaseType(I->getBaseClass(), 0);
4386 // Non-virtual base classes are initialized in the order in the class
4387 // definition. We have already checked for virtual base classes.
4388 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4389 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4390 "base class initializers not in expected order");
4393 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4394 BaseType->getAsCXXRecordDecl(), &Layout))
4396 Value = &Result.getStructBase(BasesSeen++);
4397 } else if ((FD = I->getMember())) {
4398 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4400 if (RD->isUnion()) {
4401 Result = APValue(FD);
4402 Value = &Result.getUnionValue();
4404 Value = &Result.getStructField(FD->getFieldIndex());
4406 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4407 // Walk the indirect field decl's chain to find the object to initialize,
4408 // and make sure we've initialized every step along it.
4409 for (auto *C : IFD->chain()) {
4410 FD = cast<FieldDecl>(C);
4411 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4412 // Switch the union field if it differs. This happens if we had
4413 // preceding zero-initialization, and we're now initializing a union
4414 // subobject other than the first.
4415 // FIXME: In this case, the values of the other subobjects are
4416 // specified, since zero-initialization sets all padding bits to zero.
4417 if (Value->isUninit() ||
4418 (Value->isUnion() && Value->getUnionField() != FD)) {
4420 *Value = APValue(FD);
4422 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4423 std::distance(CD->field_begin(), CD->field_end()));
4425 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4428 Value = &Value->getUnionValue();
4430 Value = &Value->getStructField(FD->getFieldIndex());
4433 llvm_unreachable("unknown base initializer kind");
4436 FullExpressionRAII InitScope(Info);
4437 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4438 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4440 // If we're checking for a potential constant expression, evaluate all
4441 // initializers even if some of them fail.
4442 if (!Info.noteFailure())
4449 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4452 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4453 ArrayRef<const Expr*> Args,
4454 const CXXConstructorDecl *Definition,
4455 EvalInfo &Info, APValue &Result) {
4456 ArgVector ArgValues(Args.size());
4457 if (!EvaluateArgs(Args, ArgValues, Info))
4460 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4464 //===----------------------------------------------------------------------===//
4465 // Generic Evaluation
4466 //===----------------------------------------------------------------------===//
4469 template <class Derived>
4470 class ExprEvaluatorBase
4471 : public ConstStmtVisitor<Derived, bool> {
4473 Derived &getDerived() { return static_cast<Derived&>(*this); }
4474 bool DerivedSuccess(const APValue &V, const Expr *E) {
4475 return getDerived().Success(V, E);
4477 bool DerivedZeroInitialization(const Expr *E) {
4478 return getDerived().ZeroInitialization(E);
4481 // Check whether a conditional operator with a non-constant condition is a
4482 // potential constant expression. If neither arm is a potential constant
4483 // expression, then the conditional operator is not either.
4484 template<typename ConditionalOperator>
4485 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4486 assert(Info.checkingPotentialConstantExpression());
4488 // Speculatively evaluate both arms.
4489 SmallVector<PartialDiagnosticAt, 8> Diag;
4491 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4492 StmtVisitorTy::Visit(E->getFalseExpr());
4498 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4500 StmtVisitorTy::Visit(E->getTrueExpr());
4505 Error(E, diag::note_constexpr_conditional_never_const);
4509 template<typename ConditionalOperator>
4510 bool HandleConditionalOperator(const ConditionalOperator *E) {
4512 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4513 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4514 CheckPotentialConstantConditional(E);
4517 if (Info.noteFailure()) {
4518 StmtVisitorTy::Visit(E->getTrueExpr());
4519 StmtVisitorTy::Visit(E->getFalseExpr());
4524 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4525 return StmtVisitorTy::Visit(EvalExpr);
4530 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4531 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4533 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4534 return Info.CCEDiag(E, D);
4537 bool ZeroInitialization(const Expr *E) { return Error(E); }
4540 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4542 EvalInfo &getEvalInfo() { return Info; }
4544 /// Report an evaluation error. This should only be called when an error is
4545 /// first discovered. When propagating an error, just return false.
4546 bool Error(const Expr *E, diag::kind D) {
4550 bool Error(const Expr *E) {
4551 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4554 bool VisitStmt(const Stmt *) {
4555 llvm_unreachable("Expression evaluator should not be called on stmts");
4557 bool VisitExpr(const Expr *E) {
4561 bool VisitParenExpr(const ParenExpr *E)
4562 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4563 bool VisitUnaryExtension(const UnaryOperator *E)
4564 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4565 bool VisitUnaryPlus(const UnaryOperator *E)
4566 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4567 bool VisitChooseExpr(const ChooseExpr *E)
4568 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4569 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4570 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4571 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4572 { return StmtVisitorTy::Visit(E->getReplacement()); }
4573 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4574 { return StmtVisitorTy::Visit(E->getExpr()); }
4575 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4576 // The initializer may not have been parsed yet, or might be erroneous.
4579 return StmtVisitorTy::Visit(E->getExpr());
4581 // We cannot create any objects for which cleanups are required, so there is
4582 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4583 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4584 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4586 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4587 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4588 return static_cast<Derived*>(this)->VisitCastExpr(E);
4590 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4591 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4592 return static_cast<Derived*>(this)->VisitCastExpr(E);
4595 bool VisitBinaryOperator(const BinaryOperator *E) {
4596 switch (E->getOpcode()) {
4601 VisitIgnoredValue(E->getLHS());
4602 return StmtVisitorTy::Visit(E->getRHS());
4607 if (!HandleMemberPointerAccess(Info, E, Obj))
4610 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4612 return DerivedSuccess(Result, E);
4617 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4618 // Evaluate and cache the common expression. We treat it as a temporary,
4619 // even though it's not quite the same thing.
4620 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4621 Info, E->getCommon()))
4624 return HandleConditionalOperator(E);
4627 bool VisitConditionalOperator(const ConditionalOperator *E) {
4628 bool IsBcpCall = false;
4629 // If the condition (ignoring parens) is a __builtin_constant_p call,
4630 // the result is a constant expression if it can be folded without
4631 // side-effects. This is an important GNU extension. See GCC PR38377
4633 if (const CallExpr *CallCE =
4634 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4635 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4638 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4639 // constant expression; we can't check whether it's potentially foldable.
4640 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4643 FoldConstant Fold(Info, IsBcpCall);
4644 if (!HandleConditionalOperator(E)) {
4645 Fold.keepDiagnostics();
4652 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4653 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4654 return DerivedSuccess(*Value, E);
4656 const Expr *Source = E->getSourceExpr();
4659 if (Source == E) { // sanity checking.
4660 assert(0 && "OpaqueValueExpr recursively refers to itself");
4663 return StmtVisitorTy::Visit(Source);
4666 bool VisitCallExpr(const CallExpr *E) {
4668 if (!handleCallExpr(E, Result, nullptr))
4670 return DerivedSuccess(Result, E);
4673 bool handleCallExpr(const CallExpr *E, APValue &Result,
4674 const LValue *ResultSlot) {
4675 const Expr *Callee = E->getCallee()->IgnoreParens();
4676 QualType CalleeType = Callee->getType();
4678 const FunctionDecl *FD = nullptr;
4679 LValue *This = nullptr, ThisVal;
4680 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4681 bool HasQualifier = false;
4683 // Extract function decl and 'this' pointer from the callee.
4684 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4685 const ValueDecl *Member = nullptr;
4686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4687 // Explicit bound member calls, such as x.f() or p->g();
4688 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4690 Member = ME->getMemberDecl();
4692 HasQualifier = ME->hasQualifier();
4693 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4694 // Indirect bound member calls ('.*' or '->*').
4695 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4696 if (!Member) return false;
4699 return Error(Callee);
4701 FD = dyn_cast<FunctionDecl>(Member);
4703 return Error(Callee);
4704 } else if (CalleeType->isFunctionPointerType()) {
4706 if (!EvaluatePointer(Callee, Call, Info))
4709 if (!Call.getLValueOffset().isZero())
4710 return Error(Callee);
4711 FD = dyn_cast_or_null<FunctionDecl>(
4712 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4714 return Error(Callee);
4715 // Don't call function pointers which have been cast to some other type.
4716 // Per DR (no number yet), the caller and callee can differ in noexcept.
4717 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4718 CalleeType->getPointeeType(), FD->getType())) {
4722 // Overloaded operator calls to member functions are represented as normal
4723 // calls with '*this' as the first argument.
4724 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4725 if (MD && !MD->isStatic()) {
4726 // FIXME: When selecting an implicit conversion for an overloaded
4727 // operator delete, we sometimes try to evaluate calls to conversion
4728 // operators without a 'this' parameter!
4732 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4735 Args = Args.slice(1);
4736 } else if (MD && MD->isLambdaStaticInvoker()) {
4737 // Map the static invoker for the lambda back to the call operator.
4738 // Conveniently, we don't have to slice out the 'this' argument (as is
4739 // being done for the non-static case), since a static member function
4740 // doesn't have an implicit argument passed in.
4741 const CXXRecordDecl *ClosureClass = MD->getParent();
4743 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4744 "Number of captures must be zero for conversion to function-ptr");
4746 const CXXMethodDecl *LambdaCallOp =
4747 ClosureClass->getLambdaCallOperator();
4749 // Set 'FD', the function that will be called below, to the call
4750 // operator. If the closure object represents a generic lambda, find
4751 // the corresponding specialization of the call operator.
4753 if (ClosureClass->isGenericLambda()) {
4754 assert(MD->isFunctionTemplateSpecialization() &&
4755 "A generic lambda's static-invoker function must be a "
4756 "template specialization");
4757 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4758 FunctionTemplateDecl *CallOpTemplate =
4759 LambdaCallOp->getDescribedFunctionTemplate();
4760 void *InsertPos = nullptr;
4761 FunctionDecl *CorrespondingCallOpSpecialization =
4762 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4763 assert(CorrespondingCallOpSpecialization &&
4764 "We must always have a function call operator specialization "
4765 "that corresponds to our static invoker specialization");
4766 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4775 if (This && !This->checkSubobject(Info, E, CSK_This))
4778 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4779 // calls to such functions in constant expressions.
4780 if (This && !HasQualifier &&
4781 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4782 return Error(E, diag::note_constexpr_virtual_call);
4784 const FunctionDecl *Definition = nullptr;
4785 Stmt *Body = FD->getBody(Definition);
4787 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4788 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4789 Result, ResultSlot))
4795 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4796 return StmtVisitorTy::Visit(E->getInitializer());
4798 bool VisitInitListExpr(const InitListExpr *E) {
4799 if (E->getNumInits() == 0)
4800 return DerivedZeroInitialization(E);
4801 if (E->getNumInits() == 1)
4802 return StmtVisitorTy::Visit(E->getInit(0));
4805 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4806 return DerivedZeroInitialization(E);
4808 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4809 return DerivedZeroInitialization(E);
4811 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4812 return DerivedZeroInitialization(E);
4815 /// A member expression where the object is a prvalue is itself a prvalue.
4816 bool VisitMemberExpr(const MemberExpr *E) {
4817 assert(!E->isArrow() && "missing call to bound member function?");
4820 if (!Evaluate(Val, Info, E->getBase()))
4823 QualType BaseTy = E->getBase()->getType();
4825 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4826 if (!FD) return Error(E);
4827 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4828 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4829 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4831 CompleteObject Obj(&Val, BaseTy);
4832 SubobjectDesignator Designator(BaseTy);
4833 Designator.addDeclUnchecked(FD);
4836 return extractSubobject(Info, E, Obj, Designator, Result) &&
4837 DerivedSuccess(Result, E);
4840 bool VisitCastExpr(const CastExpr *E) {
4841 switch (E->getCastKind()) {
4845 case CK_AtomicToNonAtomic: {
4847 // This does not need to be done in place even for class/array types:
4848 // atomic-to-non-atomic conversion implies copying the object
4850 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4852 return DerivedSuccess(AtomicVal, E);
4856 case CK_UserDefinedConversion:
4857 return StmtVisitorTy::Visit(E->getSubExpr());
4859 case CK_LValueToRValue: {
4861 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4864 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4865 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4868 return DerivedSuccess(RVal, E);
4875 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4876 return VisitUnaryPostIncDec(UO);
4878 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4879 return VisitUnaryPostIncDec(UO);
4881 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4882 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4886 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4889 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4890 UO->isIncrementOp(), &RVal))
4892 return DerivedSuccess(RVal, UO);
4895 bool VisitStmtExpr(const StmtExpr *E) {
4896 // We will have checked the full-expressions inside the statement expression
4897 // when they were completed, and don't need to check them again now.
4898 if (Info.checkingForOverflow())
4901 BlockScopeRAII Scope(Info);
4902 const CompoundStmt *CS = E->getSubStmt();
4903 if (CS->body_empty())
4906 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4907 BE = CS->body_end();
4910 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4912 Info.FFDiag((*BI)->getLocStart(),
4913 diag::note_constexpr_stmt_expr_unsupported);
4916 return this->Visit(FinalExpr);
4919 APValue ReturnValue;
4920 StmtResult Result = { ReturnValue, nullptr };
4921 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4922 if (ESR != ESR_Succeeded) {
4923 // FIXME: If the statement-expression terminated due to 'return',
4924 // 'break', or 'continue', it would be nice to propagate that to
4925 // the outer statement evaluation rather than bailing out.
4926 if (ESR != ESR_Failed)
4927 Info.FFDiag((*BI)->getLocStart(),
4928 diag::note_constexpr_stmt_expr_unsupported);
4933 llvm_unreachable("Return from function from the loop above.");
4936 /// Visit a value which is evaluated, but whose value is ignored.
4937 void VisitIgnoredValue(const Expr *E) {
4938 EvaluateIgnoredValue(Info, E);
4941 /// Potentially visit a MemberExpr's base expression.
4942 void VisitIgnoredBaseExpression(const Expr *E) {
4943 // While MSVC doesn't evaluate the base expression, it does diagnose the
4944 // presence of side-effecting behavior.
4945 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4947 VisitIgnoredValue(E);
4953 //===----------------------------------------------------------------------===//
4954 // Common base class for lvalue and temporary evaluation.
4955 //===----------------------------------------------------------------------===//
4957 template<class Derived>
4958 class LValueExprEvaluatorBase
4959 : public ExprEvaluatorBase<Derived> {
4963 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4964 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4966 bool Success(APValue::LValueBase B) {
4971 bool evaluatePointer(const Expr *E, LValue &Result) {
4972 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4976 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4977 : ExprEvaluatorBaseTy(Info), Result(Result),
4978 InvalidBaseOK(InvalidBaseOK) {}
4980 bool Success(const APValue &V, const Expr *E) {
4981 Result.setFrom(this->Info.Ctx, V);
4985 bool VisitMemberExpr(const MemberExpr *E) {
4986 // Handle non-static data members.
4990 EvalOK = evaluatePointer(E->getBase(), Result);
4991 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4992 } else if (E->getBase()->isRValue()) {
4993 assert(E->getBase()->getType()->isRecordType());
4994 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4995 BaseTy = E->getBase()->getType();
4997 EvalOK = this->Visit(E->getBase());
4998 BaseTy = E->getBase()->getType();
5003 Result.setInvalid(E);
5007 const ValueDecl *MD = E->getMemberDecl();
5008 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5009 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5010 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5012 if (!HandleLValueMember(this->Info, E, Result, FD))
5014 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5015 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5018 return this->Error(E);
5020 if (MD->getType()->isReferenceType()) {
5022 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5025 return Success(RefValue, E);
5030 bool VisitBinaryOperator(const BinaryOperator *E) {
5031 switch (E->getOpcode()) {
5033 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5037 return HandleMemberPointerAccess(this->Info, E, Result);
5041 bool VisitCastExpr(const CastExpr *E) {
5042 switch (E->getCastKind()) {
5044 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5046 case CK_DerivedToBase:
5047 case CK_UncheckedDerivedToBase:
5048 if (!this->Visit(E->getSubExpr()))
5051 // Now figure out the necessary offset to add to the base LV to get from
5052 // the derived class to the base class.
5053 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5060 //===----------------------------------------------------------------------===//
5061 // LValue Evaluation
5063 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5064 // function designators (in C), decl references to void objects (in C), and
5065 // temporaries (if building with -Wno-address-of-temporary).
5067 // LValue evaluation produces values comprising a base expression of one of the
5073 // * CompoundLiteralExpr in C (and in global scope in C++)
5077 // * ObjCStringLiteralExpr
5081 // * CallExpr for a MakeStringConstant builtin
5082 // - Locals and temporaries
5083 // * MaterializeTemporaryExpr
5084 // * Any Expr, with a CallIndex indicating the function in which the temporary
5085 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5086 // from the AST (FIXME).
5087 // * A MaterializeTemporaryExpr that has static storage duration, with no
5088 // CallIndex, for a lifetime-extended temporary.
5089 // plus an offset in bytes.
5090 //===----------------------------------------------------------------------===//
5092 class LValueExprEvaluator
5093 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5095 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5096 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5098 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5099 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5101 bool VisitDeclRefExpr(const DeclRefExpr *E);
5102 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5103 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5104 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5105 bool VisitMemberExpr(const MemberExpr *E);
5106 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5107 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5108 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5109 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5110 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5111 bool VisitUnaryDeref(const UnaryOperator *E);
5112 bool VisitUnaryReal(const UnaryOperator *E);
5113 bool VisitUnaryImag(const UnaryOperator *E);
5114 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5115 return VisitUnaryPreIncDec(UO);
5117 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5118 return VisitUnaryPreIncDec(UO);
5120 bool VisitBinAssign(const BinaryOperator *BO);
5121 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5123 bool VisitCastExpr(const CastExpr *E) {
5124 switch (E->getCastKind()) {
5126 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5128 case CK_LValueBitCast:
5129 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5130 if (!Visit(E->getSubExpr()))
5132 Result.Designator.setInvalid();
5135 case CK_BaseToDerived:
5136 if (!Visit(E->getSubExpr()))
5138 return HandleBaseToDerivedCast(Info, E, Result);
5142 } // end anonymous namespace
5144 /// Evaluate an expression as an lvalue. This can be legitimately called on
5145 /// expressions which are not glvalues, in three cases:
5146 /// * function designators in C, and
5147 /// * "extern void" objects
5148 /// * @selector() expressions in Objective-C
5149 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5150 bool InvalidBaseOK) {
5151 assert(E->isGLValue() || E->getType()->isFunctionType() ||
5152 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5153 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5156 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5157 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5159 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5160 return VisitVarDecl(E, VD);
5161 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5162 return Visit(BD->getBinding());
5167 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5169 // If we are within a lambda's call operator, check whether the 'VD' referred
5170 // to within 'E' actually represents a lambda-capture that maps to a
5171 // data-member/field within the closure object, and if so, evaluate to the
5172 // field or what the field refers to.
5173 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5174 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5175 if (Info.checkingPotentialConstantExpression())
5177 // Start with 'Result' referring to the complete closure object...
5178 Result = *Info.CurrentCall->This;
5179 // ... then update it to refer to the field of the closure object
5180 // that represents the capture.
5181 if (!HandleLValueMember(Info, E, Result, FD))
5183 // And if the field is of reference type, update 'Result' to refer to what
5184 // the field refers to.
5185 if (FD->getType()->isReferenceType()) {
5187 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5190 Result.setFrom(Info.Ctx, RVal);
5195 CallStackFrame *Frame = nullptr;
5196 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5197 // Only if a local variable was declared in the function currently being
5198 // evaluated, do we expect to be able to find its value in the current
5199 // frame. (Otherwise it was likely declared in an enclosing context and
5200 // could either have a valid evaluatable value (for e.g. a constexpr
5201 // variable) or be ill-formed (and trigger an appropriate evaluation
5203 if (Info.CurrentCall->Callee &&
5204 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5205 Frame = Info.CurrentCall;
5209 if (!VD->getType()->isReferenceType()) {
5211 Result.set(VD, Frame->Index);
5218 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5220 if (V->isUninit()) {
5221 if (!Info.checkingPotentialConstantExpression())
5222 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5225 return Success(*V, E);
5228 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5229 const MaterializeTemporaryExpr *E) {
5230 // Walk through the expression to find the materialized temporary itself.
5231 SmallVector<const Expr *, 2> CommaLHSs;
5232 SmallVector<SubobjectAdjustment, 2> Adjustments;
5233 const Expr *Inner = E->GetTemporaryExpr()->
5234 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5236 // If we passed any comma operators, evaluate their LHSs.
5237 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5238 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5241 // A materialized temporary with static storage duration can appear within the
5242 // result of a constant expression evaluation, so we need to preserve its
5243 // value for use outside this evaluation.
5245 if (E->getStorageDuration() == SD_Static) {
5246 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5250 Value = &Info.CurrentCall->
5251 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5252 Result.set(E, Info.CurrentCall->Index);
5255 QualType Type = Inner->getType();
5257 // Materialize the temporary itself.
5258 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5259 (E->getStorageDuration() == SD_Static &&
5260 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5265 // Adjust our lvalue to refer to the desired subobject.
5266 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5268 switch (Adjustments[I].Kind) {
5269 case SubobjectAdjustment::DerivedToBaseAdjustment:
5270 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5273 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5276 case SubobjectAdjustment::FieldAdjustment:
5277 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5279 Type = Adjustments[I].Field->getType();
5282 case SubobjectAdjustment::MemberPointerAdjustment:
5283 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5284 Adjustments[I].Ptr.RHS))
5286 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5295 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5296 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5297 "lvalue compound literal in c++?");
5298 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5299 // only see this when folding in C, so there's no standard to follow here.
5303 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5304 if (!E->isPotentiallyEvaluated())
5307 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5308 << E->getExprOperand()->getType()
5309 << E->getExprOperand()->getSourceRange();
5313 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5317 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5318 // Handle static data members.
5319 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5320 VisitIgnoredBaseExpression(E->getBase());
5321 return VisitVarDecl(E, VD);
5324 // Handle static member functions.
5325 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5326 if (MD->isStatic()) {
5327 VisitIgnoredBaseExpression(E->getBase());
5332 // Handle non-static data members.
5333 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5336 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5337 // FIXME: Deal with vectors as array subscript bases.
5338 if (E->getBase()->getType()->isVectorType())
5341 bool Success = true;
5342 if (!evaluatePointer(E->getBase(), Result)) {
5343 if (!Info.noteFailure())
5349 if (!EvaluateInteger(E->getIdx(), Index, Info))
5353 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5356 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5357 return evaluatePointer(E->getSubExpr(), Result);
5360 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5361 if (!Visit(E->getSubExpr()))
5363 // __real is a no-op on scalar lvalues.
5364 if (E->getSubExpr()->getType()->isAnyComplexType())
5365 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5369 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5370 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5371 "lvalue __imag__ on scalar?");
5372 if (!Visit(E->getSubExpr()))
5374 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5378 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5379 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5382 if (!this->Visit(UO->getSubExpr()))
5385 return handleIncDec(
5386 this->Info, UO, Result, UO->getSubExpr()->getType(),
5387 UO->isIncrementOp(), nullptr);
5390 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5391 const CompoundAssignOperator *CAO) {
5392 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5397 // The overall lvalue result is the result of evaluating the LHS.
5398 if (!this->Visit(CAO->getLHS())) {
5399 if (Info.noteFailure())
5400 Evaluate(RHS, this->Info, CAO->getRHS());
5404 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5407 return handleCompoundAssignment(
5409 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5410 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5413 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5419 if (!this->Visit(E->getLHS())) {
5420 if (Info.noteFailure())
5421 Evaluate(NewVal, this->Info, E->getRHS());
5425 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5428 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5432 //===----------------------------------------------------------------------===//
5433 // Pointer Evaluation
5434 //===----------------------------------------------------------------------===//
5436 /// \brief Attempts to compute the number of bytes available at the pointer
5437 /// returned by a function with the alloc_size attribute. Returns true if we
5438 /// were successful. Places an unsigned number into `Result`.
5440 /// This expects the given CallExpr to be a call to a function with an
5441 /// alloc_size attribute.
5442 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5443 const CallExpr *Call,
5444 llvm::APInt &Result) {
5445 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5447 // alloc_size args are 1-indexed, 0 means not present.
5448 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5449 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5450 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5451 if (Call->getNumArgs() <= SizeArgNo)
5454 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5455 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5457 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5459 Into = Into.zextOrSelf(BitsInSizeT);
5464 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5467 if (!AllocSize->getNumElemsParam()) {
5468 Result = std::move(SizeOfElem);
5472 APSInt NumberOfElems;
5473 // Argument numbers start at 1
5474 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5475 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5479 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5483 Result = std::move(BytesAvailable);
5487 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5489 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5491 llvm::APInt &Result) {
5492 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5493 "Can't get the size of a non alloc_size function");
5494 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5495 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5496 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5499 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5500 /// a function with the alloc_size attribute. If it was possible to do so, this
5501 /// function will return true, make Result's Base point to said function call,
5502 /// and mark Result's Base as invalid.
5503 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5508 // Because we do no form of static analysis, we only support const variables.
5510 // Additionally, we can't support parameters, nor can we support static
5511 // variables (in the latter case, use-before-assign isn't UB; in the former,
5512 // we have no clue what they'll be assigned to).
5514 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5515 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5518 const Expr *Init = VD->getAnyInitializer();
5522 const Expr *E = Init->IgnoreParens();
5523 if (!tryUnwrapAllocSizeCall(E))
5526 // Store E instead of E unwrapped so that the type of the LValue's base is
5527 // what the user wanted.
5528 Result.setInvalid(E);
5530 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5531 Result.addUnsizedArray(Info, E, Pointee);
5536 class PointerExprEvaluator
5537 : public ExprEvaluatorBase<PointerExprEvaluator> {
5541 bool Success(const Expr *E) {
5546 bool evaluateLValue(const Expr *E, LValue &Result) {
5547 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5550 bool evaluatePointer(const Expr *E, LValue &Result) {
5551 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5554 bool visitNonBuiltinCallExpr(const CallExpr *E);
5557 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5558 : ExprEvaluatorBaseTy(info), Result(Result),
5559 InvalidBaseOK(InvalidBaseOK) {}
5561 bool Success(const APValue &V, const Expr *E) {
5562 Result.setFrom(Info.Ctx, V);
5565 bool ZeroInitialization(const Expr *E) {
5566 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5567 Result.setNull(E->getType(), TargetVal);
5571 bool VisitBinaryOperator(const BinaryOperator *E);
5572 bool VisitCastExpr(const CastExpr* E);
5573 bool VisitUnaryAddrOf(const UnaryOperator *E);
5574 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5575 { return Success(E); }
5576 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5577 if (Info.noteFailure())
5578 EvaluateIgnoredValue(Info, E->getSubExpr());
5581 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5582 { return Success(E); }
5583 bool VisitCallExpr(const CallExpr *E);
5584 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5585 bool VisitBlockExpr(const BlockExpr *E) {
5586 if (!E->getBlockDecl()->hasCaptures())
5590 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5591 // Can't look at 'this' when checking a potential constant expression.
5592 if (Info.checkingPotentialConstantExpression())
5594 if (!Info.CurrentCall->This) {
5595 if (Info.getLangOpts().CPlusPlus11)
5596 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5601 Result = *Info.CurrentCall->This;
5602 // If we are inside a lambda's call operator, the 'this' expression refers
5603 // to the enclosing '*this' object (either by value or reference) which is
5604 // either copied into the closure object's field that represents the '*this'
5605 // or refers to '*this'.
5606 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5607 // Update 'Result' to refer to the data member/field of the closure object
5608 // that represents the '*this' capture.
5609 if (!HandleLValueMember(Info, E, Result,
5610 Info.CurrentCall->LambdaThisCaptureField))
5612 // If we captured '*this' by reference, replace the field with its referent.
5613 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5614 ->isPointerType()) {
5616 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5620 Result.setFrom(Info.Ctx, RVal);
5626 // FIXME: Missing: @protocol, @selector
5628 } // end anonymous namespace
5630 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5631 bool InvalidBaseOK) {
5632 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5633 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5636 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5637 if (E->getOpcode() != BO_Add &&
5638 E->getOpcode() != BO_Sub)
5639 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5641 const Expr *PExp = E->getLHS();
5642 const Expr *IExp = E->getRHS();
5643 if (IExp->getType()->isPointerType())
5644 std::swap(PExp, IExp);
5646 bool EvalPtrOK = evaluatePointer(PExp, Result);
5647 if (!EvalPtrOK && !Info.noteFailure())
5650 llvm::APSInt Offset;
5651 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5654 if (E->getOpcode() == BO_Sub)
5655 negateAsSigned(Offset);
5657 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5658 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5661 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5662 return evaluateLValue(E->getSubExpr(), Result);
5665 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5666 const Expr* SubExpr = E->getSubExpr();
5668 switch (E->getCastKind()) {
5673 case CK_CPointerToObjCPointerCast:
5674 case CK_BlockPointerToObjCPointerCast:
5675 case CK_AnyPointerToBlockPointerCast:
5676 case CK_AddressSpaceConversion:
5677 if (!Visit(SubExpr))
5679 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5680 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5681 // also static_casts, but we disallow them as a resolution to DR1312.
5682 if (!E->getType()->isVoidPointerType()) {
5683 Result.Designator.setInvalid();
5684 if (SubExpr->getType()->isVoidPointerType())
5685 CCEDiag(E, diag::note_constexpr_invalid_cast)
5686 << 3 << SubExpr->getType();
5688 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5690 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5691 ZeroInitialization(E);
5694 case CK_DerivedToBase:
5695 case CK_UncheckedDerivedToBase:
5696 if (!evaluatePointer(E->getSubExpr(), Result))
5698 if (!Result.Base && Result.Offset.isZero())
5701 // Now figure out the necessary offset to add to the base LV to get from
5702 // the derived class to the base class.
5703 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5704 castAs<PointerType>()->getPointeeType(),
5707 case CK_BaseToDerived:
5708 if (!Visit(E->getSubExpr()))
5710 if (!Result.Base && Result.Offset.isZero())
5712 return HandleBaseToDerivedCast(Info, E, Result);
5714 case CK_NullToPointer:
5715 VisitIgnoredValue(E->getSubExpr());
5716 return ZeroInitialization(E);
5718 case CK_IntegralToPointer: {
5719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5722 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5725 if (Value.isInt()) {
5726 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5727 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5728 Result.Base = (Expr*)nullptr;
5729 Result.InvalidBase = false;
5730 Result.Offset = CharUnits::fromQuantity(N);
5731 Result.CallIndex = 0;
5732 Result.Designator.setInvalid();
5733 Result.IsNullPtr = false;
5736 // Cast is of an lvalue, no need to change value.
5737 Result.setFrom(Info.Ctx, Value);
5742 case CK_ArrayToPointerDecay: {
5743 if (SubExpr->isGLValue()) {
5744 if (!evaluateLValue(SubExpr, Result))
5747 Result.set(SubExpr, Info.CurrentCall->Index);
5748 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5749 Info, Result, SubExpr))
5752 // The result is a pointer to the first element of the array.
5753 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5754 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5755 Result.addArray(Info, E, CAT);
5757 Result.addUnsizedArray(Info, E, AT->getElementType());
5761 case CK_FunctionToPointerDecay:
5762 return evaluateLValue(SubExpr, Result);
5764 case CK_LValueToRValue: {
5766 if (!evaluateLValue(E->getSubExpr(), LVal))
5770 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5771 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5773 return InvalidBaseOK &&
5774 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5775 return Success(RVal, E);
5779 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5782 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5783 // C++ [expr.alignof]p3:
5784 // When alignof is applied to a reference type, the result is the
5785 // alignment of the referenced type.
5786 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5787 T = Ref->getPointeeType();
5789 // __alignof is defined to return the preferred alignment.
5790 if (T.getQualifiers().hasUnaligned())
5791 return CharUnits::One();
5792 return Info.Ctx.toCharUnitsFromBits(
5793 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5796 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5797 E = E->IgnoreParens();
5799 // The kinds of expressions that we have special-case logic here for
5800 // should be kept up to date with the special checks for those
5801 // expressions in Sema.
5803 // alignof decl is always accepted, even if it doesn't make sense: we default
5804 // to 1 in those cases.
5805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5806 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5807 /*RefAsPointee*/true);
5809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5810 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5811 /*RefAsPointee*/true);
5813 return GetAlignOfType(Info, E->getType());
5816 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5817 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5818 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5821 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5824 Result.setInvalid(E);
5825 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5826 Result.addUnsizedArray(Info, E, PointeeTy);
5830 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5831 if (IsStringLiteralCall(E))
5834 if (unsigned BuiltinOp = E->getBuiltinCallee())
5835 return VisitBuiltinCallExpr(E, BuiltinOp);
5837 return visitNonBuiltinCallExpr(E);
5840 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5841 unsigned BuiltinOp) {
5842 switch (BuiltinOp) {
5843 case Builtin::BI__builtin_addressof:
5844 return evaluateLValue(E->getArg(0), Result);
5845 case Builtin::BI__builtin_assume_aligned: {
5846 // We need to be very careful here because: if the pointer does not have the
5847 // asserted alignment, then the behavior is undefined, and undefined
5848 // behavior is non-constant.
5849 if (!evaluatePointer(E->getArg(0), Result))
5852 LValue OffsetResult(Result);
5854 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5856 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5858 if (E->getNumArgs() > 2) {
5860 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5863 int64_t AdditionalOffset = -Offset.getZExtValue();
5864 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5867 // If there is a base object, then it must have the correct alignment.
5868 if (OffsetResult.Base) {
5869 CharUnits BaseAlignment;
5870 if (const ValueDecl *VD =
5871 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5872 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5875 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5878 if (BaseAlignment < Align) {
5879 Result.Designator.setInvalid();
5880 // FIXME: Add support to Diagnostic for long / long long.
5881 CCEDiag(E->getArg(0),
5882 diag::note_constexpr_baa_insufficient_alignment) << 0
5883 << (unsigned)BaseAlignment.getQuantity()
5884 << (unsigned)Align.getQuantity();
5889 // The offset must also have the correct alignment.
5890 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5891 Result.Designator.setInvalid();
5894 ? CCEDiag(E->getArg(0),
5895 diag::note_constexpr_baa_insufficient_alignment) << 1
5896 : CCEDiag(E->getArg(0),
5897 diag::note_constexpr_baa_value_insufficient_alignment))
5898 << (int)OffsetResult.Offset.getQuantity()
5899 << (unsigned)Align.getQuantity();
5906 case Builtin::BIstrchr:
5907 case Builtin::BIwcschr:
5908 case Builtin::BImemchr:
5909 case Builtin::BIwmemchr:
5910 if (Info.getLangOpts().CPlusPlus11)
5911 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5912 << /*isConstexpr*/0 << /*isConstructor*/0
5913 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5915 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5917 case Builtin::BI__builtin_strchr:
5918 case Builtin::BI__builtin_wcschr:
5919 case Builtin::BI__builtin_memchr:
5920 case Builtin::BI__builtin_char_memchr:
5921 case Builtin::BI__builtin_wmemchr: {
5922 if (!Visit(E->getArg(0)))
5925 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5927 uint64_t MaxLength = uint64_t(-1);
5928 if (BuiltinOp != Builtin::BIstrchr &&
5929 BuiltinOp != Builtin::BIwcschr &&
5930 BuiltinOp != Builtin::BI__builtin_strchr &&
5931 BuiltinOp != Builtin::BI__builtin_wcschr) {
5933 if (!EvaluateInteger(E->getArg(2), N, Info))
5935 MaxLength = N.getExtValue();
5938 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5940 // Figure out what value we're actually looking for (after converting to
5941 // the corresponding unsigned type if necessary).
5942 uint64_t DesiredVal;
5943 bool StopAtNull = false;
5944 switch (BuiltinOp) {
5945 case Builtin::BIstrchr:
5946 case Builtin::BI__builtin_strchr:
5947 // strchr compares directly to the passed integer, and therefore
5948 // always fails if given an int that is not a char.
5949 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5950 E->getArg(1)->getType(),
5953 return ZeroInitialization(E);
5956 case Builtin::BImemchr:
5957 case Builtin::BI__builtin_memchr:
5958 case Builtin::BI__builtin_char_memchr:
5959 // memchr compares by converting both sides to unsigned char. That's also
5960 // correct for strchr if we get this far (to cope with plain char being
5961 // unsigned in the strchr case).
5962 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5965 case Builtin::BIwcschr:
5966 case Builtin::BI__builtin_wcschr:
5969 case Builtin::BIwmemchr:
5970 case Builtin::BI__builtin_wmemchr:
5971 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5972 DesiredVal = Desired.getZExtValue();
5976 for (; MaxLength; --MaxLength) {
5978 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5981 if (Char.getInt().getZExtValue() == DesiredVal)
5983 if (StopAtNull && !Char.getInt())
5985 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5988 // Not found: return nullptr.
5989 return ZeroInitialization(E);
5993 return visitNonBuiltinCallExpr(E);
5997 //===----------------------------------------------------------------------===//
5998 // Member Pointer Evaluation
5999 //===----------------------------------------------------------------------===//
6002 class MemberPointerExprEvaluator
6003 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6006 bool Success(const ValueDecl *D) {
6007 Result = MemberPtr(D);
6012 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6013 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6015 bool Success(const APValue &V, const Expr *E) {
6019 bool ZeroInitialization(const Expr *E) {
6020 return Success((const ValueDecl*)nullptr);
6023 bool VisitCastExpr(const CastExpr *E);
6024 bool VisitUnaryAddrOf(const UnaryOperator *E);
6026 } // end anonymous namespace
6028 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6030 assert(E->isRValue() && E->getType()->isMemberPointerType());
6031 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6034 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6035 switch (E->getCastKind()) {
6037 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6039 case CK_NullToMemberPointer:
6040 VisitIgnoredValue(E->getSubExpr());
6041 return ZeroInitialization(E);
6043 case CK_BaseToDerivedMemberPointer: {
6044 if (!Visit(E->getSubExpr()))
6046 if (E->path_empty())
6048 // Base-to-derived member pointer casts store the path in derived-to-base
6049 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6050 // the wrong end of the derived->base arc, so stagger the path by one class.
6051 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6052 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6053 PathI != PathE; ++PathI) {
6054 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6055 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6056 if (!Result.castToDerived(Derived))
6059 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6060 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6065 case CK_DerivedToBaseMemberPointer:
6066 if (!Visit(E->getSubExpr()))
6068 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6069 PathE = E->path_end(); PathI != PathE; ++PathI) {
6070 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6071 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6072 if (!Result.castToBase(Base))
6079 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6080 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6081 // member can be formed.
6082 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6085 //===----------------------------------------------------------------------===//
6086 // Record Evaluation
6087 //===----------------------------------------------------------------------===//
6090 class RecordExprEvaluator
6091 : public ExprEvaluatorBase<RecordExprEvaluator> {
6096 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6097 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6099 bool Success(const APValue &V, const Expr *E) {
6103 bool ZeroInitialization(const Expr *E) {
6104 return ZeroInitialization(E, E->getType());
6106 bool ZeroInitialization(const Expr *E, QualType T);
6108 bool VisitCallExpr(const CallExpr *E) {
6109 return handleCallExpr(E, Result, &This);
6111 bool VisitCastExpr(const CastExpr *E);
6112 bool VisitInitListExpr(const InitListExpr *E);
6113 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6114 return VisitCXXConstructExpr(E, E->getType());
6116 bool VisitLambdaExpr(const LambdaExpr *E);
6117 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6118 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6119 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6123 /// Perform zero-initialization on an object of non-union class type.
6124 /// C++11 [dcl.init]p5:
6125 /// To zero-initialize an object or reference of type T means:
6127 /// -- if T is a (possibly cv-qualified) non-union class type,
6128 /// each non-static data member and each base-class subobject is
6129 /// zero-initialized
6130 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6131 const RecordDecl *RD,
6132 const LValue &This, APValue &Result) {
6133 assert(!RD->isUnion() && "Expected non-union class type");
6134 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6135 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6136 std::distance(RD->field_begin(), RD->field_end()));
6138 if (RD->isInvalidDecl()) return false;
6139 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6143 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6144 End = CD->bases_end(); I != End; ++I, ++Index) {
6145 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6146 LValue Subobject = This;
6147 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6149 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6150 Result.getStructBase(Index)))
6155 for (const auto *I : RD->fields()) {
6156 // -- if T is a reference type, no initialization is performed.
6157 if (I->getType()->isReferenceType())
6160 LValue Subobject = This;
6161 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6164 ImplicitValueInitExpr VIE(I->getType());
6165 if (!EvaluateInPlace(
6166 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6173 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6174 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6175 if (RD->isInvalidDecl()) return false;
6176 if (RD->isUnion()) {
6177 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6178 // object's first non-static named data member is zero-initialized
6179 RecordDecl::field_iterator I = RD->field_begin();
6180 if (I == RD->field_end()) {
6181 Result = APValue((const FieldDecl*)nullptr);
6185 LValue Subobject = This;
6186 if (!HandleLValueMember(Info, E, Subobject, *I))
6188 Result = APValue(*I);
6189 ImplicitValueInitExpr VIE(I->getType());
6190 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6193 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6194 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6198 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6201 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6202 switch (E->getCastKind()) {
6204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6206 case CK_ConstructorConversion:
6207 return Visit(E->getSubExpr());
6209 case CK_DerivedToBase:
6210 case CK_UncheckedDerivedToBase: {
6211 APValue DerivedObject;
6212 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6214 if (!DerivedObject.isStruct())
6215 return Error(E->getSubExpr());
6217 // Derived-to-base rvalue conversion: just slice off the derived part.
6218 APValue *Value = &DerivedObject;
6219 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6220 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6221 PathE = E->path_end(); PathI != PathE; ++PathI) {
6222 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6223 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6224 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6233 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6234 if (E->isTransparent())
6235 return Visit(E->getInit(0));
6237 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6238 if (RD->isInvalidDecl()) return false;
6239 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6241 if (RD->isUnion()) {
6242 const FieldDecl *Field = E->getInitializedFieldInUnion();
6243 Result = APValue(Field);
6247 // If the initializer list for a union does not contain any elements, the
6248 // first element of the union is value-initialized.
6249 // FIXME: The element should be initialized from an initializer list.
6250 // Is this difference ever observable for initializer lists which
6252 ImplicitValueInitExpr VIE(Field->getType());
6253 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6255 LValue Subobject = This;
6256 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6259 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6260 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6261 isa<CXXDefaultInitExpr>(InitExpr));
6263 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6266 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6267 if (Result.isUninit())
6268 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6269 std::distance(RD->field_begin(), RD->field_end()));
6270 unsigned ElementNo = 0;
6271 bool Success = true;
6273 // Initialize base classes.
6275 for (const auto &Base : CXXRD->bases()) {
6276 assert(ElementNo < E->getNumInits() && "missing init for base class");
6277 const Expr *Init = E->getInit(ElementNo);
6279 LValue Subobject = This;
6280 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6283 APValue &FieldVal = Result.getStructBase(ElementNo);
6284 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6285 if (!Info.noteFailure())
6293 // Initialize members.
6294 for (const auto *Field : RD->fields()) {
6295 // Anonymous bit-fields are not considered members of the class for
6296 // purposes of aggregate initialization.
6297 if (Field->isUnnamedBitfield())
6300 LValue Subobject = This;
6302 bool HaveInit = ElementNo < E->getNumInits();
6304 // FIXME: Diagnostics here should point to the end of the initializer
6305 // list, not the start.
6306 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6307 Subobject, Field, &Layout))
6310 // Perform an implicit value-initialization for members beyond the end of
6311 // the initializer list.
6312 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6313 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6315 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6316 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6317 isa<CXXDefaultInitExpr>(Init));
6319 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6320 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6321 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6322 FieldVal, Field))) {
6323 if (!Info.noteFailure())
6332 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6334 // Note that E's type is not necessarily the type of our class here; we might
6335 // be initializing an array element instead.
6336 const CXXConstructorDecl *FD = E->getConstructor();
6337 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6339 bool ZeroInit = E->requiresZeroInitialization();
6340 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6341 // If we've already performed zero-initialization, we're already done.
6342 if (!Result.isUninit())
6345 // We can get here in two different ways:
6346 // 1) We're performing value-initialization, and should zero-initialize
6348 // 2) We're performing default-initialization of an object with a trivial
6349 // constexpr default constructor, in which case we should start the
6350 // lifetimes of all the base subobjects (there can be no data member
6351 // subobjects in this case) per [basic.life]p1.
6352 // Either way, ZeroInitialization is appropriate.
6353 return ZeroInitialization(E, T);
6356 const FunctionDecl *Definition = nullptr;
6357 auto Body = FD->getBody(Definition);
6359 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6362 // Avoid materializing a temporary for an elidable copy/move constructor.
6363 if (E->isElidable() && !ZeroInit)
6364 if (const MaterializeTemporaryExpr *ME
6365 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6366 return Visit(ME->GetTemporaryExpr());
6368 if (ZeroInit && !ZeroInitialization(E, T))
6371 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6372 return HandleConstructorCall(E, This, Args,
6373 cast<CXXConstructorDecl>(Definition), Info,
6377 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6378 const CXXInheritedCtorInitExpr *E) {
6379 if (!Info.CurrentCall) {
6380 assert(Info.checkingPotentialConstantExpression());
6384 const CXXConstructorDecl *FD = E->getConstructor();
6385 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6388 const FunctionDecl *Definition = nullptr;
6389 auto Body = FD->getBody(Definition);
6391 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6394 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6395 cast<CXXConstructorDecl>(Definition), Info,
6399 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6400 const CXXStdInitializerListExpr *E) {
6401 const ConstantArrayType *ArrayType =
6402 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6405 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6408 // Get a pointer to the first element of the array.
6409 Array.addArray(Info, E, ArrayType);
6411 // FIXME: Perform the checks on the field types in SemaInit.
6412 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6413 RecordDecl::field_iterator Field = Record->field_begin();
6414 if (Field == Record->field_end())
6418 if (!Field->getType()->isPointerType() ||
6419 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6420 ArrayType->getElementType()))
6423 // FIXME: What if the initializer_list type has base classes, etc?
6424 Result = APValue(APValue::UninitStruct(), 0, 2);
6425 Array.moveInto(Result.getStructField(0));
6427 if (++Field == Record->field_end())
6430 if (Field->getType()->isPointerType() &&
6431 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6432 ArrayType->getElementType())) {
6434 if (!HandleLValueArrayAdjustment(Info, E, Array,
6435 ArrayType->getElementType(),
6436 ArrayType->getSize().getZExtValue()))
6438 Array.moveInto(Result.getStructField(1));
6439 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6441 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6445 if (++Field != Record->field_end())
6451 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6452 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6453 if (ClosureClass->isInvalidDecl()) return false;
6455 if (Info.checkingPotentialConstantExpression()) return true;
6457 const size_t NumFields =
6458 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6460 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6461 E->capture_init_end()) &&
6462 "The number of lambda capture initializers should equal the number of "
6463 "fields within the closure type");
6465 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6466 // Iterate through all the lambda's closure object's fields and initialize
6468 auto *CaptureInitIt = E->capture_init_begin();
6469 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6470 bool Success = true;
6471 for (const auto *Field : ClosureClass->fields()) {
6472 assert(CaptureInitIt != E->capture_init_end());
6473 // Get the initializer for this field
6474 Expr *const CurFieldInit = *CaptureInitIt++;
6476 // If there is no initializer, either this is a VLA or an error has
6481 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6482 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6483 if (!Info.keepEvaluatingAfterFailure())
6492 static bool EvaluateRecord(const Expr *E, const LValue &This,
6493 APValue &Result, EvalInfo &Info) {
6494 assert(E->isRValue() && E->getType()->isRecordType() &&
6495 "can't evaluate expression as a record rvalue");
6496 return RecordExprEvaluator(Info, This, Result).Visit(E);
6499 //===----------------------------------------------------------------------===//
6500 // Temporary Evaluation
6502 // Temporaries are represented in the AST as rvalues, but generally behave like
6503 // lvalues. The full-object of which the temporary is a subobject is implicitly
6504 // materialized so that a reference can bind to it.
6505 //===----------------------------------------------------------------------===//
6507 class TemporaryExprEvaluator
6508 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6510 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6511 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6513 /// Visit an expression which constructs the value of this temporary.
6514 bool VisitConstructExpr(const Expr *E) {
6515 Result.set(E, Info.CurrentCall->Index);
6516 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6520 bool VisitCastExpr(const CastExpr *E) {
6521 switch (E->getCastKind()) {
6523 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6525 case CK_ConstructorConversion:
6526 return VisitConstructExpr(E->getSubExpr());
6529 bool VisitInitListExpr(const InitListExpr *E) {
6530 return VisitConstructExpr(E);
6532 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6533 return VisitConstructExpr(E);
6535 bool VisitCallExpr(const CallExpr *E) {
6536 return VisitConstructExpr(E);
6538 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6539 return VisitConstructExpr(E);
6541 bool VisitLambdaExpr(const LambdaExpr *E) {
6542 return VisitConstructExpr(E);
6545 } // end anonymous namespace
6547 /// Evaluate an expression of record type as a temporary.
6548 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6549 assert(E->isRValue() && E->getType()->isRecordType());
6550 return TemporaryExprEvaluator(Info, Result).Visit(E);
6553 //===----------------------------------------------------------------------===//
6554 // Vector Evaluation
6555 //===----------------------------------------------------------------------===//
6558 class VectorExprEvaluator
6559 : public ExprEvaluatorBase<VectorExprEvaluator> {
6563 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6564 : ExprEvaluatorBaseTy(info), Result(Result) {}
6566 bool Success(ArrayRef<APValue> V, const Expr *E) {
6567 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6568 // FIXME: remove this APValue copy.
6569 Result = APValue(V.data(), V.size());
6572 bool Success(const APValue &V, const Expr *E) {
6573 assert(V.isVector());
6577 bool ZeroInitialization(const Expr *E);
6579 bool VisitUnaryReal(const UnaryOperator *E)
6580 { return Visit(E->getSubExpr()); }
6581 bool VisitCastExpr(const CastExpr* E);
6582 bool VisitInitListExpr(const InitListExpr *E);
6583 bool VisitUnaryImag(const UnaryOperator *E);
6584 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6585 // binary comparisons, binary and/or/xor,
6586 // shufflevector, ExtVectorElementExpr
6588 } // end anonymous namespace
6590 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6591 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6592 return VectorExprEvaluator(Info, Result).Visit(E);
6595 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6596 const VectorType *VTy = E->getType()->castAs<VectorType>();
6597 unsigned NElts = VTy->getNumElements();
6599 const Expr *SE = E->getSubExpr();
6600 QualType SETy = SE->getType();
6602 switch (E->getCastKind()) {
6603 case CK_VectorSplat: {
6604 APValue Val = APValue();
6605 if (SETy->isIntegerType()) {
6607 if (!EvaluateInteger(SE, IntResult, Info))
6609 Val = APValue(std::move(IntResult));
6610 } else if (SETy->isRealFloatingType()) {
6611 APFloat FloatResult(0.0);
6612 if (!EvaluateFloat(SE, FloatResult, Info))
6614 Val = APValue(std::move(FloatResult));
6619 // Splat and create vector APValue.
6620 SmallVector<APValue, 4> Elts(NElts, Val);
6621 return Success(Elts, E);
6624 // Evaluate the operand into an APInt we can extract from.
6625 llvm::APInt SValInt;
6626 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6628 // Extract the elements
6629 QualType EltTy = VTy->getElementType();
6630 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6631 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6632 SmallVector<APValue, 4> Elts;
6633 if (EltTy->isRealFloatingType()) {
6634 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6635 unsigned FloatEltSize = EltSize;
6636 if (&Sem == &APFloat::x87DoubleExtended())
6638 for (unsigned i = 0; i < NElts; i++) {
6641 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6643 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6644 Elts.push_back(APValue(APFloat(Sem, Elt)));
6646 } else if (EltTy->isIntegerType()) {
6647 for (unsigned i = 0; i < NElts; i++) {
6650 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6652 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6653 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6658 return Success(Elts, E);
6661 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6666 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6667 const VectorType *VT = E->getType()->castAs<VectorType>();
6668 unsigned NumInits = E->getNumInits();
6669 unsigned NumElements = VT->getNumElements();
6671 QualType EltTy = VT->getElementType();
6672 SmallVector<APValue, 4> Elements;
6674 // The number of initializers can be less than the number of
6675 // vector elements. For OpenCL, this can be due to nested vector
6676 // initialization. For GCC compatibility, missing trailing elements
6677 // should be initialized with zeroes.
6678 unsigned CountInits = 0, CountElts = 0;
6679 while (CountElts < NumElements) {
6680 // Handle nested vector initialization.
6681 if (CountInits < NumInits
6682 && E->getInit(CountInits)->getType()->isVectorType()) {
6684 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6686 unsigned vlen = v.getVectorLength();
6687 for (unsigned j = 0; j < vlen; j++)
6688 Elements.push_back(v.getVectorElt(j));
6690 } else if (EltTy->isIntegerType()) {
6691 llvm::APSInt sInt(32);
6692 if (CountInits < NumInits) {
6693 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6695 } else // trailing integer zero.
6696 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6697 Elements.push_back(APValue(sInt));
6700 llvm::APFloat f(0.0);
6701 if (CountInits < NumInits) {
6702 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6704 } else // trailing float zero.
6705 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6706 Elements.push_back(APValue(f));
6711 return Success(Elements, E);
6715 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6716 const VectorType *VT = E->getType()->getAs<VectorType>();
6717 QualType EltTy = VT->getElementType();
6718 APValue ZeroElement;
6719 if (EltTy->isIntegerType())
6720 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6723 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6725 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6726 return Success(Elements, E);
6729 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6730 VisitIgnoredValue(E->getSubExpr());
6731 return ZeroInitialization(E);
6734 //===----------------------------------------------------------------------===//
6736 //===----------------------------------------------------------------------===//
6739 class ArrayExprEvaluator
6740 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6745 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6746 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6748 bool Success(const APValue &V, const Expr *E) {
6749 assert((V.isArray() || V.isLValue()) &&
6750 "expected array or string literal");
6755 bool ZeroInitialization(const Expr *E) {
6756 const ConstantArrayType *CAT =
6757 Info.Ctx.getAsConstantArrayType(E->getType());
6761 Result = APValue(APValue::UninitArray(), 0,
6762 CAT->getSize().getZExtValue());
6763 if (!Result.hasArrayFiller()) return true;
6765 // Zero-initialize all elements.
6766 LValue Subobject = This;
6767 Subobject.addArray(Info, E, CAT);
6768 ImplicitValueInitExpr VIE(CAT->getElementType());
6769 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6772 bool VisitCallExpr(const CallExpr *E) {
6773 return handleCallExpr(E, Result, &This);
6775 bool VisitInitListExpr(const InitListExpr *E);
6776 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6777 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6778 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6779 const LValue &Subobject,
6780 APValue *Value, QualType Type);
6782 } // end anonymous namespace
6784 static bool EvaluateArray(const Expr *E, const LValue &This,
6785 APValue &Result, EvalInfo &Info) {
6786 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6787 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6790 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6791 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6795 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6796 // an appropriately-typed string literal enclosed in braces.
6797 if (E->isStringLiteralInit()) {
6799 if (!EvaluateLValue(E->getInit(0), LV, Info))
6803 return Success(Val, E);
6806 bool Success = true;
6808 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6809 "zero-initialized array shouldn't have any initialized elts");
6811 if (Result.isArray() && Result.hasArrayFiller())
6812 Filler = Result.getArrayFiller();
6814 unsigned NumEltsToInit = E->getNumInits();
6815 unsigned NumElts = CAT->getSize().getZExtValue();
6816 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6818 // If the initializer might depend on the array index, run it for each
6819 // array element. For now, just whitelist non-class value-initialization.
6820 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6821 NumEltsToInit = NumElts;
6823 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6825 // If the array was previously zero-initialized, preserve the
6826 // zero-initialized values.
6827 if (!Filler.isUninit()) {
6828 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6829 Result.getArrayInitializedElt(I) = Filler;
6830 if (Result.hasArrayFiller())
6831 Result.getArrayFiller() = Filler;
6834 LValue Subobject = This;
6835 Subobject.addArray(Info, E, CAT);
6836 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6838 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6839 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6840 Info, Subobject, Init) ||
6841 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6842 CAT->getElementType(), 1)) {
6843 if (!Info.noteFailure())
6849 if (!Result.hasArrayFiller())
6852 // If we get here, we have a trivial filler, which we can just evaluate
6853 // once and splat over the rest of the array elements.
6854 assert(FillerExpr && "no array filler for incomplete init list");
6855 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6856 FillerExpr) && Success;
6859 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6860 if (E->getCommonExpr() &&
6861 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6862 Info, E->getCommonExpr()->getSourceExpr()))
6865 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6867 uint64_t Elements = CAT->getSize().getZExtValue();
6868 Result = APValue(APValue::UninitArray(), Elements, Elements);
6870 LValue Subobject = This;
6871 Subobject.addArray(Info, E, CAT);
6873 bool Success = true;
6874 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6875 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6876 Info, Subobject, E->getSubExpr()) ||
6877 !HandleLValueArrayAdjustment(Info, E, Subobject,
6878 CAT->getElementType(), 1)) {
6879 if (!Info.noteFailure())
6888 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6889 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6892 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6893 const LValue &Subobject,
6896 bool HadZeroInit = !Value->isUninit();
6898 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6899 unsigned N = CAT->getSize().getZExtValue();
6901 // Preserve the array filler if we had prior zero-initialization.
6903 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6906 *Value = APValue(APValue::UninitArray(), N, N);
6909 for (unsigned I = 0; I != N; ++I)
6910 Value->getArrayInitializedElt(I) = Filler;
6912 // Initialize the elements.
6913 LValue ArrayElt = Subobject;
6914 ArrayElt.addArray(Info, E, CAT);
6915 for (unsigned I = 0; I != N; ++I)
6916 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6917 CAT->getElementType()) ||
6918 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6919 CAT->getElementType(), 1))
6925 if (!Type->isRecordType())
6928 return RecordExprEvaluator(Info, Subobject, *Value)
6929 .VisitCXXConstructExpr(E, Type);
6932 //===----------------------------------------------------------------------===//
6933 // Integer Evaluation
6935 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6936 // types and back in constant folding. Integer values are thus represented
6937 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6938 //===----------------------------------------------------------------------===//
6941 class IntExprEvaluator
6942 : public ExprEvaluatorBase<IntExprEvaluator> {
6945 IntExprEvaluator(EvalInfo &info, APValue &result)
6946 : ExprEvaluatorBaseTy(info), Result(result) {}
6948 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6949 assert(E->getType()->isIntegralOrEnumerationType() &&
6950 "Invalid evaluation result.");
6951 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6952 "Invalid evaluation result.");
6953 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6954 "Invalid evaluation result.");
6955 Result = APValue(SI);
6958 bool Success(const llvm::APSInt &SI, const Expr *E) {
6959 return Success(SI, E, Result);
6962 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6963 assert(E->getType()->isIntegralOrEnumerationType() &&
6964 "Invalid evaluation result.");
6965 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6966 "Invalid evaluation result.");
6967 Result = APValue(APSInt(I));
6968 Result.getInt().setIsUnsigned(
6969 E->getType()->isUnsignedIntegerOrEnumerationType());
6972 bool Success(const llvm::APInt &I, const Expr *E) {
6973 return Success(I, E, Result);
6976 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6977 assert(E->getType()->isIntegralOrEnumerationType() &&
6978 "Invalid evaluation result.");
6979 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6982 bool Success(uint64_t Value, const Expr *E) {
6983 return Success(Value, E, Result);
6986 bool Success(CharUnits Size, const Expr *E) {
6987 return Success(Size.getQuantity(), E);
6990 bool Success(const APValue &V, const Expr *E) {
6991 if (V.isLValue() || V.isAddrLabelDiff()) {
6995 return Success(V.getInt(), E);
6998 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7000 //===--------------------------------------------------------------------===//
7002 //===--------------------------------------------------------------------===//
7004 bool VisitIntegerLiteral(const IntegerLiteral *E) {
7005 return Success(E->getValue(), E);
7007 bool VisitCharacterLiteral(const CharacterLiteral *E) {
7008 return Success(E->getValue(), E);
7011 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7012 bool VisitDeclRefExpr(const DeclRefExpr *E) {
7013 if (CheckReferencedDecl(E, E->getDecl()))
7016 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7018 bool VisitMemberExpr(const MemberExpr *E) {
7019 if (CheckReferencedDecl(E, E->getMemberDecl())) {
7020 VisitIgnoredBaseExpression(E->getBase());
7024 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7027 bool VisitCallExpr(const CallExpr *E);
7028 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7029 bool VisitBinaryOperator(const BinaryOperator *E);
7030 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7031 bool VisitUnaryOperator(const UnaryOperator *E);
7033 bool VisitCastExpr(const CastExpr* E);
7034 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7036 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7037 return Success(E->getValue(), E);
7040 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7041 return Success(E->getValue(), E);
7044 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7045 if (Info.ArrayInitIndex == uint64_t(-1)) {
7046 // We were asked to evaluate this subexpression independent of the
7047 // enclosing ArrayInitLoopExpr. We can't do that.
7051 return Success(Info.ArrayInitIndex, E);
7054 // Note, GNU defines __null as an integer, not a pointer.
7055 bool VisitGNUNullExpr(const GNUNullExpr *E) {
7056 return ZeroInitialization(E);
7059 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7060 return Success(E->getValue(), E);
7063 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7064 return Success(E->getValue(), E);
7067 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7068 return Success(E->getValue(), E);
7071 bool VisitUnaryReal(const UnaryOperator *E);
7072 bool VisitUnaryImag(const UnaryOperator *E);
7074 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7075 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7077 // FIXME: Missing: array subscript of vector, member of vector
7079 } // end anonymous namespace
7081 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7082 /// produce either the integer value or a pointer.
7084 /// GCC has a heinous extension which folds casts between pointer types and
7085 /// pointer-sized integral types. We support this by allowing the evaluation of
7086 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7087 /// Some simple arithmetic on such values is supported (they are treated much
7089 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7091 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7092 return IntExprEvaluator(Info, Result).Visit(E);
7095 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7097 if (!EvaluateIntegerOrLValue(E, Val, Info))
7100 // FIXME: It would be better to produce the diagnostic for casting
7101 // a pointer to an integer.
7102 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7105 Result = Val.getInt();
7109 /// Check whether the given declaration can be directly converted to an integral
7110 /// rvalue. If not, no diagnostic is produced; there are other things we can
7112 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7113 // Enums are integer constant exprs.
7114 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7115 // Check for signedness/width mismatches between E type and ECD value.
7116 bool SameSign = (ECD->getInitVal().isSigned()
7117 == E->getType()->isSignedIntegerOrEnumerationType());
7118 bool SameWidth = (ECD->getInitVal().getBitWidth()
7119 == Info.Ctx.getIntWidth(E->getType()));
7120 if (SameSign && SameWidth)
7121 return Success(ECD->getInitVal(), E);
7123 // Get rid of mismatch (otherwise Success assertions will fail)
7124 // by computing a new value matching the type of E.
7125 llvm::APSInt Val = ECD->getInitVal();
7127 Val.setIsSigned(!ECD->getInitVal().isSigned());
7129 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7130 return Success(Val, E);
7136 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7138 static int EvaluateBuiltinClassifyType(const CallExpr *E,
7139 const LangOptions &LangOpts) {
7140 // The following enum mimics the values returned by GCC.
7141 // FIXME: Does GCC differ between lvalue and rvalue references here?
7142 enum gcc_type_class {
7144 void_type_class, integer_type_class, char_type_class,
7145 enumeral_type_class, boolean_type_class,
7146 pointer_type_class, reference_type_class, offset_type_class,
7147 real_type_class, complex_type_class,
7148 function_type_class, method_type_class,
7149 record_type_class, union_type_class,
7150 array_type_class, string_type_class,
7154 // If no argument was supplied, default to "no_type_class". This isn't
7155 // ideal, however it is what gcc does.
7156 if (E->getNumArgs() == 0)
7157 return no_type_class;
7159 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7160 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7162 switch (CanTy->getTypeClass()) {
7163 #define TYPE(ID, BASE)
7164 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7165 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7166 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7167 #include "clang/AST/TypeNodes.def"
7168 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7171 switch (BT->getKind()) {
7172 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7173 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7174 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7175 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7176 #include "clang/AST/BuiltinTypes.def"
7177 case BuiltinType::Void:
7178 return void_type_class;
7180 case BuiltinType::Bool:
7181 return boolean_type_class;
7183 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7184 case BuiltinType::UChar:
7185 case BuiltinType::UShort:
7186 case BuiltinType::UInt:
7187 case BuiltinType::ULong:
7188 case BuiltinType::ULongLong:
7189 case BuiltinType::UInt128:
7190 return integer_type_class;
7192 case BuiltinType::NullPtr:
7193 return pointer_type_class;
7195 case BuiltinType::WChar_U:
7196 case BuiltinType::Char16:
7197 case BuiltinType::Char32:
7198 case BuiltinType::ObjCId:
7199 case BuiltinType::ObjCClass:
7200 case BuiltinType::ObjCSel:
7201 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7202 case BuiltinType::Id:
7203 #include "clang/Basic/OpenCLImageTypes.def"
7204 case BuiltinType::OCLSampler:
7205 case BuiltinType::OCLEvent:
7206 case BuiltinType::OCLClkEvent:
7207 case BuiltinType::OCLQueue:
7208 case BuiltinType::OCLReserveID:
7209 case BuiltinType::Dependent:
7210 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7215 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7219 return pointer_type_class;
7222 case Type::MemberPointer:
7223 if (CanTy->isMemberDataPointerType())
7224 return offset_type_class;
7226 // We expect member pointers to be either data or function pointers,
7228 assert(CanTy->isMemberFunctionPointerType());
7229 return method_type_class;
7233 return complex_type_class;
7235 case Type::FunctionNoProto:
7236 case Type::FunctionProto:
7237 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7240 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7241 switch (RT->getDecl()->getTagKind()) {
7242 case TagTypeKind::TTK_Struct:
7243 case TagTypeKind::TTK_Class:
7244 case TagTypeKind::TTK_Interface:
7245 return record_type_class;
7247 case TagTypeKind::TTK_Enum:
7248 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7250 case TagTypeKind::TTK_Union:
7251 return union_type_class;
7254 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7256 case Type::ConstantArray:
7257 case Type::VariableArray:
7258 case Type::IncompleteArray:
7259 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7261 case Type::BlockPointer:
7262 case Type::LValueReference:
7263 case Type::RValueReference:
7265 case Type::ExtVector:
7267 case Type::DeducedTemplateSpecialization:
7268 case Type::ObjCObject:
7269 case Type::ObjCInterface:
7270 case Type::ObjCObjectPointer:
7273 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7276 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7279 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7280 /// __builtin_constant_p when applied to the given lvalue.
7282 /// An lvalue is only "constant" if it is a pointer or reference to the first
7283 /// character of a string literal.
7284 template<typename LValue>
7285 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7286 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7287 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7290 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7291 /// GCC as we can manage.
7292 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7293 QualType ArgType = Arg->getType();
7295 // __builtin_constant_p always has one operand. The rules which gcc follows
7296 // are not precisely documented, but are as follows:
7298 // - If the operand is of integral, floating, complex or enumeration type,
7299 // and can be folded to a known value of that type, it returns 1.
7300 // - If the operand and can be folded to a pointer to the first character
7301 // of a string literal (or such a pointer cast to an integral type), it
7304 // Otherwise, it returns 0.
7306 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7307 // its support for this does not currently work.
7308 if (ArgType->isIntegralOrEnumerationType()) {
7309 Expr::EvalResult Result;
7310 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7313 APValue &V = Result.Val;
7314 if (V.getKind() == APValue::Int)
7316 if (V.getKind() == APValue::LValue)
7317 return EvaluateBuiltinConstantPForLValue(V);
7318 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7319 return Arg->isEvaluatable(Ctx);
7320 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7322 Expr::EvalStatus Status;
7323 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7324 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7325 : EvaluatePointer(Arg, LV, Info)) &&
7326 !Status.HasSideEffects)
7327 return EvaluateBuiltinConstantPForLValue(LV);
7330 // Anything else isn't considered to be sufficiently constant.
7334 /// Retrieves the "underlying object type" of the given expression,
7335 /// as used by __builtin_object_size.
7336 static QualType getObjectType(APValue::LValueBase B) {
7337 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7338 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7339 return VD->getType();
7340 } else if (const Expr *E = B.get<const Expr*>()) {
7341 if (isa<CompoundLiteralExpr>(E))
7342 return E->getType();
7348 /// A more selective version of E->IgnoreParenCasts for
7349 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7350 /// to change the type of E.
7351 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7353 /// Always returns an RValue with a pointer representation.
7354 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7355 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7357 auto *NoParens = E->IgnoreParens();
7358 auto *Cast = dyn_cast<CastExpr>(NoParens);
7359 if (Cast == nullptr)
7362 // We only conservatively allow a few kinds of casts, because this code is
7363 // inherently a simple solution that seeks to support the common case.
7364 auto CastKind = Cast->getCastKind();
7365 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7366 CastKind != CK_AddressSpaceConversion)
7369 auto *SubExpr = Cast->getSubExpr();
7370 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7372 return ignorePointerCastsAndParens(SubExpr);
7375 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7376 /// record layout. e.g.
7377 /// struct { struct { int a, b; } fst, snd; } obj;
7383 /// obj.snd.b // yes
7385 /// Please note: this function is specialized for how __builtin_object_size
7386 /// views "objects".
7388 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7389 /// correct result, it will always return true.
7390 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7391 assert(!LVal.Designator.Invalid);
7393 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7394 const RecordDecl *Parent = FD->getParent();
7395 Invalid = Parent->isInvalidDecl();
7396 if (Invalid || Parent->isUnion())
7398 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7399 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7402 auto &Base = LVal.getLValueBase();
7403 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7404 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7406 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7408 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7409 for (auto *FD : IFD->chain()) {
7411 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7418 QualType BaseType = getType(Base);
7419 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7420 // If we don't know the array bound, conservatively assume we're looking at
7421 // the final array element.
7423 if (BaseType->isIncompleteArrayType())
7424 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7426 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7429 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7430 const auto &Entry = LVal.Designator.Entries[I];
7431 if (BaseType->isArrayType()) {
7432 // Because __builtin_object_size treats arrays as objects, we can ignore
7433 // the index iff this is the last array in the Designator.
7436 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7437 uint64_t Index = Entry.ArrayIndex;
7438 if (Index + 1 != CAT->getSize())
7440 BaseType = CAT->getElementType();
7441 } else if (BaseType->isAnyComplexType()) {
7442 const auto *CT = BaseType->castAs<ComplexType>();
7443 uint64_t Index = Entry.ArrayIndex;
7446 BaseType = CT->getElementType();
7447 } else if (auto *FD = getAsField(Entry)) {
7449 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7451 BaseType = FD->getType();
7453 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7460 /// Tests to see if the LValue has a user-specified designator (that isn't
7461 /// necessarily valid). Note that this always returns 'true' if the LValue has
7462 /// an unsized array as its first designator entry, because there's currently no
7463 /// way to tell if the user typed *foo or foo[0].
7464 static bool refersToCompleteObject(const LValue &LVal) {
7465 if (LVal.Designator.Invalid)
7468 if (!LVal.Designator.Entries.empty())
7469 return LVal.Designator.isMostDerivedAnUnsizedArray();
7471 if (!LVal.InvalidBase)
7474 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7476 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7477 return !E || !isa<MemberExpr>(E);
7480 /// Attempts to detect a user writing into a piece of memory that's impossible
7481 /// to figure out the size of by just using types.
7482 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7483 const SubobjectDesignator &Designator = LVal.Designator;
7485 // - Users can only write off of the end when we have an invalid base. Invalid
7486 // bases imply we don't know where the memory came from.
7487 // - We used to be a bit more aggressive here; we'd only be conservative if
7488 // the array at the end was flexible, or if it had 0 or 1 elements. This
7489 // broke some common standard library extensions (PR30346), but was
7490 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7491 // with some sort of whitelist. OTOH, it seems that GCC is always
7492 // conservative with the last element in structs (if it's an array), so our
7493 // current behavior is more compatible than a whitelisting approach would
7495 return LVal.InvalidBase &&
7496 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7497 Designator.MostDerivedIsArrayElement &&
7498 isDesignatorAtObjectEnd(Ctx, LVal);
7501 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7502 /// Fails if the conversion would cause loss of precision.
7503 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7504 CharUnits &Result) {
7505 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7506 if (Int.ugt(CharUnitsMax))
7508 Result = CharUnits::fromQuantity(Int.getZExtValue());
7512 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7513 /// determine how many bytes exist from the beginning of the object to either
7514 /// the end of the current subobject, or the end of the object itself, depending
7515 /// on what the LValue looks like + the value of Type.
7517 /// If this returns false, the value of Result is undefined.
7518 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7519 unsigned Type, const LValue &LVal,
7520 CharUnits &EndOffset) {
7521 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7523 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7524 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7526 return HandleSizeof(Info, ExprLoc, Ty, Result);
7529 // We want to evaluate the size of the entire object. This is a valid fallback
7530 // for when Type=1 and the designator is invalid, because we're asked for an
7532 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7533 // Type=3 wants a lower bound, so we can't fall back to this.
7534 if (Type == 3 && !DetermineForCompleteObject)
7537 llvm::APInt APEndOffset;
7538 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7539 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7540 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7542 if (LVal.InvalidBase)
7545 QualType BaseTy = getObjectType(LVal.getLValueBase());
7546 return CheckedHandleSizeof(BaseTy, EndOffset);
7549 // We want to evaluate the size of a subobject.
7550 const SubobjectDesignator &Designator = LVal.Designator;
7552 // The following is a moderately common idiom in C:
7554 // struct Foo { int a; char c[1]; };
7555 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7556 // strcpy(&F->c[0], Bar);
7558 // In order to not break too much legacy code, we need to support it.
7559 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7560 // If we can resolve this to an alloc_size call, we can hand that back,
7561 // because we know for certain how many bytes there are to write to.
7562 llvm::APInt APEndOffset;
7563 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7564 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7565 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7567 // If we cannot determine the size of the initial allocation, then we can't
7568 // given an accurate upper-bound. However, we are still able to give
7569 // conservative lower-bounds for Type=3.
7574 CharUnits BytesPerElem;
7575 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7578 // According to the GCC documentation, we want the size of the subobject
7579 // denoted by the pointer. But that's not quite right -- what we actually
7580 // want is the size of the immediately-enclosing array, if there is one.
7581 int64_t ElemsRemaining;
7582 if (Designator.MostDerivedIsArrayElement &&
7583 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7584 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7585 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7586 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7588 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7591 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7595 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7596 /// returns true and stores the result in @p Size.
7598 /// If @p WasError is non-null, this will report whether the failure to evaluate
7599 /// is to be treated as an Error in IntExprEvaluator.
7600 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7601 EvalInfo &Info, uint64_t &Size) {
7602 // Determine the denoted object.
7605 // The operand of __builtin_object_size is never evaluated for side-effects.
7606 // If there are any, but we can determine the pointed-to object anyway, then
7607 // ignore the side-effects.
7608 SpeculativeEvaluationRAII SpeculativeEval(Info);
7609 FoldOffsetRAII Fold(Info);
7611 if (E->isGLValue()) {
7612 // It's possible for us to be given GLValues if we're called via
7613 // Expr::tryEvaluateObjectSize.
7615 if (!EvaluateAsRValue(Info, E, RVal))
7617 LVal.setFrom(Info.Ctx, RVal);
7618 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7619 /*InvalidBaseOK=*/true))
7623 // If we point to before the start of the object, there are no accessible
7625 if (LVal.getLValueOffset().isNegative()) {
7630 CharUnits EndOffset;
7631 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7634 // If we've fallen outside of the end offset, just pretend there's nothing to
7635 // write to/read from.
7636 if (EndOffset <= LVal.getLValueOffset())
7639 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7643 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7644 if (unsigned BuiltinOp = E->getBuiltinCallee())
7645 return VisitBuiltinCallExpr(E, BuiltinOp);
7647 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7650 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7651 unsigned BuiltinOp) {
7652 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7654 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7656 case Builtin::BI__builtin_object_size: {
7657 // The type was checked when we built the expression.
7659 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7660 assert(Type <= 3 && "unexpected type");
7663 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7664 return Success(Size, E);
7666 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7667 return Success((Type & 2) ? 0 : -1, E);
7669 // Expression had no side effects, but we couldn't statically determine the
7670 // size of the referenced object.
7671 switch (Info.EvalMode) {
7672 case EvalInfo::EM_ConstantExpression:
7673 case EvalInfo::EM_PotentialConstantExpression:
7674 case EvalInfo::EM_ConstantFold:
7675 case EvalInfo::EM_EvaluateForOverflow:
7676 case EvalInfo::EM_IgnoreSideEffects:
7677 case EvalInfo::EM_OffsetFold:
7678 // Leave it to IR generation.
7680 case EvalInfo::EM_ConstantExpressionUnevaluated:
7681 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7682 // Reduce it to a constant now.
7683 return Success((Type & 2) ? 0 : -1, E);
7686 llvm_unreachable("unexpected EvalMode");
7689 case Builtin::BI__builtin_bswap16:
7690 case Builtin::BI__builtin_bswap32:
7691 case Builtin::BI__builtin_bswap64: {
7693 if (!EvaluateInteger(E->getArg(0), Val, Info))
7696 return Success(Val.byteSwap(), E);
7699 case Builtin::BI__builtin_classify_type:
7700 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7702 // FIXME: BI__builtin_clrsb
7703 // FIXME: BI__builtin_clrsbl
7704 // FIXME: BI__builtin_clrsbll
7706 case Builtin::BI__builtin_clz:
7707 case Builtin::BI__builtin_clzl:
7708 case Builtin::BI__builtin_clzll:
7709 case Builtin::BI__builtin_clzs: {
7711 if (!EvaluateInteger(E->getArg(0), Val, Info))
7716 return Success(Val.countLeadingZeros(), E);
7719 case Builtin::BI__builtin_constant_p:
7720 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7722 case Builtin::BI__builtin_ctz:
7723 case Builtin::BI__builtin_ctzl:
7724 case Builtin::BI__builtin_ctzll:
7725 case Builtin::BI__builtin_ctzs: {
7727 if (!EvaluateInteger(E->getArg(0), Val, Info))
7732 return Success(Val.countTrailingZeros(), E);
7735 case Builtin::BI__builtin_eh_return_data_regno: {
7736 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7737 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7738 return Success(Operand, E);
7741 case Builtin::BI__builtin_expect:
7742 return Visit(E->getArg(0));
7744 case Builtin::BI__builtin_ffs:
7745 case Builtin::BI__builtin_ffsl:
7746 case Builtin::BI__builtin_ffsll: {
7748 if (!EvaluateInteger(E->getArg(0), Val, Info))
7751 unsigned N = Val.countTrailingZeros();
7752 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7755 case Builtin::BI__builtin_fpclassify: {
7757 if (!EvaluateFloat(E->getArg(5), Val, Info))
7760 switch (Val.getCategory()) {
7761 case APFloat::fcNaN: Arg = 0; break;
7762 case APFloat::fcInfinity: Arg = 1; break;
7763 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7764 case APFloat::fcZero: Arg = 4; break;
7766 return Visit(E->getArg(Arg));
7769 case Builtin::BI__builtin_isinf_sign: {
7771 return EvaluateFloat(E->getArg(0), Val, Info) &&
7772 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7775 case Builtin::BI__builtin_isinf: {
7777 return EvaluateFloat(E->getArg(0), Val, Info) &&
7778 Success(Val.isInfinity() ? 1 : 0, E);
7781 case Builtin::BI__builtin_isfinite: {
7783 return EvaluateFloat(E->getArg(0), Val, Info) &&
7784 Success(Val.isFinite() ? 1 : 0, E);
7787 case Builtin::BI__builtin_isnan: {
7789 return EvaluateFloat(E->getArg(0), Val, Info) &&
7790 Success(Val.isNaN() ? 1 : 0, E);
7793 case Builtin::BI__builtin_isnormal: {
7795 return EvaluateFloat(E->getArg(0), Val, Info) &&
7796 Success(Val.isNormal() ? 1 : 0, E);
7799 case Builtin::BI__builtin_parity:
7800 case Builtin::BI__builtin_parityl:
7801 case Builtin::BI__builtin_parityll: {
7803 if (!EvaluateInteger(E->getArg(0), Val, Info))
7806 return Success(Val.countPopulation() % 2, E);
7809 case Builtin::BI__builtin_popcount:
7810 case Builtin::BI__builtin_popcountl:
7811 case Builtin::BI__builtin_popcountll: {
7813 if (!EvaluateInteger(E->getArg(0), Val, Info))
7816 return Success(Val.countPopulation(), E);
7819 case Builtin::BIstrlen:
7820 case Builtin::BIwcslen:
7821 // A call to strlen is not a constant expression.
7822 if (Info.getLangOpts().CPlusPlus11)
7823 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7824 << /*isConstexpr*/0 << /*isConstructor*/0
7825 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7827 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7829 case Builtin::BI__builtin_strlen:
7830 case Builtin::BI__builtin_wcslen: {
7831 // As an extension, we support __builtin_strlen() as a constant expression,
7832 // and support folding strlen() to a constant.
7834 if (!EvaluatePointer(E->getArg(0), String, Info))
7837 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7839 // Fast path: if it's a string literal, search the string value.
7840 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7841 String.getLValueBase().dyn_cast<const Expr *>())) {
7842 // The string literal may have embedded null characters. Find the first
7843 // one and truncate there.
7844 StringRef Str = S->getBytes();
7845 int64_t Off = String.Offset.getQuantity();
7846 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7847 S->getCharByteWidth() == 1 &&
7848 // FIXME: Add fast-path for wchar_t too.
7849 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7850 Str = Str.substr(Off);
7852 StringRef::size_type Pos = Str.find(0);
7853 if (Pos != StringRef::npos)
7854 Str = Str.substr(0, Pos);
7856 return Success(Str.size(), E);
7859 // Fall through to slow path to issue appropriate diagnostic.
7862 // Slow path: scan the bytes of the string looking for the terminating 0.
7863 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7865 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7869 return Success(Strlen, E);
7870 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7875 case Builtin::BIstrcmp:
7876 case Builtin::BIwcscmp:
7877 case Builtin::BIstrncmp:
7878 case Builtin::BIwcsncmp:
7879 case Builtin::BImemcmp:
7880 case Builtin::BIwmemcmp:
7881 // A call to strlen is not a constant expression.
7882 if (Info.getLangOpts().CPlusPlus11)
7883 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7884 << /*isConstexpr*/0 << /*isConstructor*/0
7885 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7887 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7889 case Builtin::BI__builtin_strcmp:
7890 case Builtin::BI__builtin_wcscmp:
7891 case Builtin::BI__builtin_strncmp:
7892 case Builtin::BI__builtin_wcsncmp:
7893 case Builtin::BI__builtin_memcmp:
7894 case Builtin::BI__builtin_wmemcmp: {
7895 LValue String1, String2;
7896 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7897 !EvaluatePointer(E->getArg(1), String2, Info))
7900 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7902 uint64_t MaxLength = uint64_t(-1);
7903 if (BuiltinOp != Builtin::BIstrcmp &&
7904 BuiltinOp != Builtin::BIwcscmp &&
7905 BuiltinOp != Builtin::BI__builtin_strcmp &&
7906 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7908 if (!EvaluateInteger(E->getArg(2), N, Info))
7910 MaxLength = N.getExtValue();
7912 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7913 BuiltinOp != Builtin::BIwmemcmp &&
7914 BuiltinOp != Builtin::BI__builtin_memcmp &&
7915 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7916 for (; MaxLength; --MaxLength) {
7917 APValue Char1, Char2;
7918 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7919 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7920 !Char1.isInt() || !Char2.isInt())
7922 if (Char1.getInt() != Char2.getInt())
7923 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7924 if (StopAtNull && !Char1.getInt())
7925 return Success(0, E);
7926 assert(!(StopAtNull && !Char2.getInt()));
7927 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7928 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7931 // We hit the strncmp / memcmp limit.
7932 return Success(0, E);
7935 case Builtin::BI__atomic_always_lock_free:
7936 case Builtin::BI__atomic_is_lock_free:
7937 case Builtin::BI__c11_atomic_is_lock_free: {
7939 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7942 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7943 // of two less than the maximum inline atomic width, we know it is
7944 // lock-free. If the size isn't a power of two, or greater than the
7945 // maximum alignment where we promote atomics, we know it is not lock-free
7946 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7947 // the answer can only be determined at runtime; for example, 16-byte
7948 // atomics have lock-free implementations on some, but not all,
7949 // x86-64 processors.
7951 // Check power-of-two.
7952 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7953 if (Size.isPowerOfTwo()) {
7954 // Check against inlining width.
7955 unsigned InlineWidthBits =
7956 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7957 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7958 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7959 Size == CharUnits::One() ||
7960 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7961 Expr::NPC_NeverValueDependent))
7962 // OK, we will inline appropriately-aligned operations of this size,
7963 // and _Atomic(T) is appropriately-aligned.
7964 return Success(1, E);
7966 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7967 castAs<PointerType>()->getPointeeType();
7968 if (!PointeeType->isIncompleteType() &&
7969 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7970 // OK, we will inline operations on this object.
7971 return Success(1, E);
7976 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7977 Success(0, E) : Error(E);
7979 case Builtin::BIomp_is_initial_device:
7980 // We can decide statically which value the runtime would return if called.
7981 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
7985 static bool HasSameBase(const LValue &A, const LValue &B) {
7986 if (!A.getLValueBase())
7987 return !B.getLValueBase();
7988 if (!B.getLValueBase())
7991 if (A.getLValueBase().getOpaqueValue() !=
7992 B.getLValueBase().getOpaqueValue()) {
7993 const Decl *ADecl = GetLValueBaseDecl(A);
7996 const Decl *BDecl = GetLValueBaseDecl(B);
7997 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
8001 return IsGlobalLValue(A.getLValueBase()) ||
8002 A.getLValueCallIndex() == B.getLValueCallIndex();
8005 /// \brief Determine whether this is a pointer past the end of the complete
8006 /// object referred to by the lvalue.
8007 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8009 // A null pointer can be viewed as being "past the end" but we don't
8010 // choose to look at it that way here.
8011 if (!LV.getLValueBase())
8014 // If the designator is valid and refers to a subobject, we're not pointing
8016 if (!LV.getLValueDesignator().Invalid &&
8017 !LV.getLValueDesignator().isOnePastTheEnd())
8020 // A pointer to an incomplete type might be past-the-end if the type's size is
8021 // zero. We cannot tell because the type is incomplete.
8022 QualType Ty = getType(LV.getLValueBase());
8023 if (Ty->isIncompleteType())
8026 // We're a past-the-end pointer if we point to the byte after the object,
8027 // no matter what our type or path is.
8028 auto Size = Ctx.getTypeSizeInChars(Ty);
8029 return LV.getLValueOffset() == Size;
8034 /// \brief Data recursive integer evaluator of certain binary operators.
8036 /// We use a data recursive algorithm for binary operators so that we are able
8037 /// to handle extreme cases of chained binary operators without causing stack
8039 class DataRecursiveIntBinOpEvaluator {
8044 EvalResult() : Failed(false) { }
8046 void swap(EvalResult &RHS) {
8048 Failed = RHS.Failed;
8055 EvalResult LHSResult; // meaningful only for binary operator expression.
8056 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8059 Job(Job &&) = default;
8061 void startSpeculativeEval(EvalInfo &Info) {
8062 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8066 SpeculativeEvaluationRAII SpecEvalRAII;
8069 SmallVector<Job, 16> Queue;
8071 IntExprEvaluator &IntEval;
8073 APValue &FinalResult;
8076 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8077 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8079 /// \brief True if \param E is a binary operator that we are going to handle
8080 /// data recursively.
8081 /// We handle binary operators that are comma, logical, or that have operands
8082 /// with integral or enumeration type.
8083 static bool shouldEnqueue(const BinaryOperator *E) {
8084 return E->getOpcode() == BO_Comma ||
8087 E->getType()->isIntegralOrEnumerationType() &&
8088 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8089 E->getRHS()->getType()->isIntegralOrEnumerationType());
8092 bool Traverse(const BinaryOperator *E) {
8094 EvalResult PrevResult;
8095 while (!Queue.empty())
8096 process(PrevResult);
8098 if (PrevResult.Failed) return false;
8100 FinalResult.swap(PrevResult.Val);
8105 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8106 return IntEval.Success(Value, E, Result);
8108 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8109 return IntEval.Success(Value, E, Result);
8111 bool Error(const Expr *E) {
8112 return IntEval.Error(E);
8114 bool Error(const Expr *E, diag::kind D) {
8115 return IntEval.Error(E, D);
8118 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8119 return Info.CCEDiag(E, D);
8122 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8123 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8124 bool &SuppressRHSDiags);
8126 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8127 const BinaryOperator *E, APValue &Result);
8129 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8130 Result.Failed = !Evaluate(Result.Val, Info, E);
8132 Result.Val = APValue();
8135 void process(EvalResult &Result);
8137 void enqueue(const Expr *E) {
8138 E = E->IgnoreParens();
8139 Queue.resize(Queue.size()+1);
8141 Queue.back().Kind = Job::AnyExprKind;
8147 bool DataRecursiveIntBinOpEvaluator::
8148 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8149 bool &SuppressRHSDiags) {
8150 if (E->getOpcode() == BO_Comma) {
8151 // Ignore LHS but note if we could not evaluate it.
8152 if (LHSResult.Failed)
8153 return Info.noteSideEffect();
8157 if (E->isLogicalOp()) {
8159 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8160 // We were able to evaluate the LHS, see if we can get away with not
8161 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8162 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8163 Success(LHSAsBool, E, LHSResult.Val);
8164 return false; // Ignore RHS
8167 LHSResult.Failed = true;
8169 // Since we weren't able to evaluate the left hand side, it
8170 // might have had side effects.
8171 if (!Info.noteSideEffect())
8174 // We can't evaluate the LHS; however, sometimes the result
8175 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8176 // Don't ignore RHS and suppress diagnostics from this arm.
8177 SuppressRHSDiags = true;
8183 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8184 E->getRHS()->getType()->isIntegralOrEnumerationType());
8186 if (LHSResult.Failed && !Info.noteFailure())
8187 return false; // Ignore RHS;
8192 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8194 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8195 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8197 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8198 CharUnits &Offset = LVal.getLValueOffset();
8199 uint64_t Offset64 = Offset.getQuantity();
8200 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8201 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8202 : Offset64 + Index64);
8205 bool DataRecursiveIntBinOpEvaluator::
8206 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8207 const BinaryOperator *E, APValue &Result) {
8208 if (E->getOpcode() == BO_Comma) {
8209 if (RHSResult.Failed)
8211 Result = RHSResult.Val;
8215 if (E->isLogicalOp()) {
8216 bool lhsResult, rhsResult;
8217 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8218 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8222 if (E->getOpcode() == BO_LOr)
8223 return Success(lhsResult || rhsResult, E, Result);
8225 return Success(lhsResult && rhsResult, E, Result);
8229 // We can't evaluate the LHS; however, sometimes the result
8230 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8231 if (rhsResult == (E->getOpcode() == BO_LOr))
8232 return Success(rhsResult, E, Result);
8239 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8240 E->getRHS()->getType()->isIntegralOrEnumerationType());
8242 if (LHSResult.Failed || RHSResult.Failed)
8245 const APValue &LHSVal = LHSResult.Val;
8246 const APValue &RHSVal = RHSResult.Val;
8248 // Handle cases like (unsigned long)&a + 4.
8249 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8251 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8255 // Handle cases like 4 + (unsigned long)&a
8256 if (E->getOpcode() == BO_Add &&
8257 RHSVal.isLValue() && LHSVal.isInt()) {
8259 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8263 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8264 // Handle (intptr_t)&&A - (intptr_t)&&B.
8265 if (!LHSVal.getLValueOffset().isZero() ||
8266 !RHSVal.getLValueOffset().isZero())
8268 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8269 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8270 if (!LHSExpr || !RHSExpr)
8272 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8273 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8274 if (!LHSAddrExpr || !RHSAddrExpr)
8276 // Make sure both labels come from the same function.
8277 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8278 RHSAddrExpr->getLabel()->getDeclContext())
8280 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8284 // All the remaining cases expect both operands to be an integer
8285 if (!LHSVal.isInt() || !RHSVal.isInt())
8288 // Set up the width and signedness manually, in case it can't be deduced
8289 // from the operation we're performing.
8290 // FIXME: Don't do this in the cases where we can deduce it.
8291 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8292 E->getType()->isUnsignedIntegerOrEnumerationType());
8293 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8294 RHSVal.getInt(), Value))
8296 return Success(Value, E, Result);
8299 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8300 Job &job = Queue.back();
8303 case Job::AnyExprKind: {
8304 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8305 if (shouldEnqueue(Bop)) {
8306 job.Kind = Job::BinOpKind;
8307 enqueue(Bop->getLHS());
8312 EvaluateExpr(job.E, Result);
8317 case Job::BinOpKind: {
8318 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8319 bool SuppressRHSDiags = false;
8320 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8324 if (SuppressRHSDiags)
8325 job.startSpeculativeEval(Info);
8326 job.LHSResult.swap(Result);
8327 job.Kind = Job::BinOpVisitedLHSKind;
8328 enqueue(Bop->getRHS());
8332 case Job::BinOpVisitedLHSKind: {
8333 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8336 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8342 llvm_unreachable("Invalid Job::Kind!");
8346 /// Used when we determine that we should fail, but can keep evaluating prior to
8347 /// noting that we had a failure.
8348 class DelayedNoteFailureRAII {
8353 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8354 : Info(Info), NoteFailure(NoteFailure) {}
8355 ~DelayedNoteFailureRAII() {
8357 bool ContinueAfterFailure = Info.noteFailure();
8358 (void)ContinueAfterFailure;
8359 assert(ContinueAfterFailure &&
8360 "Shouldn't have kept evaluating on failure.");
8366 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8367 // We don't call noteFailure immediately because the assignment happens after
8368 // we evaluate LHS and RHS.
8369 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8372 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8373 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8374 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8376 QualType LHSTy = E->getLHS()->getType();
8377 QualType RHSTy = E->getRHS()->getType();
8379 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8380 ComplexValue LHS, RHS;
8382 if (E->isAssignmentOp()) {
8384 EvaluateLValue(E->getLHS(), LV, Info);
8386 } else if (LHSTy->isRealFloatingType()) {
8387 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8389 LHS.makeComplexFloat();
8390 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8393 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8395 if (!LHSOK && !Info.noteFailure())
8398 if (E->getRHS()->getType()->isRealFloatingType()) {
8399 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8401 RHS.makeComplexFloat();
8402 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8403 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8406 if (LHS.isComplexFloat()) {
8407 APFloat::cmpResult CR_r =
8408 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8409 APFloat::cmpResult CR_i =
8410 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8412 if (E->getOpcode() == BO_EQ)
8413 return Success((CR_r == APFloat::cmpEqual &&
8414 CR_i == APFloat::cmpEqual), E);
8416 assert(E->getOpcode() == BO_NE &&
8417 "Invalid complex comparison.");
8418 return Success(((CR_r == APFloat::cmpGreaterThan ||
8419 CR_r == APFloat::cmpLessThan ||
8420 CR_r == APFloat::cmpUnordered) ||
8421 (CR_i == APFloat::cmpGreaterThan ||
8422 CR_i == APFloat::cmpLessThan ||
8423 CR_i == APFloat::cmpUnordered)), E);
8426 if (E->getOpcode() == BO_EQ)
8427 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8428 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8430 assert(E->getOpcode() == BO_NE &&
8431 "Invalid compex comparison.");
8432 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8433 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8438 if (LHSTy->isRealFloatingType() &&
8439 RHSTy->isRealFloatingType()) {
8440 APFloat RHS(0.0), LHS(0.0);
8442 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8443 if (!LHSOK && !Info.noteFailure())
8446 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8449 APFloat::cmpResult CR = LHS.compare(RHS);
8451 switch (E->getOpcode()) {
8453 llvm_unreachable("Invalid binary operator!");
8455 return Success(CR == APFloat::cmpLessThan, E);
8457 return Success(CR == APFloat::cmpGreaterThan, E);
8459 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8461 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8464 return Success(CR == APFloat::cmpEqual, E);
8466 return Success(CR == APFloat::cmpGreaterThan
8467 || CR == APFloat::cmpLessThan
8468 || CR == APFloat::cmpUnordered, E);
8472 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8473 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8474 LValue LHSValue, RHSValue;
8476 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8477 if (!LHSOK && !Info.noteFailure())
8480 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8483 // Reject differing bases from the normal codepath; we special-case
8484 // comparisons to null.
8485 if (!HasSameBase(LHSValue, RHSValue)) {
8486 if (E->getOpcode() == BO_Sub) {
8487 // Handle &&A - &&B.
8488 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8490 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8491 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8492 if (!LHSExpr || !RHSExpr)
8494 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8495 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8496 if (!LHSAddrExpr || !RHSAddrExpr)
8498 // Make sure both labels come from the same function.
8499 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8500 RHSAddrExpr->getLabel()->getDeclContext())
8502 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8504 // Inequalities and subtractions between unrelated pointers have
8505 // unspecified or undefined behavior.
8506 if (!E->isEqualityOp())
8508 // A constant address may compare equal to the address of a symbol.
8509 // The one exception is that address of an object cannot compare equal
8510 // to a null pointer constant.
8511 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8512 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8514 // It's implementation-defined whether distinct literals will have
8515 // distinct addresses. In clang, the result of such a comparison is
8516 // unspecified, so it is not a constant expression. However, we do know
8517 // that the address of a literal will be non-null.
8518 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8519 LHSValue.Base && RHSValue.Base)
8521 // We can't tell whether weak symbols will end up pointing to the same
8523 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8525 // We can't compare the address of the start of one object with the
8526 // past-the-end address of another object, per C++ DR1652.
8527 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8528 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8529 (RHSValue.Base && RHSValue.Offset.isZero() &&
8530 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8532 // We can't tell whether an object is at the same address as another
8533 // zero sized object.
8534 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8535 (LHSValue.Base && isZeroSized(RHSValue)))
8537 // Pointers with different bases cannot represent the same object.
8538 // (Note that clang defaults to -fmerge-all-constants, which can
8539 // lead to inconsistent results for comparisons involving the address
8540 // of a constant; this generally doesn't matter in practice.)
8541 return Success(E->getOpcode() == BO_NE, E);
8544 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8545 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8547 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8548 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8550 if (E->getOpcode() == BO_Sub) {
8551 // C++11 [expr.add]p6:
8552 // Unless both pointers point to elements of the same array object, or
8553 // one past the last element of the array object, the behavior is
8555 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8556 !AreElementsOfSameArray(getType(LHSValue.Base),
8557 LHSDesignator, RHSDesignator))
8558 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8560 QualType Type = E->getLHS()->getType();
8561 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8563 CharUnits ElementSize;
8564 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8567 // As an extension, a type may have zero size (empty struct or union in
8568 // C, array of zero length). Pointer subtraction in such cases has
8569 // undefined behavior, so is not constant.
8570 if (ElementSize.isZero()) {
8571 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8576 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8577 // and produce incorrect results when it overflows. Such behavior
8578 // appears to be non-conforming, but is common, so perhaps we should
8579 // assume the standard intended for such cases to be undefined behavior
8580 // and check for them.
8582 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8583 // overflow in the final conversion to ptrdiff_t.
8585 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8587 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8589 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8590 APSInt TrueResult = (LHS - RHS) / ElemSize;
8591 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8593 if (Result.extend(65) != TrueResult &&
8594 !HandleOverflow(Info, E, TrueResult, E->getType()))
8596 return Success(Result, E);
8599 // C++11 [expr.rel]p3:
8600 // Pointers to void (after pointer conversions) can be compared, with a
8601 // result defined as follows: If both pointers represent the same
8602 // address or are both the null pointer value, the result is true if the
8603 // operator is <= or >= and false otherwise; otherwise the result is
8605 // We interpret this as applying to pointers to *cv* void.
8606 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8607 E->isRelationalOp())
8608 CCEDiag(E, diag::note_constexpr_void_comparison);
8610 // C++11 [expr.rel]p2:
8611 // - If two pointers point to non-static data members of the same object,
8612 // or to subobjects or array elements fo such members, recursively, the
8613 // pointer to the later declared member compares greater provided the
8614 // two members have the same access control and provided their class is
8617 // - Otherwise pointer comparisons are unspecified.
8618 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8619 E->isRelationalOp()) {
8622 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8623 RHSDesignator, WasArrayIndex);
8624 // At the point where the designators diverge, the comparison has a
8625 // specified value if:
8626 // - we are comparing array indices
8627 // - we are comparing fields of a union, or fields with the same access
8628 // Otherwise, the result is unspecified and thus the comparison is not a
8629 // constant expression.
8630 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8631 Mismatch < RHSDesignator.Entries.size()) {
8632 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8633 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8635 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8637 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8638 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8639 << RF->getParent() << RF;
8641 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8642 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8643 << LF->getParent() << LF;
8644 else if (!LF->getParent()->isUnion() &&
8645 LF->getAccess() != RF->getAccess())
8646 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8647 << LF << LF->getAccess() << RF << RF->getAccess()
8652 // The comparison here must be unsigned, and performed with the same
8653 // width as the pointer.
8654 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8655 uint64_t CompareLHS = LHSOffset.getQuantity();
8656 uint64_t CompareRHS = RHSOffset.getQuantity();
8657 assert(PtrSize <= 64 && "Unexpected pointer width");
8658 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8662 // If there is a base and this is a relational operator, we can only
8663 // compare pointers within the object in question; otherwise, the result
8664 // depends on where the object is located in memory.
8665 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8666 QualType BaseTy = getType(LHSValue.Base);
8667 if (BaseTy->isIncompleteType())
8669 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8670 uint64_t OffsetLimit = Size.getQuantity();
8671 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8675 switch (E->getOpcode()) {
8676 default: llvm_unreachable("missing comparison operator");
8677 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8678 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8679 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8680 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8681 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8682 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8687 if (LHSTy->isMemberPointerType()) {
8688 assert(E->isEqualityOp() && "unexpected member pointer operation");
8689 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8691 MemberPtr LHSValue, RHSValue;
8693 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8694 if (!LHSOK && !Info.noteFailure())
8697 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8700 // C++11 [expr.eq]p2:
8701 // If both operands are null, they compare equal. Otherwise if only one is
8702 // null, they compare unequal.
8703 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8704 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8705 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8708 // Otherwise if either is a pointer to a virtual member function, the
8709 // result is unspecified.
8710 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8711 if (MD->isVirtual())
8712 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8713 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8714 if (MD->isVirtual())
8715 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8717 // Otherwise they compare equal if and only if they would refer to the
8718 // same member of the same most derived object or the same subobject if
8719 // they were dereferenced with a hypothetical object of the associated
8721 bool Equal = LHSValue == RHSValue;
8722 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8725 if (LHSTy->isNullPtrType()) {
8726 assert(E->isComparisonOp() && "unexpected nullptr operation");
8727 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8728 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8729 // are compared, the result is true of the operator is <=, >= or ==, and
8731 BinaryOperator::Opcode Opcode = E->getOpcode();
8732 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8735 assert((!LHSTy->isIntegralOrEnumerationType() ||
8736 !RHSTy->isIntegralOrEnumerationType()) &&
8737 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8738 // We can't continue from here for non-integral types.
8739 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8742 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8743 /// a result as the expression's type.
8744 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8745 const UnaryExprOrTypeTraitExpr *E) {
8746 switch(E->getKind()) {
8747 case UETT_AlignOf: {
8748 if (E->isArgumentType())
8749 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8751 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8754 case UETT_VecStep: {
8755 QualType Ty = E->getTypeOfArgument();
8757 if (Ty->isVectorType()) {
8758 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8760 // The vec_step built-in functions that take a 3-component
8761 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8765 return Success(n, E);
8767 return Success(1, E);
8771 QualType SrcTy = E->getTypeOfArgument();
8772 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8773 // the result is the size of the referenced type."
8774 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8775 SrcTy = Ref->getPointeeType();
8778 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8780 return Success(Sizeof, E);
8782 case UETT_OpenMPRequiredSimdAlign:
8783 assert(E->isArgumentType());
8785 Info.Ctx.toCharUnitsFromBits(
8786 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8791 llvm_unreachable("unknown expr/type trait");
8794 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8796 unsigned n = OOE->getNumComponents();
8799 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8800 for (unsigned i = 0; i != n; ++i) {
8801 OffsetOfNode ON = OOE->getComponent(i);
8802 switch (ON.getKind()) {
8803 case OffsetOfNode::Array: {
8804 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8806 if (!EvaluateInteger(Idx, IdxResult, Info))
8808 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8811 CurrentType = AT->getElementType();
8812 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8813 Result += IdxResult.getSExtValue() * ElementSize;
8817 case OffsetOfNode::Field: {
8818 FieldDecl *MemberDecl = ON.getField();
8819 const RecordType *RT = CurrentType->getAs<RecordType>();
8822 RecordDecl *RD = RT->getDecl();
8823 if (RD->isInvalidDecl()) return false;
8824 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8825 unsigned i = MemberDecl->getFieldIndex();
8826 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8827 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8828 CurrentType = MemberDecl->getType().getNonReferenceType();
8832 case OffsetOfNode::Identifier:
8833 llvm_unreachable("dependent __builtin_offsetof");
8835 case OffsetOfNode::Base: {
8836 CXXBaseSpecifier *BaseSpec = ON.getBase();
8837 if (BaseSpec->isVirtual())
8840 // Find the layout of the class whose base we are looking into.
8841 const RecordType *RT = CurrentType->getAs<RecordType>();
8844 RecordDecl *RD = RT->getDecl();
8845 if (RD->isInvalidDecl()) return false;
8846 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8848 // Find the base class itself.
8849 CurrentType = BaseSpec->getType();
8850 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8854 // Add the offset to the base.
8855 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8860 return Success(Result, OOE);
8863 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8864 switch (E->getOpcode()) {
8866 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8870 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8871 // If so, we could clear the diagnostic ID.
8872 return Visit(E->getSubExpr());
8874 // The result is just the value.
8875 return Visit(E->getSubExpr());
8877 if (!Visit(E->getSubExpr()))
8879 if (!Result.isInt()) return Error(E);
8880 const APSInt &Value = Result.getInt();
8881 if (Value.isSigned() && Value.isMinSignedValue() &&
8882 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8885 return Success(-Value, E);
8888 if (!Visit(E->getSubExpr()))
8890 if (!Result.isInt()) return Error(E);
8891 return Success(~Result.getInt(), E);
8895 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8897 return Success(!bres, E);
8902 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8903 /// result type is integer.
8904 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8905 const Expr *SubExpr = E->getSubExpr();
8906 QualType DestType = E->getType();
8907 QualType SrcType = SubExpr->getType();
8909 switch (E->getCastKind()) {
8910 case CK_BaseToDerived:
8911 case CK_DerivedToBase:
8912 case CK_UncheckedDerivedToBase:
8915 case CK_ArrayToPointerDecay:
8916 case CK_FunctionToPointerDecay:
8917 case CK_NullToPointer:
8918 case CK_NullToMemberPointer:
8919 case CK_BaseToDerivedMemberPointer:
8920 case CK_DerivedToBaseMemberPointer:
8921 case CK_ReinterpretMemberPointer:
8922 case CK_ConstructorConversion:
8923 case CK_IntegralToPointer:
8925 case CK_VectorSplat:
8926 case CK_IntegralToFloating:
8927 case CK_FloatingCast:
8928 case CK_CPointerToObjCPointerCast:
8929 case CK_BlockPointerToObjCPointerCast:
8930 case CK_AnyPointerToBlockPointerCast:
8931 case CK_ObjCObjectLValueCast:
8932 case CK_FloatingRealToComplex:
8933 case CK_FloatingComplexToReal:
8934 case CK_FloatingComplexCast:
8935 case CK_FloatingComplexToIntegralComplex:
8936 case CK_IntegralRealToComplex:
8937 case CK_IntegralComplexCast:
8938 case CK_IntegralComplexToFloatingComplex:
8939 case CK_BuiltinFnToFnPtr:
8940 case CK_ZeroToOCLEvent:
8941 case CK_ZeroToOCLQueue:
8942 case CK_NonAtomicToAtomic:
8943 case CK_AddressSpaceConversion:
8944 case CK_IntToOCLSampler:
8945 llvm_unreachable("invalid cast kind for integral value");
8949 case CK_LValueBitCast:
8950 case CK_ARCProduceObject:
8951 case CK_ARCConsumeObject:
8952 case CK_ARCReclaimReturnedObject:
8953 case CK_ARCExtendBlockObject:
8954 case CK_CopyAndAutoreleaseBlockObject:
8957 case CK_UserDefinedConversion:
8958 case CK_LValueToRValue:
8959 case CK_AtomicToNonAtomic:
8961 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8963 case CK_MemberPointerToBoolean:
8964 case CK_PointerToBoolean:
8965 case CK_IntegralToBoolean:
8966 case CK_FloatingToBoolean:
8967 case CK_BooleanToSignedIntegral:
8968 case CK_FloatingComplexToBoolean:
8969 case CK_IntegralComplexToBoolean: {
8971 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8973 uint64_t IntResult = BoolResult;
8974 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8975 IntResult = (uint64_t)-1;
8976 return Success(IntResult, E);
8979 case CK_IntegralCast: {
8980 if (!Visit(SubExpr))
8983 if (!Result.isInt()) {
8984 // Allow casts of address-of-label differences if they are no-ops
8985 // or narrowing. (The narrowing case isn't actually guaranteed to
8986 // be constant-evaluatable except in some narrow cases which are hard
8987 // to detect here. We let it through on the assumption the user knows
8988 // what they are doing.)
8989 if (Result.isAddrLabelDiff())
8990 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8991 // Only allow casts of lvalues if they are lossless.
8992 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8995 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8996 Result.getInt()), E);
8999 case CK_PointerToIntegral: {
9000 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9003 if (!EvaluatePointer(SubExpr, LV, Info))
9006 if (LV.getLValueBase()) {
9007 // Only allow based lvalue casts if they are lossless.
9008 // FIXME: Allow a larger integer size than the pointer size, and allow
9009 // narrowing back down to pointer width in subsequent integral casts.
9010 // FIXME: Check integer type's active bits, not its type size.
9011 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9014 LV.Designator.setInvalid();
9015 LV.moveInto(Result);
9020 if (LV.isNullPointer())
9021 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9023 V = LV.getLValueOffset().getQuantity();
9025 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9026 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9029 case CK_IntegralComplexToReal: {
9031 if (!EvaluateComplex(SubExpr, C, Info))
9033 return Success(C.getComplexIntReal(), E);
9036 case CK_FloatingToIntegral: {
9038 if (!EvaluateFloat(SubExpr, F, Info))
9042 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9044 return Success(Value, E);
9048 llvm_unreachable("unknown cast resulting in integral value");
9051 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9052 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9054 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9056 if (!LV.isComplexInt())
9058 return Success(LV.getComplexIntReal(), E);
9061 return Visit(E->getSubExpr());
9064 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9065 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9067 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9069 if (!LV.isComplexInt())
9071 return Success(LV.getComplexIntImag(), E);
9074 VisitIgnoredValue(E->getSubExpr());
9075 return Success(0, E);
9078 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9079 return Success(E->getPackLength(), E);
9082 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9083 return Success(E->getValue(), E);
9086 //===----------------------------------------------------------------------===//
9088 //===----------------------------------------------------------------------===//
9091 class FloatExprEvaluator
9092 : public ExprEvaluatorBase<FloatExprEvaluator> {
9095 FloatExprEvaluator(EvalInfo &info, APFloat &result)
9096 : ExprEvaluatorBaseTy(info), Result(result) {}
9098 bool Success(const APValue &V, const Expr *e) {
9099 Result = V.getFloat();
9103 bool ZeroInitialization(const Expr *E) {
9104 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9108 bool VisitCallExpr(const CallExpr *E);
9110 bool VisitUnaryOperator(const UnaryOperator *E);
9111 bool VisitBinaryOperator(const BinaryOperator *E);
9112 bool VisitFloatingLiteral(const FloatingLiteral *E);
9113 bool VisitCastExpr(const CastExpr *E);
9115 bool VisitUnaryReal(const UnaryOperator *E);
9116 bool VisitUnaryImag(const UnaryOperator *E);
9118 // FIXME: Missing: array subscript of vector, member of vector
9120 } // end anonymous namespace
9122 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9123 assert(E->isRValue() && E->getType()->isRealFloatingType());
9124 return FloatExprEvaluator(Info, Result).Visit(E);
9127 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9131 llvm::APFloat &Result) {
9132 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9133 if (!S) return false;
9135 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9139 // Treat empty strings as if they were zero.
9140 if (S->getString().empty())
9141 fill = llvm::APInt(32, 0);
9142 else if (S->getString().getAsInteger(0, fill))
9145 if (Context.getTargetInfo().isNan2008()) {
9147 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9149 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9151 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9152 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9153 // a different encoding to what became a standard in 2008, and for pre-
9154 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9155 // sNaN. This is now known as "legacy NaN" encoding.
9157 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9159 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9165 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9166 switch (E->getBuiltinCallee()) {
9168 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9170 case Builtin::BI__builtin_huge_val:
9171 case Builtin::BI__builtin_huge_valf:
9172 case Builtin::BI__builtin_huge_vall:
9173 case Builtin::BI__builtin_inf:
9174 case Builtin::BI__builtin_inff:
9175 case Builtin::BI__builtin_infl: {
9176 const llvm::fltSemantics &Sem =
9177 Info.Ctx.getFloatTypeSemantics(E->getType());
9178 Result = llvm::APFloat::getInf(Sem);
9182 case Builtin::BI__builtin_nans:
9183 case Builtin::BI__builtin_nansf:
9184 case Builtin::BI__builtin_nansl:
9185 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9190 case Builtin::BI__builtin_nan:
9191 case Builtin::BI__builtin_nanf:
9192 case Builtin::BI__builtin_nanl:
9193 // If this is __builtin_nan() turn this into a nan, otherwise we
9194 // can't constant fold it.
9195 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9200 case Builtin::BI__builtin_fabs:
9201 case Builtin::BI__builtin_fabsf:
9202 case Builtin::BI__builtin_fabsl:
9203 if (!EvaluateFloat(E->getArg(0), Result, Info))
9206 if (Result.isNegative())
9207 Result.changeSign();
9210 // FIXME: Builtin::BI__builtin_powi
9211 // FIXME: Builtin::BI__builtin_powif
9212 // FIXME: Builtin::BI__builtin_powil
9214 case Builtin::BI__builtin_copysign:
9215 case Builtin::BI__builtin_copysignf:
9216 case Builtin::BI__builtin_copysignl: {
9218 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9219 !EvaluateFloat(E->getArg(1), RHS, Info))
9221 Result.copySign(RHS);
9227 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9228 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9230 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9232 Result = CV.FloatReal;
9236 return Visit(E->getSubExpr());
9239 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9240 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9242 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9244 Result = CV.FloatImag;
9248 VisitIgnoredValue(E->getSubExpr());
9249 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9250 Result = llvm::APFloat::getZero(Sem);
9254 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9255 switch (E->getOpcode()) {
9256 default: return Error(E);
9258 return EvaluateFloat(E->getSubExpr(), Result, Info);
9260 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9262 Result.changeSign();
9267 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9268 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9269 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9272 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9273 if (!LHSOK && !Info.noteFailure())
9275 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9276 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9279 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9280 Result = E->getValue();
9284 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9285 const Expr* SubExpr = E->getSubExpr();
9287 switch (E->getCastKind()) {
9289 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9291 case CK_IntegralToFloating: {
9293 return EvaluateInteger(SubExpr, IntResult, Info) &&
9294 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9295 E->getType(), Result);
9298 case CK_FloatingCast: {
9299 if (!Visit(SubExpr))
9301 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9305 case CK_FloatingComplexToReal: {
9307 if (!EvaluateComplex(SubExpr, V, Info))
9309 Result = V.getComplexFloatReal();
9315 //===----------------------------------------------------------------------===//
9316 // Complex Evaluation (for float and integer)
9317 //===----------------------------------------------------------------------===//
9320 class ComplexExprEvaluator
9321 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9322 ComplexValue &Result;
9325 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9326 : ExprEvaluatorBaseTy(info), Result(Result) {}
9328 bool Success(const APValue &V, const Expr *e) {
9333 bool ZeroInitialization(const Expr *E);
9335 //===--------------------------------------------------------------------===//
9337 //===--------------------------------------------------------------------===//
9339 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9340 bool VisitCastExpr(const CastExpr *E);
9341 bool VisitBinaryOperator(const BinaryOperator *E);
9342 bool VisitUnaryOperator(const UnaryOperator *E);
9343 bool VisitInitListExpr(const InitListExpr *E);
9345 } // end anonymous namespace
9347 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9349 assert(E->isRValue() && E->getType()->isAnyComplexType());
9350 return ComplexExprEvaluator(Info, Result).Visit(E);
9353 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9354 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9355 if (ElemTy->isRealFloatingType()) {
9356 Result.makeComplexFloat();
9357 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9358 Result.FloatReal = Zero;
9359 Result.FloatImag = Zero;
9361 Result.makeComplexInt();
9362 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9363 Result.IntReal = Zero;
9364 Result.IntImag = Zero;
9369 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9370 const Expr* SubExpr = E->getSubExpr();
9372 if (SubExpr->getType()->isRealFloatingType()) {
9373 Result.makeComplexFloat();
9374 APFloat &Imag = Result.FloatImag;
9375 if (!EvaluateFloat(SubExpr, Imag, Info))
9378 Result.FloatReal = APFloat(Imag.getSemantics());
9381 assert(SubExpr->getType()->isIntegerType() &&
9382 "Unexpected imaginary literal.");
9384 Result.makeComplexInt();
9385 APSInt &Imag = Result.IntImag;
9386 if (!EvaluateInteger(SubExpr, Imag, Info))
9389 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9394 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9396 switch (E->getCastKind()) {
9398 case CK_BaseToDerived:
9399 case CK_DerivedToBase:
9400 case CK_UncheckedDerivedToBase:
9403 case CK_ArrayToPointerDecay:
9404 case CK_FunctionToPointerDecay:
9405 case CK_NullToPointer:
9406 case CK_NullToMemberPointer:
9407 case CK_BaseToDerivedMemberPointer:
9408 case CK_DerivedToBaseMemberPointer:
9409 case CK_MemberPointerToBoolean:
9410 case CK_ReinterpretMemberPointer:
9411 case CK_ConstructorConversion:
9412 case CK_IntegralToPointer:
9413 case CK_PointerToIntegral:
9414 case CK_PointerToBoolean:
9416 case CK_VectorSplat:
9417 case CK_IntegralCast:
9418 case CK_BooleanToSignedIntegral:
9419 case CK_IntegralToBoolean:
9420 case CK_IntegralToFloating:
9421 case CK_FloatingToIntegral:
9422 case CK_FloatingToBoolean:
9423 case CK_FloatingCast:
9424 case CK_CPointerToObjCPointerCast:
9425 case CK_BlockPointerToObjCPointerCast:
9426 case CK_AnyPointerToBlockPointerCast:
9427 case CK_ObjCObjectLValueCast:
9428 case CK_FloatingComplexToReal:
9429 case CK_FloatingComplexToBoolean:
9430 case CK_IntegralComplexToReal:
9431 case CK_IntegralComplexToBoolean:
9432 case CK_ARCProduceObject:
9433 case CK_ARCConsumeObject:
9434 case CK_ARCReclaimReturnedObject:
9435 case CK_ARCExtendBlockObject:
9436 case CK_CopyAndAutoreleaseBlockObject:
9437 case CK_BuiltinFnToFnPtr:
9438 case CK_ZeroToOCLEvent:
9439 case CK_ZeroToOCLQueue:
9440 case CK_NonAtomicToAtomic:
9441 case CK_AddressSpaceConversion:
9442 case CK_IntToOCLSampler:
9443 llvm_unreachable("invalid cast kind for complex value");
9445 case CK_LValueToRValue:
9446 case CK_AtomicToNonAtomic:
9448 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9451 case CK_LValueBitCast:
9452 case CK_UserDefinedConversion:
9455 case CK_FloatingRealToComplex: {
9456 APFloat &Real = Result.FloatReal;
9457 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9460 Result.makeComplexFloat();
9461 Result.FloatImag = APFloat(Real.getSemantics());
9465 case CK_FloatingComplexCast: {
9466 if (!Visit(E->getSubExpr()))
9469 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9471 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9473 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9474 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9477 case CK_FloatingComplexToIntegralComplex: {
9478 if (!Visit(E->getSubExpr()))
9481 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9483 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9484 Result.makeComplexInt();
9485 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9486 To, Result.IntReal) &&
9487 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9488 To, Result.IntImag);
9491 case CK_IntegralRealToComplex: {
9492 APSInt &Real = Result.IntReal;
9493 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9496 Result.makeComplexInt();
9497 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9501 case CK_IntegralComplexCast: {
9502 if (!Visit(E->getSubExpr()))
9505 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9507 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9509 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9510 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9514 case CK_IntegralComplexToFloatingComplex: {
9515 if (!Visit(E->getSubExpr()))
9518 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9520 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9521 Result.makeComplexFloat();
9522 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9523 To, Result.FloatReal) &&
9524 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9525 To, Result.FloatImag);
9529 llvm_unreachable("unknown cast resulting in complex value");
9532 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9533 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9534 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9536 // Track whether the LHS or RHS is real at the type system level. When this is
9537 // the case we can simplify our evaluation strategy.
9538 bool LHSReal = false, RHSReal = false;
9541 if (E->getLHS()->getType()->isRealFloatingType()) {
9543 APFloat &Real = Result.FloatReal;
9544 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9546 Result.makeComplexFloat();
9547 Result.FloatImag = APFloat(Real.getSemantics());
9550 LHSOK = Visit(E->getLHS());
9552 if (!LHSOK && !Info.noteFailure())
9556 if (E->getRHS()->getType()->isRealFloatingType()) {
9558 APFloat &Real = RHS.FloatReal;
9559 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9561 RHS.makeComplexFloat();
9562 RHS.FloatImag = APFloat(Real.getSemantics());
9563 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9566 assert(!(LHSReal && RHSReal) &&
9567 "Cannot have both operands of a complex operation be real.");
9568 switch (E->getOpcode()) {
9569 default: return Error(E);
9571 if (Result.isComplexFloat()) {
9572 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9573 APFloat::rmNearestTiesToEven);
9575 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9577 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9578 APFloat::rmNearestTiesToEven);
9580 Result.getComplexIntReal() += RHS.getComplexIntReal();
9581 Result.getComplexIntImag() += RHS.getComplexIntImag();
9585 if (Result.isComplexFloat()) {
9586 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9587 APFloat::rmNearestTiesToEven);
9589 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9590 Result.getComplexFloatImag().changeSign();
9591 } else if (!RHSReal) {
9592 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9593 APFloat::rmNearestTiesToEven);
9596 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9597 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9601 if (Result.isComplexFloat()) {
9602 // This is an implementation of complex multiplication according to the
9603 // constraints laid out in C11 Annex G. The implemention uses the
9604 // following naming scheme:
9605 // (a + ib) * (c + id)
9606 ComplexValue LHS = Result;
9607 APFloat &A = LHS.getComplexFloatReal();
9608 APFloat &B = LHS.getComplexFloatImag();
9609 APFloat &C = RHS.getComplexFloatReal();
9610 APFloat &D = RHS.getComplexFloatImag();
9611 APFloat &ResR = Result.getComplexFloatReal();
9612 APFloat &ResI = Result.getComplexFloatImag();
9614 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9617 } else if (RHSReal) {
9621 // In the fully general case, we need to handle NaNs and infinities
9629 if (ResR.isNaN() && ResI.isNaN()) {
9630 bool Recalc = false;
9631 if (A.isInfinity() || B.isInfinity()) {
9632 A = APFloat::copySign(
9633 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9634 B = APFloat::copySign(
9635 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9637 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9639 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9642 if (C.isInfinity() || D.isInfinity()) {
9643 C = APFloat::copySign(
9644 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9645 D = APFloat::copySign(
9646 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9648 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9650 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9653 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9654 AD.isInfinity() || BC.isInfinity())) {
9656 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9658 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9660 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9662 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9666 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9667 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9672 ComplexValue LHS = Result;
9673 Result.getComplexIntReal() =
9674 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9675 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9676 Result.getComplexIntImag() =
9677 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9678 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9682 if (Result.isComplexFloat()) {
9683 // This is an implementation of complex division according to the
9684 // constraints laid out in C11 Annex G. The implemention uses the
9685 // following naming scheme:
9686 // (a + ib) / (c + id)
9687 ComplexValue LHS = Result;
9688 APFloat &A = LHS.getComplexFloatReal();
9689 APFloat &B = LHS.getComplexFloatImag();
9690 APFloat &C = RHS.getComplexFloatReal();
9691 APFloat &D = RHS.getComplexFloatImag();
9692 APFloat &ResR = Result.getComplexFloatReal();
9693 APFloat &ResI = Result.getComplexFloatImag();
9699 // No real optimizations we can do here, stub out with zero.
9700 B = APFloat::getZero(A.getSemantics());
9703 APFloat MaxCD = maxnum(abs(C), abs(D));
9704 if (MaxCD.isFinite()) {
9705 DenomLogB = ilogb(MaxCD);
9706 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9707 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9709 APFloat Denom = C * C + D * D;
9710 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9711 APFloat::rmNearestTiesToEven);
9712 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9713 APFloat::rmNearestTiesToEven);
9714 if (ResR.isNaN() && ResI.isNaN()) {
9715 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9716 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9717 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9718 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9720 A = APFloat::copySign(
9721 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9722 B = APFloat::copySign(
9723 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9724 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9725 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9726 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9727 C = APFloat::copySign(
9728 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9729 D = APFloat::copySign(
9730 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9731 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9732 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9737 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9738 return Error(E, diag::note_expr_divide_by_zero);
9740 ComplexValue LHS = Result;
9741 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9742 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9743 Result.getComplexIntReal() =
9744 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9745 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9746 Result.getComplexIntImag() =
9747 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9748 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9756 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9757 // Get the operand value into 'Result'.
9758 if (!Visit(E->getSubExpr()))
9761 switch (E->getOpcode()) {
9767 // The result is always just the subexpr.
9770 if (Result.isComplexFloat()) {
9771 Result.getComplexFloatReal().changeSign();
9772 Result.getComplexFloatImag().changeSign();
9775 Result.getComplexIntReal() = -Result.getComplexIntReal();
9776 Result.getComplexIntImag() = -Result.getComplexIntImag();
9780 if (Result.isComplexFloat())
9781 Result.getComplexFloatImag().changeSign();
9783 Result.getComplexIntImag() = -Result.getComplexIntImag();
9788 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9789 if (E->getNumInits() == 2) {
9790 if (E->getType()->isComplexType()) {
9791 Result.makeComplexFloat();
9792 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9794 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9797 Result.makeComplexInt();
9798 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9800 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9805 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9808 //===----------------------------------------------------------------------===//
9809 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9810 // implicit conversion.
9811 //===----------------------------------------------------------------------===//
9814 class AtomicExprEvaluator :
9815 public ExprEvaluatorBase<AtomicExprEvaluator> {
9819 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9820 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9822 bool Success(const APValue &V, const Expr *E) {
9827 bool ZeroInitialization(const Expr *E) {
9828 ImplicitValueInitExpr VIE(
9829 E->getType()->castAs<AtomicType>()->getValueType());
9830 // For atomic-qualified class (and array) types in C++, initialize the
9831 // _Atomic-wrapped subobject directly, in-place.
9832 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9833 : Evaluate(Result, Info, &VIE);
9836 bool VisitCastExpr(const CastExpr *E) {
9837 switch (E->getCastKind()) {
9839 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9840 case CK_NonAtomicToAtomic:
9841 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9842 : Evaluate(Result, Info, E->getSubExpr());
9846 } // end anonymous namespace
9848 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9850 assert(E->isRValue() && E->getType()->isAtomicType());
9851 return AtomicExprEvaluator(Info, This, Result).Visit(E);
9854 //===----------------------------------------------------------------------===//
9855 // Void expression evaluation, primarily for a cast to void on the LHS of a
9857 //===----------------------------------------------------------------------===//
9860 class VoidExprEvaluator
9861 : public ExprEvaluatorBase<VoidExprEvaluator> {
9863 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9865 bool Success(const APValue &V, const Expr *e) { return true; }
9867 bool ZeroInitialization(const Expr *E) { return true; }
9869 bool VisitCastExpr(const CastExpr *E) {
9870 switch (E->getCastKind()) {
9872 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9874 VisitIgnoredValue(E->getSubExpr());
9879 bool VisitCallExpr(const CallExpr *E) {
9880 switch (E->getBuiltinCallee()) {
9882 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9883 case Builtin::BI__assume:
9884 case Builtin::BI__builtin_assume:
9885 // The argument is not evaluated!
9890 } // end anonymous namespace
9892 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9893 assert(E->isRValue() && E->getType()->isVoidType());
9894 return VoidExprEvaluator(Info).Visit(E);
9897 //===----------------------------------------------------------------------===//
9898 // Top level Expr::EvaluateAsRValue method.
9899 //===----------------------------------------------------------------------===//
9901 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9902 // In C, function designators are not lvalues, but we evaluate them as if they
9904 QualType T = E->getType();
9905 if (E->isGLValue() || T->isFunctionType()) {
9907 if (!EvaluateLValue(E, LV, Info))
9909 LV.moveInto(Result);
9910 } else if (T->isVectorType()) {
9911 if (!EvaluateVector(E, Result, Info))
9913 } else if (T->isIntegralOrEnumerationType()) {
9914 if (!IntExprEvaluator(Info, Result).Visit(E))
9916 } else if (T->hasPointerRepresentation()) {
9918 if (!EvaluatePointer(E, LV, Info))
9920 LV.moveInto(Result);
9921 } else if (T->isRealFloatingType()) {
9922 llvm::APFloat F(0.0);
9923 if (!EvaluateFloat(E, F, Info))
9925 Result = APValue(F);
9926 } else if (T->isAnyComplexType()) {
9928 if (!EvaluateComplex(E, C, Info))
9931 } else if (T->isMemberPointerType()) {
9933 if (!EvaluateMemberPointer(E, P, Info))
9937 } else if (T->isArrayType()) {
9939 LV.set(E, Info.CurrentCall->Index);
9940 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9941 if (!EvaluateArray(E, LV, Value, Info))
9944 } else if (T->isRecordType()) {
9946 LV.set(E, Info.CurrentCall->Index);
9947 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9948 if (!EvaluateRecord(E, LV, Value, Info))
9951 } else if (T->isVoidType()) {
9952 if (!Info.getLangOpts().CPlusPlus11)
9953 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9955 if (!EvaluateVoid(E, Info))
9957 } else if (T->isAtomicType()) {
9958 QualType Unqual = T.getAtomicUnqualifiedType();
9959 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9961 LV.set(E, Info.CurrentCall->Index);
9962 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9963 if (!EvaluateAtomic(E, &LV, Value, Info))
9966 if (!EvaluateAtomic(E, nullptr, Result, Info))
9969 } else if (Info.getLangOpts().CPlusPlus11) {
9970 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9973 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9980 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9981 /// cases, the in-place evaluation is essential, since later initializers for
9982 /// an object can indirectly refer to subobjects which were initialized earlier.
9983 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9984 const Expr *E, bool AllowNonLiteralTypes) {
9985 assert(!E->isValueDependent());
9987 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9990 if (E->isRValue()) {
9991 // Evaluate arrays and record types in-place, so that later initializers can
9992 // refer to earlier-initialized members of the object.
9993 QualType T = E->getType();
9994 if (T->isArrayType())
9995 return EvaluateArray(E, This, Result, Info);
9996 else if (T->isRecordType())
9997 return EvaluateRecord(E, This, Result, Info);
9998 else if (T->isAtomicType()) {
9999 QualType Unqual = T.getAtomicUnqualifiedType();
10000 if (Unqual->isArrayType() || Unqual->isRecordType())
10001 return EvaluateAtomic(E, &This, Result, Info);
10005 // For any other type, in-place evaluation is unimportant.
10006 return Evaluate(Result, Info, E);
10009 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10010 /// lvalue-to-rvalue cast if it is an lvalue.
10011 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10012 if (E->getType().isNull())
10015 if (!CheckLiteralType(Info, E))
10018 if (!::Evaluate(Result, Info, E))
10021 if (E->isGLValue()) {
10023 LV.setFrom(Info.Ctx, Result);
10024 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10028 // Check this core constant expression is a constant expression.
10029 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10032 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10033 const ASTContext &Ctx, bool &IsConst) {
10034 // Fast-path evaluations of integer literals, since we sometimes see files
10035 // containing vast quantities of these.
10036 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10037 Result.Val = APValue(APSInt(L->getValue(),
10038 L->getType()->isUnsignedIntegerType()));
10043 // This case should be rare, but we need to check it before we check on
10045 if (Exp->getType().isNull()) {
10050 // FIXME: Evaluating values of large array and record types can cause
10051 // performance problems. Only do so in C++11 for now.
10052 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10053 Exp->getType()->isRecordType()) &&
10054 !Ctx.getLangOpts().CPlusPlus11) {
10062 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10063 /// any crazy technique (that has nothing to do with language standards) that
10064 /// we want to. If this function returns true, it returns the folded constant
10065 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10066 /// will be applied to the result.
10067 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
10069 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
10072 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10073 return ::EvaluateAsRValue(Info, this, Result.Val);
10076 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10077 const ASTContext &Ctx) const {
10078 EvalResult Scratch;
10079 return EvaluateAsRValue(Scratch, Ctx) &&
10080 HandleConversionToBool(Scratch.Val, Result);
10083 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10084 Expr::SideEffectsKind SEK) {
10085 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10086 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10089 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10090 SideEffectsKind AllowSideEffects) const {
10091 if (!getType()->isIntegralOrEnumerationType())
10094 EvalResult ExprResult;
10095 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10096 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10099 Result = ExprResult.Val.getInt();
10103 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10104 SideEffectsKind AllowSideEffects) const {
10105 if (!getType()->isRealFloatingType())
10108 EvalResult ExprResult;
10109 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10110 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10113 Result = ExprResult.Val.getFloat();
10117 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10118 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10121 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10122 !CheckLValueConstantExpression(Info, getExprLoc(),
10123 Ctx.getLValueReferenceType(getType()), LV))
10126 LV.moveInto(Result.Val);
10130 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10132 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10133 // FIXME: Evaluating initializers for large array and record types can cause
10134 // performance problems. Only do so in C++11 for now.
10135 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10136 !Ctx.getLangOpts().CPlusPlus11)
10139 Expr::EvalStatus EStatus;
10140 EStatus.Diag = &Notes;
10142 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10143 ? EvalInfo::EM_ConstantExpression
10144 : EvalInfo::EM_ConstantFold);
10145 InitInfo.setEvaluatingDecl(VD, Value);
10150 // C++11 [basic.start.init]p2:
10151 // Variables with static storage duration or thread storage duration shall be
10152 // zero-initialized before any other initialization takes place.
10153 // This behavior is not present in C.
10154 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10155 !VD->getType()->isReferenceType()) {
10156 ImplicitValueInitExpr VIE(VD->getType());
10157 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10158 /*AllowNonLiteralTypes=*/true))
10162 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10163 /*AllowNonLiteralTypes=*/true) ||
10164 EStatus.HasSideEffects)
10167 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10171 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10172 /// constant folded, but discard the result.
10173 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10175 return EvaluateAsRValue(Result, Ctx) &&
10176 !hasUnacceptableSideEffect(Result, SEK);
10179 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10180 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10181 EvalResult EvalResult;
10182 EvalResult.Diag = Diag;
10183 bool Result = EvaluateAsRValue(EvalResult, Ctx);
10185 assert(Result && "Could not evaluate expression");
10186 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10188 return EvalResult.Val.getInt();
10191 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10193 EvalResult EvalResult;
10194 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10195 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10196 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10200 bool Expr::EvalResult::isGlobalLValue() const {
10201 assert(Val.isLValue());
10202 return IsGlobalLValue(Val.getLValueBase());
10206 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10207 /// an integer constant expression.
10209 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10212 // CheckICE - This function does the fundamental ICE checking: the returned
10213 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10214 // and a (possibly null) SourceLocation indicating the location of the problem.
10216 // Note that to reduce code duplication, this helper does no evaluation
10217 // itself; the caller checks whether the expression is evaluatable, and
10218 // in the rare cases where CheckICE actually cares about the evaluated
10219 // value, it calls into Evaluate.
10224 /// This expression is an ICE.
10226 /// This expression is not an ICE, but if it isn't evaluated, it's
10227 /// a legal subexpression for an ICE. This return value is used to handle
10228 /// the comma operator in C99 mode, and non-constant subexpressions.
10229 IK_ICEIfUnevaluated,
10230 /// This expression is not an ICE, and is not a legal subexpression for one.
10236 SourceLocation Loc;
10238 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10243 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10245 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10247 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10248 Expr::EvalResult EVResult;
10249 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10250 !EVResult.Val.isInt())
10251 return ICEDiag(IK_NotICE, E->getLocStart());
10256 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10257 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10258 if (!E->getType()->isIntegralOrEnumerationType())
10259 return ICEDiag(IK_NotICE, E->getLocStart());
10261 switch (E->getStmtClass()) {
10262 #define ABSTRACT_STMT(Node)
10263 #define STMT(Node, Base) case Expr::Node##Class:
10264 #define EXPR(Node, Base)
10265 #include "clang/AST/StmtNodes.inc"
10266 case Expr::PredefinedExprClass:
10267 case Expr::FloatingLiteralClass:
10268 case Expr::ImaginaryLiteralClass:
10269 case Expr::StringLiteralClass:
10270 case Expr::ArraySubscriptExprClass:
10271 case Expr::OMPArraySectionExprClass:
10272 case Expr::MemberExprClass:
10273 case Expr::CompoundAssignOperatorClass:
10274 case Expr::CompoundLiteralExprClass:
10275 case Expr::ExtVectorElementExprClass:
10276 case Expr::DesignatedInitExprClass:
10277 case Expr::ArrayInitLoopExprClass:
10278 case Expr::ArrayInitIndexExprClass:
10279 case Expr::NoInitExprClass:
10280 case Expr::DesignatedInitUpdateExprClass:
10281 case Expr::ImplicitValueInitExprClass:
10282 case Expr::ParenListExprClass:
10283 case Expr::VAArgExprClass:
10284 case Expr::AddrLabelExprClass:
10285 case Expr::StmtExprClass:
10286 case Expr::CXXMemberCallExprClass:
10287 case Expr::CUDAKernelCallExprClass:
10288 case Expr::CXXDynamicCastExprClass:
10289 case Expr::CXXTypeidExprClass:
10290 case Expr::CXXUuidofExprClass:
10291 case Expr::MSPropertyRefExprClass:
10292 case Expr::MSPropertySubscriptExprClass:
10293 case Expr::CXXNullPtrLiteralExprClass:
10294 case Expr::UserDefinedLiteralClass:
10295 case Expr::CXXThisExprClass:
10296 case Expr::CXXThrowExprClass:
10297 case Expr::CXXNewExprClass:
10298 case Expr::CXXDeleteExprClass:
10299 case Expr::CXXPseudoDestructorExprClass:
10300 case Expr::UnresolvedLookupExprClass:
10301 case Expr::TypoExprClass:
10302 case Expr::DependentScopeDeclRefExprClass:
10303 case Expr::CXXConstructExprClass:
10304 case Expr::CXXInheritedCtorInitExprClass:
10305 case Expr::CXXStdInitializerListExprClass:
10306 case Expr::CXXBindTemporaryExprClass:
10307 case Expr::ExprWithCleanupsClass:
10308 case Expr::CXXTemporaryObjectExprClass:
10309 case Expr::CXXUnresolvedConstructExprClass:
10310 case Expr::CXXDependentScopeMemberExprClass:
10311 case Expr::UnresolvedMemberExprClass:
10312 case Expr::ObjCStringLiteralClass:
10313 case Expr::ObjCBoxedExprClass:
10314 case Expr::ObjCArrayLiteralClass:
10315 case Expr::ObjCDictionaryLiteralClass:
10316 case Expr::ObjCEncodeExprClass:
10317 case Expr::ObjCMessageExprClass:
10318 case Expr::ObjCSelectorExprClass:
10319 case Expr::ObjCProtocolExprClass:
10320 case Expr::ObjCIvarRefExprClass:
10321 case Expr::ObjCPropertyRefExprClass:
10322 case Expr::ObjCSubscriptRefExprClass:
10323 case Expr::ObjCIsaExprClass:
10324 case Expr::ObjCAvailabilityCheckExprClass:
10325 case Expr::ShuffleVectorExprClass:
10326 case Expr::ConvertVectorExprClass:
10327 case Expr::BlockExprClass:
10328 case Expr::NoStmtClass:
10329 case Expr::OpaqueValueExprClass:
10330 case Expr::PackExpansionExprClass:
10331 case Expr::SubstNonTypeTemplateParmPackExprClass:
10332 case Expr::FunctionParmPackExprClass:
10333 case Expr::AsTypeExprClass:
10334 case Expr::ObjCIndirectCopyRestoreExprClass:
10335 case Expr::MaterializeTemporaryExprClass:
10336 case Expr::PseudoObjectExprClass:
10337 case Expr::AtomicExprClass:
10338 case Expr::LambdaExprClass:
10339 case Expr::CXXFoldExprClass:
10340 case Expr::CoawaitExprClass:
10341 case Expr::DependentCoawaitExprClass:
10342 case Expr::CoyieldExprClass:
10343 return ICEDiag(IK_NotICE, E->getLocStart());
10345 case Expr::InitListExprClass: {
10346 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10347 // form "T x = { a };" is equivalent to "T x = a;".
10348 // Unless we're initializing a reference, T is a scalar as it is known to be
10349 // of integral or enumeration type.
10351 if (cast<InitListExpr>(E)->getNumInits() == 1)
10352 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10353 return ICEDiag(IK_NotICE, E->getLocStart());
10356 case Expr::SizeOfPackExprClass:
10357 case Expr::GNUNullExprClass:
10358 // GCC considers the GNU __null value to be an integral constant expression.
10361 case Expr::SubstNonTypeTemplateParmExprClass:
10363 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10365 case Expr::ParenExprClass:
10366 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10367 case Expr::GenericSelectionExprClass:
10368 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10369 case Expr::IntegerLiteralClass:
10370 case Expr::CharacterLiteralClass:
10371 case Expr::ObjCBoolLiteralExprClass:
10372 case Expr::CXXBoolLiteralExprClass:
10373 case Expr::CXXScalarValueInitExprClass:
10374 case Expr::TypeTraitExprClass:
10375 case Expr::ArrayTypeTraitExprClass:
10376 case Expr::ExpressionTraitExprClass:
10377 case Expr::CXXNoexceptExprClass:
10379 case Expr::CallExprClass:
10380 case Expr::CXXOperatorCallExprClass: {
10381 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10382 // constant expressions, but they can never be ICEs because an ICE cannot
10383 // contain an operand of (pointer to) function type.
10384 const CallExpr *CE = cast<CallExpr>(E);
10385 if (CE->getBuiltinCallee())
10386 return CheckEvalInICE(E, Ctx);
10387 return ICEDiag(IK_NotICE, E->getLocStart());
10389 case Expr::DeclRefExprClass: {
10390 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10392 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10393 if (Ctx.getLangOpts().CPlusPlus &&
10394 D && IsConstNonVolatile(D->getType())) {
10395 // Parameter variables are never constants. Without this check,
10396 // getAnyInitializer() can find a default argument, which leads
10398 if (isa<ParmVarDecl>(D))
10399 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10402 // A variable of non-volatile const-qualified integral or enumeration
10403 // type initialized by an ICE can be used in ICEs.
10404 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10405 if (!Dcl->getType()->isIntegralOrEnumerationType())
10406 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10409 // Look for a declaration of this variable that has an initializer, and
10410 // check whether it is an ICE.
10411 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10414 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10417 return ICEDiag(IK_NotICE, E->getLocStart());
10419 case Expr::UnaryOperatorClass: {
10420 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10421 switch (Exp->getOpcode()) {
10429 // C99 6.6/3 allows increment and decrement within unevaluated
10430 // subexpressions of constant expressions, but they can never be ICEs
10431 // because an ICE cannot contain an lvalue operand.
10432 return ICEDiag(IK_NotICE, E->getLocStart());
10440 return CheckICE(Exp->getSubExpr(), Ctx);
10443 // OffsetOf falls through here.
10446 case Expr::OffsetOfExprClass: {
10447 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10448 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10449 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10450 // compliance: we should warn earlier for offsetof expressions with
10451 // array subscripts that aren't ICEs, and if the array subscripts
10452 // are ICEs, the value of the offsetof must be an integer constant.
10453 return CheckEvalInICE(E, Ctx);
10455 case Expr::UnaryExprOrTypeTraitExprClass: {
10456 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10457 if ((Exp->getKind() == UETT_SizeOf) &&
10458 Exp->getTypeOfArgument()->isVariableArrayType())
10459 return ICEDiag(IK_NotICE, E->getLocStart());
10462 case Expr::BinaryOperatorClass: {
10463 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10464 switch (Exp->getOpcode()) {
10478 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
10479 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10480 // constant expressions, but they can never be ICEs because an ICE cannot
10481 // contain an lvalue operand.
10482 return ICEDiag(IK_NotICE, E->getLocStart());
10501 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10502 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10503 if (Exp->getOpcode() == BO_Div ||
10504 Exp->getOpcode() == BO_Rem) {
10505 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10506 // we don't evaluate one.
10507 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10508 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10510 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10511 if (REval.isSigned() && REval.isAllOnesValue()) {
10512 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10513 if (LEval.isMinSignedValue())
10514 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10518 if (Exp->getOpcode() == BO_Comma) {
10519 if (Ctx.getLangOpts().C99) {
10520 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10521 // if it isn't evaluated.
10522 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10523 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10525 // In both C89 and C++, commas in ICEs are illegal.
10526 return ICEDiag(IK_NotICE, E->getLocStart());
10529 return Worst(LHSResult, RHSResult);
10533 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10534 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10535 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10536 // Rare case where the RHS has a comma "side-effect"; we need
10537 // to actually check the condition to see whether the side
10538 // with the comma is evaluated.
10539 if ((Exp->getOpcode() == BO_LAnd) !=
10540 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10545 return Worst(LHSResult, RHSResult);
10550 case Expr::ImplicitCastExprClass:
10551 case Expr::CStyleCastExprClass:
10552 case Expr::CXXFunctionalCastExprClass:
10553 case Expr::CXXStaticCastExprClass:
10554 case Expr::CXXReinterpretCastExprClass:
10555 case Expr::CXXConstCastExprClass:
10556 case Expr::ObjCBridgedCastExprClass: {
10557 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10558 if (isa<ExplicitCastExpr>(E)) {
10559 if (const FloatingLiteral *FL
10560 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10561 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10562 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10563 APSInt IgnoredVal(DestWidth, !DestSigned);
10565 // If the value does not fit in the destination type, the behavior is
10566 // undefined, so we are not required to treat it as a constant
10568 if (FL->getValue().convertToInteger(IgnoredVal,
10569 llvm::APFloat::rmTowardZero,
10570 &Ignored) & APFloat::opInvalidOp)
10571 return ICEDiag(IK_NotICE, E->getLocStart());
10575 switch (cast<CastExpr>(E)->getCastKind()) {
10576 case CK_LValueToRValue:
10577 case CK_AtomicToNonAtomic:
10578 case CK_NonAtomicToAtomic:
10580 case CK_IntegralToBoolean:
10581 case CK_IntegralCast:
10582 return CheckICE(SubExpr, Ctx);
10584 return ICEDiag(IK_NotICE, E->getLocStart());
10587 case Expr::BinaryConditionalOperatorClass: {
10588 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10589 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10590 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10591 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10592 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10593 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10594 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10595 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10596 return FalseResult;
10598 case Expr::ConditionalOperatorClass: {
10599 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10600 // If the condition (ignoring parens) is a __builtin_constant_p call,
10601 // then only the true side is actually considered in an integer constant
10602 // expression, and it is fully evaluated. This is an important GNU
10603 // extension. See GCC PR38377 for discussion.
10604 if (const CallExpr *CallCE
10605 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10606 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10607 return CheckEvalInICE(E, Ctx);
10608 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10609 if (CondResult.Kind == IK_NotICE)
10612 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10613 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10615 if (TrueResult.Kind == IK_NotICE)
10617 if (FalseResult.Kind == IK_NotICE)
10618 return FalseResult;
10619 if (CondResult.Kind == IK_ICEIfUnevaluated)
10621 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10623 // Rare case where the diagnostics depend on which side is evaluated
10624 // Note that if we get here, CondResult is 0, and at least one of
10625 // TrueResult and FalseResult is non-zero.
10626 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10627 return FalseResult;
10630 case Expr::CXXDefaultArgExprClass:
10631 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10632 case Expr::CXXDefaultInitExprClass:
10633 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10634 case Expr::ChooseExprClass: {
10635 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10639 llvm_unreachable("Invalid StmtClass!");
10642 /// Evaluate an expression as a C++11 integral constant expression.
10643 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10645 llvm::APSInt *Value,
10646 SourceLocation *Loc) {
10647 if (!E->getType()->isIntegralOrEnumerationType()) {
10648 if (Loc) *Loc = E->getExprLoc();
10653 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10656 if (!Result.isInt()) {
10657 if (Loc) *Loc = E->getExprLoc();
10661 if (Value) *Value = Result.getInt();
10665 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10666 SourceLocation *Loc) const {
10667 if (Ctx.getLangOpts().CPlusPlus11)
10668 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10670 ICEDiag D = CheckICE(this, Ctx);
10671 if (D.Kind != IK_ICE) {
10672 if (Loc) *Loc = D.Loc;
10678 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10679 SourceLocation *Loc, bool isEvaluated) const {
10680 if (Ctx.getLangOpts().CPlusPlus11)
10681 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10683 if (!isIntegerConstantExpr(Ctx, Loc))
10685 // The only possible side-effects here are due to UB discovered in the
10686 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10687 // required to treat the expression as an ICE, so we produce the folded
10689 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10690 llvm_unreachable("ICE cannot be evaluated!");
10694 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10695 return CheckICE(this, Ctx).Kind == IK_ICE;
10698 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10699 SourceLocation *Loc) const {
10700 // We support this checking in C++98 mode in order to diagnose compatibility
10702 assert(Ctx.getLangOpts().CPlusPlus);
10704 // Build evaluation settings.
10705 Expr::EvalStatus Status;
10706 SmallVector<PartialDiagnosticAt, 8> Diags;
10707 Status.Diag = &Diags;
10708 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10711 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10713 if (!Diags.empty()) {
10714 IsConstExpr = false;
10715 if (Loc) *Loc = Diags[0].first;
10716 } else if (!IsConstExpr) {
10717 // FIXME: This shouldn't happen.
10718 if (Loc) *Loc = getExprLoc();
10721 return IsConstExpr;
10724 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10725 const FunctionDecl *Callee,
10726 ArrayRef<const Expr*> Args,
10727 const Expr *This) const {
10728 Expr::EvalStatus Status;
10729 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10732 const LValue *ThisPtr = nullptr;
10735 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10736 assert(MD && "Don't provide `this` for non-methods.");
10737 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10739 if (EvaluateObjectArgument(Info, This, ThisVal))
10740 ThisPtr = &ThisVal;
10741 if (Info.EvalStatus.HasSideEffects)
10745 ArgVector ArgValues(Args.size());
10746 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10748 if ((*I)->isValueDependent() ||
10749 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10750 // If evaluation fails, throw away the argument entirely.
10751 ArgValues[I - Args.begin()] = APValue();
10752 if (Info.EvalStatus.HasSideEffects)
10756 // Build fake call to Callee.
10757 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10759 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10762 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10764 PartialDiagnosticAt> &Diags) {
10765 // FIXME: It would be useful to check constexpr function templates, but at the
10766 // moment the constant expression evaluator cannot cope with the non-rigorous
10767 // ASTs which we build for dependent expressions.
10768 if (FD->isDependentContext())
10771 Expr::EvalStatus Status;
10772 Status.Diag = &Diags;
10774 EvalInfo Info(FD->getASTContext(), Status,
10775 EvalInfo::EM_PotentialConstantExpression);
10777 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10778 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10780 // Fabricate an arbitrary expression on the stack and pretend that it
10781 // is a temporary being used as the 'this' pointer.
10783 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10784 This.set(&VIE, Info.CurrentCall->Index);
10786 ArrayRef<const Expr*> Args;
10789 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10790 // Evaluate the call as a constant initializer, to allow the construction
10791 // of objects of non-literal types.
10792 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10793 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10795 SourceLocation Loc = FD->getLocation();
10796 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10797 Args, FD->getBody(), Info, Scratch, nullptr);
10800 return Diags.empty();
10803 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10804 const FunctionDecl *FD,
10806 PartialDiagnosticAt> &Diags) {
10807 Expr::EvalStatus Status;
10808 Status.Diag = &Diags;
10810 EvalInfo Info(FD->getASTContext(), Status,
10811 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10813 // Fabricate a call stack frame to give the arguments a plausible cover story.
10814 ArrayRef<const Expr*> Args;
10815 ArgVector ArgValues(0);
10816 bool Success = EvaluateArgs(Args, ArgValues, Info);
10819 "Failed to set up arguments for potential constant evaluation");
10820 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10822 APValue ResultScratch;
10823 Evaluate(ResultScratch, Info, E);
10824 return Diags.empty();
10827 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10828 unsigned Type) const {
10829 if (!getType()->isPointerType())
10832 Expr::EvalStatus Status;
10833 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10834 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);