Lines Matching +full:x +full:- +full:tal

1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
20 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
29 // fold a potential constant sub-expression will be indicated by a 'false'
31 // expression is not necessarily non-constant).
33 //===----------------------------------------------------------------------===//
108 if (E->isPRValue())
109 return E->getType();
110 return Ctx.getLValueReferenceType(E->getType());
115 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
116 return DirectCallee->getAttr<AllocSizeAttr>();
117 if (const Decl *IndirectCallee = CE->getCalleeDecl())
118 return IndirectCallee->getAttr<AllocSizeAttr>();
127 if (!E->getType()->isPointerType())
130 E = E->IgnoreParens();
133 // top-level ExprWithCleanups. Ignore them either way.
135 E = FE->getSubExpr()->IgnoreParens();
138 E = Cast->getSubExpr()->IgnoreParens();
149 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
160 // Note that non-type template arguments of class type are emitted as
191 /// Find the path length and type of the most-derived subobject in the given
206 if (Type->isArrayType()) {
208 Type = AT->getElementType();
213 ArraySize = CAT->getZExtSize();
219 } else if (Type->isAnyComplexType()) {
220 const ComplexType *CT = Type->castAs<ComplexType>();
221 Type = CT->getElementType();
226 Type = FD->getType();
243 /// and we cannot perform lvalue-to-rvalue conversions on them.
255 /// Indicator of whether the most-derived object is an array element.
259 /// The length of the path to the most-derived object of which this is a
263 /// The size of the array of which the most-derived object is an element.
264 /// This will always be 0 if the most-derived object is not an array
265 /// element. 0 is not an indicator of whether or not the most-derived object
266 /// is an array, however, because 0-length arrays are allowed.
292 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
349 /// Determine whether this is a one-past-the-end pointer.
355 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
377 return {ArrayIndex, ArraySize - ArrayIndex};
402 // This is a most-derived object.
403 MostDerivedType = CAT->getElementType();
405 MostDerivedArraySize = CAT->getZExtSize();
426 // If this isn't a base class, it's a new most-derived object.
428 MostDerivedType = FD->getType();
438 // This is technically a most-derived object, though in practice this
454 // Can't verify -- trust that the user is doing the right thing (or if
472 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
477 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
485 "bounds check succeeded for out-of-bounds index");
512 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
532 /// Parent - The caller of this stack frame.
535 /// Callee - The function which was called.
538 /// This - The binding for the this pointer in this call, if any.
541 /// CallExpr - The syntactical structure of member function calls
557 /// Temporaries - Temporary lvalues materialized within this stack frame.
560 /// CallRange - The source range of the call expression for this call.
563 /// Index - The call index of this call.
585 // on the overall stack usage of deeply-recursing constexpr evaluations.
590 /// LambdaCaptureFields - Mapping from captured variables/this to
604 if (LB != Temporaries.end() && LB->first == KV)
605 return &LB->second;
612 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
613 return &std::prev(UB)->second;
620 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
621 return std::prev(UB)->first.second;
643 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
644 if (DC->isStdNamespace())
680 return E->getSourceRange().printToString(Ctx.getSourceManager());
708 /// A cleanup, and a flag indicating whether it is lifetime-extended.
728 Loc = VD->getLocation();
730 Loc = E->getExprLoc();
783 /// A dynamically-allocated heap object.
785 /// The value of this heap-allocated object.
802 return NE->isArray() ? ArrayNew : New;
814 /// EvalInfo - This is a private struct used by the evaluator to capture
832 /// EvalStatus - Contains information about the evaluation.
835 /// CurrentCall - The top of the constexpr call stack.
838 /// CallStackDepth - The number of calls in the call stack right now.
841 /// NextCallIndex - The next call index to assign.
844 /// StepsLeft - The remaining number of evaluation steps we're permitted
853 /// BottomFrame - The frame in which evaluation started. This must be
861 /// EvaluatingDecl - This is the declaration whose initializer is being
874 /// EvaluatingDeclValue - This is the value being constructed for the
946 uint64_t ArrayInitIndex = -1;
948 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
981 /// Fold the expression to a constant. Stop if we hit a side-effect that
985 /// Evaluate in any way we know how. Don't worry about side-effects that
1080 while (Frame->Index > CallIndex) {
1081 Frame = Frame->Caller;
1082 --Depth;
1084 if (Frame->Index == CallIndex)
1091 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1094 --StepsLeft;
1104 Result = &It->second;
1111 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1124 Call = Call->Caller) {
1125 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1128 const IdentifierInfo *FnII = MD->getIdentifier();
1129 if (!FnII || !FnII->isStr(FnName))
1133 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1137 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1138 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1139 if (CTSD->isInStdNamespace() && ClassII &&
1140 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1141 TAL[0].getKind() == TemplateArgument::Type)
1142 return {Call->Index, TAL[0].getAsType()};
1149 // Disable the cleanups for lifetime-extended temporaries.
1156 /// cleanups would have had a side-effect, note that as an unmodeled
1157 /// side-effect and return false. Otherwise, return true.
1189 if (!EvalStatus.Diag->empty()) {
1209 /// Should we continue evaluation after encountering a side-effect that we
1227 /// Note that we have had a side-effect, and determine whether we should
1249 /// that we can evaluate past it (such as signed overflow or floating-point
1288 // subexpression implies that a side-effect has potentially happened. We
1322 Info.EvalStatus.Diag->empty() &&
1330 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1332 Info.EvalStatus.Diag->clear();
1338 /// side-effects.
1350 /// RAII object used to optionally suppress diagnostics and side-effects from
1368 Info->EvalStatus = OldStatus;
1369 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1397 /// RAII object wrapping a full-expression or block scope, and handling
1408 Info.CurrentCall->pushTempVersion();
1412 OldStackSize = -1U;
1416 if (OldStackSize != -1U)
1420 Info.CurrentCall->popTempVersion();
1428 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1429 // for a full-expression scope.
1431 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1432 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1433 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1490 << N << /*non-array*/ 1;
1506 --Info.CallStackDepth;
1634 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1664 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1727 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1751 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1786 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1801 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1805 /// Path - The path of base/derived classes from the member declaration's
1815 Expected = Path[Path.size() - 2];
1818 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1830 /// Perform a base-to-derived member pointer cast.
1844 /// Perform a derived-to-base member pointer cast.
1862 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1899 //===----------------------------------------------------------------------===//
1901 //===----------------------------------------------------------------------===//
1910 Int = -Int;
1929 // them to live to the end of the full-expression at runtime, in order to
1931 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1965 Result.first->second.AllocExpr = E;
1966 return &Result.first->second.Value;
1974 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
1977 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
1982 const Expr *Object = MCE->getImplicitObjectArgument();
1983 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
1985 if (Object->getType()->isPointerType())
1986 Out << "->";
1991 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
1997 This->moveInto(Val);
2000 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2003 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2010 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2011 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2018 V->printPretty(Out, Info.Ctx, Param->getType());
2023 Out << "->" << *Callee << '(';
2029 /// Evaluate an expression to see if it had side-effects, and discard its
2033 assert(!E->isValueDependent());
2041 /// Should this call expression be treated as a no-op?
2043 unsigned Builtin = E->getBuiltinCallee();
2062 return VD->hasGlobalStorage();
2075 switch (E->getStmtClass()) {
2080 return CLE->isFileScope() && CLE->isLValue();
2083 // A materialized temporary might have been lifetime-extended to static
2085 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2093 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2102 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2131 return Decl && Decl->isWeak();
2137 QualType Ty = Decl->getType();
2138 if (Ty->isArrayType())
2139 return Ty->isIncompleteType() ||
2140 Decl->getASTContext().getTypeSize(Ty) == 0;
2167 unsigned Idx = PVD->getFunctionScopeIndex();
2168 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2169 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2170 F->Arguments.Version == Base.getVersion() && F->Callee &&
2171 Idx < F->Callee->getNumParams()) {
2172 VD = F->Callee->getParamDecl(Idx);
2179 Info.Note(VD->getLocation(), diag::note_declared_at);
2181 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2185 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2216 bool IsReferenceType = Type->isReferenceType();
2228 int InvalidBaseKind = -1;
2239 Ident = PE->getIdentKindName();
2242 if (InvalidBaseKind != -1) {
2251 FD && FD->isImmediateFunction()) {
2253 << !Type->isAnyPointerType();
2254 Info.Note(FD->getLocation(), diag::note_declared_at);
2267 if (VarD && VarD->isConstexpr()) {
2268 // Non-static local constexpr variables have unintuitive semantics:
2273 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2275 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2298 // Check if this is a thread-local variable.
2299 if (Var->getTLSKind())
2305 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2314 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2315 !Var->hasAttr<CUDAConstantAttr>() &&
2316 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2317 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2318 Var->hasAttr<HIPManagedAttr>())
2325 // Doing otherwise would allow the same id-expression to yield
2334 FD->hasAttr<DLLImportAttr>())
2343 Info.FFDiag(MTE->getExprLoc(),
2349 APValue *V = MTE->getOrCreateValue(false);
2352 Info, MTE->getExprLoc(), TempType, *V, Kind,
2358 // Allow address constant expressions to be past-the-end pointers. This is
2381 /// non-virtual dllimport member function.
2391 if (FD->isImmediateFunction()) {
2393 Info.Note(FD->getLocation(), diag::note_declared_at);
2396 return isForManglingOnly(Kind) || FD->isVirtual() ||
2397 !FD->hasAttr<DLLImportAttr>();
2404 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2409 // are of non-literal class types.
2415 // static const foo_t x = {{0}};
2416 // because "i" is a subobject with non-literal initialization (due to the
2418 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2420 if (This && Info.EvaluatingDecl == This->getLValueBase())
2426 << E->getType();
2442 Info.Note(SubobjectDecl->getLocation(),
2453 if (const AtomicType *AT = Type->getAs<AtomicType>())
2454 Type = AT->getValueType();
2460 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2475 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2479 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2482 for (const CXXBaseSpecifier &BS : CD->bases()) {
2497 for (const auto *I : RD->fields()) {
2498 if (I->isUnnamedBitField())
2501 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2502 Value.getStructField(I->getFieldIndex()), Kind,
2531 if (Type->isVoidType())
2540 /// Check that this evaluated value is fully-initialized and can be loaded by
2541 /// an lvalue-to-rvalue conversion.
2550 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2554 // We can still fold to a constant despite a compile-time memory leak,
2557 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2559 << unsigned(Info.HeapAllocs.size() - 1);
2568 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2573 // We have a non-null base. These are generally known to be true, but if it's
2577 return !Decl || !Decl->isWeak();
2606 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2624 assert(!E->isValueDependent());
2625 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2645 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2662 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2672 // exception state matches the default floating-point environment.
2676 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2701 // - evaluation triggered other FP exception, and
2702 // - exception mode is not "ignore", and
2703 // - the expression being evaluated is not a part of global variable
2732 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2733 if (DestType->isBooleanType())
2750 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2753 // Trying to store a pointer-cast-to-integer into a bitfield.
2763 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2786 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2790 << E->getType() << E->getSourceRange();
2791 return HandleOverflow(Info, E, Value, E->getType());
2821 << E->getRHS()->getSourceRange();
2824 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2829 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2836 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2839 // During constant-folding, a negative shift is an opposite shift. Such
2844 RHS = -RHS;
2850 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2853 << RHS << E->getType() << LHS.getBitWidth();
2857 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2860 // E1 x 2^E2 module 2^N.
2878 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2881 // During constant-folding, a negative shift is an opposite shift. Such a
2886 RHS = -RHS;
2892 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2895 << RHS << E->getType() << LHS.getBitWidth();
2915 /// Perform the given binary floating-point operation, in-place, on LHS.
3020 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3021 // to -1 to make sure that we produce the correct value.
3047 const auto *VT = E->getType()->castAs<VectorType>();
3048 unsigned NumElements = VT->getNumElements();
3049 QualType EltTy = VT->getElementType();
3070 if (EltTy->isIntegerType()) {
3072 EltTy->isUnsignedIntegerType()};
3089 } else if (EltTy->isFloatingType()) {
3124 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3127 if (RD->isInvalidDecl()) return false;
3131 Result.Offset -= Layout.getVBaseClassOffset(Base);
3133 Result.Offset -= Layout.getBaseClassOffset(Base);
3145 if (Derived->isInvalidDecl()) return false;
3149 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3157 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3159 if (!Base->isVirtual())
3166 // Extract most-derived object and corresponding type.
3167 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3172 if (DerivedDecl->isInvalidDecl()) return false;
3181 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3182 PathE = E->path_end();
3184 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3187 Type = (*PathI)->getType();
3198 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3213 if (FD->getParent()->isInvalidDecl()) return false;
3214 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3217 unsigned I = FD->getFieldIndex();
3218 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3227 for (const auto *C : IFD->chain())
3243 if (Type->isVoidType() || Type->isFunctionType()) {
3248 if (Type->isDependentType()) {
3253 if (!Type->isConstantSizeType()) {
3268 /// \param Info - Information about the ongoing evaluation.
3269 /// \param E - The expression being evaluated, for diagnostic purposes.
3270 /// \param LVal - The pointer value to be updated.
3271 /// \param EltTy - The pointee type represented by LVal.
3272 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3277 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3292 /// \param Info - Information about the ongoing evaluation.
3293 /// \param LVal - The lvalue to be updated.
3294 /// \param EltTy - The complex number's component type.
3295 /// \param Imag - False for the real component, true for the imaginary.
3301 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3321 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3325 Result = Frame->getTemporary(VD, Version);
3334 assert(isLambdaCallOperator(Frame->Callee) &&
3335 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3341 Info.FFDiag(E->getBeginLoc(),
3349 // in-flight value.
3359 !Info.CurrentCall->Callee ||
3360 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3372 if (E->isValueDependent())
3378 const Expr *Init = VD->getAnyInitializer(VD);
3390 if (Init->isValueDependent()) {
3391 // The DeclRefExpr is not value-dependent, but the variable it refers to
3392 // has a value-dependent initializer. This should only happen in
3393 // constant-folding cases, where the variable is not actually of a suitable
3395 // have been value-dependent too), so diagnose that.
3396 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3401 << VD << VD->getType();
3409 if (!VD->evaluateValue()) {
3416 // const integral variable or a reference, we might have a non-constant
3424 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3425 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3427 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3434 if (VD->isWeak()) {
3440 Result = VD->getEvaluatedValue();
3448 Base = Base->getCanonicalDecl();
3450 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3451 E = Derived->bases_end(); I != E; ++I, ++Index) {
3452 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3468 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3474 Lit = PE->getFunctionName();
3477 Info.Ctx.getAsConstantArrayType(S->getType());
3479 QualType CharType = CAT->getElementType();
3480 assert(CharType->isIntegerType() && "unexpected character type");
3482 CharType->isUnsignedIntegerType());
3483 if (Index < S->getLength())
3484 Value = S->getCodeUnit(Index);
3496 AllocType.isNull() ? S->getType() : AllocType);
3498 QualType CharType = CAT->getElementType();
3499 assert(CharType->isIntegerType() && "unexpected character type");
3501 unsigned Elts = CAT->getZExtSize();
3503 std::min(S->getLength(), Elts), Elts);
3505 CharType->isUnsignedIntegerType());
3509 Value = S->getCodeUnit(I);
3535 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3539 /// a non-class type.
3542 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3548 if (RD->isUnion())
3549 return !RD->field_empty();
3550 if (RD->isEmpty())
3553 for (auto *Field : RD->fields())
3554 if (!Field->isUnnamedBitField() &&
3555 isReadByLvalueToRvalueConversion(Field->getType()))
3558 for (auto &BaseSpec : RD->bases())
3569 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3573 if (!RD->hasMutableFields())
3576 for (auto *Field : RD->fields()) {
3581 if (Field->isMutable() &&
3582 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3584 Info.Note(Field->getLocation(), diag::note_declared_at);
3588 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3592 for (auto &BaseSpec : RD->bases())
3616 // A temporary lifetime-extended by the variable whose initializer we're
3620 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3625 // [during constant destruction] the lifetime of a and its non-mutable
3630 // FIXME: We can meaningfully extend this to cover non-const objects, but
3634 return T.isConstQualified() || T->isReferenceType();
3643 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3644 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3686 // - A const object is an object of type const T or a non-mutable subobject
3690 // - A volatile object is an object of type const T or a subobject of a
3697 /// Find the designated sub-object of an rvalue.
3724 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3725 (O->isIndeterminate() &&
3729 << handler.AccessKind << O->isIndeterminate()
3730 << E->getSourceRange();
3738 ObjType->isRecordType() &&
3749 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3758 Loc = VolatileField->getLocation();
3762 Loc = VD->getLocation();
3767 Loc = E->getExprLoc();
3782 if (ObjType->isRecordType() &&
3792 // If we modified a bit-field, truncate it to the right width.
3794 LastField && LastField->isBitField() &&
3802 if (ObjType->isArrayType()) {
3807 if (CAT->getSize().ule(Index)) {
3818 ObjType = CAT->getElementType();
3820 if (O->getArrayInitializedElts() > Index)
3821 O = &O->getArrayInitializedElt(Index);
3823 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
3827 O = &O->getArrayInitializedElt(Index);
3829 O = &O->getArrayFiller();
3830 } else if (ObjType->isAnyComplexType()) {
3843 ObjType, ObjType->castAs<ComplexType>()->getElementType());
3845 assert(I == N - 1 && "extracting subobject of scalar?");
3846 if (O->isComplexInt()) {
3847 return handler.found(Index ? O->getComplexIntImag()
3848 : O->getComplexIntReal(), ObjType);
3850 assert(O->isComplexFloat());
3851 return handler.found(Index ? O->getComplexFloatImag()
3852 : O->getComplexFloatReal(), ObjType);
3855 if (Field->isMutable() &&
3859 Info.Note(Field->getLocation(), diag::note_declared_at);
3864 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3865 if (RD->isUnion()) {
3866 const FieldDecl *UnionField = O->getUnionField();
3868 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3869 if (I == N - 1 && handler.AccessKind == AK_Construct) {
3871 O->setUnion(Field, APValue());
3873 // FIXME: If O->getUnionValue() is absent, report that there's no
3882 O = &O->getUnionValue();
3884 O = &O->getStructField(Field->getFieldIndex());
3886 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3888 if (Field->getType().isVolatileQualified())
3892 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3894 O = &O->getStructBase(getBaseIndex(Derived, Base));
3914 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3927 /// Extract the designated sub-object of an rvalue.
3985 /// Update the designated sub-object of an rvalue to the given value.
4003 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4009 if (ObjType->isAnyComplexType())
4010 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4012 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4021 ObjType = FD->getType();
4049 return CommonLength >= A.Entries.size() - IsArray;
4081 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4082 // is not a constant expression (even if the object is non-volatile). We also
4111 APValue &V = GD->getAsAPValue();
4114 << GD->getType();
4117 return CompleteObject(LVal.Base, &V, GD->getType());
4126 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4127 GCD->getType());
4136 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4137 TPO->getType());
4140 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4141 // In C++11, constexpr, non-volatile variables initialized with constant
4143 // parameters are constant expressions even if they're non-const.
4149 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4152 if (!VD || VD->isInvalidDecl()) {
4161 ConstexprVar = VD->isConstexpr();
4179 } else if (VD->isConstexpr()) {
4184 } else if (BaseType->isIntegralOrEnumerationType()) {
4190 Info.Note(VD->getLocation(), diag::note_declared_at);
4199 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4203 // folding of const floating-point types, in order to make static const
4210 Info.Note(VD->getLocation(), diag::note_declared_at);
4215 // Never allow reading a non-const value.
4221 Info.Note(VD->getLocation(), diag::note_declared_at);
4237 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4245 assert(MTE->getStorageDuration() == SD_Static &&
4246 "should have a frame for a non-global materialized temporary");
4250 // - a temporary object of non-volatile const-qualified literal type
4255 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4256 // - a non-volatile glvalue that refers to an object that is usable
4258 // - a non-volatile glvalue of literal type that refers to a
4259 // non-volatile object whose lifetime began within the evaluation
4265 // int x = ++r;
4267 // Therefore we use the C++14-onwards rules in C++11 too.
4271 // corresponding destructor, not even if they're of const-qualified
4273 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4278 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4282 BaseVal = MTE->getOrCreateValue(false);
4297 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4305 // modified in a speculatively-evaluated call.
4321 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4322 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4325 /// \param Info - Information about the ongoing evaluation.
4326 /// \param Conv - The expression for which we are performing the conversion.
4328 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4329 /// case of a non-class type).
4330 /// \param LVal - The glvalue on which we are attempting to perform this action.
4331 /// \param RVal - The produced value will be placed here.
4332 /// \param WantObjectRepresentation - If true, we're looking for the object
4359 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4368 // const-qualified type. If foo and its initializer had elements of type
4375 QualType CLETy = CLE->getType();
4376 if (CLETy->isArrayType() && !Type->isArrayType()) {
4379 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4384 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4387 // Special-case character extraction so we don't have to construct an
4470 << E->getLHS()->getSourceRange();
4483 if (!SubobjType->isVectorType()) {
4494 if (!SubobjType->isIntegerType()) {
4495 // We don't support compound assignment on integer-cast-to-pointer
4509 const FPOptions FPO = E->getFPFeaturesInEffect(
4534 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4535 PointeeType = PT->getPointeeType();
4601 // if we're post-incrementing a complex.
4614 SubobjType->castAs<ComplexType>()->getElementType()
4618 SubobjType->castAs<ComplexType>()->getElementType()
4632 if (!SubobjType->isIntegerType()) {
4633 // We don't support increment / decrement on integer-cast-to-pointer
4642 // doesn't reduce mod 2^n, so special-case it.
4643 if (SubobjType->isBooleanType()) {
4655 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4660 --Value;
4662 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4691 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4692 PointeeType = PT->getPointeeType();
4701 AccessKind == AK_Increment ? 1 : -1))
4729 if (Object->getType()->isPointerType() && Object->isPRValue())
4732 if (Object->isGLValue())
4735 if (Object->getType()->isLiteralType(Info.Ctx))
4738 if (Object->getType()->isRecordType() && Object->isPRValue())
4741 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4745 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4748 /// \param Info - Information about the ongoing evaluation.
4749 /// \param LV - An lvalue referring to the base of the member pointer.
4750 /// \param RHS - The member pointer expression.
4751 /// \param IncludeMember - Specifies whether the member itself is included in
4775 // The end of the derived-to-base path for the base object must match the
4776 // derived-to-base path for the member pointer.
4783 LV.Designator.Entries.size() - MemPtr.Path.size();
4788 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4804 if (const PointerType *PT = LVType->getAs<PointerType>())
4805 LVType = PT->getPointeeType();
4806 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4807 assert(RD && "member pointer access on non-class-type expression");
4810 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4842 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4844 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4847 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4852 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4853 BO->getRHS(), IncludeMember);
4856 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4864 QualType TargetQT = E->getType();
4865 if (const PointerType *PT = TargetQT->getAs<PointerType>())
4866 TargetQT = PT->getPointeeType();
4868 // Check this cast lands within the final derived-to-base subobject path.
4869 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4877 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4878 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4881 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4883 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4884 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4894 /// Get the value to use for a default-initialized object of type T.
4903 if (auto *RD = T->getAsCXXRecordDecl()) {
4904 if (RD->isInvalidDecl()) {
4908 if (RD->isUnion()) {
4912 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4913 std::distance(RD->field_begin(), RD->field_end()));
4916 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4917 End = RD->bases_end();
4920 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
4922 for (const auto *I : RD->fields()) {
4923 if (I->isUnnamedBitField())
4926 I->getType(), Result.getStructField(I->getFieldIndex()));
4932 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4933 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
4936 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4963 if (VD->isInvalidDecl())
4966 if (!VD->hasLocalStorage())
4970 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4973 const Expr *InitE = VD->getInit();
4975 if (VD->getType()->isDependentType())
4977 return handleDefaultInitValue(VD->getType(), Val);
4979 if (InitE->isValueDependent())
4983 // Wipe out any partially-computed value, to allow tracking that this
4999 for (auto *BD : DD->bindings())
5000 if (auto *VD = BD->getHoldingVar())
5007 assert(E->isValueDependent());
5010 assert(E->containsErrors() && "valid value-dependent expression should never "
5018 if (Cond->isValueDependent())
5088 if (const Stmt *Init = SS->getInit()) {
5098 if (SS->getConditionVariable() &&
5099 !EvaluateDecl(Info, SS->getConditionVariable()))
5101 if (SS->getCond()->isValueDependent()) {
5103 EvaluateDependentExpr(SS->getCond(), Info);
5106 if (!EvaluateInteger(SS->getCond(), Value, Info))
5116 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5117 SC = SC->getNextSwitchCase()) {
5124 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5125 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5137 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5152 Info.FFDiag(Found->getBeginLoc(),
5161 // would evaluate one of the following: [C++23] - a control flow that passes
5164 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5165 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5166 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5167 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5182 switch (S->getStmtClass()) {
5209 if (const Stmt *Init = IS->getInit()) {
5222 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5227 if (!IS->getElse())
5230 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5240 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5252 if (const Stmt *Init = FS->getInit()) {
5261 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5264 if (const auto *Inc = FS->getInc()) {
5265 if (Inc->isValueDependent()) {
5281 for (const auto *D : DS->decls()) {
5285 if (VD->hasLocalStorage() && !VD->getInit())
5289 // over, bail out of any immediately-surrounding compound-statement
5301 switch (S->getStmtClass()) {
5304 if (E->isValueDependent()) {
5308 // Don't bother evaluating beyond an expression-statement which couldn't
5319 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5327 for (const auto *D : DS->decls()) {
5331 // Each declaration initialization is its own full-expression.
5342 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5344 if (RetExpr && RetExpr->isValueDependent()) {
5361 for (const auto *BI : CS->body()) {
5381 if (const Stmt *Init = IS->getInit()) {
5390 if (IS->isConsteval()) {
5391 Cond = IS->isNonNegatedConsteval();
5396 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5400 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5416 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5422 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5438 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5443 if (DS->getCond()->isValueDependent()) {
5444 EvaluateDependentExpr(DS->getCond(), Info);
5449 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5459 if (FS->getInit()) {
5460 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5470 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5471 FS->getCond(), Continue))
5476 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5483 if (const auto *Inc = FS->getInc()) {
5484 if (Inc->isValueDependent()) {
5504 // Evaluate the init-statement if present.
5505 if (FS->getInit()) {
5506 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5515 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5522 // In error-recovery cases it's possible to get here even if we failed to
5524 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5528 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5534 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5544 if (FS->getCond()->isValueDependent()) {
5545 EvaluateDependentExpr(FS->getCond(), Info);
5551 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5559 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5567 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5573 if (FS->getInc()->isValueDependent()) {
5574 if (!EvaluateDependentExpr(FS->getInc(), Info))
5578 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5599 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5603 const auto *SS = AS->getSubStmt();
5605 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5610 for (auto *Attr : AS->getAttrs()) {
5615 auto *Assumption = AA->getAssumption();
5616 if (Assumption->isValueDependent())
5619 if (Assumption->HasSideEffects(Info.getCtx()))
5626 Info.CCEDiag(Assumption->getExprLoc(),
5638 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5641 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5645 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5652 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5655 // Value-initialization does not call a trivial default constructor, so such a
5658 if (!CD->isConstexpr() && !IsValueInitialization) {
5660 // FIXME: If DiagDecl is an implicitly-declared special member function,
5664 Info.Note(CD->getLocation(), diag::note_declared_at);
5672 /// CheckConstexprFunction - Check that a function can be called in a constant
5681 Declaration->isConstexpr())
5686 // note the problematic sub-expression.
5687 if (Declaration->isInvalidDecl()) {
5693 // constant expression (prior to C++20). We can still constant-fold such a
5696 cast<CXXMethodDecl>(Declaration)->isVirtual())
5699 if (Definition && Definition->isInvalidDecl()) {
5706 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5707 Definition->hasAttr<MSConstexprAttr>())))
5714 // non-constexpr constructor, diagnose that directly.
5716 if (CD && CD->isInheritingConstructor()) {
5717 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5718 if (!Inherited->isConstexpr())
5722 // FIXME: If DiagDecl is an implicitly-declared special member function
5725 if (CD && CD->isInheritingConstructor())
5727 << CD->getInheritedConstructor().getConstructor()->getParent();
5730 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5731 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5763 // its value to see if it's in-lifetime or what the active union members
5764 // are. We can still check for a one-past-the-end lvalue.
5813 ? Designator.MostDerivedType->getAsCXXRecordDecl()
5814 : getAsBaseClass(Designator.Entries[PathLength - 1]);
5823 // meaningful dynamic type. (We consider objects of non-class type to have no
5829 // shouldn't happen other than in constant-folding situations, since literal
5835 This.Designator.MostDerivedType->getAsCXXRecordDecl();
5836 if (!Class || Class->getNumVBases()) {
5889 unsigned PathLength = DynType->PathLength;
5893 Found->getCorrespondingMethodDeclaredInClass(Class, false);
5903 if (Callee->isPureVirtual()) {
5905 Info.Note(Callee->getLocation(), diag::note_declared_at);
5911 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5912 Found->getReturnType())) {
5913 CovariantAdjustmentPath.push_back(Callee->getReturnType());
5920 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5922 Next->getReturnType(), CovariantAdjustmentPath.back()))
5923 CovariantAdjustmentPath.push_back(Next->getReturnType());
5925 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5927 CovariantAdjustmentPath.push_back(Found->getReturnType());
5931 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5951 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5953 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5969 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5970 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5983 // We can't do anything with a non-symbolic pointer value.
5990 if (Ptr.isNullPointer() && !E->isGLValue())
6004 if (E->getType()->isVoidPointerType())
6005 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6007 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6013 if (!E->isGLValue()) {
6016 Ptr.setNull(Info.Ctx, E->getType());
6022 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6023 DynType->Type->isDerivedFrom(C)))
6025 else if (!Paths || Paths->begin() == Paths->end())
6027 else if (Paths->isAmbiguous(CQT))
6030 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6035 << Info.Ctx.getRecordType(DynType->Type)
6036 << E->getType().getUnqualifiedType();
6044 PathLength >= (int)DynType->PathLength; --PathLength) {
6049 if (PathLength > (int)DynType->PathLength &&
6050 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6059 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6062 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6091 // * All base, non-variant member, and array element subobjects' lifetimes
6095 assert(SubobjType->isUnionType());
6097 // This union member is already active. If it's also in-lifetime, there's
6110 Failed = !handleDefaultInitValue(Field->getType(), Result);
6125 /// Handle a builtin simple-assignment or a call to a trivial assignment
6126 /// operator whose left-hand side might involve a union member access. If it
6140 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6142 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6145 if (!FD || FD->getType()->isReferenceType())
6149 if (FD->getParent()->isUnion()) {
6150 // ... of a non-class, non-array type, or of a class type with a
6154 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6155 if (!RD || RD->hasTrivialDefaultConstructor())
6156 UnionPathLengths.push_back({PathLength - 1, FD});
6159 E = ME->getBase();
6160 --PathLength;
6165 // -- If E is of the form A[B] and is interpreted as a built-in array
6169 auto *Base = ASE->getBase()->IgnoreImplicit();
6170 if (!Base->getType()->isArrayType())
6174 --PathLength;
6177 // Step over a derived-to-base conversion.
6178 E = ICE->getSubExpr();
6179 if (ICE->getCastKind() == CK_NoOp)
6181 if (ICE->getCastKind() != CK_DerivedToBase &&
6182 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6185 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6186 if (Elt->isVirtual()) {
6193 --PathLength;
6194 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6199 // -- Otherwise, S(E) is empty.
6209 // if modification of X [would access an inactive union member], an object
6210 // of the type of X is implicitly created
6212 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6241 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6242 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6248 // undefined behavior, so is non-constant.
6263 if (Callee->hasAttr<NonNullAttr>()) {
6265 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6266 if (!Attr->args_size()) {
6270 for (auto Idx : Attr->args()) {
6279 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6281 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6301 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6311 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6324 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6330 // Skip this for non-union classes with no fields; in that case, the defaulted
6333 if (MD && MD->isDefaulted() &&
6334 (MD->getParent()->isUnion() ||
6335 (MD->isTrivial() &&
6336 isReadByLvalueToRvalueConversion(MD->getParent())))) {
6338 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6340 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6341 MD->getParent()->isUnion()))
6343 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6346 This->moveInto(Result);
6352 // we're inferring constexpr-ness), so we don't have access to them in this
6356 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6363 if (Callee->getReturnType()->isVoidType())
6365 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6375 SourceLocation CallLoc = E->getExprLoc();
6379 const CXXRecordDecl *RD = Definition->getParent();
6380 if (RD->getNumVBases()) {
6388 RD->getNumBases());
6389 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6397 if (Definition->isDelegatingConstructor()) {
6398 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6399 if ((*I)->getInit()->isValueDependent()) {
6400 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6404 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6408 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6414 // ctor-initializers.
6416 // Skip this for empty non-union classes; we should not perform an
6417 // lvalue-to-rvalue conversion on them because their copy constructor does not
6419 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6420 (Definition->getParent()->isUnion() ||
6421 (Definition->isTrivial() &&
6422 isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6423 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6424 Definition->getParent()->isUnion());
6429 if (!RD->isUnion())
6430 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6431 std::distance(RD->field_begin(), RD->field_end()));
6437 if (RD->isInvalidDecl()) return false;
6440 // A scope for temporaries lifetime-extended by reference members.
6446 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6448 CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6452 if (FieldIt == RD->field_end() ||
6453 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6458 // Default-initialize any fields with no explicit initializer.
6460 assert(FieldIt != RD->field_end() && "missing field?");
6461 if (!FieldIt->isUnnamedBitField())
6463 FieldIt->getType(),
6464 Result.getStructField(FieldIt->getFieldIndex()));
6468 for (const auto *I : Definition->inits()) {
6475 if (I->isBaseInitializer()) {
6476 QualType BaseType(I->getBaseClass(), 0);
6478 // Non-virtual base classes are initialized in the order in the class
6480 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6481 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6485 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6486 BaseType->getAsCXXRecordDecl(), &Layout))
6489 } else if ((FD = I->getMember())) {
6490 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6492 if (RD->isUnion()) {
6497 Value = &Result.getStructField(FD->getFieldIndex());
6499 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6502 auto IndirectFieldChain = IFD->chain();
6505 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6507 // preceding zero-initialization, and we're now initializing a union
6510 // specified, since zero-initialization sets all padding bits to zero.
6511 if (!Value->hasValue() ||
6512 (Value->isUnion() && Value->getUnionField() != FD)) {
6513 if (CD->isUnion())
6526 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6528 if (CD->isUnion())
6529 Value = &Value->getUnionValue();
6531 if (C == IndirectFieldChain.front() && !RD->isUnion())
6533 Value = &Value->getStructField(FD->getFieldIndex());
6543 const Expr *Init = I->getInit();
6544 if (Init->isValueDependent()) {
6552 (FD && FD->isBitField() &&
6564 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6568 // Default-initialize any remaining fields.
6569 if (!RD->isUnion()) {
6570 for (; FieldIt != RD->field_end(); ++FieldIt) {
6571 if (!FieldIt->isUnnamedBitField())
6573 FieldIt->getType(),
6574 Result.getStructField(FieldIt->getFieldIndex()));
6581 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6590 CallRef Call = Info.CurrentCall->createCall(Definition);
6605 if (Value.isAbsent() && !T->isNullPtrType()) {
6618 // For arrays, destroy elements right-to-left.
6620 uint64_t Size = CAT->getZExtSize();
6621 QualType ElemT = CAT->getElementType();
6635 expandArray(Value, Value.getArraySize() - 1);
6637 for (; Size != 0; --Size) {
6638 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6639 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6649 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6662 if (RD->getNumVBases()) {
6667 const CXXDestructorDecl *DD = RD->getDestructor();
6668 if (!DD && !RD->hasTrivialDestructor()) {
6673 if (!DD || DD->isTrivial() ||
6674 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6692 const Stmt *Body = DD->getBody(Definition);
6701 unsigned BasesLeft = RD->getNumBases();
6720 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6724 if (RD->isUnion())
6731 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6733 if (FD->isUnnamedBitField())
6740 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6742 FD->getType()))
6750 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6751 --BasesLeft;
6756 BaseType->getAsCXXRecordDecl(), &Layout))
6781 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
6795 /// Perform a destructor or pseudo-destructor call on the given object, which
6808 // If we've had an unmodeled side-effect, we can't rely on mutable state
6828 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6835 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6836 Info.FFDiag(E->getExprLoc(),
6838 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6843 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6846 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6847 EvaluateIgnoredValue(Info, E->getArg(I));
6848 IsNothrow |= E->getType()->isNothrowT();
6852 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6859 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6864 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
6867 Result.setNull(Info.Ctx, E->getType());
6882 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6883 if (CXXDestructorDecl *DD = RD->getDestructor())
6884 return DD->isVirtual();
6889 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6890 if (CXXDestructorDecl *DD = RD->getDestructor())
6891 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6922 if (DeallocKind != (*Alloc)->getKind()) {
6925 << DeallocKind << (*Alloc)->getKind() << AllocType;
6955 Info.FFDiag(E->getExprLoc());
6960 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6962 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6963 EvaluateIgnoredValue(Info, E->getArg(I));
6971 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6982 //===----------------------------------------------------------------------===//
6984 //===----------------------------------------------------------------------===//
6988 // FIXME: We're going to need bit-level granularity when we support
6989 // bit-fields.
7056 if (Ty->isNullPtrType())
7084 Info.FFDiag(BCE->getBeginLoc(),
7097 const RecordDecl *RD = Ty->getAsRecordDecl();
7102 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7103 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7104 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7114 for (FieldDecl *FD : RD->fields()) {
7115 if (FD->isBitField()) {
7116 Info.FFDiag(BCE->getBeginLoc(),
7124 "only bit-fields can have sub-char alignment");
7127 QualType FieldTy = FD->getType();
7138 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7142 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7148 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7156 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7165 const VectorType *VTy = Ty->castAs<VectorType>();
7166 QualType EltTy = VTy->getElementType();
7167 unsigned NElts = VTy->getNumElements();
7169 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7176 Info.FFDiag(BCE->getBeginLoc(),
7183 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7188 Info.FFDiag(BCE->getBeginLoc(),
7194 if (VTy->isExtVectorBoolType()) {
7209 "bool vector element must be 1-bit unsigned integer!");
7211 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7233 if (Ty->isBooleanType()) {
7252 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7254 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7274 Info.FFDiag(BCE->getBeginLoc(),
7281 Info.FFDiag(BCE->getBeginLoc(),
7289 if (T->isNullPtrType()) {
7301 if (T->isRealFloatingType()) {
7315 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7317 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7318 T->isSpecificBuiltinType(BuiltinType::Char_U));
7321 Info.FFDiag(BCE->getExprLoc(),
7333 if (T->isIntegralOrEnumerationType()) {
7334 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7347 if (T->isRealFloatingType()) {
7357 const RecordDecl *RD = RTy->getAsRecordDecl();
7362 NumBases = CXXRD->getNumBases();
7365 std::distance(RD->field_begin(), RD->field_end()));
7369 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7370 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7371 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7383 for (FieldDecl *FD : RD->fields()) {
7384 // FIXME: We don't currently support bit-fields. A lot of the logic for
7386 if (FD->isBitField()) {
7387 Info.FFDiag(BCE->getBeginLoc(),
7398 QualType FieldTy = FD->getType();
7410 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7414 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7421 size_t Size = Ty->getLimitedSize();
7422 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7427 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7437 QualType EltTy = VTy->getElementType();
7438 unsigned NElts = VTy->getNumElements();
7440 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7447 Info.FFDiag(BCE->getBeginLoc(),
7453 if (EltTy->isRealFloatingType() && &Info.Ctx.getFloatTypeSemantics(EltTy) ==
7458 Info.FFDiag(BCE->getBeginLoc(),
7466 if (VTy->isExtVectorBoolType()) {
7487 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7489 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7514 switch (Can->getTypeClass()) {
7521 llvm_unreachable("non-canonical type should be impossible!");
7539 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7551 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7557 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7562 if (Ty->isUnionType())
7564 if (Ty->isPointerType())
7566 if (Ty->isMemberPointerType())
7571 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7573 for (CXXBaseSpecifier &BS : CXXRD->bases())
7578 for (FieldDecl *FD : Record->fields()) {
7579 if (FD->getType()->isReferenceType())
7581 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7583 return note(0, FD->getType(), FD->getBeginLoc());
7587 if (Ty->isArrayType() &&
7599 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7601 BCE->getBeginLoc(),
7602 BCE->getSubExpr()->getType(), Info, Ctx, false);
7610 "no host or target supports non 8-bit chars");
7635 "no host or target supports non 8-bit chars");
7643 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7662 // Check whether a conditional operator with a non-constant condition is a
7673 StmtVisitorTy::Visit(E->getFalseExpr());
7681 StmtVisitorTy::Visit(E->getTrueExpr());
7693 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7699 StmtVisitorTy::Visit(E->getTrueExpr());
7700 StmtVisitorTy::Visit(E->getFalseExpr());
7705 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7721 unsigned BuiltinOp = E->getBuiltinCallee();
7734 Info.FFDiag(E, D) << E->getSourceRange();
7749 const auto It = E->begin();
7754 return StmtVisitorTy::Visit(E->getFunctionName());
7757 if (E->hasAPValueResult())
7758 return DerivedSuccess(E->getAPValueResult(), E);
7760 return StmtVisitorTy::Visit(E->getSubExpr());
7764 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7766 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7768 { return StmtVisitorTy::Visit(E->getSubExpr()); }
7770 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7772 { return StmtVisitorTy::Visit(E->getResultExpr()); }
7774 { return StmtVisitorTy::Visit(E->getReplacement()); }
7777 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7778 return StmtVisitorTy::Visit(E->getExpr());
7783 if (!E->getExpr())
7785 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7786 return StmtVisitorTy::Visit(E->getExpr());
7791 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7797 return StmtVisitorTy::Visit(E->getSubExpr());
7802 return static_cast<Derived*>(this)->VisitCastExpr(E);
7807 return static_cast<Derived*>(this)->VisitCastExpr(E);
7810 return static_cast<Derived*>(this)->VisitCastExpr(E);
7814 switch (E->getOpcode()) {
7819 VisitIgnoredValue(E->getLHS());
7820 return StmtVisitorTy::Visit(E->getRHS());
7828 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7836 return StmtVisitorTy::Visit(E->getSemanticForm());
7843 if (!Evaluate(Info.CurrentCall->createTemporary(
7844 E->getOpaqueValue(),
7845 getStorageType(Info.Ctx, E->getOpaqueValue()),
7847 Info, E->getCommon()))
7857 // side-effects. This is an important GNU extension. See GCC PR38377
7860 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7861 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7866 // FIXME: We should instead treat __builtin_constant_p as non-constant if
7881 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
7882 Value && !Value->isAbsent())
7885 const Expr *Source = E->getSourceExpr();
7896 for (const Expr *SemE : E->semantics()) {
7901 if (SemE == E->getResultExpr())
7906 if (OVE->isUnique())
7910 if (!Evaluate(Info.CurrentCall->createTemporary(
7913 Info, OVE->getSourceExpr()))
7915 } else if (SemE == E->getResultExpr()) {
7937 const Expr *Callee = E->getCallee()->IgnoreParens();
7938 QualType CalleeType = Callee->getType();
7942 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
7948 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7951 // Explicit bound member calls, such as x.f() or p->g();
7952 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7954 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7958 HasQualifier = ME->hasQualifier();
7960 // Indirect bound member calls ('.*' or '->*').
7972 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7973 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7977 } else if (CalleeType->isFunctionPointerType()) {
7996 CalleeType->getPointeeType(), FD->getType())) {
8003 if (OCE && OCE->isAssignmentOp()) {
8005 Call = Info.CurrentCall->createCall(FD);
8008 HasThis = MD->isImplicitObjectMemberFunction();
8018 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8030 if (MD->isInstance())
8037 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8042 } else if (MD && MD->isLambdaStaticInvoker()) {
8045 // being done for the non-static case), since a static member function
8047 const CXXRecordDecl *ClosureClass = MD->getParent();
8049 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8050 "Number of captures must be zero for conversion to function-ptr");
8053 ClosureClass->getLambdaCallOperator();
8059 if (ClosureClass->isGenericLambda()) {
8060 assert(MD->isFunctionTemplateSpecialization() &&
8061 "A generic lambda's static-invoker function must be a "
8063 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
8065 LambdaCallOp->getDescribedFunctionTemplate();
8068 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8076 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8077 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8078 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8093 Call = Info.CurrentCall->createCall(FD);
8101 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8107 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8120 Info.Ctx.getRecordType(DD->getParent())) &&
8125 Stmt *Body = FD->getBody(Definition);
8127 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8128 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8141 return StmtVisitorTy::Visit(E->getInitializer());
8144 if (E->getNumInits() == 0)
8146 if (E->getNumInits() == 1)
8147 return StmtVisitorTy::Visit(E->getInit(0));
8164 assert(!E->isArrow() && "missing call to bound member function?");
8167 if (!Evaluate(Val, Info, E->getBase()))
8170 QualType BaseTy = E->getBase()->getType();
8172 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8174 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8175 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8176 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8192 if (!Evaluate(Val, Info, E->getBase()))
8197 E->getEncodedElementAccess(Indices);
8216 switch (E->getCastKind()) {
8223 // atomic-to-non-atomic conversion implies copying the object
8225 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8232 return StmtVisitorTy::Visit(E->getSubExpr());
8236 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8239 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8240 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8247 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8256 if (!Evaluate(Value, Info, E->getSubExpr()))
8276 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8279 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8280 UO->isIncrementOp(), &RVal))
8286 // We will have checked the full-expressions inside the statement expression
8291 const CompoundStmt *CS = E->getSubStmt();
8292 if (CS->body_empty())
8296 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
8297 BE = CS->body_end();
8302 Info.FFDiag((*BI)->getBeginLoc(),
8306 return this->Visit(FinalExpr) && Scope.destroy();
8313 // FIXME: If the statement-expression terminated due to 'return',
8317 Info.FFDiag((*BI)->getBeginLoc(),
8327 return StmtVisitorTy::Visit(E->getSelectedExpr());
8338 // presence of side-effecting behavior.
8339 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8347 //===----------------------------------------------------------------------===//
8349 //===----------------------------------------------------------------------===//
8366 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8375 Result.setFrom(this->Info.Ctx, V);
8380 // Handle non-static data members.
8383 if (E->isArrow()) {
8384 EvalOK = evaluatePointer(E->getBase(), Result);
8385 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8386 } else if (E->getBase()->isPRValue()) {
8387 assert(E->getBase()->getType()->isRecordType());
8388 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8389 BaseTy = E->getBase()->getType();
8391 EvalOK = this->Visit(E->getBase());
8392 BaseTy = E->getBase()->getType();
8401 const ValueDecl *MD = E->getMemberDecl();
8402 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8403 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8404 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8406 if (!HandleLValueMember(this->Info, E, Result, FD))
8409 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8412 return this->Error(E);
8414 if (MD->getType()->isReferenceType()) {
8416 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8425 switch (E->getOpcode()) {
8431 return HandleMemberPointerAccess(this->Info, E, Result);
8436 switch (E->getCastKind()) {
8442 if (!this->Visit(E->getSubExpr()))
8447 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8454 //===----------------------------------------------------------------------===//
8459 // temporaries (if building with -Wno-address-of-temporary).
8463 // - Declarations
8466 // - Literals
8475 // - typeid(T) expressions, as TypeInfoLValues
8476 // - Locals and temporaries
8482 // CallIndex, for a lifetime-extended temporary.
8486 //===----------------------------------------------------------------------===//
8521 switch (E->getCastKind()) {
8526 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8528 if (!Visit(E->getSubExpr()))
8534 if (!Visit(E->getSubExpr()))
8539 if (!Visit(E->getSubExpr()))
8553 if (MD->isStatic()) {
8554 assert(Info.CurrentCall->This == nullptr &&
8560 if (MD->isExplicitObjectMemberFunction()) {
8562 const ParmVarDecl *Self = MD->getParamDecl(0);
8563 if (Self->getType()->isReferenceType()) {
8564 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8567 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8569 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8571 unsigned Version = Info.CurrentCall->Arguments.Version;
8572 Result.set({VD, Frame->Index, Version});
8575 Result = *Info.CurrentCall->This;
8587 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8598 /// * @selector() expressions in Objective-C
8601 assert(!E->isValueDependent());
8602 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8603 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8608 const NamedDecl *D = E->getDecl();
8615 return Visit(BD->getBinding());
8623 // to within 'E' actually represents a lambda-capture that maps to a
8624 // data-member/field within the closure object, and if so, evaluate to the
8626 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8628 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8629 // We don't always have a complete capture-map when checking or inferring if
8631 // - but we don't need to evaluate the captures to determine constexprness
8636 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8637 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8639 FD->getType()->isReferenceType());
8645 if (VD->hasLocalStorage()) {
8650 // variable) or be ill-formed (and trigger an appropriate evaluation
8653 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8658 if (CurrFrame->Arguments) {
8659 VD = CurrFrame->Arguments.getOrigParam(PVD);
8661 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8662 Version = CurrFrame->Arguments.Version;
8666 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8671 if (!VD->getType()->isReferenceType()) {
8673 Result.set({VD, Frame->Index, Version});
8681 << VD << VD->getType();
8682 Info.Note(VD->getLocation(), diag::note_declared_at);
8688 if (!V->hasValue()) {
8702 switch (E->getBuiltinCallee()) {
8710 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8711 return Visit(E->getArg(0));
8724 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8735 if (E->getStorageDuration() == SD_Static) {
8739 Value = E->getOrCreateValue(true);
8743 Value = &Info.CurrentCall->createTemporary(
8744 E, Inner->getType(),
8745 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8750 QualType Type = Inner->getType();
8760 --I;
8766 Type = Adjustments[I].DerivedToBase.BasePath->getType();
8772 Type = Adjustments[I].Field->getType();
8776 if (!HandleMemberPointerAccess(this->Info, Type, Result,
8779 Type = Adjustments[I].Ptr.MPT->getPointeeType();
8789 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8791 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8799 if (!E->isPotentiallyEvaluated()) {
8800 if (E->isTypeOperand())
8801 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8803 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8807 << E->getExprOperand()->getType()
8808 << E->getExprOperand()->getSourceRange();
8811 if (!Visit(E->getExprOperand()))
8820 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8823 return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8827 return Success(E->getGuidDecl());
8832 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8833 VisitIgnoredBaseExpression(E->getBase());
8838 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8839 if (MD->isStatic()) {
8840 VisitIgnoredBaseExpression(E->getBase());
8845 // Handle non-static data members.
8851 if (E->getBase()->getType()->isVectorType() ||
8852 E->getBase()->getType()->isSveVLSBuiltinType())
8860 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8861 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8870 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8874 return evaluatePointer(E->getSubExpr(), Result);
8878 if (!Visit(E->getSubExpr()))
8880 // __real is a no-op on scalar lvalues.
8881 if (E->getSubExpr()->getType()->isAnyComplexType())
8882 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8887 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8889 if (!Visit(E->getSubExpr()))
8891 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8899 if (!this->Visit(UO->getSubExpr()))
8903 this->Info, UO, Result, UO->getSubExpr()->getType(),
8904 UO->isIncrementOp(), nullptr);
8916 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8923 if (!this->Visit(CAO->getLHS()) || !Success)
8927 this->Info, CAO,
8928 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8929 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8940 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8946 if (!this->Visit(E->getLHS()) || !Success)
8950 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8953 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8957 //===----------------------------------------------------------------------===//
8959 //===----------------------------------------------------------------------===//
8972 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8973 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8975 if (Call->getNumArgs() <= SizeArgNo)
8980 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8990 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8993 if (!AllocSize->getNumElemsParam().isValid()) {
8999 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9000 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9036 // variables (in the latter case, use-before-assign isn't UB; in the former,
9040 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9043 const Expr *Init = VD->getAnyInitializer();
9044 if (!Init || Init->getType().isNull())
9047 const Expr *E = Init->IgnoreParens();
9055 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9091 Result.setNull(Info.Ctx, E->getType());
9101 if (E->isExpressibleAsConstantInitializer())
9104 EvaluateIgnoredValue(Info, E->getSubExpr());
9112 if (!E->getBlockDecl()->hasCaptures())
9119 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9129 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9131 if (!Info.CurrentCall->This) {
9136 Result = *Info.CurrentCall->This;
9139 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9144 if (!Info.CurrentCall->LambdaThisCaptureField) {
9145 if (IsExplicitLambda && !Info.CurrentCall->This) {
9153 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9155 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9156 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9164 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9165 APValue LValResult = E->EvaluateInContext(
9166 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9177 std::string ResultStr = E->ComputeName(Info.Ctx);
9187 /*Pascal*/ false, ArrayTy, E->getLocation());
9200 assert(!E->isValueDependent());
9201 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9206 if (E->getOpcode() != BO_Add &&
9207 E->getOpcode() != BO_Sub)
9210 const Expr *PExp = E->getLHS();
9211 const Expr *IExp = E->getRHS();
9212 if (IExp->getType()->isPointerType())
9223 if (E->getOpcode() == BO_Sub)
9226 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9231 return evaluateLValue(E->getSubExpr(), Result);
9238 const IdentifierInfo *FnII = FD->getIdentifier();
9239 if (!FnII || !FnII->isStr("current"))
9242 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9246 const IdentifierInfo *ClassII = RD->getIdentifier();
9247 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9251 const Expr *SubExpr = E->getSubExpr();
9253 switch (E->getCastKind()) {
9266 if (!E->getType()->isVoidPointerType()) {
9275 E->getType()->getPointeeType()));
9278 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9279 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9285 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9289 if (SubExpr->getType()->isVoidPointerType() &&
9293 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9295 << E->getType()->getPointeeType();
9298 << 3 << SubExpr->getType();
9305 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9311 if (!evaluatePointer(E->getSubExpr(), Result))
9318 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9319 castAs<PointerType>()->getPointeeType(),
9323 if (!Visit(E->getSubExpr()))
9330 if (!Visit(E->getSubExpr()))
9335 VisitIgnoredValue(E->getSubExpr());
9347 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9370 if (SubExpr->isGLValue()) {
9374 APValue &Value = Info.CurrentCall->createTemporary(
9375 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9380 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9384 Result.addUnsizedArray(Info, E, AT->getElementType());
9393 if (!evaluateLValue(E->getSubExpr(), LVal))
9397 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9398 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9432 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9437 E = E->IgnoreParens();
9439 // The kinds of expressions that we have special-case logic here for
9446 return Info.Ctx.getDeclAlign(DRE->getDecl(),
9450 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
9453 return GetAlignOfType(Info, E->getType(), ExprKind);
9475 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9501 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9509 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9515 return T->isCharType() || T->isChar8Type();
9527 return evaluateLValue(E->getArg(0), Result);
9531 // behavior is non-constant.
9532 if (!evaluatePointer(E->getArg(0), Result))
9537 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9542 if (E->getNumArgs() > 2) {
9544 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9547 int64_t AdditionalOffset = -Offset.getZExtValue();
9558 CCEDiag(E->getArg(0),
9571 ? CCEDiag(E->getArg(0),
9573 : CCEDiag(E->getArg(0),
9584 if (!evaluatePointer(E->getArg(0), Result))
9587 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9597 // The alignment could be greater than the minimum at run-time, so we cannot
9604 "Cannot handle > 64-bit address-space");
9610 Result.adjustOffset(NewOffset - Result.Offset);
9611 // TODO: diagnose out-of-bounds values/only allow for arrays?
9614 // Otherwise, we cannot constant-evaluate the result.
9615 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9622 return evaluatePointer(E->getArg(0), Result);
9639 if (!Visit(E->getArg(0)))
9642 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9644 uint64_t MaxLength = uint64_t(-1);
9650 if (!EvaluateInteger(E->getArg(2), N, Info))
9665 CharTy, E->getArg(0)->getType()->getPointeeType()));
9667 if (IsRawByte && CharTy->isIncompleteType()) {
9671 // Give up on byte-oriented matching against multibyte elements.
9689 E->getArg(1)->getType(),
9715 for (; MaxLength; --MaxLength) {
9756 if (!Visit(E->getArg(0)))
9761 if (!EvaluatePointer(E->getArg(1), Src, Info))
9765 if (!EvaluateInteger(E->getArg(2), N, Info))
9769 // If the size is zero, we treat this as always being a valid no-op.
9782 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9789 // trivially-copyable type. (For the wide version, the designator will be
9798 if (T->isIncompleteType()) {
9842 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9849 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9850 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9852 Direction = -1;
9854 SrcOffset - DestOffset < NBytes) {
9864 // char-like type?
9870 if (--NElems == 0)
9899 FunctionDecl *OperatorNew = E->getOperatorNew();
9903 if (OperatorNew->isReservedGlobalPlacementOperator() &&
9904 Info.CurrentCall->isStdFunction() && !E->isArray()) {
9906 assert(E->getNumPlacementArgs() == 1);
9907 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9912 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9916 } else if (E->getNumPlacementArgs()) {
9917 // The only new-placement list we support is of the form (std::nothrow).
9922 // new (std::align_val_t{N}) X(int)
9926 // alignof(X) and X has new-extended alignment).
9927 if (E->getNumPlacementArgs() != 1 ||
9928 !E->getPlacementArg(0)->getType()->isNothrowT())
9932 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9937 const Expr *Init = E->getInitializer();
9942 QualType AllocType = E->getAllocatedType();
9943 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
9946 Stripped = ICE->getSubExpr())
9947 if (ICE->getCastKind() != CK_NoOp &&
9948 ICE->getCastKind() != CK_IntegralCast)
9957 // -- [...] its value before converting to size_t [or] applying the
9964 << ArrayBound << (*ArraySize)->getSourceRange();
9968 // -- its value is such that the size of the allocated object would
9969 // exceed the implementation-defined limit
9970 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
9979 // -- the new-initializer is a braced-init-list and the number of
9990 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9994 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
9995 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10004 << (*ArraySize)->getSourceRange();
10017 assert(!AllocType->isArrayType() &&
10018 "array allocation with non-array new");
10093 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10098 //===----------------------------------------------------------------------===//
10100 //===----------------------------------------------------------------------===//
10131 assert(!E->isValueDependent());
10132 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10137 switch (E->getCastKind()) {
10142 VisitIgnoredValue(E->getSubExpr());
10146 if (!Visit(E->getSubExpr()))
10148 if (E->path_empty())
10150 // Base-to-derived member pointer casts store the path in derived-to-base
10152 // the wrong end of the derived->base arc, so stagger the path by one class.
10154 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10156 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10157 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10161 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10162 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10168 if (!Visit(E->getSubExpr()))
10170 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10171 PathE = E->path_end(); PathI != PathE; ++PathI) {
10172 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10173 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10184 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10187 //===----------------------------------------------------------------------===//
10189 //===----------------------------------------------------------------------===//
10206 return ZeroInitialization(E, E->getType());
10216 return VisitCXXConstructExpr(E, E->getType());
10229 /// Perform zero-initialization on an object of non-union class type.
10231 /// To zero-initialize an object or reference of type T means:
10233 /// -- if T is a (possibly cv-qualified) non-union class type,
10234 /// each non-static data member and each base-class subobject is
10235 /// zero-initialized
10239 assert(!RD->isUnion() && "Expected non-union class type");
10241 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10242 std::distance(RD->field_begin(), RD->field_end()));
10244 if (RD->isInvalidDecl()) return false;
10249 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
10250 End = CD->bases_end(); I != End; ++I, ++Index) {
10251 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10261 for (const auto *I : RD->fields()) {
10262 // -- if T is a reference type, no initialization is performed.
10263 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10270 ImplicitValueInitExpr VIE(I->getType());
10272 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10280 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10281 if (RD->isInvalidDecl()) return false;
10282 if (RD->isUnion()) {
10283 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10284 // object's first non-static named data member is zero-initialized
10285 RecordDecl::field_iterator I = RD->field_begin();
10286 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10288 if (I == RD->field_end()) {
10297 ImplicitValueInitExpr VIE(I->getType());
10301 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10310 switch (E->getCastKind()) {
10315 return Visit(E->getSubExpr());
10320 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10323 return Error(E->getSubExpr());
10325 // Derived-to-base rvalue conversion: just slice off the derived part.
10327 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10328 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10329 PathE = E->path_end(); PathI != PathE; ++PathI) {
10330 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10331 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10332 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10342 if (E->isTransparent())
10343 return Visit(E->getInit(0));
10344 return VisitCXXParenListOrInitListExpr(E, E->inits());
10350 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10351 if (RD->isInvalidDecl()) return false;
10358 CXXRD && CXXRD->getNumBases());
10360 if (RD->isUnion()) {
10363 Field = ILE->getInitializedFieldInUnion();
10365 Field = PLIE->getInitializedFieldInUnion();
10376 // first element of the union is value-initialized.
10380 ImplicitValueInitExpr VIE(Field->getType());
10392 if (Field->isBitField())
10402 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10403 std::distance(RD->field_begin(), RD->field_end()));
10408 if (CXXRD && CXXRD->getNumBases()) {
10409 for (const auto &Base : CXXRD->bases()) {
10430 for (const auto *Field : RD->fields()) {
10431 // Anonymous bit-fields are not considered members of the class for
10433 if (Field->isUnnamedBitField())
10446 // Perform an implicit value-initialization for members beyond the end of
10448 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10451 if (Field->getType()->isIncompleteArrayType()) {
10452 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10453 if (!CAT->isZeroSize()) {
10466 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10468 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10485 const CXXConstructorDecl *FD = E->getConstructor();
10486 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10488 bool ZeroInit = E->requiresZeroInitialization();
10489 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10490 // If we've already performed zero-initialization, we're already done.
10501 auto Body = FD->getBody(Definition);
10503 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10507 if (E->isElidable() && !ZeroInit) {
10513 const Expr *SrcObj = E->getArg(0);
10514 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10515 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10518 return Visit(ME->getSubExpr());
10524 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10537 const CXXConstructorDecl *FD = E->getConstructor();
10538 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10542 auto Body = FD->getBody(Definition);
10544 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10547 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10555 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10558 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10570 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10571 RecordDecl::field_iterator Field = Record->field_begin();
10572 assert(Field != Record->field_end() &&
10573 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10574 ArrayType->getElementType()) &&
10577 assert(Field != Record->field_end() &&
10580 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10582 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10585 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10586 ArrayType->getElementType()) &&
10589 ArrayType->getElementType(),
10590 ArrayType->getZExtSize()))
10595 assert(++Field == Record->field_end() &&
10602 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10603 if (ClosureClass->isInvalidDecl())
10607 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10609 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10610 E->capture_init_end()) &&
10617 auto *CaptureInitIt = E->capture_init_begin();
10620 for (const auto *Field : ClosureClass->fields()) {
10621 assert(CaptureInitIt != E->capture_init_end());
10635 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10647 assert(!E->isValueDependent());
10648 assert(E->isPRValue() && E->getType()->isRecordType() &&
10653 //===----------------------------------------------------------------------===//
10657 // lvalues. The full-object of which the temporary is a subobject is implicitly
10659 //===----------------------------------------------------------------------===//
10669 APValue &Value = Info.CurrentCall->createTemporary(
10670 E, E->getType(), ScopeKind::FullExpression, Result);
10675 switch (E->getCastKind()) {
10680 return VisitConstructExpr(E->getSubExpr());
10703 assert(!E->isValueDependent());
10704 assert(E->isPRValue() && E->getType()->isRecordType());
10708 //===----------------------------------------------------------------------===//
10710 //===----------------------------------------------------------------------===//
10722 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10735 { return Visit(E->getSubExpr()); }
10750 assert(E->isPRValue() && E->getType()->isVectorType() &&
10756 const VectorType *VTy = E->getType()->castAs<VectorType>();
10757 unsigned NElts = VTy->getNumElements();
10759 const Expr *SE = E->getSubExpr();
10760 QualType SETy = SE->getType();
10762 switch (E->getCastKind()) {
10765 if (SETy->isIntegerType()) {
10770 } else if (SETy->isRealFloatingType()) {
10808 const VectorType *VT = E->getType()->castAs<VectorType>();
10809 unsigned NumInits = E->getNumInits();
10810 unsigned NumElements = VT->getNumElements();
10812 QualType EltTy = VT->getElementType();
10823 && E->getInit(CountInits)->getType()->isVectorType()) {
10825 if (!EvaluateVector(E->getInit(CountInits), v, Info))
10831 } else if (EltTy->isIntegerType()) {
10834 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10843 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10857 const auto *VT = E->getType()->castAs<VectorType>();
10858 QualType EltTy = VT->getElementType();
10860 if (EltTy->isIntegerType())
10866 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10871 VisitIgnoredValue(E->getSubExpr());
10876 BinaryOperatorKind Op = E->getOpcode();
10883 Expr *LHS = E->getLHS();
10884 Expr *RHS = E->getRHS();
10886 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10890 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10891 E->getType()->castAs<VectorType>()->getNumElements() &&
10892 RHS->getType()->castAs<VectorType>()->getNumElements() ==
10893 E->getType()->castAs<VectorType>()->getNumElements() &&
10937 // operator ! on vectors returns -1 for 'truth', so negate it.
10943 // Float types result in an int of the same size, but -1 for true, or 0 for
10946 ResultTy->isUnsignedIntegerType()};
10961 Expr *SubExpr = E->getSubExpr();
10962 const auto *VD = SubExpr->getType()->castAs<VectorType>();
10966 const QualType ResultEltTy = VD->getElementType();
10967 UnaryOperatorKind Op = E->getOpcode();
10982 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
10986 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11000 if (SourceTy->isIntegerType()) {
11001 if (DestTy->isRealFloatingType()) {
11006 if (DestTy->isIntegerType()) {
11011 } else if (SourceTy->isRealFloatingType()) {
11012 if (DestTy->isRealFloatingType()) {
11017 if (DestTy->isIntegerType()) {
11031 QualType SourceVecType = E->getSrcExpr()->getType();
11032 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11035 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11036 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11038 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11061 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11063 // The spec says that -1 should be treated as undef for optimizations,
11065 // which is prohibited from being a top-level constant value. Emit a
11067 if (index == -1) {
11079 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11087 const Expr *Vec1 = E->getExpr(0);
11091 const Expr *Vec2 = E->getExpr(1);
11095 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11096 QualType DestElTy = DestVecTy->getElementType();
11098 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11112 //===----------------------------------------------------------------------===//
11114 //===----------------------------------------------------------------------===//
11134 Info.Ctx.getAsConstantArrayType(E->getType());
11136 if (E->getType()->isIncompleteArrayType()) {
11137 // We can be asked to zero-initialize a flexible array member; this
11147 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11151 // Zero-initialize all elements.
11154 ImplicitValueInitExpr VIE(CAT->getElementType());
11183 assert(!E->isValueDependent());
11184 assert(E->isPRValue() && E->getType()->isArrayType() &&
11192 assert(!ILE->isValueDependent());
11193 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11203 assert(!CCE->isValueDependent());
11204 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11212 // For now, just allow non-class value-initialization and initialization
11217 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11218 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11222 if (ILE->hasArrayFiller() &&
11223 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11234 AllocType.isNull() ? E->getType() : AllocType);
11239 // an appropriately-typed string literal enclosed in braces.
11240 if (E->isStringLiteralInit()) {
11241 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11250 assert(!E->isTransparent() &&
11253 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11261 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11266 "zero-initialized array shouldn't have any initialized elts");
11272 unsigned NumElts = CAT->getZExtSize();
11281 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11282 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11293 // If the array was previously zero-initialized, preserve the
11294 // zero-initialized values.
11308 CAT->getElementType(), 1)) {
11316 QualType DestTy = CAT->getElementType();
11317 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11322 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11323 StringLiteral *SL = EmbedS->getDataStringLiteral();
11324 for (unsigned I = EmbedS->getStartingElementPos(),
11325 N = EmbedS->getDataElementCount();
11326 I != EmbedS->getStartingElementPos() + N; ++I) {
11327 Value = SL->getCodeUnit(I);
11328 if (DestTy->isIntegerType()) {
11331 assert(DestTy->isFloatingType() && "unexpected type");
11333 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11335 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11362 if (E->getCommonExpr() &&
11363 !Evaluate(Info.CurrentCall->createTemporary(
11364 E->getCommonExpr(),
11365 getStorageType(Info.Ctx, E->getCommonExpr()),
11367 Info, E->getCommonExpr()->getSourceExpr()))
11370 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11372 uint64_t Elements = CAT->getZExtSize();
11382 // point than the end of the full-expression. [...] The second context is
11391 Info, Subobject, E->getSubExpr()) ||
11393 CAT->getElementType(), 1)) {
11407 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11414 bool HadZeroInit = Value->hasValue();
11417 unsigned FinalSize = CAT->getZExtSize();
11419 // Preserve the array filler if we had prior zero-initialization.
11421 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11429 Info, E->getExprLoc(), E->getConstructor(),
11430 E->requiresZeroInitialization());
11439 unsigned OldElts = Value->getArrayInitializedElts();
11447 Value->getArrayInitializedElt(I));
11448 Value->swap(NewValue);
11452 Value->getArrayInitializedElt(I) = Filler;
11457 APValue &FirstResult = Value->getArrayInitializedElt(0);
11459 Value->getArrayInitializedElt(I) = FirstResult;
11463 &Value->getArrayInitializedElt(I),
11464 CAT->getElementType()) ||
11466 CAT->getElementType(), 1))
11470 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11480 if (!Type->isRecordType())
11489 assert(E->getType()->isConstantArrayType() &&
11492 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11493 E->getArrayFiller());
11496 //===----------------------------------------------------------------------===//
11499 // As a GNU extension, we support casting pointers to sufficiently-wide integer
11501 // either as an integer-valued APValue, or as an lvalue-valued APValue.
11502 //===----------------------------------------------------------------------===//
11513 assert(E->getType()->isIntegralOrEnumerationType() &&
11515 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11517 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11527 assert(E->getType()->isIntegralOrEnumerationType() &&
11529 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11533 E->getType()->isUnsignedIntegerOrEnumerationType());
11541 assert(E->getType()->isIntegralOrEnumerationType() &&
11543 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11564 //===--------------------------------------------------------------------===//
11566 //===--------------------------------------------------------------------===//
11569 return Success(E->getValue(), E);
11572 return Success(E->getValue(), E);
11577 if (CheckReferencedDecl(E, E->getDecl()))
11583 if (CheckReferencedDecl(E, E->getMemberDecl())) {
11584 VisitIgnoredBaseExpression(E->getBase());
11601 return Success(E->getValue(), E);
11605 return Success(E->getValue(), E);
11609 if (Info.ArrayInitIndex == uint64_t(-1)) {
11624 return Success(E->getValue(), E);
11628 return Success(E->getValue(), E);
11632 return Success(E->getValue(), E);
11656 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11661 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
11669 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
11670 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11680 //===--------------------------------------------------------------------===//
11682 //===--------------------------------------------------------------------===//
11685 return Success(E->getValue(), E);
11694 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
11698 /// pointer-sized integral types. We support this by allowing the evaluation of
11704 assert(!E->isValueDependent());
11705 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
11710 assert(!E->isValueDependent());
11725 APValue Evaluated = E->EvaluateInContext(
11726 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
11732 assert(!E->isValueDependent());
11733 if (E->getType()->isFixedPointType()) {
11748 assert(!E->isValueDependent());
11749 if (E->getType()->isIntegerType()) {
11750 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
11756 } else if (E->getType()->isFixedPointType()) {
11769 bool SameSign = (ECD->getInitVal().isSigned()
11770 == E->getType()->isSignedIntegerOrEnumerationType());
11771 bool SameWidth = (ECD->getInitVal().getBitWidth()
11772 == Info.Ctx.getIntWidth(E->getType()));
11774 return Success(ECD->getInitVal(), E);
11778 llvm::APSInt Val = ECD->getInitVal();
11780 Val.setIsSigned(!ECD->getInitVal().isSigned());
11782 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
11789 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11793 assert(!T->isDependentType() && "unexpected dependent type");
11797 switch (CanTy->getTypeClass()) {
11805 llvm_unreachable("unexpected non-canonical or dependent type");
11808 switch (cast<BuiltinType>(CanTy)->getKind()) {
11898 return CanTy->isMemberDataPointerType()
11906 return CanTy->isUnionType() ? GCCTypeClass::Union
11912 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11939 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11945 if (E->getNumArgs() == 0)
11951 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11954 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11978 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11981 // This evaluation is not permitted to have side-effects, so evaluate it in
11985 // Constant-folding is always enabled for the operand of __builtin_constant_p
11987 // language-specific constant expression).
11990 QualType ArgType = Arg->getType();
11995 // - If the operand is of integral, floating, complex or enumeration type,
11997 // - If the operand can be folded to a pointer to the first character
12006 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12007 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12008 ArgType->isNullPtrType()) {
12032 return VD->getType();
12035 return E->getType();
12045 /// A more selective version of E->IgnoreParenCasts for
12052 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12054 const Expr *NoParens = E->IgnoreParens();
12061 auto CastKind = Cast->getCastKind();
12066 const auto *SubExpr = Cast->getSubExpr();
12067 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12091 const RecordDecl *Parent = FD->getParent();
12092 Invalid = Parent->isInvalidDecl();
12093 if (Invalid || Parent->isUnion())
12096 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12101 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12105 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12106 for (auto *FD : IFD->chain()) {
12120 if (BaseType->isIncompleteArrayType())
12121 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12123 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12128 if (BaseType->isArrayType()) {
12135 if (Index + 1 != CAT->getZExtSize())
12137 BaseType = CAT->getElementType();
12138 } else if (BaseType->isAnyComplexType()) {
12139 const auto *CT = BaseType->castAs<ComplexType>();
12143 BaseType = CT->getElementType();
12148 BaseType = FD->getType();
12157 /// Tests to see if the LValue has a user-specified designator (that isn't
12182 // - Users can only write off of the end when we have an invalid base. Invalid
12184 // - We used to be a bit more aggressive here; we'd only be conservative if
12235 if (!T.isNull() && T->isStructureType() &&
12236 T->getAsStructureType()->getDecl()->hasFlexibleArrayMember())
12239 if (VD->hasInit())
12240 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12243 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12255 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12262 // upper-bound.
12289 // strcpy(&F->c[0], Bar);
12301 // given an accurate upper-bound. However, we are still able to give
12302 // conservative lower-bounds for Type=3.
12312 // denoted by the pointer. But that's not quite right -- what we actually
12313 // want is the size of the immediately-enclosing array, if there is one.
12319 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12331 /// If @p WasError is non-null, this will report whether the failure to evaluate
12338 // The operand of __builtin_object_size is never evaluated for side-effects.
12339 // If there are any, but we can determine the pointed-to object anyway, then
12340 // ignore the side-effects.
12344 if (E->isGLValue()) {
12364 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12372 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12379 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12384 QualType SrcTy = E->getArg(0)->getType();
12385 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12389 if (SrcTy->isPointerType()) {
12391 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12394 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12395 Info.FFDiag(E->getArg(0));
12399 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12419 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12423 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12426 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12427 return Success((Type & 2) ? 0 : -1, E);
12439 return Success((Type & 2) ? 0 : -1, E);
12471 // the run-time value can never be aligned.
12478 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12483 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12493 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12506 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12516 if (!EvaluateInteger(E->getArg(0), Val, Info))
12526 if (!EvaluateInteger(E->getArg(0), Val, Info))
12539 if (!EvaluateInteger(E->getArg(0), Val, Info))
12542 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12550 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
12554 if (!EvaluateInteger(E->getArg(0), Val, Info))
12558 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
12560 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12570 // whereas for Microsoft intrinsics, the result is the bit-width of the
12584 const Expr *Arg = E->getArg(0);
12587 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
12589 // of side-effects in order to avoid -Wunsequenced false-positives in
12598 const auto *Callee = Info.CurrentCall->getCallee();
12601 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
12602 Callee->getIdentifier() &&
12603 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
12607 ? E->getExprLoc()
12608 : Info.CurrentCall->getCallRange().getBegin(),
12623 if (!EvaluateInteger(E->getArg(0), Val, Info))
12627 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
12629 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
12645 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12652 return Visit(E->getArg(0));
12656 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
12657 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
12665 if (!EvaluateInteger(E->getArg(0), Val, Info))
12674 if (!EvaluateFloat(E->getArg(5), Val, Info))
12683 return Visit(E->getArg(Arg));
12688 return EvaluateFloat(E->getArg(0), Val, Info) &&
12689 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
12694 return EvaluateFloat(E->getArg(0), Val, Info) &&
12700 return EvaluateFloat(E->getArg(0), Val, Info) &&
12706 return EvaluateFloat(E->getArg(0), Val, Info) &&
12712 return EvaluateFloat(E->getArg(0), Val, Info) &&
12718 return EvaluateFloat(E->getArg(0), Val, Info) &&
12724 return EvaluateFloat(E->getArg(0), Val, Info) &&
12730 return EvaluateFloat(E->getArg(0), Val, Info) &&
12736 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
12740 return EvaluateFloat(E->getArg(0), Val, Info) &&
12748 if (!EvaluateInteger(E->getArg(0), Val, Info))
12762 if (!EvaluateInteger(E->getArg(0), Val, Info))
12778 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12779 !EvaluateInteger(E->getArg(1), Amt, Info))
12795 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
12796 !EvaluateInteger(E->getArg(1), Amt, Info))
12817 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
12845 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
12846 !EvaluatePointer(E->getArg(1), String2, Info))
12849 uint64_t MaxLength = uint64_t(-1);
12855 if (!EvaluateInteger(E->getArg(2), N, Info))
12879 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
12916 for (; MaxLength; --MaxLength) {
12922 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
12924 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
12940 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
12945 // is lock-free. If the size isn't a power of two, or greater than the
12946 // maximum alignment where we promote atomics, we know it is not lock-free
12948 // the answer can only be determined at runtime; for example, 16-byte
12949 // atomics have lock-free implementations on some, but not all,
12950 // x86-64 processors.
12952 // Check power-of-two.
12963 // If the pointer argument can be evaluated to a compile-time constant
12965 const Expr *PtrArg = E->getArg(1);
12968 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
12969 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
12976 // Drop the potential implicit-cast to 'const volatile void*', getting
12978 if (ICE->getCastKind() == CK_BitCast)
12979 PtrArg = ICE->getSubExpr();
12982 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
12983 QualType PointeeType = PtrTy->getPointeeType();
12984 if (!PointeeType->isIncompleteType() &&
13008 QualType ResultType = E->getArg(0)->getType();
13009 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13010 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13011 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13012 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13073 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13074 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13075 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13076 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13087 ResultType->isSignedIntegerOrEnumerationType();
13089 ResultType->isSignedIntegerOrEnumerationType();
13098 // caught in the shrink-to-result later anyway.
13151 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13154 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13184 // A pointer to an incomplete type might be past-the-end if the type's size is
13187 if (Ty->isIncompleteType())
13194 // We're a past-the-end pointer if we point to the byte after the object,
13252 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13253 (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
13254 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13255 E->getRHS()->getType()->isIntegralOrEnumerationType());
13304 E = E->IgnoreParens();
13316 if (E->getOpcode() == BO_Comma) {
13323 if (E->isLogicalOp()) {
13327 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
13328 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
13341 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13349 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13350 E->getRHS()->getType()->isIntegralOrEnumerationType());
13361 // FIXME: When compiling for a 32-bit target, we should use 32-bit
13367 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
13374 if (E->getOpcode() == BO_Comma) {
13381 if (E->isLogicalOp()) {
13388 if (E->getOpcode() == BO_LOr)
13396 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
13397 if (rhsResult == (E->getOpcode() == BO_LOr))
13405 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13406 E->getRHS()->getType()->isIntegralOrEnumerationType());
13415 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
13417 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
13422 if (E->getOpcode() == BO_Add &&
13429 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
13430 // Handle (intptr_t)&&A - (intptr_t)&&B.
13443 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13444 RHSAddrExpr->getLabel()->getDeclContext())
13457 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
13458 E->getType()->isUnsignedIntegerOrEnumerationType());
13459 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
13473 enqueue(Bop->getLHS());
13494 enqueue(Bop->getRHS());
13525 assert(!E->isValueDependent());
13526 assert(E->isComparisonOp() && "expected comparison operator");
13527 assert((E->getOpcode() == BO_Cmp ||
13528 E->getType()->isIntegralOrEnumerationType()) &&
13535 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
13536 bool IsEquality = E->isEqualityOp();
13538 QualType LHSTy = E->getLHS()->getType();
13539 QualType RHSTy = E->getRHS()->getType();
13541 if (LHSTy->isIntegralOrEnumerationType() &&
13542 RHSTy->isIntegralOrEnumerationType()) {
13544 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
13547 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
13556 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
13560 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
13563 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
13572 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
13575 if (E->isAssignmentOp()) {
13577 EvaluateLValue(E->getLHS(), LV, Info);
13579 } else if (LHSTy->isRealFloatingType()) {
13580 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
13586 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
13591 if (E->getRHS()->getType()->isRealFloatingType()) {
13592 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
13596 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13614 if (LHSTy->isRealFloatingType() &&
13615 RHSTy->isRealFloatingType()) {
13618 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
13622 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
13625 assert(E->isComparisonOp() && "Invalid binary operator!");
13629 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
13650 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
13653 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13657 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13660 // Reject differing bases from the normal codepath; we special-case
13664 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
13665 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
13684 // It's implementation-defined whether distinct literals will have
13687 // that the address of a literal will be non-null.
13697 // past-the-end address of another object, per C++ DR1652.
13728 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
13732 // - If two pointers point to non-static data members of the same object,
13738 // - Otherwise pointer comparisons are unspecified.
13745 // - we are comparing array indices
13746 // - we are comparing fields of a union, or fields with the same access
13758 << RF->getParent() << RF;
13762 << LF->getParent() << LF;
13763 else if (!LF->getParent()->isUnion() &&
13764 LF->getAccess() != RF->getAccess())
13767 << LF << LF->getAccess() << RF << RF->getAccess()
13768 << LF->getParent();
13778 uint64_t Mask = ~0ULL >> (64 - PtrSize);
13787 if (BaseTy->isIncompleteType())
13802 if (LHSTy->isMemberPointerType()) {
13804 assert(RHSTy->isMemberPointerType() && "invalid comparison");
13808 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
13812 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13817 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
13822 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
13839 if (MD->isVirtual())
13842 if (MD->isVirtual())
13853 if (LHSTy->isNullPtrType()) {
13854 assert(E->isComparisonOp() && "unexpected nullptr operation");
13855 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
13860 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
13861 !EvaluatePointer(E->getRHS(), Res, Info))
13877 llvm_unreachable("should never produce Unequal for three-way comparison");
13894 Info.Ctx.CompCategories.getInfoForType(E->getType());
13895 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
13899 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13901 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
13911 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
13917 if (E->isAssignmentOp()) {
13926 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
13927 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
13930 if (E->isComparisonOp()) {
13931 // Evaluate builtin binary comparisons by evaluating them as three-way
13934 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
13939 auto Op = E->getOpcode();
13961 QualType LHSTy = E->getLHS()->getType();
13962 QualType RHSTy = E->getRHS()->getType();
13964 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
13965 E->getOpcode() == BO_Sub) {
13968 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
13972 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
13975 // Reject differing bases from the normal codepath; we special-case
13978 // Handle &&A - &&B.
13990 if (LHSAddrExpr->getLabel()->getDeclContext() !=
13991 RHSAddrExpr->getLabel()->getDeclContext())
14010 QualType Type = E->getLHS()->getType();
14011 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14014 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14026 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14028 // appears to be non-conforming, but is common, so perhaps we should
14032 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14038 APSInt TrueResult = (LHS - RHS) / ElemSize;
14039 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14042 !HandleOverflow(Info, E, TrueResult, E->getType()))
14050 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14054 switch(E->getKind()) {
14057 if (E->isArgumentType())
14058 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
14061 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
14066 if (E->getArgumentType()->isDependentType())
14069 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14072 QualType Ty = E->getTypeOfArgument();
14074 if (Ty->isVectorType()) {
14075 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14077 // The vec_step built-in functions that take a 3-component
14089 QualType SrcTy = E->getTypeOfArgument();
14092 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14093 SrcTy = Ref->getPointeeType();
14096 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14097 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14104 assert(E->isArgumentType());
14107 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14111 QualType Ty = E->getTypeOfArgument();
14114 if (const auto *VT = Ty->getAs<VectorType>())
14115 return Success(VT->getNumElements(), E);
14117 assert(Ty->isSizelessVectorType());
14120 << E->getSourceRange();
14131 unsigned n = OOE->getNumComponents();
14134 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14136 OffsetOfNode ON = OOE->getComponent(i);
14139 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14146 CurrentType = AT->getElementType();
14154 const RecordType *RT = CurrentType->getAs<RecordType>();
14157 RecordDecl *RD = RT->getDecl();
14158 if (RD->isInvalidDecl()) return false;
14160 unsigned i = MemberDecl->getFieldIndex();
14163 CurrentType = MemberDecl->getType().getNonReferenceType();
14172 if (BaseSpec->isVirtual())
14176 const RecordType *RT = CurrentType->getAs<RecordType>();
14179 RecordDecl *RD = RT->getDecl();
14180 if (RD->isInvalidDecl()) return false;
14184 CurrentType = BaseSpec->getType();
14185 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14190 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14199 switch (E->getOpcode()) {
14205 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14207 return Visit(E->getSubExpr());
14210 return Visit(E->getSubExpr());
14212 if (!Visit(E->getSubExpr()))
14216 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14218 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14222 << E->getType() << E->getSourceRange();
14224 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14225 E->getType()))
14228 return Success(-Value, E);
14231 if (!Visit(E->getSubExpr()))
14238 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14245 /// HandleCast - This is used to evaluate implicit or explicit casts where the
14248 const Expr *SubExpr = E->getSubExpr();
14249 QualType DestType = E->getType();
14250 QualType SrcType = SubExpr->getType();
14252 switch (E->getCastKind()) {
14324 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
14325 IntResult = (uint64_t)-1;
14336 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
14355 // Allow casts of address-of-label differences if they are no-ops
14357 // be constant-evaluatable except in some narrow cases which are hard
14368 DestType->isEnumeralType()) {
14379 ConstexprVar = VD->isConstexpr();
14382 const EnumDecl *ED = ET->getDecl();
14393 if (!ED->isFixed()) {
14397 ED->getValueRange(Max, Min);
14398 --Max;
14400 if (ED->getNumNegativeBits() && ConstexprVar &&
14404 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14407 else if (!ED->getNumNegativeBits() && ConstexprVar &&
14410 E->getExprLoc(), diag::warn_constexpr_unscoped_enum_out_of_range)
14422 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
14473 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14475 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14482 return Visit(E->getSubExpr());
14486 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
14488 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
14495 VisitIgnoredValue(E->getSubExpr());
14500 return Success(E->getPackLength(), E);
14504 return Success(E->getValue(), E);
14509 return Success(E->isSatisfied(), E);
14513 return Success(E->isSatisfied(), E);
14517 switch (E->getOpcode()) {
14523 return Visit(E->getSubExpr());
14525 if (!Visit(E->getSubExpr())) return false;
14530 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
14536 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14544 const Expr *SubExpr = E->getSubExpr();
14545 QualType DestType = E->getType();
14546 assert(DestType->isFixedPointType() &&
14550 switch (E->getCastKind()) {
14552 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14559 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14561 << Result.toString() << E->getType();
14562 if (!HandleOverflow(Info, E, Result, E->getType()))
14578 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14580 << IntResult.toString() << E->getType();
14581 if (!HandleOverflow(Info, E, IntResult, E->getType()))
14598 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14600 << Result.toString() << E->getType();
14601 if (!HandleOverflow(Info, E, Result, E->getType()))
14616 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14619 const Expr *LHS = E->getLHS();
14620 const Expr *RHS = E->getRHS();
14622 Info.Ctx.getFixedPointSemantics(E->getType());
14624 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
14627 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
14633 switch (E->getOpcode()) {
14664 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
14665 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
14666 // Embedded-C 4.1.6.2.2:
14668 // of (nonpadding) bits of the fixed-point operand ...
14673 << RHSVal << E->getType() << ShiftBW;
14675 if (E->getOpcode() == BO_Shl)
14686 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14688 << Result.toString() << E->getType();
14689 if (!HandleOverflow(Info, E, Result, E->getType()))
14695 //===----------------------------------------------------------------------===//
14697 //===----------------------------------------------------------------------===//
14713 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
14732 assert(!E->isValueDependent());
14733 assert(E->isPRValue() && E->getType()->isRealFloatingType());
14742 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
14750 if (S->getString().empty())
14752 else if (S->getString().getAsInteger(0, fill))
14761 // Prior to IEEE 754-2008, architectures were allowed to choose whether
14763 // a different encoding to what became a standard in 2008, and for pre-
14764 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
14779 switch (E->getBuiltinCallee()) {
14794 Info.Ctx.getFloatTypeSemantics(E->getType());
14804 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14816 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
14825 // The C standard says "fabs raises no floating-point exceptions,
14826 // even if x is a signaling NaN. The returned value is independent of
14830 if (!EvaluateFloat(E->getArg(0), Result, Info))
14838 return EvaluateFloat(E->getArg(0), Result, Info);
14849 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14850 !EvaluateFloat(E->getArg(1), RHS, Info))
14863 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14864 !EvaluateFloat(E->getArg(1), RHS, Info))
14881 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
14882 !EvaluateFloat(E->getArg(1), RHS, Info))
14884 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
14895 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14897 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14903 return Visit(E->getSubExpr());
14907 if (E->getSubExpr()->getType()->isAnyComplexType()) {
14909 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
14915 VisitIgnoredValue(E->getSubExpr());
14916 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
14922 switch (E->getOpcode()) {
14925 return EvaluateFloat(E->getSubExpr(), Result, Info);
14928 // "the unary - raises no floating point exceptions,
14930 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
14938 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14942 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
14945 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
14946 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
14950 Result = E->getValue();
14955 const Expr* SubExpr = E->getSubExpr();
14957 switch (E->getCastKind()) {
14963 const FPOptions FPO = E->getFPFeaturesInEffect(
14966 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
14967 IntResult, E->getType(), Result);
14971 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
14975 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
14982 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
14996 //===----------------------------------------------------------------------===//
14998 //===----------------------------------------------------------------------===//
15016 //===--------------------------------------------------------------------===//
15018 //===--------------------------------------------------------------------===//
15031 assert(!E->isValueDependent());
15032 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15037 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15038 if (ElemTy->isRealFloatingType()) {
15053 const Expr* SubExpr = E->getSubExpr();
15055 if (SubExpr->getType()->isRealFloatingType()) {
15064 assert(SubExpr->getType()->isIntegerType() &&
15079 switch (E->getCastKind()) {
15149 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15158 if (!Visit(E->getSubExpr()))
15161 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15163 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15170 if (!Visit(E->getSubExpr()))
15173 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15175 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15185 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15194 if (!Visit(E->getSubExpr()))
15197 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15199 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15207 if (!Visit(E->getSubExpr()))
15210 const FPOptions FPO = E->getFPFeaturesInEffect(
15212 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15214 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15237 ResR = AC - BD;
15276 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
15293 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
15294 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
15298 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15300 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
15312 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
15319 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
15325 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15333 if (E->getLHS()->getType()->isRealFloatingType()) {
15336 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
15342 LHSOK = Visit(E->getLHS());
15348 if (E->getRHS()->getType()->isRealFloatingType()) {
15351 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
15355 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
15360 switch (E->getOpcode()) {
15388 Result.getComplexIntReal() -= RHS.getComplexIntReal();
15389 Result.getComplexIntImag() -= RHS.getComplexIntImag();
15428 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
15474 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
15485 if (!Visit(E->getSubExpr()))
15488 switch (E->getOpcode()) {
15502 Result.getComplexIntReal() = -Result.getComplexIntReal();
15503 Result.getComplexIntImag() = -Result.getComplexIntImag();
15510 Result.getComplexIntImag() = -Result.getComplexIntImag();
15516 if (E->getNumInits() == 2) {
15517 if (E->getType()->isComplexType()) {
15519 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
15521 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
15525 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
15527 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
15539 switch (E->getBuiltinCallee()) {
15542 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
15544 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
15553 //===----------------------------------------------------------------------===//
15556 //===----------------------------------------------------------------------===//
15574 E->getType()->castAs<AtomicType>()->getValueType());
15575 // For atomic-qualified class (and array) types in C++, initialize the
15576 // _Atomic-wrapped subobject directly, in-place.
15582 switch (E->getCastKind()) {
15586 VisitIgnoredValue(E->getSubExpr());
15589 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
15590 : Evaluate(Result, Info, E->getSubExpr());
15598 assert(!E->isValueDependent());
15599 assert(E->isPRValue() && E->getType()->isAtomicType());
15603 //===----------------------------------------------------------------------===//
15606 //===----------------------------------------------------------------------===//
15619 switch (E->getCastKind()) {
15623 VisitIgnoredValue(E->getSubExpr());
15632 switch (E->getBuiltinCallee()) {
15655 FunctionDecl *OperatorDelete = E->getOperatorDelete();
15656 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
15662 const Expr *Arg = E->getArgument();
15681 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
15686 // For the non-array case, the designator must be empty if the static type
15688 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
15689 !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
15691 << Arg->getType()->getPointeeType() << AllocType;
15697 if (!E->isArrayForm() && !E->isGlobalDelete()) {
15700 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
15707 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
15708 (*Alloc)->Value, AllocType))
15724 assert(!E->isValueDependent());
15725 assert(E->isPRValue() && E->getType()->isVoidType());
15729 //===----------------------------------------------------------------------===//
15731 //===----------------------------------------------------------------------===//
15734 assert(!E->isValueDependent());
15737 QualType T = E->getType();
15738 if (E->isGLValue() || T->isFunctionType()) {
15743 } else if (T->isVectorType()) {
15746 } else if (T->isIntegralOrEnumerationType()) {
15749 } else if (T->hasPointerRepresentation()) {
15754 } else if (T->isRealFloatingType()) {
15759 } else if (T->isAnyComplexType()) {
15764 } else if (T->isFixedPointType()) {
15766 } else if (T->isMemberPointerType()) {
15772 } else if (T->isArrayType()) {
15775 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15779 } else if (T->isRecordType()) {
15782 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
15786 } else if (T->isVoidType()) {
15789 << E->getType();
15792 } else if (T->isAtomicType()) {
15794 if (Unqual->isArrayType() || Unqual->isRecordType()) {
15796 APValue &Value = Info.CurrentCall->createTemporary(
15806 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
15816 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
15817 /// cases, the in-place evaluation is essential, since later initializers for
15821 assert(!E->isValueDependent());
15826 if (E->isPRValue()) {
15827 // Evaluate arrays and record types in-place, so that later initializers can
15828 // refer to earlier-initialized members of the object.
15829 QualType T = E->getType();
15830 if (T->isArrayType())
15832 else if (T->isRecordType())
15834 else if (T->isAtomicType()) {
15836 if (Unqual->isArrayType() || Unqual->isRecordType())
15841 // For any other type, in-place evaluation is unimportant.
15845 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
15846 /// lvalue-to-rvalue cast if it is an lvalue.
15848 assert(!E->isValueDependent());
15850 if (E->getType().isNull())
15859 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15866 // Implicit lvalue-to-rvalue cast.
15867 if (E->isGLValue()) {
15870 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
15875 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
15882 // Fast-path evaluations of integer literals, since we sometimes see files
15885 Result.Val = APValue(APSInt(L->getValue(),
15886 L->getType()->isUnsignedIntegerType()));
15892 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
15898 if (CE->hasAPValueResult()) {
15899 APValue APV = CE->getAPValueResult();
15908 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
15913 if (Exp->getType().isNull()) {
15929 assert(!E->isValueDependent());
15941 assert(!E->isValueDependent());
15942 if (!E->getType()->isIntegralOrEnumerationType())
15957 assert(!E->isValueDependent());
15958 if (!E->getType()->isFixedPointType())
15971 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
15974 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16024 if (!getType()->isRealFloatingType())
16122 // A full-expression is [...] a constant-expression
16164 VD->printQualifiedName(OS);
16179 SourceLocation DeclLoc = VD->getLocation();
16180 QualType DeclTy = VD->getType();
16195 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16196 // mem-initializer.
16210 // At this point, any lifetime-extended temporaries are completely
16233 // Otherwise, treat the value as default-initialized; if the destructor works
16236 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
16247 ensureEvaluatedStmt()->HasConstantDestruction = true;
16251 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
16320 /// isIntegerConstantExpr - this recursive routine will test if an expression is
16323 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
16326 // CheckICE - This function does the fundamental ICE checking: the returned
16342 /// the comma operator in C99 mode, and non-constant subexpressions.
16369 return ICEDiag(IK_NotICE, E->getBeginLoc());
16375 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
16376 if (!E->getType()->isIntegralOrEnumerationType())
16377 return ICEDiag(IK_NotICE, E->getBeginLoc());
16379 switch (E->getStmtClass()) {
16468 return ICEDiag(IK_NotICE, E->getBeginLoc());
16472 // form "T x = { a };" is equivalent to "T x = a;".
16475 if (E->isPRValue())
16476 if (cast<InitListExpr>(E)->getNumInits() == 1)
16477 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
16478 return ICEDiag(IK_NotICE, E->getBeginLoc());
16488 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
16492 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
16495 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
16498 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
16500 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
16520 if (CE->getBuiltinCallee())
16522 return ICEDiag(IK_NotICE, E->getBeginLoc());
16525 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
16528 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
16532 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
16536 // A variable of non-volatile const-qualified integral or enumeration
16542 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
16543 !VD->getType()->isReferenceType())
16546 return ICEDiag(IK_NotICE, E->getBeginLoc());
16550 switch (Exp->getOpcode()) {
16561 return ICEDiag(IK_NotICE, E->getBeginLoc());
16569 return CheckICE(Exp->getSubExpr(), Ctx);
16576 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
16584 if ((Exp->getKind() == UETT_SizeOf) &&
16585 Exp->getTypeOfArgument()->isVariableArrayType())
16586 return ICEDiag(IK_NotICE, E->getBeginLoc());
16591 switch (Exp->getOpcode()) {
16608 return ICEDiag(IK_NotICE, E->getBeginLoc());
16628 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16629 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16630 if (Exp->getOpcode() == BO_Div ||
16631 Exp->getOpcode() == BO_Rem) {
16635 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
16637 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16639 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
16641 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16645 if (Exp->getOpcode() == BO_Comma) {
16650 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
16653 return ICEDiag(IK_NotICE, E->getBeginLoc());
16660 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
16661 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
16663 // Rare case where the RHS has a comma "side-effect"; we need
16666 if ((Exp->getOpcode() == BO_LAnd) !=
16667 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
16684 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
16687 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
16688 unsigned DestWidth = Ctx.getIntWidth(E->getType());
16689 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
16695 if (FL->getValue().convertToInteger(IgnoredVal,
16698 return ICEDiag(IK_NotICE, E->getBeginLoc());
16702 switch (cast<CastExpr>(E)->getCastKind()) {
16711 return ICEDiag(IK_NotICE, E->getBeginLoc());
16716 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
16718 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16722 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
16732 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
16733 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
16735 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
16739 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
16740 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
16752 // TrueResult and FalseResult is non-zero.
16753 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
16758 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
16760 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
16762 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
16766 return ICEDiag(IK_NotICE, E->getBeginLoc());
16767 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
16779 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16780 if (Loc) *Loc = E->getExprLoc();
16785 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
16789 if (Loc) *Loc = E->getExprLoc();
16833 // The only possible side-effects here are due to UB discovered in the
16874 // call us on arbitrary full-expressions should generally not care.
16898 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
16912 assert(MD && "Don't provide `this` for non-methods.");
16913 assert(MD->isImplicitObjectMemberFunction() &&
16916 if (!This->isValueDependent() &&
16921 // Ignore any side-effects from a failed evaluation. This is safe because
16926 CallRef Call = Info.CurrentCall->createCall(Callee);
16929 unsigned Idx = I - Args.begin();
16930 if (Idx >= Callee->getNumParams())
16932 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
16933 if ((*I)->isValueDependent() ||
16941 // Ignore any side-effects from a failed evaluation. This is safe because
16952 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
16964 // moment the constant expression evaluator cannot cope with the non-rigorous
16966 if (FD->isDependentContext())
16972 FD->getNameForDiagnostic(OS, FD->getASTContext().getPrintingPolicy(),
16980 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
16991 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
16997 This.set({&VIE, Info.CurrentCall->Index});
17004 // of objects of non-literal types.
17008 SourceLocation Loc = FD->getLocation();
17010 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17011 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17022 assert(!E->isValueDependent() &&
17028 EvalInfo Info(FD->getASTContext(), Status,
17044 if (!getType()->isPointerType())
17054 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17062 QualType CharTy = E->getType()->getPointeeType();
17067 StringRef Str = S->getBytes();
17070 S->getCharByteWidth() == 1 &&
17071 // FIXME: Add fast-path for wchar_t too.
17098 StringResult->push_back(Char.getInt().getExtValue());
17133 QualType CharTy = PtrExpression->getType()->getPointeeType();