62#include "llvm/ADT/APFixedPoint.h"
63#include "llvm/ADT/Sequence.h"
64#include "llvm/ADT/SmallBitVector.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/ADT/bit.h"
67#include "llvm/Support/CRC.h"
68#include "llvm/Support/Casting.h"
69#include "llvm/Support/Debug.h"
70#include "llvm/Support/MathExtras.h"
71#include "llvm/Support/SaveAndRestore.h"
72#include "llvm/Support/SipHash.h"
73#include "llvm/Support/TimeProfiler.h"
74#include "llvm/Support/raw_ostream.h"
80#define DEBUG_TYPE "exprconstant"
83using llvm::APFixedPoint;
87using llvm::FixedPointSemantics;
94 using SourceLocExprScopeGuard =
125 static unsigned countNonVirtualBases(
const CXXRecordDecl *RD) {
126 return llvm::count_if(RD->
bases(), [](
auto &B) { return !B.isVirtual(); });
133 static const CallExpr *tryUnwrapAllocSizeCall(
const Expr *E) {
141 if (
const auto *FE = dyn_cast<FullExpr>(E))
144 if (
const auto *Cast = dyn_cast<CastExpr>(E))
145 E = Cast->getSubExpr()->IgnoreParens();
147 if (
const auto *CE = dyn_cast<CallExpr>(E))
148 return CE->getCalleeAllocSizeAttr() ? CE :
nullptr;
155 const auto *E =
Base.dyn_cast<
const Expr *>();
156 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162 static const uint64_t AssumedSizeForUnsizedArray =
163 std::numeric_limits<uint64_t>::max() / 2;
173 bool &FirstEntryIsUnsizedArray) {
176 assert(!isBaseAnAllocSizeCall(
Base) &&
177 "Unsized arrays shouldn't appear here");
178 unsigned MostDerivedLength = 0;
183 for (
unsigned I = 0, N = Path.size(); I != N; ++I) {
187 MostDerivedLength = I + 1;
190 if (
auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
191 ArraySize = CAT->getZExtSize();
193 assert(I == 0 &&
"unexpected unsized array designator");
194 FirstEntryIsUnsizedArray =
true;
195 ArraySize = AssumedSizeForUnsizedArray;
201 MostDerivedLength = I + 1;
204 Type = VT->getElementType();
205 ArraySize = VT->getNumElements();
206 MostDerivedLength = I + 1;
208 }
else if (
const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
211 MostDerivedLength = I + 1;
219 return MostDerivedLength;
223 struct SubobjectDesignator {
227 LLVM_PREFERRED_TYPE(
bool)
231 LLVM_PREFERRED_TYPE(
bool)
232 unsigned IsOnePastTheEnd : 1;
235 LLVM_PREFERRED_TYPE(
bool)
236 unsigned FirstEntryIsAnUnsizedArray : 1;
239 LLVM_PREFERRED_TYPE(
bool)
240 unsigned MostDerivedIsArrayElement : 1;
244 unsigned MostDerivedPathLength : 28;
262 SubobjectDesignator() :
Invalid(
true) {}
265 :
Invalid(
false), IsOnePastTheEnd(
false),
266 FirstEntryIsAnUnsizedArray(
false), MostDerivedIsArrayElement(
false),
267 MostDerivedPathLength(0), MostDerivedArraySize(0),
268 MostDerivedType(
T.isNull() ?
QualType() :
T.getNonReferenceType()) {}
271 :
Invalid(!
V.isLValue() || !
V.hasLValuePath()), IsOnePastTheEnd(
false),
272 FirstEntryIsAnUnsizedArray(
false), MostDerivedIsArrayElement(
false),
273 MostDerivedPathLength(0), MostDerivedArraySize(0) {
274 assert(
V.isLValue() &&
"Non-LValue used to make an LValue designator?");
276 IsOnePastTheEnd =
V.isLValueOnePastTheEnd();
277 llvm::append_range(Entries,
V.getLValuePath());
278 if (
V.getLValueBase()) {
279 bool IsArray =
false;
280 bool FirstIsUnsizedArray =
false;
281 MostDerivedPathLength = findMostDerivedSubobject(
282 Ctx,
V.getLValueBase(),
V.getLValuePath(), MostDerivedArraySize,
283 MostDerivedType, IsArray, FirstIsUnsizedArray);
284 MostDerivedIsArrayElement = IsArray;
285 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
291 unsigned NewLength) {
295 assert(
Base &&
"cannot truncate path for null pointer");
296 assert(NewLength <= Entries.size() &&
"not a truncation");
298 if (NewLength == Entries.size())
300 Entries.resize(NewLength);
302 bool IsArray =
false;
303 bool FirstIsUnsizedArray =
false;
304 MostDerivedPathLength = findMostDerivedSubobject(
305 Ctx,
Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
306 FirstIsUnsizedArray);
307 MostDerivedIsArrayElement = IsArray;
308 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
318 bool isMostDerivedAnUnsizedArray()
const {
319 assert(!
Invalid &&
"Calling this makes no sense on invalid designators");
320 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
325 uint64_t getMostDerivedArraySize()
const {
326 assert(!isMostDerivedAnUnsizedArray() &&
"Unsized array has no size");
327 return MostDerivedArraySize;
331 bool isOnePastTheEnd()
const {
335 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
336 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
337 MostDerivedArraySize)
345 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
346 if (
Invalid || isMostDerivedAnUnsizedArray())
352 bool IsArray = MostDerivedPathLength == Entries.size() &&
353 MostDerivedIsArrayElement;
354 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
357 IsArray ? getMostDerivedArraySize() : (
uint64_t)1;
358 return {ArrayIndex, ArraySize - ArrayIndex};
362 bool isValidSubobject()
const {
365 return !isOnePastTheEnd();
373 assert(!
Invalid &&
"invalid designator has no subobject type");
374 return MostDerivedPathLength == Entries.size()
385 MostDerivedIsArrayElement =
true;
387 MostDerivedPathLength = Entries.size();
391 void addUnsizedArrayUnchecked(
QualType ElemTy) {
394 MostDerivedType = ElemTy;
395 MostDerivedIsArrayElement =
true;
399 MostDerivedArraySize = AssumedSizeForUnsizedArray;
400 MostDerivedPathLength = Entries.size();
404 void addDeclUnchecked(
const Decl *D,
bool Virtual =
false) {
408 if (
const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
409 MostDerivedType = FD->getType();
410 MostDerivedIsArrayElement =
false;
411 MostDerivedArraySize = 0;
412 MostDerivedPathLength = Entries.size();
416 void addComplexUnchecked(
QualType EltTy,
bool Imag) {
421 MostDerivedType = EltTy;
422 MostDerivedIsArrayElement =
true;
423 MostDerivedArraySize = 2;
424 MostDerivedPathLength = Entries.size();
430 MostDerivedType = EltTy;
431 MostDerivedPathLength = Entries.size();
432 MostDerivedArraySize = 0;
433 MostDerivedIsArrayElement =
false;
436 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
const Expr *E);
437 void diagnosePointerArithmetic(EvalInfo &Info,
const Expr *E,
440 void adjustIndex(EvalInfo &Info,
const Expr *E,
APSInt N,
const LValue &LV);
444 enum class ScopeKind {
452 CallRef() : OrigCallee(), CallIndex(0), Version() {}
453 CallRef(
const FunctionDecl *Callee,
unsigned CallIndex,
unsigned Version)
454 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
456 explicit operator bool()
const {
return OrigCallee; }
482 CallStackFrame *Caller;
504 typedef std::pair<const void *, unsigned> MapKeyTy;
505 typedef std::map<MapKeyTy, APValue>
MapTy;
517 unsigned CurTempVersion = TempVersionStack.back();
519 unsigned getTempVersion()
const {
return TempVersionStack.back(); }
521 void pushTempVersion() {
522 TempVersionStack.push_back(++CurTempVersion);
525 void popTempVersion() {
526 TempVersionStack.pop_back();
530 return {Callee, Index, ++CurTempVersion};
541 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
542 FieldDecl *LambdaThisCaptureField =
nullptr;
544 CallStackFrame(EvalInfo &Info,
SourceRange CallRange,
550 APValue *getTemporary(
const void *Key,
unsigned Version) {
551 MapKeyTy KV(Key, Version);
552 auto LB = Temporaries.lower_bound(KV);
553 if (LB != Temporaries.end() && LB->first == KV)
559 APValue *getCurrentTemporary(
const void *Key) {
560 auto UB = Temporaries.upper_bound(MapKeyTy(Key,
UINT_MAX));
561 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
562 return &std::prev(UB)->second;
567 unsigned getCurrentTemporaryVersion(
const void *Key)
const {
568 auto UB = Temporaries.upper_bound(MapKeyTy(Key,
UINT_MAX));
569 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
570 return std::prev(UB)->first.second;
578 template<
typename KeyT>
580 ScopeKind
Scope, LValue &LV);
585 void describe(llvm::raw_ostream &OS)
const override;
587 Frame *getCaller()
const override {
return Caller; }
588 SourceRange getCallRange()
const override {
return CallRange; }
591 bool isStdFunction()
const {
592 for (
const DeclContext *DC = Callee; DC; DC = DC->getParent())
593 if (DC->isStdNamespace())
600 bool CanEvalMSConstexpr =
false;
608 class ThisOverrideRAII {
610 ThisOverrideRAII(CallStackFrame &Frame,
const LValue *NewThis,
bool Enable)
611 : Frame(Frame), OldThis(Frame.This) {
613 Frame.This = NewThis;
615 ~ThisOverrideRAII() {
616 Frame.This = OldThis;
619 CallStackFrame &Frame;
620 const LValue *OldThis;
625 class ExprTimeTraceScope {
627 ExprTimeTraceScope(
const Expr *E,
const ASTContext &Ctx, StringRef Name)
628 : TimeScope(Name, [E, &Ctx] {
633 llvm::TimeTraceScope TimeScope;
638 struct MSConstexprContextRAII {
639 CallStackFrame &Frame;
641 explicit MSConstexprContextRAII(CallStackFrame &Frame,
bool Value)
642 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
643 Frame.CanEvalMSConstexpr =
Value;
646 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
659 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
660 APValue::LValueBase Base;
666 : Value(Val, Scope), Base(Base), T(T) {}
670 bool isDestroyedAtEndOf(ScopeKind K)
const {
671 return (
int)Value.getInt() >= (
int)K;
673 bool endLifetime(EvalInfo &Info,
bool RunDestructors) {
674 if (RunDestructors) {
676 if (
const ValueDecl *VD = Base.dyn_cast<
const ValueDecl*>())
677 Loc = VD->getLocation();
678 else if (
const Expr *E = Base.dyn_cast<
const Expr*>())
679 Loc = E->getExprLoc();
682 *Value.getPointer() =
APValue();
686 bool hasSideEffect() {
687 return T.isDestructedType();
692 struct ObjectUnderConstruction {
693 APValue::LValueBase Base;
694 ArrayRef<APValue::LValuePathEntry> Path;
695 friend bool operator==(
const ObjectUnderConstruction &LHS,
696 const ObjectUnderConstruction &RHS) {
697 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
699 friend llvm::hash_code
hash_value(
const ObjectUnderConstruction &Obj) {
700 return llvm::hash_combine(Obj.Base, Obj.Path);
703 enum class ConstructionPhase {
714template<>
struct DenseMapInfo<ObjectUnderConstruction> {
715 using Base = DenseMapInfo<APValue::LValueBase>;
719 static bool isEqual(
const ObjectUnderConstruction &LHS,
720 const ObjectUnderConstruction &RHS) {
734 const Expr *AllocExpr =
nullptr;
739 if (
auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
740 return NE->isArray() ? DynAllocKind::ArrayNew : DynAllocKind::New;
742 return DynAllocKind::StdAllocator;
748 struct DynAllocOrder {
749 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R)
const {
771 CallStackFrame *CurrentCall;
774 unsigned CallStackDepth;
777 unsigned NextCallIndex;
786 CallStackFrame BottomFrame;
790 llvm::SmallVector<Cleanup, 16> CleanupStack;
794 APValue::LValueBase EvaluatingDecl;
796 enum class EvaluatingDeclKind {
803 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
812 SmallVector<const Stmt *> BreakContinueStack;
815 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
816 ObjectsUnderConstruction;
821 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
826 struct EvaluatingConstructorRAII {
828 ObjectUnderConstruction Object;
830 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
832 : EI(EI), Object(Object) {
834 EI.ObjectsUnderConstruction
835 .insert({Object, HasBases ? ConstructionPhase::Bases
836 : ConstructionPhase::AfterBases})
839 void finishedConstructingBases() {
840 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
842 void finishedConstructingFields() {
843 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
845 ~EvaluatingConstructorRAII() {
846 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
850 struct EvaluatingDestructorRAII {
852 ObjectUnderConstruction Object;
854 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
855 : EI(EI), Object(Object) {
856 DidInsert = EI.ObjectsUnderConstruction
857 .insert({Object, ConstructionPhase::Destroying})
860 void startedDestroyingBases() {
861 EI.ObjectsUnderConstruction[Object] =
862 ConstructionPhase::DestroyingBases;
864 ~EvaluatingDestructorRAII() {
866 EI.ObjectsUnderConstruction.erase(Object);
871 isEvaluatingCtorDtor(APValue::LValueBase Base,
872 ArrayRef<APValue::LValuePathEntry> Path) {
873 return ObjectsUnderConstruction.lookup({
Base, Path});
878 unsigned SpeculativeEvaluationDepth = 0;
884 EvalInfo(
const ASTContext &
C, SemaProxy *SProxy, Expr::EvalStatus &S,
886 : State(const_cast<ASTContext &>(
C), SProxy, S), CurrentCall(
nullptr),
887 CallStackDepth(0), NextCallIndex(1),
888 StepsLeft(
C.getLangOpts().ConstexprStepLimit),
889 BottomFrame(*this, SourceLocation(),
nullptr,
892 EvaluatingDecl((const ValueDecl *)
nullptr),
901 void setEvaluatingDecl(APValue::LValueBase Base,
APValue &
Value,
902 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
903 EvaluatingDecl =
Base;
904 IsEvaluatingDecl = EDK;
905 EvaluatingDeclValue = &
Value;
908 bool CheckCallLimit(SourceLocation Loc) {
911 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
913 if (NextCallIndex == 0) {
915 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
918 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
920 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
921 << getLangOpts().ConstexprCallDepth;
932 ElemCount >
uint64_t(std::numeric_limits<unsigned>::max())) {
934 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
943 uint64_t Limit = getLangOpts().ConstexprStepLimit;
944 if (Limit != 0 && ElemCount > Limit) {
946 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
947 << ElemCount << Limit;
948 Note(Loc, diag::note_constexpr_steps);
955 std::pair<CallStackFrame *, unsigned>
956 getCallFrameAndDepth(
unsigned CallIndex) {
957 assert(CallIndex &&
"no call index in getCallFrameAndDepth");
960 unsigned Depth = CallStackDepth;
961 CallStackFrame *Frame = CurrentCall;
962 while (Frame->Index > CallIndex) {
963 Frame = Frame->Caller;
966 if (Frame->Index == CallIndex)
967 return {Frame, Depth};
971 bool nextStep(
const Stmt *S) {
972 if (getLangOpts().ConstexprStepLimit == 0)
976 FFDiag(S->
getBeginLoc(), diag::note_constexpr_step_limit_exceeded, 1)
977 << getLangOpts().ConstexprStepLimit;
985 APValue *createHeapAlloc(
const Expr *E, QualType
T, LValue &LV);
987 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
988 std::optional<DynAlloc *>
Result;
989 auto It = HeapAllocs.find(DA);
990 if (It != HeapAllocs.end())
996 APValue *getParamSlot(CallRef
Call,
const ParmVarDecl *PVD) {
997 CallStackFrame *Frame = getCallFrameAndDepth(
Call.CallIndex).first;
998 return Frame ? Frame->getTemporary(
Call.getOrigParam(PVD),
Call.Version)
1003 struct StdAllocatorCaller {
1004 unsigned FrameIndex;
1007 explicit operator bool()
const {
return FrameIndex != 0; };
1010 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName)
const {
1011 for (
const CallStackFrame *
Call = CurrentCall;
Call->Caller !=
nullptr;
1013 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(
Call->Callee);
1016 const IdentifierInfo *FnII = MD->getIdentifier();
1017 if (!FnII || !FnII->
isStr(FnName))
1021 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1025 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1026 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1027 if (CTSD->isInStdNamespace() && ClassII &&
1028 ClassII->
isStr(
"allocator") && TAL.
size() >= 1 &&
1030 return {
Call->Index, TAL[0].getAsType(),
Call->CallExpr};
1036 void performLifetimeExtension() {
1038 llvm::erase_if(CleanupStack, [](Cleanup &
C) {
1039 return !
C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1046 bool discardCleanups() {
1047 for (Cleanup &
C : CleanupStack) {
1048 if (
C.hasSideEffect() && !noteSideEffect()) {
1049 CleanupStack.clear();
1053 CleanupStack.clear();
1058 const interp::Frame *getCurrentFrame()
override {
return CurrentCall; }
1060 unsigned getCallStackDepth()
override {
return CallStackDepth; }
1061 bool stepsLeft()
const override {
return StepsLeft > 0; }
1074 [[nodiscard]]
bool noteFailure() {
1082 bool KeepGoing = keepEvaluatingAfterFailure();
1083 EvalStatus.HasSideEffects |= KeepGoing;
1087 class ArrayInitLoopIndex {
1092 ArrayInitLoopIndex(EvalInfo &Info)
1093 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1094 Info.ArrayInitIndex = 0;
1096 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1098 operator uint64_t&() {
return Info.ArrayInitIndex; }
1103 struct FoldConstant {
1106 bool HadNoPriorDiags;
1109 explicit FoldConstant(EvalInfo &Info,
bool Enabled)
1112 HadNoPriorDiags(Info.EvalStatus.
Diag &&
1113 Info.EvalStatus.
Diag->empty() &&
1114 !Info.EvalStatus.HasSideEffects),
1115 OldMode(Info.EvalMode) {
1117 Info.EvalMode = EvaluationMode::ConstantFold;
1119 void keepDiagnostics() { Enabled =
false; }
1121 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1122 !Info.EvalStatus.HasSideEffects) {
1123 Info.EvalStatus.Diag->clear();
1124 Info.EvalStatus.DiagEmitted =
false;
1126 Info.EvalMode = OldMode;
1132 struct IgnoreSideEffectsRAII {
1135 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1136 : Info(Info), OldMode(Info.EvalMode) {
1137 Info.EvalMode = EvaluationMode::IgnoreSideEffects;
1140 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1145 class SpeculativeEvaluationRAII {
1146 EvalInfo *Info =
nullptr;
1147 Expr::EvalStatus OldStatus;
1148 unsigned OldSpeculativeEvaluationDepth = 0;
1150 void moveFromAndCancel(SpeculativeEvaluationRAII &&
Other) {
1152 OldStatus =
Other.OldStatus;
1153 OldSpeculativeEvaluationDepth =
Other.OldSpeculativeEvaluationDepth;
1154 Other.Info =
nullptr;
1157 void maybeRestoreState() {
1161 Info->EvalStatus = OldStatus;
1162 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1166 SpeculativeEvaluationRAII() =
default;
1168 SpeculativeEvaluationRAII(
1169 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag =
nullptr)
1170 : Info(&Info), OldStatus(Info.EvalStatus),
1171 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1172 Info.EvalStatus.Diag = NewDiag;
1173 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1176 SpeculativeEvaluationRAII(
const SpeculativeEvaluationRAII &
Other) =
delete;
1177 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&
Other) {
1178 moveFromAndCancel(std::move(
Other));
1181 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&
Other) {
1182 maybeRestoreState();
1183 moveFromAndCancel(std::move(
Other));
1187 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1192 template<ScopeKind Kind>
1195 unsigned OldStackSize;
1197 ScopeRAII(EvalInfo &Info)
1198 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1201 Info.CurrentCall->pushTempVersion();
1203 bool destroy(
bool RunDestructors =
true) {
1204 bool OK =
cleanup(Info, RunDestructors, OldStackSize);
1205 OldStackSize = std::numeric_limits<unsigned>::max();
1209 if (OldStackSize != std::numeric_limits<unsigned>::max())
1213 Info.CurrentCall->popTempVersion();
1216 static bool cleanup(EvalInfo &Info,
bool RunDestructors,
1217 unsigned OldStackSize) {
1218 assert(OldStackSize <= Info.CleanupStack.size() &&
1219 "running cleanups out of order?");
1224 for (
unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1225 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1226 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1234 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1235 if (Kind != ScopeKind::Block)
1237 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &
C) {
1238 return C.isDestroyedAtEndOf(Kind);
1240 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1244 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1245 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1246 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1249bool SubobjectDesignator::checkSubobject(EvalInfo &Info,
const Expr *E,
1253 if (isOnePastTheEnd()) {
1254 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1265void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1267 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1272void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1277 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1278 Info.CCEDiag(E, diag::note_constexpr_array_index)
1280 <<
static_cast<unsigned>(getMostDerivedArraySize());
1282 Info.CCEDiag(E, diag::note_constexpr_array_index)
1287CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1288 const FunctionDecl *Callee,
const LValue *This,
1289 const Expr *CallExpr, CallRef Call)
1291 CallExpr(CallExpr),
Arguments(Call), CallRange(CallRange),
1292 Index(Info.NextCallIndex++) {
1293 Info.CurrentCall =
this;
1294 ++Info.CallStackDepth;
1297CallStackFrame::~CallStackFrame() {
1298 assert(Info.CurrentCall ==
this &&
"calls retired out of order");
1299 --Info.CallStackDepth;
1300 Info.CurrentCall = Caller;
1325 llvm_unreachable(
"unknown access kind");
1362 llvm_unreachable(
"unknown access kind");
1366 struct ComplexValue {
1374 ComplexValue() : FloatReal(
APFloat::Bogus()), FloatImag(
APFloat::Bogus()) {}
1376 void makeComplexFloat() { IsInt =
false; }
1377 bool isComplexFloat()
const {
return !IsInt; }
1378 APFloat &getComplexFloatReal() {
return FloatReal; }
1379 APFloat &getComplexFloatImag() {
return FloatImag; }
1381 void makeComplexInt() { IsInt =
true; }
1382 bool isComplexInt()
const {
return IsInt; }
1383 APSInt &getComplexIntReal() {
return IntReal; }
1384 APSInt &getComplexIntImag() {
return IntImag; }
1386 void moveInto(
APValue &v)
const {
1387 if (isComplexFloat())
1388 v =
APValue(FloatReal, FloatImag);
1390 v =
APValue(IntReal, IntImag);
1392 void setFrom(
const APValue &v) {
1407 APValue::LValueBase
Base;
1409 SubobjectDesignator Designator;
1411 bool InvalidBase : 1;
1413 bool AllowConstexprUnknown =
false;
1415 const APValue::LValueBase getLValueBase()
const {
return Base; }
1416 bool allowConstexprUnknown()
const {
return AllowConstexprUnknown; }
1417 CharUnits &getLValueOffset() {
return Offset; }
1418 CharUnits getLValueOffset()
const {
return Offset; }
1419 SubobjectDesignator &getLValueDesignator() {
return Designator; }
1420 const SubobjectDesignator &getLValueDesignator()
const {
return Designator;}
1421 bool isNullPointer()
const {
return IsNullPtr;}
1423 unsigned getLValueCallIndex()
const {
return Base.getCallIndex(); }
1424 unsigned getLValueVersion()
const {
return Base.getVersion(); }
1426 bool pointsToCompleteClass(
const CXXRecordDecl *D)
const {
1427 if (Designator.Entries.empty())
1434 if (Designator.Invalid)
1435 V =
APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1437 assert(!InvalidBase &&
"APValues can't handle invalid LValue bases");
1438 V =
APValue(Base, Offset, Designator.Entries,
1439 Designator.IsOnePastTheEnd, IsNullPtr);
1441 if (AllowConstexprUnknown)
1442 V.setConstexprUnknown();
1444 void setFrom(
const ASTContext &Ctx,
const APValue &
V) {
1445 assert(
V.isLValue() &&
"Setting LValue from a non-LValue?");
1446 Base =
V.getLValueBase();
1447 Offset =
V.getLValueOffset();
1448 InvalidBase =
false;
1449 Designator = SubobjectDesignator(Ctx,
V);
1450 IsNullPtr =
V.isNullPointer();
1451 AllowConstexprUnknown =
V.allowConstexprUnknown();
1454 void set(APValue::LValueBase B,
bool BInvalid =
false) {
1458 const auto *E = B.
get<
const Expr *>();
1460 "Unexpected type of invalid base");
1466 InvalidBase = BInvalid;
1467 Designator = SubobjectDesignator(
getType(B));
1469 AllowConstexprUnknown =
false;
1472 void setNull(ASTContext &Ctx, QualType PointerTy) {
1473 Base = (
const ValueDecl *)
nullptr;
1476 InvalidBase =
false;
1479 AllowConstexprUnknown =
false;
1482 void setInvalid(APValue::LValueBase B,
unsigned I = 0) {
1486 std::string
toString(ASTContext &Ctx, QualType
T)
const {
1488 moveInto(Printable);
1495 template <
typename GenDiagType>
1496 bool checkNullPointerDiagnosingWith(
const GenDiagType &GenDiag) {
1497 if (Designator.Invalid)
1501 Designator.setInvalid();
1508 bool checkNullPointer(EvalInfo &Info,
const Expr *E,
1510 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1511 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1515 bool checkNullPointerForFoldAccess(EvalInfo &Info,
const Expr *E,
1517 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1518 if (AK == AccessKinds::AK_Dereference)
1519 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
1521 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1529 Designator.checkSubobject(Info, E, CSK);
1532 void addDecl(EvalInfo &Info,
const Expr *E,
1533 const Decl *D,
bool Virtual =
false) {
1535 Designator.addDeclUnchecked(D,
Virtual);
1537 void addUnsizedArray(EvalInfo &Info,
const Expr *E, QualType ElemTy) {
1538 if (!Designator.Entries.empty()) {
1539 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1540 Designator.setInvalid();
1544 assert(!Base ||
getType(Base).getNonReferenceType()->isPointerType() ||
1545 getType(Base).getNonReferenceType()->isArrayType());
1546 Designator.FirstEntryIsAnUnsizedArray =
true;
1547 Designator.addUnsizedArrayUnchecked(ElemTy);
1550 void addArray(EvalInfo &Info,
const Expr *E,
const ConstantArrayType *CAT) {
1552 Designator.addArrayUnchecked(CAT);
1554 void addComplex(EvalInfo &Info,
const Expr *E, QualType EltTy,
bool Imag) {
1556 Designator.addComplexUnchecked(EltTy, Imag);
1558 void addVectorElement(EvalInfo &Info,
const Expr *E, QualType EltTy,
1561 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1563 void clearIsNullPointer() {
1566 void adjustOffsetAndIndex(EvalInfo &Info,
const Expr *E,
1567 const APSInt &Index, CharUnits ElementSize) {
1578 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1582 Designator.adjustIndex(Info, E, Index, *
this);
1583 clearIsNullPointer();
1585 void adjustOffset(CharUnits N) {
1588 clearIsNullPointer();
1594 explicit MemberPtr(
const ValueDecl *Decl)
1595 : DeclAndIsDerivedMember(
Decl,
false) {}
1599 const ValueDecl *getDecl()
const {
1600 return DeclAndIsDerivedMember.getPointer();
1603 bool isDerivedMember()
const {
1604 return DeclAndIsDerivedMember.getInt();
1607 const CXXRecordDecl *getContainingRecord()
const {
1609 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1613 V =
APValue(getDecl(), isDerivedMember(), Path);
1616 assert(
V.isMemberPointer());
1617 DeclAndIsDerivedMember.setPointer(
V.getMemberPointerDecl());
1618 DeclAndIsDerivedMember.setInt(
V.isMemberPointerToDerivedMember());
1620 llvm::append_range(Path,
V.getMemberPointerPath());
1626 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1629 SmallVector<const CXXRecordDecl*, 4> Path;
1633 bool castBack(
const CXXRecordDecl *
Class) {
1634 assert(!Path.empty());
1635 const CXXRecordDecl *Expected;
1636 if (Path.size() >= 2)
1637 Expected = Path[Path.size() - 2];
1639 Expected = getContainingRecord();
1653 bool castToDerived(
const CXXRecordDecl *Derived) {
1656 if (!isDerivedMember()) {
1657 Path.push_back(Derived);
1660 if (!castBack(Derived))
1663 DeclAndIsDerivedMember.setInt(
false);
1671 DeclAndIsDerivedMember.setInt(
true);
1672 if (isDerivedMember()) {
1673 Path.push_back(Base);
1676 return castBack(Base);
1681 static bool operator==(
const MemberPtr &LHS,
const MemberPtr &RHS) {
1682 if (!LHS.getDecl() || !RHS.getDecl())
1683 return !LHS.getDecl() && !RHS.getDecl();
1684 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1686 return LHS.Path == RHS.Path;
1690void SubobjectDesignator::adjustIndex(EvalInfo &Info,
const Expr *E,
APSInt N,
1694 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
1695 if (isMostDerivedAnUnsizedArray()) {
1696 diagnoseUnsizedArrayPointerArithmetic(Info, E);
1701 PathEntry::ArrayIndex(Entries.back().getAsArrayIndex() + TruncatedN);
1709 MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement;
1711 IsArray ? Entries.back().getAsArrayIndex() : (
uint64_t)IsOnePastTheEnd;
1714 if (N < -(
int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
1715 if (!Info.checkingPotentialConstantExpression() ||
1716 !LV.AllowConstexprUnknown) {
1719 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
1720 (llvm::APInt &)N += ArrayIndex;
1721 assert(N.ugt(ArraySize) &&
"bounds check failed for in-bounds index");
1722 diagnosePointerArithmetic(Info, E, N);
1728 ArrayIndex += TruncatedN;
1729 assert(ArrayIndex <= ArraySize &&
1730 "bounds check succeeded for out-of-bounds index");
1733 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
1735 IsOnePastTheEnd = (ArrayIndex != 0);
1740 const LValue &This,
const Expr *E,
1741 bool AllowNonLiteralTypes =
false);
1743 bool InvalidBaseOK =
false);
1745 bool InvalidBaseOK =
false);
1753static bool EvaluateComplex(
const Expr *E, ComplexValue &Res, EvalInfo &Info);
1758static std::optional<uint64_t>
1760 std::string *StringResult =
nullptr);
1777 if (
Int.isUnsigned() ||
Int.isMinSignedValue()) {
1778 Int =
Int.extend(
Int.getBitWidth() + 1);
1779 Int.setIsSigned(
true);
1784template<
typename KeyT>
1785APValue &CallStackFrame::createTemporary(
const KeyT *Key, QualType
T,
1786 ScopeKind Scope, LValue &LV) {
1787 unsigned Version = getTempVersion();
1788 APValue::LValueBase
Base(Key, Index, Version);
1790 return createLocal(Base, Key,
T, Scope);
1794APValue &CallStackFrame::createParam(CallRef Args,
const ParmVarDecl *PVD,
1796 assert(Args.CallIndex == Index &&
"creating parameter in wrong frame");
1797 APValue::LValueBase
Base(PVD, Index, Args.Version);
1802 return createLocal(Base, PVD, PVD->
getType(), ScopeKind::Call);
1805APValue &CallStackFrame::createLocal(APValue::LValueBase Base,
const void *Key,
1806 QualType
T, ScopeKind Scope) {
1807 assert(
Base.getCallIndex() == Index &&
"lvalue for wrong frame");
1808 unsigned Version =
Base.getVersion();
1810 assert(
Result.isAbsent() &&
"local created multiple times");
1816 if (Index <= Info.SpeculativeEvaluationDepth) {
1817 if (
T.isDestructedType())
1818 Info.noteSideEffect();
1829 "should only be called on dynamically allocated blocks");
1831 "__builtin_operator_new should have been allowed only from "
1832 "std::allocator::allocate");
1838 assert(
TypeAlignment > 0 &&
"Unknown alignment for allocated type!");
1842 if (AllocSize == 0) {
1843 switch (AllocKind) {
1857 llvm_unreachable(
"Unhandled DynAllocKind");
1861 assert(
TypeAlignment <= AllocSize &&
"Invalid alignment/size for type!");
1862 assert(AllocSize %
TypeAlignment == 0 &&
"Invalid alignment/size for type!");
1872 switch (AllocKind) {
1888 std::min(DefaultNewAlign,
uint64_t(1) << llvm::countr_zero(AllocSize)));
1910 uint64_t MaxFundamentalAlign =
1913 {DefaultNewAlign, MaxFundamentalAlign, llvm::bit_floor(AllocSize)}));
1917 llvm_unreachable(
"Unhandled DynAllocKind");
1923 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1927 DynamicAllocLValue DA(NumHeapAllocs++, DynAlloc::kindOfExpr(E));
1929 auto Result = HeapAllocs.emplace(std::piecewise_construct,
1930 std::forward_as_tuple(DA), std::tuple<>());
1931 assert(
Result.second &&
"reused a heap alloc index?");
1932 Result.first->second.AllocExpr = E;
1933 return &
Result.first->second.Value;
1937void CallStackFrame::describe(raw_ostream &Out)
const {
1938 bool IsMemberCall =
false;
1939 bool ExplicitInstanceParam =
false;
1940 clang::PrintingPolicy PrintingPolicy = Info.Ctx.getPrintingPolicy();
1943 if (
const auto *MD = dyn_cast<CXXMethodDecl>(Callee)) {
1945 ExplicitInstanceParam = MD->isExplicitObjectMemberFunction();
1949 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1952 if (This && IsMemberCall) {
1953 if (
const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
1954 const Expr *
Object = MCE->getImplicitObjectArgument();
1955 Object->printPretty(Out,
nullptr, PrintingPolicy,
1957 if (
Object->getType()->isPointerType())
1961 }
else if (
const auto *OCE =
1962 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
1963 OCE->getArg(0)->printPretty(Out,
nullptr, PrintingPolicy,
1968 This->moveInto(Val);
1971 Info.Ctx.getLValueReferenceType(
This->Designator.MostDerivedType));
1974 Callee->getNameForDiagnostic(Out, PrintingPolicy,
1980 llvm::ListSeparator
Comma;
1981 for (
const ParmVarDecl *Param :
1982 Callee->parameters().slice(ExplicitInstanceParam)) {
1984 const APValue *
V = Info.getParamSlot(Arguments, Param);
1986 V->printPretty(Out, Info.Ctx, Param->getType());
2002 return Info.noteSideEffect();
2007 const auto *BaseExpr =
2008 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.
dyn_cast<
const Expr *>());
2031 if (
const VarDecl *VD = dyn_cast<VarDecl>(D))
2032 return VD->hasGlobalStorage();
2046 case Expr::CompoundLiteralExprClass: {
2050 case Expr::MaterializeTemporaryExprClass:
2055 case Expr::StringLiteralClass:
2056 case Expr::PredefinedExprClass:
2057 case Expr::ObjCStringLiteralClass:
2058 case Expr::ObjCEncodeExprClass:
2060 case Expr::ObjCBoxedExprClass:
2061 case Expr::ObjCArrayLiteralClass:
2062 case Expr::ObjCDictionaryLiteralClass:
2064 case Expr::CallExprClass:
2067 case Expr::AddrLabelExprClass:
2071 case Expr::BlockExprClass:
2075 case Expr::SourceLocExprClass:
2077 case Expr::ImplicitValueInitExprClass:
2087 llvm_unreachable(
"Unhandled stmt kind in switch with default?");
2104 const auto *BaseExpr = LVal.Base.
dyn_cast<
const Expr *>();
2109 if (
const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2110 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2118 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2119 if (
const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2120 Lit = PE->getFunctionName();
2125 AsString.
Bytes = Lit->getBytes();
2126 AsString.
CharWidth = Lit->getCharByteWidth();
2146 const LValue &RHS) {
2155 CharUnits Offset = RHS.Offset - LHS.Offset;
2156 if (Offset.isNegative()) {
2157 if (LHSString.
Bytes.size() < (
size_t)-Offset.getQuantity())
2159 LHSString.
Bytes = LHSString.
Bytes.drop_front(-Offset.getQuantity());
2161 if (RHSString.
Bytes.size() < (
size_t)Offset.getQuantity())
2163 RHSString.
Bytes = RHSString.
Bytes.drop_front(Offset.getQuantity());
2166 bool LHSIsLonger = LHSString.
Bytes.size() > RHSString.
Bytes.size();
2167 StringRef Longer = LHSIsLonger ? LHSString.
Bytes : RHSString.
Bytes;
2168 StringRef Shorter = LHSIsLonger ? RHSString.
Bytes : LHSString.
Bytes;
2169 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2174 for (
int NullByte : llvm::seq(ShorterCharWidth)) {
2175 if (Shorter.size() + NullByte >= Longer.size())
2177 if (Longer[Shorter.size() + NullByte])
2183 return Shorter == Longer.take_front(Shorter.size());
2193 if (isa_and_nonnull<VarDecl>(
Decl)) {
2203 if (!A.getLValueBase())
2204 return !B.getLValueBase();
2205 if (!B.getLValueBase())
2208 if (A.getLValueBase().getOpaqueValue() !=
2209 B.getLValueBase().getOpaqueValue())
2212 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2213 A.getLValueVersion() == B.getLValueVersion();
2217 assert(
Base &&
"no location for a null lvalue");
2223 if (
auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2225 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2226 if (F->Arguments.CallIndex ==
Base.getCallIndex() &&
2227 F->Arguments.Version ==
Base.getVersion() && F->Callee &&
2228 Idx < F->Callee->getNumParams()) {
2229 VD = F->Callee->getParamDecl(Idx);
2236 Info.Note(VD->
getLocation(), diag::note_declared_at);
2238 Info.Note(E->
getExprLoc(), diag::note_constexpr_temporary_here);
2241 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2242 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2243 diag::note_constexpr_dynamic_alloc_here);
2265 bool IsCompleteClass =
true);
2277 const SubobjectDesignator &
Designator = LVal.getLValueDesignator();
2286 int InvalidBaseKind = -1;
2289 InvalidBaseKind = 0;
2290 else if (isa_and_nonnull<StringLiteral>(BaseE))
2291 InvalidBaseKind = 1;
2292 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2293 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2294 InvalidBaseKind = 2;
2295 else if (
auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2296 InvalidBaseKind = 3;
2297 Ident = PE->getIdentKindName();
2300 if (InvalidBaseKind != -1) {
2301 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2302 << IsReferenceType << !
Designator.Entries.empty() << InvalidBaseKind
2308 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2309 FD && FD->isImmediateFunction()) {
2310 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2312 Info.Note(FD->getLocation(), diag::note_declared_at);
2320 if (Info.getLangOpts().CPlusPlus11) {
2321 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2322 << IsReferenceType << !
Designator.Entries.empty() << !!BaseVD
2324 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2325 if (VarD && VarD->isConstexpr()) {
2331 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2343 assert((Info.checkingPotentialConstantExpression() ||
2344 LVal.getLValueCallIndex() == 0) &&
2345 "have call index for global lvalue");
2347 if (LVal.allowConstexprUnknown()) {
2349 Info.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << BaseVD;
2358 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2359 << IsReferenceType << !
Designator.Entries.empty();
2365 if (
const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2367 if (Var->getTLSKind())
2376 !Var->isStaticLocal())
2380 if (Info.getLangOpts().CUDA && Var->hasAttr<HIPManagedAttr>())
2385 if (Info.getLangOpts().CUDA && Info.getLangOpts().CUDAIsDevice &&
2386 Info.Ctx.CUDAConstantEvalCtx.NoWrongSidedVars) {
2387 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2388 !Var->hasAttr<CUDAConstantAttr>() &&
2389 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2390 !Var->getType()->isCUDADeviceBuiltinTextureType()))
2394 if (
const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2406 FD->hasAttr<DLLImportAttr>())
2410 }
else if (
const auto *MTE =
2411 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2412 if (CheckedTemps.insert(MTE).second) {
2415 Info.FFDiag(MTE->getExprLoc(),
2416 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2421 APValue *
V = MTE->getOrCreateValue(
false);
2422 assert(
V &&
"evasluation result refers to uninitialised temporary");
2424 Info, MTE->getExprLoc(), TempType, *
V, Kind,
2425 nullptr, CheckedTemps))
2432 if (!IsReferenceType)
2444 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2445 << !
Designator.Entries.empty() << !!BaseVD << BaseVD;
2460 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(
Member);
2463 if (FD->isImmediateFunction()) {
2464 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << 0;
2465 Info.Note(FD->getLocation(), diag::note_declared_at);
2469 !FD->hasAttr<DLLImportAttr>();
2475 const LValue *
This =
nullptr) {
2477 if (Info.getLangOpts().CPlusPlus23)
2496 if (
This && Info.EvaluatingDecl ==
This->getLValueBase())
2500 if (Info.getLangOpts().CPlusPlus11)
2501 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2504 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2514 bool IsCompleteClass) {
2516 if (SubobjectDecl) {
2517 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2518 << 1 << SubobjectDecl;
2520 diag::note_constexpr_subobject_declared_here);
2522 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2531 Type = AT->getValueType();
2536 if (
Value.isArray()) {
2538 for (
unsigned I = 0, N =
Value.getArrayInitializedElts(); I != N; ++I) {
2540 Value.getArrayInitializedElt(I), Kind,
2541 SubobjectDecl, CheckedTemps))
2544 if (!
Value.hasArrayFiller())
2547 Value.getArrayFiller(), Kind, SubobjectDecl,
2550 if (
Value.isUnion() &&
Value.getUnionField()) {
2553 Value.getUnionValue(), Kind,
Value.getUnionField(), CheckedTemps);
2555 if (
Value.isStruct()) {
2557 if (
const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2558 unsigned BaseIndex = 0;
2562 const APValue &BaseValue =
Value.getStructBase(BaseIndex);
2565 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2566 << BS.getType() <<
SourceRange(TypeBeginLoc, BS.getEndLoc());
2571 CheckedTemps,
false))
2576 for (
const auto *I : RD->fields()) {
2577 if (I->isUnnamedBitField())
2581 Value.getStructField(I->getFieldIndex()), Kind,
2586 if (IsCompleteClass) {
2587 if (
const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2588 unsigned BaseIndex = 0;
2590 assert(BS.isVirtual());
2591 const APValue &BaseValue =
Value.getStructVirtualBase(BaseIndex);
2594 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2595 << BS.getType() <<
SourceRange(TypeBeginLoc, BS.getEndLoc());
2599 BaseValue, Kind,
nullptr,
2600 CheckedTemps,
false))
2608 if (
Value.isLValue() &&
2611 LVal.setFrom(Info.Ctx,
Value);
2616 if (
Value.isMemberPointer() &&
2637 nullptr, CheckedTemps);
2647 ConstantExprKind::Normal,
nullptr, CheckedTemps);
2653 if (!Info.HeapAllocs.empty()) {
2657 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2658 diag::note_constexpr_memory_leak)
2659 <<
unsigned(Info.HeapAllocs.size() - 1);
2667 if (!
Value.getLValueBase()) {
2721 llvm_unreachable(
"unknown APValue kind");
2727 assert(E->
isPRValue() &&
"missing lvalue-to-rvalue conv in bool condition");
2737 Info.CCEDiag(E, diag::note_constexpr_overflow) << SrcValue << DestType;
2738 if (
const auto *OBT = DestType->
getAs<OverflowBehaviorType>();
2739 OBT && OBT->isTrapKind()) {
2742 return Info.noteUndefinedBehavior();
2748 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2759 if (
Value.convertToInteger(
Result, llvm::APFloat::rmTowardZero, &ignored)
2760 & APFloat::opInvalidOp)
2771 llvm::RoundingMode RM =
2773 if (RM == llvm::RoundingMode::Dynamic)
2774 RM = llvm::RoundingMode::NearestTiesToEven;
2783 APFloat::opStatus St) {
2786 if (Info.InConstantContext)
2790 if ((St & APFloat::opInexact) &&
2794 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2798 if ((St != APFloat::opOK) &&
2801 FPO.getAllowFEnvAccess())) {
2802 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2806 if ((St & APFloat::opStatus::opInvalidOp) &&
2827 "HandleFloatToFloatCast has been checked with only CastExpr, "
2828 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2829 "the new expression or address the root cause of this usage.");
2831 APFloat::opStatus St;
2833 St =
Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2840 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2854 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2856 APFloat::opStatus St =
Result.convertFromAPInt(
Value,
Value.isSigned(), RM);
2862 assert(FD->
isBitField() &&
"truncateBitfieldValue on non-bitfield");
2864 if (!
Value.isInt()) {
2868 assert(
Value.isLValue() &&
"integral value neither int nor lvalue?");
2874 unsigned OldBitWidth =
Int.getBitWidth();
2876 if (NewBitWidth < OldBitWidth)
2877 Int =
Int.trunc(NewBitWidth).extend(OldBitWidth);
2884template<
typename Operation>
2887 unsigned BitWidth, Operation Op,
2889 if (LHS.isUnsigned()) {
2894 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)),
false);
2897 if (Info.checkingForUndefinedBehavior())
2898 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
2899 diag::warn_integer_constant_overflow)
2912 bool HandleOverflowResult =
true;
2919 std::multiplies<APSInt>(),
Result);
2922 std::plus<APSInt>(),
Result);
2925 std::minus<APSInt>(),
Result);
2926 case BO_And:
Result = LHS & RHS;
return true;
2927 case BO_Xor:
Result = LHS ^ RHS;
return true;
2928 case BO_Or:
Result = LHS | RHS;
return true;
2932 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2938 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2939 LHS.isMinSignedValue())
2941 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->
getType());
2942 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2943 return HandleOverflowResult;
2945 if (Info.getLangOpts().OpenCL)
2947 RHS &=
APSInt(llvm::APInt(RHS.getBitWidth(),
2948 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2950 else if (RHS.isSigned() && RHS.isNegative()) {
2953 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2954 if (!Info.noteUndefinedBehavior())
2962 unsigned SA = (
unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2964 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2965 << RHS << E->
getType() << LHS.getBitWidth();
2966 if (!Info.noteUndefinedBehavior())
2968 }
else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2973 if (LHS.isNegative()) {
2974 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2975 if (!Info.noteUndefinedBehavior())
2977 }
else if (LHS.countl_zero() < SA) {
2978 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2979 if (!Info.noteUndefinedBehavior())
2987 if (Info.getLangOpts().OpenCL)
2989 RHS &=
APSInt(llvm::APInt(RHS.getBitWidth(),
2990 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2992 else if (RHS.isSigned() && RHS.isNegative()) {
2995 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2996 if (!Info.noteUndefinedBehavior())
3004 unsigned SA = (
unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3006 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3007 << RHS << E->
getType() << LHS.getBitWidth();
3008 if (!Info.noteUndefinedBehavior())
3016 case BO_LT:
Result = LHS < RHS;
return true;
3017 case BO_GT:
Result = LHS > RHS;
return true;
3018 case BO_LE:
Result = LHS <= RHS;
return true;
3019 case BO_GE:
Result = LHS >= RHS;
return true;
3020 case BO_EQ:
Result = LHS == RHS;
return true;
3021 case BO_NE:
Result = LHS != RHS;
return true;
3023 llvm_unreachable(
"BO_Cmp should be handled elsewhere");
3030 const APFloat &RHS) {
3032 APFloat::opStatus St;
3038 St = LHS.multiply(RHS, RM);
3041 St = LHS.add(RHS, RM);
3044 St = LHS.subtract(RHS, RM);
3050 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3051 St = LHS.divide(RHS, RM);
3064 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3065 return Info.noteUndefinedBehavior();
3073 const APInt &RHSValue, APInt &
Result) {
3074 bool LHS = (LHSValue != 0);
3075 bool RHS = (RHSValue != 0);
3077 if (Opcode == BO_LAnd)
3085 const APFloat &RHSValue, APInt &
Result) {
3086 bool LHS = !LHSValue.isZero();
3087 bool RHS = !RHSValue.isZero();
3089 if (Opcode == BO_LAnd)
3108template <
typename APTy>
3111 const APTy &RHSValue, APInt &
Result) {
3114 llvm_unreachable(
"unsupported binary operator");
3116 Result = (LHSValue == RHSValue);
3119 Result = (LHSValue != RHSValue);
3122 Result = (LHSValue < RHSValue);
3125 Result = (LHSValue > RHSValue);
3128 Result = (LHSValue <= RHSValue);
3131 Result = (LHSValue >= RHSValue);
3160 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3161 "Operation not supported on vector types");
3165 QualType EltTy = VT->getElementType();
3172 "A vector result that isn't a vector OR uncalculated LValue");
3178 RHSValue.
getVectorLength() == NumElements &&
"Different vector sizes");
3182 for (
unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3187 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3197 RHSElt.
getInt(), EltResult);
3203 ResultElements.emplace_back(EltResult);
3208 "Mismatched LHS/RHS/Result Type");
3209 APFloat LHSFloat = LHSElt.
getFloat();
3217 ResultElements.emplace_back(LHSFloat);
3221 LHSValue =
APValue(ResultElements.data(), ResultElements.size());
3229 unsigned TruncatedElements) {
3230 SubobjectDesignator &D =
Result.Designator;
3233 if (TruncatedElements == D.Entries.size())
3235 assert(TruncatedElements >= D.MostDerivedPathLength &&
3236 "not casting to a derived class");
3242 for (
unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3246 if (isVirtualBaseClass(D.Entries[I]))
3252 D.Entries.resize(TruncatedElements);
3262 RL = &Info.Ctx.getASTRecordLayout(Derived);
3265 Obj.addDecl(Info, E,
Base,
false);
3266 Obj.getLValueOffset() += RL->getBaseClassOffset(
Base);
3278 RL = &Info.Ctx.getASTRecordLayout(Derived);
3281 Obj.addDecl(Info, E,
Base,
true);
3282 Obj.getLValueOffset() += RL->getVBaseClassOffset(
Base);
3291 if (!
Base->isVirtual())
3294 SubobjectDesignator &D = Obj.Designator;
3309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3310 Obj.addDecl(Info, E, BaseDecl,
true);
3319 PathI != PathE; ++PathI) {
3323 Type = (*PathI)->getType();
3335 llvm_unreachable(
"Class must be derived from the passed in base class!");
3359 RL = &Info.Ctx.getASTRecordLayout(RD);
3363 LVal.addDecl(Info, E, FD);
3364 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3372 for (
const auto *
C : IFD->
chain())
3406 Size = Info.Ctx.getTypeSizeInChars(
Type);
3408 Size = Info.Ctx.getTypeInfoDataSizeInChars(
Type).Width;
3425 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3433 APSInt::get(Adjustment));
3448 LVal.Offset += SizeOfComponent;
3450 LVal.addComplex(Info, E, EltTy, Imag);
3461 LVal.Offset += SizeOfElement * Idx;
3463 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3477 const VarDecl *VD, CallStackFrame *Frame,
3481 bool AllowConstexprUnknown =
3486 auto CheckUninitReference = [&](
bool IsLocalVariable) {
3498 if (!AllowConstexprUnknown || IsLocalVariable) {
3499 if (!Info.checkingPotentialConstantExpression())
3500 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
3510 Result = Frame->getTemporary(VD, Version);
3512 return CheckUninitReference(
true);
3521 "missing value for local variable");
3522 if (Info.checkingPotentialConstantExpression())
3526 "A variable in a frame should either be a local or a parameter");
3532 if (Info.EvaluatingDecl ==
Base) {
3533 Result = Info.EvaluatingDeclValue;
3534 return CheckUninitReference(
false);
3542 if (AllowConstexprUnknown) {
3549 if (!Info.checkingPotentialConstantExpression() ||
3550 !Info.CurrentCall->Callee ||
3552 if (Info.getLangOpts().CPlusPlus11) {
3553 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3574 if (!
Init && !AllowConstexprUnknown) {
3577 if (!Info.checkingPotentialConstantExpression()) {
3578 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3589 if (
Init &&
Init->isValueDependent()) {
3590 if (!Info.checkingPotentialConstantExpression()) {
3592 Info.getLangOpts().CPlusPlus11
3593 ? diag::note_constexpr_ltor_non_constexpr
3594 : diag::note_constexpr_ltor_non_integral,
3602 if (
Init->containsErrors())
3621 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3637 !AllowConstexprUnknown) ||
3638 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3641 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3651 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3658 if (!
Result && !AllowConstexprUnknown)
3661 return CheckUninitReference(
false);
3684 llvm_unreachable(
"base class missing from derived class's bases list");
3691 "SourceLocExpr should have already been converted to a StringLiteral");
3694 if (
const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3696 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3697 assert(Index <= Str.size() &&
"Index too large");
3698 return APSInt::getUnsigned(Str.c_str()[Index]);
3701 if (
auto PE = dyn_cast<PredefinedExpr>(Lit))
3702 Lit = PE->getFunctionName();
3705 Info.Ctx.getAsConstantArrayType(S->
getType());
3706 assert(CAT &&
"string literal isn't an array");
3708 assert(CharType->
isIntegerType() &&
"unexpected character type");
3711 if (Index < S->getLength())
3724 AllocType.isNull() ? S->
getType() : AllocType);
3725 assert(CAT &&
"string literal isn't an array");
3727 assert(CharType->
isIntegerType() &&
"unexpected character type");
3734 if (
Result.hasArrayFiller())
3736 for (
unsigned I = 0, N =
Result.getArrayInitializedElts(); I != N; ++I) {
3744 unsigned Size =
Array.getArraySize();
3745 assert(Index < Size);
3748 unsigned OldElts =
Array.getArrayInitializedElts();
3749 unsigned NewElts = std::max(Index+1, OldElts * 2);
3750 NewElts = std::min(Size, std::max(NewElts, 8u));
3754 for (
unsigned I = 0; I != OldElts; ++I)
3756 for (
unsigned I = OldElts; I != NewElts; ++I)
3760 Array.swap(NewValue);
3767 Vec =
APValue(Elts.data(), Elts.size());
3777 CXXRecordDecl *RD =
T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3788 for (
auto *Field : RD->
fields())
3789 if (!Field->isUnnamedBitField() &&
3793 for (
auto &BaseSpec : RD->
bases())
3804 CXXRecordDecl *RD =
T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3811 for (
auto *Field : RD->
fields()) {
3816 if (Field->isMutable() &&
3818 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3819 Info.Note(Field->getLocation(), diag::note_declared_at);
3827 for (
auto &BaseSpec : RD->
bases())
3837 bool MutableSubobject =
false) {
3842 switch (Info.IsEvaluatingDecl) {
3843 case EvalInfo::EvaluatingDeclKind::None:
3846 case EvalInfo::EvaluatingDeclKind::Ctor:
3848 if (Info.EvaluatingDecl ==
Base)
3853 if (
auto *BaseE =
Base.dyn_cast<
const Expr *>())
3854 if (
auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3855 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3858 case EvalInfo::EvaluatingDeclKind::Dtor:
3863 if (MutableSubobject ||
Base != Info.EvaluatingDecl)
3869 return T.isConstQualified() ||
T->isReferenceType();
3872 llvm_unreachable(
"unknown evaluating decl kind");
3877 return Info.CheckArraySize(
3900 : Info.Ctx.getIntTypeForBitwidth(64,
false);
3901 Result =
APValue(Info.Ctx.MakeIntValue(IntResult, IntType));
3906 Info.Ctx.getIntTypeForBitwidth(64,
false),
3909 Result = std::move(Result2);
3917 DestTy,
Result.getFloat());
3949 DestTy,
Result.getInt());
3953 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3966 {&
Result, ResultType, 0}};
3969 while (!WorkList.empty() && ElI < Elements.size()) {
3970 auto [Res,
Type, BitWidth] = WorkList.pop_back_val();
3987 unsigned OldBitWidth =
Int.getBitWidth();
3988 unsigned NewBitWidth = BitWidth;
3989 if (NewBitWidth < OldBitWidth)
3990 Int =
Int.trunc(NewBitWidth).extend(OldBitWidth);
3999 for (
unsigned I = 0; I < NumEl; ++I) {
4005 *Res =
APValue(Vals.data(), NumEl);
4014 for (
int64_t I = Size - 1; I > -1; --I)
4015 WorkList.emplace_back(&Res->getArrayInitializedElt(I), ElTy, 0u);
4021 unsigned NumBases = 0;
4022 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
4023 NumBases = CXXRD->getNumBases();
4030 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4031 if (CXXRD->getNumBases() > 0) {
4032 assert(CXXRD->getNumBases() == 1);
4034 ReverseList.emplace_back(&Res->getStructBase(0), BS.
getType(), 0u);
4041 if (FD->isUnnamedBitField())
4043 if (FD->isBitField()) {
4044 FDBW = FD->getBitWidthValue();
4047 ReverseList.emplace_back(&Res->getStructField(FD->getFieldIndex()),
4048 FD->getType(), FDBW);
4051 std::reverse(ReverseList.begin(), ReverseList.end());
4052 llvm::append_range(WorkList, ReverseList);
4055 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4068 assert((Elements.size() == SrcTypes.size()) &&
4069 (Elements.size() == DestTypes.size()));
4071 for (
unsigned I = 0, ESz = Elements.size(); I < ESz; ++I) {
4072 APValue Original = Elements[I];
4076 if (!
handleScalarCast(Info, FPO, E, SourceTy, DestTy, Original, Results[I]))
4087 while (!WorkList.empty()) {
4110 for (
uint64_t I = 0; I < ArrSize; ++I) {
4111 WorkList.push_back(ElTy);
4119 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4120 if (CXXRD->getNumBases() > 0) {
4121 assert(CXXRD->getNumBases() == 1);
4123 WorkList.push_back(BS.
getType());
4129 if (FD->isUnnamedBitField())
4131 WorkList.push_back(FD->getType());
4148 "Not a valid HLSLAggregateSplatCast.");
4168 unsigned Populated = 0;
4169 while (!WorkList.empty() && Populated < Size) {
4170 auto [Work,
Type] = WorkList.pop_back_val();
4172 if (Work.isFloat() || Work.isInt()) {
4173 Elements.push_back(Work);
4174 Types.push_back(
Type);
4178 if (Work.isVector()) {
4181 for (
unsigned I = 0; I < Work.getVectorLength() && Populated < Size;
4183 Elements.push_back(Work.getVectorElt(I));
4184 Types.push_back(ElTy);
4189 if (Work.isMatrix()) {
4192 QualType ElTy = MT->getElementType();
4194 for (
unsigned Row = 0; Row < Work.getMatrixNumRows() && Populated < Size;
4196 for (
unsigned Col = 0;
4197 Col < Work.getMatrixNumColumns() && Populated < Size; Col++) {
4198 Elements.push_back(Work.getMatrixElt(Row, Col));
4199 Types.push_back(ElTy);
4205 if (Work.isArray()) {
4209 for (
int64_t I = Work.getArraySize() - 1; I > -1; --I) {
4210 WorkList.emplace_back(Work.getArrayInitializedElt(I), ElTy);
4215 if (Work.isStruct()) {
4223 if (FD->isUnnamedBitField())
4225 ReverseList.emplace_back(Work.getStructField(FD->getFieldIndex()),
4229 std::reverse(ReverseList.begin(), ReverseList.end());
4230 llvm::append_range(WorkList, ReverseList);
4233 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4234 if (CXXRD->getNumBases() > 0) {
4235 assert(CXXRD->getNumBases() == 1);
4240 if (!
Base.isStruct())
4248 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4257struct CompleteObject {
4259 APValue::LValueBase
Base;
4269 bool mayAccessMutableMembers(EvalInfo &Info,
AccessKinds AK)
const {
4280 if (!Info.getLangOpts().CPlusPlus14 &&
4281 AK != AccessKinds::AK_IsWithinLifetime)
4286 explicit operator bool()
const {
return !
Type.isNull(); }
4291 bool IsMutable =
false) {
4305template <
typename Sub
objectHandler>
4306static typename SubobjectHandler::result_type
4308 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
4311 return handler.failed();
4312 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
4313 if (Info.getLangOpts().CPlusPlus11)
4314 Info.FFDiag(E, Sub.isOnePastTheEnd()
4315 ? diag::note_constexpr_access_past_end
4316 : diag::note_constexpr_access_unsized_array)
4317 << handler.AccessKind;
4320 return handler.failed();
4326 const FieldDecl *VolatileField =
nullptr;
4329 for (
unsigned I = 0, N = Sub.Entries.size(); ; ++I) {
4340 if (!Info.checkingPotentialConstantExpression()) {
4341 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4346 return handler.failed();
4354 Info.isEvaluatingCtorDtor(
4355 Obj.Base,
ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
4356 ConstructionPhase::None) {
4357 ObjType = Info.Ctx.getCanonicalType(ObjType);
4366 if (Info.getLangOpts().CPlusPlus) {
4370 if (VolatileField) {
4373 Decl = VolatileField;
4376 Loc = VD->getLocation();
4383 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
4384 << handler.AccessKind << DiagKind <<
Decl;
4385 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
4387 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
4389 return handler.failed();
4397 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
4399 return handler.failed();
4403 if (!handler.found(*O, ObjType, Obj.Base))
4415 LastField =
nullptr;
4420 ObjType = Info.Ctx.getQualifiedType(AT->getValueType(),
4425 const ArrayType *AT = Info.Ctx.getAsArrayType(ObjType);
4427 "vla in literal type?");
4428 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4429 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4430 CAT && CAT->
getSize().ule(Index)) {
4433 if (Info.getLangOpts().CPlusPlus11)
4434 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4435 << handler.AccessKind;
4438 return handler.failed();
4445 else if (!
isRead(handler.AccessKind)) {
4446 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT);
4448 return handler.failed();
4456 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4458 if (Info.getLangOpts().CPlusPlus11)
4459 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4460 << handler.AccessKind;
4463 return handler.failed();
4469 assert(I == N - 1 &&
"extracting subobject of scalar?");
4479 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4480 unsigned NumElements = VT->getNumElements();
4481 if (Index == NumElements) {
4482 if (Info.getLangOpts().CPlusPlus11)
4483 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4484 << handler.AccessKind;
4487 return handler.failed();
4490 if (Index > NumElements) {
4491 Info.CCEDiag(E, diag::note_constexpr_array_index)
4492 << Index << 0 << NumElements;
4493 return handler.failed();
4496 ObjType = VT->getElementType();
4497 assert(I == N - 1 &&
"extracting subobject of scalar?");
4500 if (
isRead(handler.AccessKind)) {
4502 return handler.failed();
4506 assert(O->
isVector() &&
"unexpected object during vector element access");
4507 return handler.found(O->
getVectorElt(Index), ObjType, Obj.Base);
4508 }
else if (
const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4509 if (Field->isMutable() &&
4510 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4511 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4512 << handler.AccessKind << Field;
4513 Info.Note(Field->getLocation(), diag::note_declared_at);
4514 return handler.failed();
4523 if (I == N - 1 && handler.AccessKind ==
AK_Construct) {
4534 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4535 << handler.AccessKind << Field << !UnionField << UnionField;
4536 return handler.failed();
4545 if (Field->getType().isVolatileQualified())
4546 VolatileField = Field;
4554 if (BaseIndex >= NumNonVirtualBases) {
4565struct ExtractSubobjectHandler {
4571 typedef bool result_type;
4572 bool failed() {
return false; }
4573 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4583 bool found(APFloat &
Value, QualType SubobjType) {
4592 const CompleteObject &Obj,
4596 ExtractSubobjectHandler Handler = {Info, E,
Result, AK};
4601struct ModifySubobjectHandler {
4606 typedef bool result_type;
4609 bool checkConst(QualType QT) {
4612 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4618 bool failed() {
return false; }
4619 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
4620 if (!checkConst(SubobjType))
4623 Subobj.
swap(NewVal);
4627 if (!checkConst(SubobjType))
4629 if (!NewVal.
isInt()) {
4637 bool found(APFloat &
Value, QualType SubobjType) {
4638 if (!checkConst(SubobjType))
4646const AccessKinds ModifySubobjectHandler::AccessKind;
4650 const CompleteObject &Obj,
4651 const SubobjectDesignator &Sub,
4653 ModifySubobjectHandler Handler = { Info, NewVal, E };
4660 const SubobjectDesignator &A,
4661 const SubobjectDesignator &B,
4662 bool &WasArrayIndex) {
4663 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4664 for (; I != N; ++I) {
4668 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4669 WasArrayIndex =
true;
4677 if (A.Entries[I].getAsBaseOrMember() !=
4678 B.Entries[I].getAsBaseOrMember()) {
4679 WasArrayIndex =
false;
4682 if (
const FieldDecl *FD = getAsField(A.Entries[I]))
4684 ObjType = FD->getType();
4690 WasArrayIndex =
false;
4697 const SubobjectDesignator &A,
4698 const SubobjectDesignator &B) {
4699 if (A.Entries.size() != B.Entries.size())
4702 bool IsArray = A.MostDerivedIsArrayElement;
4703 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4712 return CommonLength >= A.Entries.size() - IsArray;
4719 if (LVal.InvalidBase) {
4721 return CompleteObject();
4726 Info.FFDiag(E, diag::note_constexpr_dereferencing_null);
4728 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4729 return CompleteObject();
4732 CallStackFrame *Frame =
nullptr;
4734 if (LVal.getLValueCallIndex()) {
4735 std::tie(Frame, Depth) =
4736 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4738 Info.FFDiag(E, diag::note_constexpr_access_uninit, 1)
4741 return CompleteObject();
4752 if (Info.getLangOpts().CPlusPlus)
4753 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4757 return CompleteObject();
4764 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4768 BaseVal = Info.EvaluatingDeclValue;
4771 if (
auto *GD = dyn_cast<MSGuidDecl>(D)) {
4774 Info.FFDiag(E, diag::note_constexpr_modify_global);
4775 return CompleteObject();
4779 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4781 return CompleteObject();
4783 return CompleteObject(LVal.Base, &
V, GD->getType());
4787 if (
auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4789 Info.FFDiag(E, diag::note_constexpr_modify_global);
4790 return CompleteObject();
4792 return CompleteObject(LVal.Base,
const_cast<APValue *
>(&GCD->getValue()),
4797 if (
auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4799 Info.FFDiag(E, diag::note_constexpr_modify_global);
4800 return CompleteObject();
4802 return CompleteObject(LVal.Base,
const_cast<APValue *
>(&TPO->getValue()),
4813 const VarDecl *VD = dyn_cast<VarDecl>(D);
4820 return CompleteObject();
4823 bool IsConstant = BaseType.isConstant(Info.Ctx);
4824 bool ConstexprVar =
false;
4825 if (
const auto *VD = dyn_cast_if_present<VarDecl>(
4837 }
else if (Info.getLangOpts().CPlusPlus14 &&
4844 Info.FFDiag(E, diag::note_constexpr_modify_global);
4845 return CompleteObject();
4848 }
else if (Info.getLangOpts().C23 && ConstexprVar) {
4850 return CompleteObject();
4853 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4854 Info.FFDiag(E, diag::note_constexpr_ltor_for_range_var) << VD;
4855 return CompleteObject();
4856 }
else if (BaseType->isIntegralOrEnumerationType()) {
4859 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4860 if (Info.getLangOpts().CPlusPlus) {
4861 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4862 Info.Note(VD->
getLocation(), diag::note_declared_at);
4866 return CompleteObject();
4868 }
else if (!IsAccess) {
4869 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4870 }
else if ((IsConstant || BaseType->isReferenceType()) &&
4871 Info.checkingPotentialConstantExpression() &&
4872 BaseType->isLiteralType(Info.Ctx) && !VD->
hasDefinition()) {
4874 }
else if (IsConstant) {
4878 if (Info.getLangOpts().CPlusPlus) {
4879 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4880 ? diag::note_constexpr_ltor_non_constexpr
4881 : diag::note_constexpr_ltor_non_integral, 1)
4883 Info.Note(VD->
getLocation(), diag::note_declared_at);
4889 if (Info.getLangOpts().CPlusPlus) {
4890 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4891 ? diag::note_constexpr_ltor_non_constexpr
4892 : diag::note_constexpr_ltor_non_integral, 1)
4894 Info.Note(VD->
getLocation(), diag::note_declared_at);
4898 return CompleteObject();
4907 return CompleteObject();
4912 if (!Info.checkingPotentialConstantExpression()) {
4913 Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
4915 Info.Note(VD->getLocation(), diag::note_declared_at);
4917 return CompleteObject();
4920 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4922 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4923 return CompleteObject();
4925 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4935 dyn_cast_or_null<MaterializeTemporaryExpr>(
Base)) {
4936 assert(MTE->getStorageDuration() ==
SD_Static &&
4937 "should have a frame for a non-global materialized temporary");
4964 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4967 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
4968 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4969 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4970 return CompleteObject();
4973 BaseVal = MTE->getOrCreateValue(
false);
4974 assert(BaseVal &&
"got reference to unevaluated temporary");
4976 dyn_cast_or_null<CompoundLiteralExpr>(
Base)) {
4992 !CLETy.isConstant(Info.Ctx)) {
4994 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4995 return CompleteObject();
4998 BaseVal = &CLE->getStaticValue();
5001 return CompleteObject(LVal.getLValueBase(),
nullptr, BaseType);
5004 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
5007 Info.Ctx.getLValueReferenceType(LValType));
5009 return CompleteObject();
5013 assert(BaseVal &&
"missing value for temporary");
5024 unsigned VisibleDepth = Depth;
5025 if (llvm::isa_and_nonnull<ParmVarDecl>(
5028 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
5029 Info.EvalStatus.HasSideEffects) ||
5030 (
isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
5031 return CompleteObject();
5033 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
5052 const LValue &LVal,
APValue &RVal,
5053 bool WantObjectRepresentation =
false) {
5054 if (LVal.Designator.Invalid)
5063 if (
Base && !LVal.getLValueCallIndex() && !
Type.isVolatileQualified()) {
5067 assert(LVal.Designator.Entries.size() <= 1 &&
5068 "Can only read characters from string literals");
5069 if (LVal.Designator.Entries.empty()) {
5076 if (LVal.Designator.isOnePastTheEnd()) {
5077 if (Info.getLangOpts().CPlusPlus11)
5078 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
5083 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
5090 return Obj &&
extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
5104 LVal.setFrom(Info.Ctx, Val);
5120 if (LVal.Designator.Invalid)
5123 if (!Info.getLangOpts().CPlusPlus14) {
5133struct CompoundAssignSubobjectHandler {
5135 const CompoundAssignOperator *E;
5136 QualType PromotedLHSType;
5142 typedef bool result_type;
5144 bool checkConst(QualType QT) {
5147 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5153 bool failed() {
return false; }
5154 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5157 return found(Subobj.
getInt(), SubobjType);
5159 return found(Subobj.
getFloat(), SubobjType);
5166 return foundPointer(Subobj, SubobjType);
5168 return foundVector(Subobj, SubobjType);
5170 Info.FFDiag(E, diag::note_constexpr_access_uninit)
5182 bool foundVector(
APValue &
Value, QualType SubobjType) {
5183 if (!checkConst(SubobjType))
5194 if (!checkConst(SubobjType))
5213 Info.Ctx.getLangOpts());
5216 PromotedLHSType, FValue) &&
5225 bool found(APFloat &
Value, QualType SubobjType) {
5226 return checkConst(SubobjType) &&
5232 bool foundPointer(
APValue &Subobj, QualType SubobjType) {
5233 if (!checkConst(SubobjType))
5236 QualType PointeeType;
5237 if (
const PointerType *PT = SubobjType->
getAs<PointerType>())
5241 (Opcode != BO_Add && Opcode != BO_Sub)) {
5247 if (Opcode == BO_Sub)
5251 LVal.setFrom(Info.Ctx, Subobj);
5254 LVal.moveInto(Subobj);
5260const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
5265 const LValue &LVal,
QualType LValType,
5269 if (LVal.Designator.Invalid)
5272 if (!Info.getLangOpts().CPlusPlus14) {
5278 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
5280 return Obj &&
findSubobject(Info, E, Obj, LVal.Designator, Handler);
5284struct IncDecSubobjectHandler {
5286 const UnaryOperator *E;
5290 typedef bool result_type;
5292 bool checkConst(QualType QT) {
5295 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
5301 bool failed() {
return false; }
5302 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
5312 return found(Subobj.
getInt(), SubobjType);
5314 return found(Subobj.
getFloat(), SubobjType);
5317 SubobjType->
castAs<ComplexType>()->getElementType()
5321 SubobjType->
castAs<ComplexType>()->getElementType()
5324 return foundPointer(Subobj, SubobjType);
5332 if (!checkConst(SubobjType))
5354 bool WasNegative =
Value.isNegative();
5368 unsigned BitWidth =
Value.getBitWidth();
5369 APSInt ActualValue(
Value.sext(BitWidth + 1),
false);
5370 ActualValue.setBit(BitWidth);
5376 bool found(APFloat &
Value, QualType SubobjType) {
5377 if (!checkConst(SubobjType))
5384 APFloat::opStatus St;
5386 St =
Value.add(One, RM);
5388 St =
Value.subtract(One, RM);
5391 bool foundPointer(
APValue &Subobj, QualType SubobjType) {
5392 if (!checkConst(SubobjType))
5395 QualType PointeeType;
5396 if (
const PointerType *PT = SubobjType->
getAs<PointerType>())
5404 LVal.setFrom(Info.Ctx, Subobj);
5408 LVal.moveInto(Subobj);
5417 if (LVal.Designator.Invalid)
5420 if (!Info.getLangOpts().CPlusPlus14) {
5428 return Obj &&
findSubobject(Info, E, Obj, LVal.Designator, Handler);
5434 if (
Object->getType()->isPointerType() &&
Object->isPRValue())
5440 if (
Object->getType()->isLiteralType(Info.Ctx))
5443 if (
Object->getType()->isRecordType() &&
Object->isPRValue())
5446 Info.FFDiag(
Object, diag::note_constexpr_nonliteral) <<
Object->getType();
5465 bool IncludeMember =
true) {
5472 if (!MemPtr.getDecl()) {
5478 if (MemPtr.isDerivedMember()) {
5485 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5486 LV.Designator.Entries.size()) {
5490 unsigned PathLengthToMember =
5491 LV.Designator.Entries.size() - MemPtr.Path.size();
5492 for (
unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5494 LV.Designator.Entries[PathLengthToMember + I]);
5511 (PathLengthToMember > LV.Designator.MostDerivedPathLength)
5512 ? getAsBaseClass(LV.Designator.Entries[PathLengthToMember - 1])
5514 const CXXRecordDecl *LastMPDecl = MemPtr.getContainingRecord();
5522 PathLengthToMember))
5524 }
else if (!MemPtr.Path.empty()) {
5526 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5527 MemPtr.Path.size() + IncludeMember);
5533 assert(RD &&
"member pointer access on non-class-type expression");
5535 for (
unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5543 MemPtr.getContainingRecord()))
5548 if (IncludeMember) {
5549 if (
const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5553 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5557 llvm_unreachable(
"can't construct reference to bound member function");
5561 return MemPtr.getDecl();
5567 bool IncludeMember =
true) {
5571 if (Info.noteFailure()) {
5579 BO->
getRHS(), IncludeMember);
5586 SubobjectDesignator &D =
Result.Designator;
5594 auto InvalidCast = [&]() {
5595 if (!Info.checkingPotentialConstantExpression() ||
5596 !
Result.AllowConstexprUnknown) {
5597 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5598 << D.MostDerivedType << TargetQT;
5604 if (D.MostDerivedPathLength + E->
path_size() > D.Entries.size())
5605 return InvalidCast();
5609 unsigned NewEntriesSize = D.Entries.size() - E->
path_size();
5612 if (NewEntriesSize == D.MostDerivedPathLength)
5615 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5617 return InvalidCast();
5626 bool IsCompleteClass =
true) {
5633 if (
auto *RD =
T->getAsCXXRecordDecl()) {
5634 if (RD->isInvalidDecl()) {
5638 if (RD->isUnion()) {
5644 unsigned NonVirtualBases = countNonVirtualBases(RD);
5647 IsCompleteClass ? RD->getNumVBases() : 0);
5658 for (
const auto *I : RD->fields()) {
5659 if (I->isUnnamedBitField())
5662 I->getType(),
Result.getStructField(I->getFieldIndex()));
5665 if (IsCompleteClass) {
5668 for (
const auto &B : RD->vbases()) {
5670 Result.getStructVirtualBase(Index),
5676 assert(
Result.getStructNumVirtualBases() == 0);
5683 dyn_cast_or_null<ConstantArrayType>(
T->getAsArrayTypeUnsafe())) {
5685 if (
Result.hasArrayFiller())
5696enum EvalStmtResult {
5725 if (!
Result.Designator.Invalid &&
Result.Designator.isOnePastTheEnd()) {
5743 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->
getType(),
5744 ScopeKind::Block,
Result);
5749 return Info.noteSideEffect();
5770 const DecompositionDecl *DD);
5773 bool EvaluateConditionDecl =
false) {
5775 if (
const VarDecl *VD = dyn_cast<VarDecl>(D))
5779 EvaluateConditionDecl && DD)
5789 if (
auto *VD = BD->getHoldingVar())
5797 if (
auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
5806 if (Info.noteSideEffect())
5808 assert(E->
containsErrors() &&
"valid value-dependent expression should never "
5809 "reach invalid code path.");
5818 FullExpressionRAII
Scope(Info);
5825 return Scope.destroy();
5838struct TempVersionRAII {
5839 CallStackFrame &Frame;
5841 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5842 Frame.pushTempVersion();
5845 ~TempVersionRAII() {
5846 Frame.popTempVersion();
5854 const SwitchCase *SC =
nullptr);
5860 const Stmt *LoopOrSwitch,
5862 EvalStmtResult &ESR) {
5866 if (!IsSwitch && ESR == ESR_Succeeded) {
5871 if (ESR != ESR_Break && ESR != ESR_Continue)
5875 bool CanBreakOrContinue = !IsSwitch || ESR == ESR_Break;
5876 const Stmt *StackTop = Info.BreakContinueStack.back();
5877 if (CanBreakOrContinue && (StackTop ==
nullptr || StackTop == LoopOrSwitch)) {
5878 Info.BreakContinueStack.pop_back();
5879 if (ESR == ESR_Break)
5880 ESR = ESR_Succeeded;
5885 for (BlockScopeRAII *S : Scopes) {
5886 if (!S->destroy()) {
5898 BlockScopeRAII
Scope(Info);
5901 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !
Scope.destroy())
5910 BlockScopeRAII
Scope(Info);
5917 if (ESR != ESR_Succeeded) {
5918 if (ESR != ESR_Failed && !
Scope.destroy())
5924 FullExpressionRAII CondScope(Info);
5939 if (!CondScope.destroy())
5960 if (LHSValue <=
Value &&
Value <= RHSValue) {
5967 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5971 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !
Scope.destroy())
5978 llvm_unreachable(
"Should have been converted to Succeeded");
5984 case ESR_CaseNotFound:
5987 Info.FFDiag(
Found->getBeginLoc(),
5988 diag::note_constexpr_stmt_expr_unsupported);
5991 llvm_unreachable(
"Invalid EvalStmtResult!");
6001 Info.CCEDiag(VD->
getLocation(), diag::note_constexpr_static_local)
6011 if (!Info.nextStep(S))
6018 case Stmt::CompoundStmtClass:
6022 case Stmt::LabelStmtClass:
6023 case Stmt::AttributedStmtClass:
6024 case Stmt::DoStmtClass:
6027 case Stmt::CaseStmtClass:
6028 case Stmt::DefaultStmtClass:
6033 case Stmt::IfStmtClass: {
6040 BlockScopeRAII
Scope(Info);
6046 if (ESR != ESR_CaseNotFound) {
6047 assert(ESR != ESR_Succeeded);
6058 if (ESR == ESR_Failed)
6060 if (ESR != ESR_CaseNotFound)
6061 return Scope.destroy() ? ESR : ESR_Failed;
6063 return ESR_CaseNotFound;
6066 if (ESR == ESR_Failed)
6068 if (ESR != ESR_CaseNotFound)
6069 return Scope.destroy() ? ESR : ESR_Failed;
6070 return ESR_CaseNotFound;
6073 case Stmt::WhileStmtClass: {
6074 EvalStmtResult ESR =
6078 if (ESR != ESR_Continue)
6083 case Stmt::ForStmtClass: {
6085 BlockScopeRAII
Scope(Info);
6091 if (ESR != ESR_CaseNotFound) {
6092 assert(ESR != ESR_Succeeded);
6097 EvalStmtResult ESR =
6101 if (ESR != ESR_Continue)
6103 if (
const auto *Inc = FS->
getInc()) {
6104 if (Inc->isValueDependent()) {
6108 FullExpressionRAII IncScope(Info);
6116 case Stmt::DeclStmtClass: {
6120 for (
const auto *D : DS->
decls()) {
6121 if (
const auto *VD = dyn_cast<VarDecl>(D)) {
6124 if (VD->hasLocalStorage() && !VD->getInit())
6132 return ESR_CaseNotFound;
6136 return ESR_CaseNotFound;
6142 if (
const Expr *E = dyn_cast<Expr>(S)) {
6151 FullExpressionRAII
Scope(Info);
6155 return ESR_Succeeded;
6161 case Stmt::NullStmtClass:
6162 return ESR_Succeeded;
6164 case Stmt::DeclStmtClass: {
6166 for (
const auto *D : DS->
decls()) {
6167 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
6171 if (
const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6172 assert(ESD->getInstantiations() &&
"not expanded?");
6177 FullExpressionRAII
Scope(Info);
6179 !Info.noteFailure())
6181 if (!
Scope.destroy())
6184 return ESR_Succeeded;
6187 case Stmt::ReturnStmtClass: {
6189 FullExpressionRAII
Scope(Info);
6200 return Scope.destroy() ? ESR_Returned : ESR_Failed;
6203 case Stmt::CompoundStmtClass: {
6204 BlockScopeRAII
Scope(Info);
6207 for (
const auto *BI : CS->
body()) {
6209 if (ESR == ESR_Succeeded)
6211 else if (ESR != ESR_CaseNotFound) {
6212 if (ESR != ESR_Failed && !
Scope.destroy())
6218 return ESR_CaseNotFound;
6219 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6222 case Stmt::IfStmtClass: {
6226 BlockScopeRAII
Scope(Info);
6229 if (ESR != ESR_Succeeded) {
6230 if (ESR != ESR_Failed && !
Scope.destroy())
6240 if (!Info.InConstantContext)
6248 if (ESR != ESR_Succeeded) {
6249 if (ESR != ESR_Failed && !
Scope.destroy())
6254 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6257 case Stmt::WhileStmtClass: {
6260 BlockScopeRAII
Scope(Info);
6272 if (ESR != ESR_Continue) {
6273 if (ESR != ESR_Failed && !
Scope.destroy())
6277 if (!
Scope.destroy())
6280 return ESR_Succeeded;
6283 case Stmt::DoStmtClass: {
6290 if (ESR != ESR_Continue)
6299 FullExpressionRAII CondScope(Info);
6301 !CondScope.destroy())
6304 return ESR_Succeeded;
6307 case Stmt::ForStmtClass: {
6309 BlockScopeRAII ForScope(Info);
6312 if (ESR != ESR_Succeeded) {
6313 if (ESR != ESR_Failed && !ForScope.destroy())
6319 BlockScopeRAII IterScope(Info);
6320 bool Continue =
true;
6326 if (!IterScope.destroy())
6334 if (ESR != ESR_Continue) {
6335 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
6340 if (
const auto *Inc = FS->
getInc()) {
6341 if (Inc->isValueDependent()) {
6345 FullExpressionRAII IncScope(Info);
6351 if (!IterScope.destroy())
6354 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
6357 case Stmt::CXXForRangeStmtClass: {
6359 BlockScopeRAII
Scope(Info);
6364 if (ESR != ESR_Succeeded) {
6365 if (ESR != ESR_Failed && !
Scope.destroy())
6373 if (ESR != ESR_Succeeded) {
6374 if (ESR != ESR_Failed && !
Scope.destroy())
6386 if (ESR != ESR_Succeeded) {
6387 if (ESR != ESR_Failed && !
Scope.destroy())
6392 if (ESR != ESR_Succeeded) {
6393 if (ESR != ESR_Failed && !
Scope.destroy())
6406 bool Continue =
true;
6407 FullExpressionRAII CondExpr(Info);
6415 BlockScopeRAII InnerScope(Info);
6417 if (ESR != ESR_Succeeded) {
6418 if (ESR != ESR_Failed && (!InnerScope.destroy() || !
Scope.destroy()))
6427 if (ESR != ESR_Continue) {
6428 if (ESR != ESR_Failed && (!InnerScope.destroy() || !
Scope.destroy()))
6441 if (!InnerScope.destroy())
6445 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
6448 case Stmt::CXXExpansionStmtInstantiationClass: {
6449 BlockScopeRAII
Scope(Info);
6451 for (
const Stmt *PreambleStmt : Expansion->getPreambleStmts()) {
6453 if (ESR != ESR_Succeeded) {
6454 if (ESR != ESR_Failed && !
Scope.destroy())
6462 EvalStmtResult ESR = ESR_Succeeded;
6463 for (
const Stmt *Instantiation : Expansion->getInstantiations()) {
6465 if (ESR == ESR_Failed ||
6468 if (ESR != ESR_Continue) {
6470 assert(ESR == ESR_Succeeded || ESR == ESR_Returned);
6476 if (ESR == ESR_Continue)
6477 ESR = ESR_Succeeded;
6479 return Scope.destroy() ? ESR : ESR_Failed;
6482 case Stmt::SwitchStmtClass:
6485 case Stmt::ContinueStmtClass:
6486 case Stmt::BreakStmtClass: {
6488 const Stmt *LoopOrSwitch =
nullptr;
6490 LoopOrSwitch = B->getNamedLoopOrSwitch();
6493 if (!LoopOrSwitch) {
6495 diag::note_break_continue_label_outside_context)
6501 Info.BreakContinueStack.push_back(LoopOrSwitch);
6505 case Stmt::LabelStmtClass:
6508 case Stmt::AttributedStmtClass: {
6510 const auto *SS = AS->getSubStmt();
6511 MSConstexprContextRAII ConstexprContext(
6515 auto LO = Info.Ctx.getLangOpts();
6516 if (LO.CXXAssumptions && !LO.MSVCCompat) {
6517 for (
auto *
Attr : AS->getAttrs()) {
6518 auto *AA = dyn_cast<CXXAssumeAttr>(
Attr);
6522 auto *Assumption = AA->getAssumption();
6523 if (Assumption->isValueDependent())
6526 if (Assumption->HasSideEffects(Info.Ctx))
6533 Info.CCEDiag(Assumption->getExprLoc(),
6534 diag::note_constexpr_assumption_failed);
6543 case Stmt::CaseStmtClass:
6544 case Stmt::DefaultStmtClass:
6546 case Stmt::CXXTryStmtClass:
6558 bool IsValueInitialization) {
6565 if (!CD->
isConstexpr() && !IsValueInitialization) {
6566 if (Info.getLangOpts().CPlusPlus11) {
6569 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
6571 Info.Note(CD->
getLocation(), diag::note_declared_at);
6573 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
6587 if (Info.checkingPotentialConstantExpression() && !
Definition &&
6595 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6604 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
6607 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6613 (
Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
6623 StringRef Name = DiagDecl->
getName();
6625 Name ==
"__assert_rtn" || Name ==
"__assert_fail" || Name ==
"_wassert";
6627 Info.FFDiag(CallLoc, diag::note_constexpr_assert_failed);
6632 if (Info.getLangOpts().CPlusPlus11) {
6635 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
6636 if (CD && CD->isInheritingConstructor()) {
6637 auto *Inherited = CD->getInheritedConstructor().getConstructor();
6638 if (!Inherited->isConstexpr())
6639 DiagDecl = CD = Inherited;
6645 if (CD && CD->isInheritingConstructor())
6646 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
6647 << CD->getInheritedConstructor().getConstructor()->getParent();
6649 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
6651 Info.Note(DiagDecl->
getLocation(), diag::note_declared_at);
6653 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
6659struct CheckDynamicTypeHandler {
6661 typedef bool result_type;
6662 bool failed() {
return false; }
6663 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
6666 bool found(
APSInt &
Value, QualType SubobjType) {
return true; }
6667 bool found(APFloat &
Value, QualType SubobjType) {
return true; }
6675 if (
This.Designator.Invalid)
6687 if (
This.Designator.isOnePastTheEnd() ||
6688 This.Designator.isMostDerivedAnUnsizedArray()) {
6689 Info.FFDiag(E,
This.Designator.isOnePastTheEnd()
6690 ? diag::note_constexpr_access_past_end
6691 : diag::note_constexpr_access_unsized_array)
6694 }
else if (Polymorphic) {
6697 if (!Info.checkingPotentialConstantExpression() ||
6698 !
This.AllowConstexprUnknown) {
6702 Info.Ctx.getLValueReferenceType(
This.Designator.getType(Info.Ctx));
6703 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6711 CheckDynamicTypeHandler Handler{AK};
6734 unsigned PathLength) {
6735 assert(PathLength >=
Designator.MostDerivedPathLength && PathLength <=
6736 Designator.Entries.size() &&
"invalid path length");
6737 return (PathLength ==
Designator.MostDerivedPathLength)
6738 ?
Designator.MostDerivedType->getAsCXXRecordDecl()
6739 : getAsBaseClass(
Designator.Entries[PathLength - 1]);
6752 return std::nullopt;
6754 if (
This.Designator.Invalid)
6755 return std::nullopt;
6761 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6762 if (!Class || (!Info.getLangOpts().CPlusPlus26 && Class->getNumVBases())) {
6764 return std::nullopt;
6772 for (
unsigned PathLength =
This.Designator.MostDerivedPathLength;
6773 PathLength <= Path.size(); ++PathLength) {
6774 switch (Info.isEvaluatingCtorDtor(
This.getLValueBase(),
6775 Path.slice(0, PathLength))) {
6776 case ConstructionPhase::Bases:
6777 case ConstructionPhase::DestroyingBases:
6782 case ConstructionPhase::None:
6783 case ConstructionPhase::AfterBases:
6784 case ConstructionPhase::AfterFields:
6785 case ConstructionPhase::Destroying:
6797 return std::nullopt;
6815 unsigned PathLength = DynType->PathLength;
6816 for (; PathLength <=
This.Designator.Entries.size(); ++PathLength) {
6819 Found->getCorrespondingMethodDeclaredInClass(Class,
false);
6829 if (Callee->isPureVirtual()) {
6830 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6831 Info.Note(Callee->getLocation(), diag::note_declared_at);
6837 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6838 Found->getReturnType())) {
6839 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6840 for (
unsigned CovariantPathLength = PathLength + 1;
6841 CovariantPathLength !=
This.Designator.Entries.size();
6842 ++CovariantPathLength) {
6846 Found->getCorrespondingMethodDeclaredInClass(NextClass,
false);
6847 if (
Next && !Info.Ctx.hasSameUnqualifiedType(
6848 Next->getReturnType(), CovariantAdjustmentPath.back()))
6849 CovariantAdjustmentPath.push_back(
Next->getReturnType());
6851 if (!Info.Ctx.hasSameUnqualifiedType(
Found->getReturnType(),
6852 CovariantAdjustmentPath.back()))
6853 CovariantAdjustmentPath.push_back(
Found->getReturnType());
6869 assert(
Result.isLValue() &&
6870 "unexpected kind of APValue for covariant return");
6871 if (
Result.isNullPointer())
6875 LVal.setFrom(Info.Ctx,
Result);
6877 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6878 for (
unsigned I = 1; I != Path.size(); ++I) {
6879 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6880 assert(OldClass && NewClass &&
"unexpected kind of covariant return");
6881 if (OldClass != NewClass &&
6884 OldClass = NewClass;
6896 if (BaseSpec.isVirtual())
6898 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6900 return BaseSpec.getAccessSpecifier() ==
AS_public;
6903 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6905 return BaseSpec.getAccessSpecifier() ==
AS_public;
6908 llvm_unreachable(
"Base is not a direct base of Derived");
6918 SubobjectDesignator &D = Ptr.Designator;
6924 if (Ptr.isNullPointer() && !E->
isGLValue())
6930 std::optional<DynamicType> DynType =
6942 assert(
C &&
"dynamic_cast target is not void pointer nor class");
6950 Ptr.setNull(Info.Ctx, E->
getType());
6957 DynType->Type->isDerivedFrom(
C)))
6959 else if (!Paths || Paths->begin() == Paths->end())
6961 else if (Paths->isAmbiguous(CQT))
6964 assert(Paths->front().Access !=
AS_public &&
"why did the cast fail?");
6967 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6968 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6969 << Info.Ctx.getCanonicalTagType(DynType->Type)
6977 for (
int PathLength = Ptr.Designator.Entries.size();
6978 PathLength >= (
int)DynType->PathLength; --PathLength) {
6983 if (PathLength > (
int)DynType->PathLength &&
6986 return RuntimeCheckFailed(
nullptr);
6993 if (DynType->Type->isDerivedFrom(
C, Paths) && !Paths.
isAmbiguous(CQT) &&
7006 return RuntimeCheckFailed(&Paths);
7010struct StartLifetimeOfUnionMemberHandler {
7012 const Expr *LHSExpr;
7013 const FieldDecl *
Field;
7015 bool Failed =
false;
7018 typedef bool result_type;
7019 bool failed() {
return Failed; }
7020 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7035 }
else if (DuringInit) {
7039 Info.FFDiag(LHSExpr,
7040 diag::note_constexpr_union_member_change_during_init);
7049 llvm_unreachable(
"wrong value kind for union object");
7051 bool found(APFloat &
Value, QualType SubobjType) {
7052 llvm_unreachable(
"wrong value kind for union object");
7057const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
7064 const Expr *LHSExpr,
7065 const LValue &LHS) {
7066 if (LHS.InvalidBase || LHS.Designator.Invalid)
7072 unsigned PathLength = LHS.Designator.Entries.size();
7073 for (
const Expr *E = LHSExpr; E !=
nullptr;) {
7075 if (
auto *ME = dyn_cast<MemberExpr>(E)) {
7076 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
7079 if (!FD || FD->getType()->isReferenceType())
7083 if (FD->getParent()->isUnion()) {
7088 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7089 if (!RD || RD->hasTrivialDefaultConstructor())
7090 UnionPathLengths.push_back({PathLength - 1, FD});
7096 LHS.Designator.Entries[PathLength]
7097 .getAsBaseOrMember().getPointer()));
7101 }
else if (
auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
7103 auto *
Base = ASE->getBase()->IgnoreImplicit();
7104 if (!
Base->getType()->isArrayType())
7110 }
else if (
auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7113 if (ICE->getCastKind() == CK_NoOp)
7115 if (ICE->getCastKind() != CK_DerivedToBase &&
7116 ICE->getCastKind() != CK_UncheckedDerivedToBase)
7120 if (Elt->isVirtual()) {
7129 LHS.Designator.Entries[PathLength]
7130 .getAsBaseOrMember().getPointer()));
7140 if (UnionPathLengths.empty())
7145 CompleteObject Obj =
7149 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
7150 llvm::reverse(UnionPathLengths)) {
7152 SubobjectDesignator D = LHS.Designator;
7153 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
7155 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
7156 ConstructionPhase::AfterBases;
7157 StartLifetimeOfUnionMemberHandler StartLifetime{
7158 Info, LHSExpr, LengthAndField.second, DuringInit};
7167 CallRef
Call, EvalInfo &Info,
bool NonNull =
false,
7168 APValue **EvaluatedArg =
nullptr) {
7175 APValue &
V = PVD ? Info.CurrentCall->createParam(
Call, PVD, LV)
7176 : Info.CurrentCall->createTemporary(Arg, Arg->
getType(),
7177 ScopeKind::Call, LV);
7183 if (
NonNull &&
V.isLValue() &&
V.isNullPointer()) {
7184 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
7197 bool RightToLeft =
false,
7198 LValue *ObjectArg =
nullptr) {
7200 llvm::SmallBitVector ForbiddenNullArgs;
7201 if (Callee->hasAttr<NonNullAttr>()) {
7202 ForbiddenNullArgs.resize(Args.size());
7203 for (
const auto *
Attr : Callee->specific_attrs<NonNullAttr>()) {
7204 if (!
Attr->args_size()) {
7205 ForbiddenNullArgs.set();
7208 for (
auto Idx :
Attr->args()) {
7209 unsigned ASTIdx = Idx.getASTIndex();
7210 if (ASTIdx >= Args.size())
7212 ForbiddenNullArgs[ASTIdx] =
true;
7216 for (
unsigned I = 0; I < Args.size(); I++) {
7217 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
7219 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) :
nullptr;
7220 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
7225 if (!Info.noteFailure())
7230 ObjectArg->setFrom(Info.Ctx, *That);
7239 bool CopyObjectRepresentation) {
7241 CallStackFrame *Frame = Info.CurrentCall;
7242 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
7250 RefLValue.setFrom(Info.Ctx, *RefValue);
7253 CopyObjectRepresentation);
7279 SemaProxy *SProxy = Info.getSemaProxy();
7281 Info.InConstantContext)
7288 const LValue *ObjectArg,
const Expr *E,
7290 const Stmt *Body, EvalInfo &Info,
7292 if (!Info.CheckCallLimit(CallLoc))
7305 auto IsTrivialMemoryOperation = [&](
const CXXMethodDecl *MD) {
7315 if (IsTrivialMemoryOperation(MD)) {
7327 ObjectArg->moveInto(
Result);
7336 if (!Info.checkingPotentialConstantExpression())
7338 Frame.LambdaThisCaptureField);
7341 StmtResult Ret = {
Result, ResultSlot};
7343 if (ESR == ESR_Succeeded) {
7344 if (Callee->getReturnType()->isVoidType())
7346 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
7348 return ESR == ESR_Returned;
7355 bool IsCompleteClass =
true);
7361 bool IsCompleteClass =
true) {
7362 CallScopeRAII CallScope(Info);
7369 CallScope.destroy();
7377 bool IsCompleteClass) {
7380 if (!Info.CheckCallLimit(CallLoc))
7384 if (!Info.getLangOpts().CPlusPlus26 && RD->
getNumVBases()) {
7385 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
7389 EvalInfo::EvaluatingConstructorRAII EvalObj(
7391 ObjectUnderConstruction{
This.getLValueBase(),
This.Designator.Entries},
7398 StmtResult Ret = {RetVal,
nullptr};
7403 if ((*I)->getInit()->isValueDependent()) {
7407 FullExpressionRAII InitScope(Info);
7409 !InitScope.destroy())
7432 if (!
Result.hasValue()) {
7434 unsigned NonVirtualBases = countNonVirtualBases(RD);
7446 BlockScopeRAII LifetimeExtendedScope(Info);
7449 unsigned BasesSeen = 0;
7450 unsigned VirtualBasesSeen = 0;
7451 unsigned NonVirtualBases = countNonVirtualBases(RD);
7454 auto SkipToField = [&](
FieldDecl *FD,
bool Indirect) {
7459 assert(Indirect &&
"fields out of order?");
7465 assert(FieldIt != RD->
field_end() &&
"missing field?");
7466 if (!FieldIt->isUnnamedBitField())
7469 Result.getStructField(FieldIt->getFieldIndex()));
7474 LValue Subobject =
This;
7475 LValue SubobjectParent =
This;
7480 if (I->isBaseInitializer()) {
7481 QualType BaseType(I->getBaseClass(), 0);
7482 if (I->isBaseVirtual()) {
7483 if (
This.pointsToCompleteClass(RD)) {
7485 BaseType->getAsCXXRecordDecl(),
7488 Value = &
Result.getStructVirtualBase(VirtualBasesSeen++);
7495 BaseType->getAsCXXRecordDecl(), &Layout))
7499 }
else if ((FD = I->getMember())) {
7506 SkipToField(FD,
false);
7512 auto IndirectFieldChain = IFD->chain();
7513 for (
auto *
C : IndirectFieldChain) {
7522 (
Value->isUnion() &&
7535 if (
C == IndirectFieldChain.back())
7536 SubobjectParent = Subobject;
7542 if (
C == IndirectFieldChain.front() && !RD->
isUnion())
7543 SkipToField(FD,
true);
7548 llvm_unreachable(
"unknown base initializer kind");
7555 if (
Init->isValueDependent()) {
7559 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
7561 FullExpressionRAII InitScope(Info);
7567 if (!Info.noteFailure())
7576 if (!Info.noteFailure())
7584 if (I->isBaseInitializer() && BasesSeen == NonVirtualBases)
7585 EvalObj.finishedConstructingBases();
7590 for (; FieldIt != RD->
field_end(); ++FieldIt) {
7591 if (!FieldIt->isUnnamedBitField())
7594 Result.getStructField(FieldIt->getFieldIndex()));
7598 EvalObj.finishedConstructingFields();
7602 LifetimeExtendedScope.destroy();
7607 QualType T,
bool IsCompleteClass =
true) {
7612 if (
Value.isAbsent() && !
T->isNullPtrType()) {
7614 This.moveInto(Printable);
7616 diag::note_constexpr_destroy_out_of_lifetime)
7617 << Printable.
getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(
T));
7633 LValue ElemLV =
This;
7634 ElemLV.addArray(Info, &LocE, CAT);
7641 if (Size && Size >
Value.getArrayInitializedElts())
7646 for (Size =
Value.getArraySize(); Size != 0; --Size) {
7647 APValue &Elem =
Value.getArrayInitializedElt(Size - 1);
7660 if (
T.isDestructedType()) {
7662 diag::note_constexpr_unsupported_destruction)
7671 if (!Info.getLangOpts().CPlusPlus26 && RD->
getNumVBases()) {
7672 Info.FFDiag(CallRange.
getBegin(), diag::note_constexpr_virtual_base) << RD;
7700 if (!Info.CheckCallLimit(CallRange.
getBegin()))
7711 CallStackFrame Frame(Info, CallRange,
Definition, &
This,
nullptr,
7715 EvalInfo::EvaluatingDestructorRAII EvalObj(
7717 ObjectUnderConstruction{
This.getLValueBase(),
This.Designator.Entries});
7718 unsigned NonVirtualBases = countNonVirtualBases(RD);
7720 unsigned BasesLeft = NonVirtualBases;
7721 if (!EvalObj.DidInsert) {
7728 Info.FFDiag(CallRange.
getBegin(), diag::note_constexpr_double_destroy);
7735 StmtResult Ret = {RetVal,
nullptr};
7750 for (
const FieldDecl *FD : llvm::reverse(Fields)) {
7751 if (FD->isUnnamedBitField())
7754 LValue Subobject =
This;
7758 APValue *SubobjectValue = &
Value.getStructField(FD->getFieldIndex());
7764 if (BasesLeft != 0 || NumVirtualBases != 0)
7765 EvalObj.startedDestroyingBases();
7769 if (
Base.isVirtual())
7774 LValue Subobject =
This;
7776 BaseType->getAsCXXRecordDecl(), &Layout))
7779 APValue *SubobjectValue = &
Value.getStructBase(BasesLeft);
7784 assert(BasesLeft == 0 &&
"NumBases was wrong?");
7787 if (IsCompleteClass) {
7788 unsigned VirtualBasesLeft = NumVirtualBases;
7793 LValue Subobject =
This;
7795 BaseType->getAsCXXRecordDecl(),
7799 APValue *SubobjectValue = &
Value.getStructVirtualBase(VirtualBasesLeft);
7804 assert(VirtualBasesLeft == 0 &&
"NumVirtualBases was wrong?");
7813struct DestroyObjectHandler {
7819 typedef bool result_type;
7820 bool failed() {
return false; }
7821 bool found(
APValue &Subobj, QualType SubobjType, APValue::LValueBase Base) {
7826 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7829 bool found(APFloat &
Value, QualType SubobjType) {
7830 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7851 if (Info.EvalStatus.HasSideEffects)
7862 if (Info.checkingPotentialConstantExpression() ||
7863 Info.SpeculativeEvaluationDepth)
7867 auto Caller = Info.getStdAllocatorCaller(
"allocate");
7869 Info.FFDiag(E->
getExprLoc(), Info.getLangOpts().CPlusPlus20
7870 ? diag::note_constexpr_new_untyped
7871 : diag::note_constexpr_new);
7875 QualType ElemType = Caller.ElemType;
7878 diag::note_constexpr_new_not_complete_object_type)
7886 bool IsNothrow =
false;
7887 for (
unsigned I = 1, N = E->
getNumArgs(); I != N; ++I) {
7895 APInt Size, Remainder;
7896 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.
getQuantity());
7897 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7898 if (Remainder != 0) {
7900 Info.FFDiag(E->
getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7901 << ByteSize <<
APSInt(ElemSizeAP,
true) << ElemType;
7905 if (!Info.CheckArraySize(E->
getBeginLoc(), ByteSize.getActiveBits(),
7906 Size.getZExtValue(), !IsNothrow)) {
7914 QualType AllocType = Info.Ctx.getConstantArrayType(
7916 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType,
Result);
7925 return DD->isVirtual();
7932 return DD->isVirtual() ? DD->getOperatorDelete() :
nullptr;
7944 auto PointerAsString = [&] {
7945 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7950 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7951 << PointerAsString();
7954 return std::nullopt;
7957 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7959 Info.FFDiag(E, diag::note_constexpr_double_delete);
7960 return std::nullopt;
7963 if (DeallocKind != (*Alloc)->getKind()) {
7965 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7966 << DeallocKind << (*Alloc)->getKind() << AllocType;
7968 return std::nullopt;
7971 bool Subobject =
false;
7973 Subobject =
Pointer.Designator.MostDerivedPathLength != 0 ||
7974 Pointer.Designator.isOnePastTheEnd();
7976 Subobject =
Pointer.Designator.Entries.size() != 1 ||
7977 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7980 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7981 << PointerAsString() <<
Pointer.Designator.isOnePastTheEnd();
7982 return std::nullopt;
7990 if (Info.checkingPotentialConstantExpression() ||
7991 Info.SpeculativeEvaluationDepth)
7995 if (!Info.getStdAllocatorCaller(
"deallocate")) {
8003 for (
unsigned I = 1, N = E->
getNumArgs(); I != N; ++I)
8006 if (
Pointer.Designator.Invalid)
8011 if (
Pointer.isNullPointer()) {
8012 Info.CCEDiag(E->
getExprLoc(), diag::note_constexpr_deallocate_null);
8028class BitCastBuffer {
8034 SmallVector<std::optional<unsigned char>, 32> Bytes;
8036 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
8037 "Need at least 8 bit unsigned char");
8039 bool TargetIsLittleEndian;
8042 BitCastBuffer(CharUnits Width,
bool TargetIsLittleEndian)
8043 : Bytes(Width.getQuantity()),
8044 TargetIsLittleEndian(TargetIsLittleEndian) {}
8046 [[nodiscard]]
bool readObject(CharUnits Offset, CharUnits Width,
8047 SmallVectorImpl<unsigned char> &Output)
const {
8048 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
8051 if (!Bytes[I.getQuantity()])
8053 Output.push_back(*Bytes[I.getQuantity()]);
8055 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
8056 std::reverse(Output.begin(), Output.end());
8060 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
8061 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
8062 std::reverse(Input.begin(), Input.end());
8065 for (
unsigned char Byte : Input) {
8066 assert(!Bytes[Offset.
getQuantity() + Index] &&
"overwriting a byte?");
8072 size_t size() {
return Bytes.size(); }
8077class APValueToBufferConverter {
8079 BitCastBuffer Buffer;
8082 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
8085 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
8088 bool visit(
const APValue &Val, QualType Ty) {
8093 bool visit(
const APValue &Val, QualType Ty, CharUnits Offset) {
8094 assert((
size_t)Offset.
getQuantity() <= Buffer.size());
8107 return visitInt(Val.
getInt(), Ty, Offset);
8109 return visitFloat(Val.
getFloat(), Ty, Offset);
8111 return visitArray(Val, Ty, Offset);
8113 return visitRecord(Val, Ty, Offset);
8115 return visitVector(Val, Ty, Offset);
8119 return visitComplex(Val, Ty, Offset);
8130 diag::note_constexpr_bit_cast_unsupported_type)
8135 llvm_unreachable(
"Unhandled APValue::ValueKind");
8138 bool visitRecord(
const APValue &Val, QualType Ty, CharUnits Offset) {
8142 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8145 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8146 for (
size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8147 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8152 if (!
Base.isStruct())
8155 if (!visitRecord(Base, BS.
getType(),
8162 unsigned FieldIdx = 0;
8163 for (FieldDecl *FD : RD->
fields()) {
8164 if (FD->isBitField()) {
8166 diag::note_constexpr_bit_cast_unsupported_bitfield);
8172 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
8173 "only bit-fields can have sub-char alignment");
8174 CharUnits FieldOffset =
8175 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
8176 QualType FieldTy = FD->getType();
8185 bool visitArray(
const APValue &Val, QualType Ty, CharUnits Offset) {
8191 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->
getElementType());
8195 for (
unsigned I = 0; I != NumInitializedElts; ++I) {
8197 if (!visit(SubObj, CAT->
getElementType(), Offset + I * ElemWidth))
8204 for (
unsigned I = NumInitializedElts; I != ArraySize; ++I) {
8205 if (!visit(Filler, CAT->
getElementType(), Offset + I * ElemWidth))
8213 bool visitComplex(
const APValue &Val, QualType Ty, CharUnits Offset) {
8214 const ComplexType *ComplexTy = Ty->
castAs<ComplexType>();
8216 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8221 Offset + (0 * EltSizeChars)))
8224 Offset + (1 * EltSizeChars)))
8228 Offset + (0 * EltSizeChars)))
8231 Offset + (1 * EltSizeChars)))
8238 bool visitVector(
const APValue &Val, QualType Ty, CharUnits Offset) {
8239 const VectorType *VTy = Ty->
castAs<VectorType>();
8252 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8254 llvm::APInt Res = llvm::APInt::getZero(NElts);
8255 for (
unsigned I = 0; I < NElts; ++I) {
8257 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
8258 "bool vector element must be 1-bit unsigned integer!");
8260 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
8263 SmallVector<uint8_t, 8> Bytes(NElts / 8);
8264 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
8265 Buffer.writeObject(Offset, Bytes);
8269 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8270 for (
unsigned I = 0; I < NElts; ++I) {
8271 if (!visit(Val.
getVectorElt(I), EltTy, Offset + I * EltSizeChars))
8279 bool visitInt(
const APSInt &Val, QualType Ty, CharUnits Offset) {
8280 APSInt AdjustedVal = Val;
8281 unsigned Width = AdjustedVal.getBitWidth();
8283 Width = Info.Ctx.getTypeSize(Ty);
8284 AdjustedVal = AdjustedVal.extend(Width);
8287 SmallVector<uint8_t, 8> Bytes(Width / 8);
8288 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
8289 Buffer.writeObject(Offset, Bytes);
8293 bool visitFloat(
const APFloat &Val, QualType Ty, CharUnits Offset) {
8294 APSInt AsInt(Val.bitcastToAPInt());
8295 return visitInt(AsInt, Ty, Offset);
8299 static std::optional<BitCastBuffer>
8301 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->
getType());
8302 APValueToBufferConverter Converter(Info, DstSize, BCE);
8304 return std::nullopt;
8305 return Converter.Buffer;
8310class BufferToAPValueConverter {
8312 const BitCastBuffer &Buffer;
8315 BufferToAPValueConverter(EvalInfo &Info,
const BitCastBuffer &Buffer,
8317 : Info(Info), Buffer(Buffer), BCE(BCE) {}
8322 std::nullopt_t unsupportedType(QualType Ty) {
8324 diag::note_constexpr_bit_cast_unsupported_type)
8326 return std::nullopt;
8329 std::nullopt_t unrepresentableValue(QualType Ty,
const APSInt &Val) {
8331 diag::note_constexpr_bit_cast_unrepresentable_value)
8333 return std::nullopt;
8336 std::optional<APValue> visit(
const BuiltinType *
T, CharUnits Offset,
8337 const EnumType *EnumSugar =
nullptr) {
8339 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(
T, 0));
8340 return APValue((Expr *)
nullptr,
8342 APValue::NoLValuePath{},
true);
8345 CharUnits
SizeOf = Info.Ctx.getTypeSizeInChars(
T);
8351 const llvm::fltSemantics &Semantics =
8352 Info.Ctx.getFloatTypeSemantics(QualType(
T, 0));
8353 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
8354 assert(NumBits % 8 == 0);
8360 SmallVector<uint8_t, 8> Bytes;
8361 if (!Buffer.readObject(Offset,
SizeOf, Bytes)) {
8364 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
8368 if (!IsStdByte && !IsUChar) {
8369 QualType DisplayType(EnumSugar ? (
const Type *)EnumSugar :
T, 0);
8371 diag::note_constexpr_bit_cast_indet_dest)
8372 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
8373 return std::nullopt;
8379 APSInt Val(
SizeOf.getQuantity() * Info.Ctx.getCharWidth(),
true);
8380 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
8385 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(
T, 0));
8386 if (IntWidth != Val.getBitWidth()) {
8387 APSInt Truncated = Val.trunc(IntWidth);
8388 if (Truncated.extend(Val.getBitWidth()) != Val)
8389 return unrepresentableValue(QualType(
T, 0), Val);
8397 const llvm::fltSemantics &Semantics =
8398 Info.Ctx.getFloatTypeSemantics(QualType(
T, 0));
8402 return unsupportedType(QualType(
T, 0));
8405 std::optional<APValue> visit(
const RecordType *RTy, CharUnits Offset) {
8406 const RecordDecl *RD = RTy->getAsRecordDecl();
8408 return std::nullopt;
8409 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8411 unsigned NumBases = 0;
8412 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
8413 NumBases = CXXRD->getNumBases();
8418 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
8419 for (
size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
8420 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
8423 std::optional<APValue> SubObj = visitType(
8426 return std::nullopt;
8427 ResultVal.getStructBase(I) = *SubObj;
8432 unsigned FieldIdx = 0;
8433 for (FieldDecl *FD : RD->
fields()) {
8436 if (FD->isBitField()) {
8438 diag::note_constexpr_bit_cast_unsupported_bitfield);
8439 return std::nullopt;
8443 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
8445 CharUnits FieldOffset =
8448 QualType FieldTy = FD->getType();
8449 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
8451 return std::nullopt;
8452 ResultVal.getStructField(FieldIdx) = *SubObj;
8459 std::optional<APValue> visit(
const EnumType *Ty, CharUnits Offset) {
8460 QualType RepresentationType =
8461 Ty->getDecl()->getDefinitionOrSelf()->getIntegerType();
8462 assert(!RepresentationType.
isNull() &&
8463 "enum forward decl should be caught by Sema");
8464 const auto *AsBuiltin =
8468 return visit(AsBuiltin, Offset, Ty);
8471 std::optional<APValue> visit(
const ConstantArrayType *Ty, CharUnits Offset) {
8473 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->
getElementType());
8475 APValue ArrayValue(APValue::UninitArray(), Size, Size);
8476 for (
size_t I = 0; I !=
Size; ++I) {
8477 std::optional<APValue> ElementValue =
8480 return std::nullopt;
8481 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
8487 std::optional<APValue> visit(
const ComplexType *Ty, CharUnits Offset) {
8489 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
8490 bool IsInt = ElementType->isIntegerType();
8492 std::optional<APValue> Values[2];
8493 for (
unsigned I = 0; I != 2; ++I) {
8494 Values[I] = visitType(Ty->
getElementType(), Offset + I * ElementWidth);
8496 return std::nullopt;
8500 return APValue(Values[0]->getInt(), Values[1]->getInt());
8501 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
8504 std::optional<APValue> visit(
const VectorType *VTy, CharUnits Offset) {
8510 SmallVector<APValue, 4> Elts;
8511 Elts.reserve(NElts);
8521 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8523 SmallVector<uint8_t, 8> Bytes;
8524 Bytes.reserve(NElts / 8);
8526 return std::nullopt;
8528 APSInt SValInt(NElts,
true);
8529 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
8531 for (
unsigned I = 0; I < NElts; ++I) {
8533 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
8540 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
8541 for (
unsigned I = 0; I < NElts; ++I) {
8542 std::optional<APValue> EltValue =
8543 visitType(EltTy, Offset + I * EltSizeChars);
8545 return std::nullopt;
8546 Elts.push_back(std::move(*EltValue));
8550 return APValue(Elts.data(), Elts.size());
8553 std::optional<APValue> visit(
const Type *Ty, CharUnits Offset) {
8554 return unsupportedType(QualType(Ty, 0));
8557 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
8561#define TYPE(Class, Base) \
8563 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
8564#define ABSTRACT_TYPE(Class, Base)
8565#define NON_CANONICAL_TYPE(Class, Base) \
8567 llvm_unreachable("non-canonical type should be impossible!");
8568#define DEPENDENT_TYPE(Class, Base) \
8571 "dependent types aren't supported in the constant evaluator!");
8572#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
8574 llvm_unreachable("either dependent or not canonical!");
8575#include "clang/AST/TypeNodes.inc"
8577 llvm_unreachable(
"Unhandled Type::TypeClass");
8582 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
8584 BufferToAPValueConverter Converter(Info, Buffer, BCE);
8589static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
8590 QualType Ty, EvalInfo *Info,
8591 const ASTContext &Ctx,
8592 bool CheckingDest) {
8595 auto diag = [&](
int Reason) {
8597 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
8598 << CheckingDest << (Reason == 4) << Reason;
8601 auto note = [&](
int Construct, QualType NoteTy, SourceLocation NoteLoc) {
8603 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
8604 << NoteTy << Construct << Ty;
8618 if (
auto *CXXRD = dyn_cast<CXXRecordDecl>(
Record)) {
8619 for (CXXBaseSpecifier &BS : CXXRD->bases())
8620 if (!checkBitCastConstexprEligibilityType(Loc, BS.
getType(), Info, Ctx,
8624 for (FieldDecl *FD :
Record->fields()) {
8625 if (FD->getType()->isReferenceType())
8627 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
8629 return note(0, FD->getType(), FD->getBeginLoc());
8635 Info, Ctx, CheckingDest))
8638 if (
const auto *VTy = Ty->
getAs<VectorType>()) {
8650 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
8651 << QualType(VTy, 0) << EltSize << NElts << Ctx.
getCharWidth();
8661 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
8670static bool checkBitCastConstexprEligibility(EvalInfo *Info,
8671 const ASTContext &Ctx,
8673 bool DestOK = checkBitCastConstexprEligibilityType(
8675 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
8681static bool handleRValueToRValueBitCast(EvalInfo &Info,
APValue &DestValue,
8684 assert(
CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8685 "no host or target supports non 8-bit chars");
8687 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
8691 std::optional<BitCastBuffer> Buffer =
8692 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
8697 std::optional<APValue> MaybeDestValue =
8698 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
8699 if (!MaybeDestValue)
8702 DestValue = std::move(*MaybeDestValue);
8706static bool handleLValueToRValueBitCast(EvalInfo &Info,
APValue &DestValue,
8709 assert(
CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
8710 "no host or target supports non 8-bit chars");
8712 "LValueToRValueBitcast requires an lvalue operand!");
8714 LValue SourceLValue;
8716 SourceLValue.setFrom(Info.Ctx, SourceValue);
8719 SourceRValue,
true))
8722 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
8728static bool diagnoseBPFPreserveAIEnumerator(EvalInfo &Info,
8729 const PseudoObjectExpr *E) {
8733 const auto *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl());
8736 const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext());
8737 if (!ED || !ED->hasAttr<BPFPreserveAccessIndexAttr>())
8742 if (ED->getDeclName())
8743 EnumTy = Info.Ctx.getCanonicalTagType(ED);
8744 else if (
const TypedefNameDecl *TD = ED->getTypedefNameForAnonDecl())
8745 EnumTy = Info.Ctx.getTypeDeclType(TD);
8749 Info.FFDiag(E, diag::note_constexpr_bpf_preserve_ai_enumerator)
8754template <
class Derived>
8755class ExprEvaluatorBase
8756 :
public ConstStmtVisitor<Derived, bool> {
8758 Derived &getDerived() {
return static_cast<Derived&
>(*this); }
8759 bool DerivedSuccess(
const APValue &
V,
const Expr *E) {
8760 return getDerived().Success(
V, E);
8762 bool DerivedZeroInitialization(
const Expr *E) {
8763 return getDerived().ZeroInitialization(E);
8769 template<
typename ConditionalOperator>
8770 void CheckPotentialConstantConditional(
const ConditionalOperator *E) {
8771 assert(Info.checkingPotentialConstantExpression());
8774 SmallVector<PartialDiagnosticAt, 8>
Diag;
8776 SpeculativeEvaluationRAII Speculate(Info, &
Diag);
8783 SpeculativeEvaluationRAII Speculate(Info, &
Diag);
8785 Info.EvalStatus.DiagEmitted =
false;
8791 Error(E, diag::note_constexpr_conditional_never_const);
8795 template<
typename ConditionalOperator>
8796 bool HandleConditionalOperator(
const ConditionalOperator *E) {
8799 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
8800 CheckPotentialConstantConditional(E);
8803 if (Info.noteFailure()) {
8811 return StmtVisitorTy::Visit(EvalExpr);
8816 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
8817 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
8819 OptionalDiagnostic CCEDiag(
const Expr *E,
diag::kind D) {
8820 return Info.CCEDiag(E, D);
8823 bool ZeroInitialization(
const Expr *E) {
return Error(E); }
8825 bool IsConstantEvaluatedBuiltinCall(
const CallExpr *E) {
8827 return BuiltinOp != 0 &&
8828 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
8832 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
8834 EvalInfo &getEvalInfo() {
return Info; }
8842 bool Error(
const Expr *E) {
8843 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8846 bool VisitStmt(
const Stmt *) {
8847 llvm_unreachable(
"Expression evaluator should not be called on stmts");
8849 bool VisitExpr(
const Expr *E) {
8853 bool VisitEmbedExpr(
const EmbedExpr *E) {
8854 const auto It = E->
begin();
8855 return StmtVisitorTy::Visit(*It);
8858 bool VisitPredefinedExpr(
const PredefinedExpr *E) {
8861 bool VisitConstantExpr(
const ConstantExpr *E) {
8865 return StmtVisitorTy::Visit(E->
getSubExpr());
8868 bool VisitParenExpr(
const ParenExpr *E)
8869 {
return StmtVisitorTy::Visit(E->
getSubExpr()); }
8870 bool VisitUnaryExtension(
const UnaryOperator *E)
8871 {
return StmtVisitorTy::Visit(E->
getSubExpr()); }
8872 bool VisitUnaryPlus(
const UnaryOperator *E)
8873 {
return StmtVisitorTy::Visit(E->
getSubExpr()); }
8874 bool VisitChooseExpr(
const ChooseExpr *E)
8876 bool VisitGenericSelectionExpr(
const GenericSelectionExpr *E)
8878 bool VisitSubstNonTypeTemplateParmExpr(
const SubstNonTypeTemplateParmExpr *E)
8880 bool VisitCXXDefaultArgExpr(
const CXXDefaultArgExpr *E) {
8881 TempVersionRAII RAII(*Info.CurrentCall);
8882 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8883 return StmtVisitorTy::Visit(E->
getExpr());
8885 bool VisitCXXDefaultInitExpr(
const CXXDefaultInitExpr *E) {
8886 TempVersionRAII RAII(*Info.CurrentCall);
8890 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8891 return StmtVisitorTy::Visit(E->
getExpr());
8894 bool VisitExprWithCleanups(
const ExprWithCleanups *E) {
8895 FullExpressionRAII Scope(Info);
8896 return StmtVisitorTy::Visit(E->
getSubExpr()) && Scope.destroy();
8901 bool VisitCXXBindTemporaryExpr(
const CXXBindTemporaryExpr *E) {
8902 return StmtVisitorTy::Visit(E->
getSubExpr());
8905 bool VisitCXXReinterpretCastExpr(
const CXXReinterpretCastExpr *E) {
8907 CCEDiag(E, diag::note_constexpr_invalid_cast)
8908 << diag::ConstexprInvalidCastKind::Reinterpret;
8909 return static_cast<Derived*
>(
this)->VisitCastExpr(E);
8911 bool VisitCXXDynamicCastExpr(
const CXXDynamicCastExpr *E) {
8912 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8913 CCEDiag(E, diag::note_constexpr_invalid_cast)
8914 << diag::ConstexprInvalidCastKind::Dynamic;
8915 return static_cast<Derived*
>(
this)->VisitCastExpr(E);
8917 bool VisitBuiltinBitCastExpr(
const BuiltinBitCastExpr *E) {
8918 return static_cast<Derived*
>(
this)->VisitCastExpr(E);
8921 bool VisitBinaryOperator(
const BinaryOperator *E) {
8927 VisitIgnoredValue(E->
getLHS());
8928 return StmtVisitorTy::Visit(E->
getRHS());
8938 return DerivedSuccess(
Result, E);
8943 bool VisitCXXRewrittenBinaryOperator(
const CXXRewrittenBinaryOperator *E) {
8947 bool VisitBinaryConditionalOperator(
const BinaryConditionalOperator *E) {
8951 if (!
Evaluate(Info.CurrentCall->createTemporary(
8954 ScopeKind::FullExpression, CommonLV),
8958 return HandleConditionalOperator(E);
8961 bool VisitConditionalOperator(
const ConditionalOperator *E) {
8962 bool IsBcpCall =
false;
8967 if (
const CallExpr *CallCE =
8969 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8976 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8979 FoldConstant Fold(Info, IsBcpCall);
8980 if (!HandleConditionalOperator(E)) {
8981 Fold.keepDiagnostics();
8988 bool VisitOpaqueValueExpr(
const OpaqueValueExpr *E) {
8989 if (
APValue *
Value = Info.CurrentCall->getCurrentTemporary(E);
8991 return DerivedSuccess(*
Value, E);
8997 assert(0 &&
"OpaqueValueExpr recursively refers to itself");
9000 return StmtVisitorTy::Visit(Source);
9003 bool VisitPseudoObjectExpr(
const PseudoObjectExpr *E) {
9004 if (diagnoseBPFPreserveAIEnumerator(Info, E))
9006 for (
const Expr *SemE : E->
semantics()) {
9007 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
9016 if (OVE->isUnique())
9020 if (!
Evaluate(Info.CurrentCall->createTemporary(
9021 OVE, getStorageType(Info.Ctx, OVE),
9022 ScopeKind::FullExpression, LV),
9023 Info, OVE->getSourceExpr()))
9026 if (!StmtVisitorTy::Visit(SemE))
9036 bool VisitCallExpr(
const CallExpr *E) {
9038 if (!handleCallExpr(E,
Result,
nullptr))
9040 return DerivedSuccess(
Result, E);
9044 const LValue *ResultSlot) {
9045 CallScopeRAII CallScope(Info);
9048 QualType CalleeType =
Callee->getType();
9050 const FunctionDecl *FD =
nullptr;
9051 LValue *
This =
nullptr, ObjectArg;
9053 bool HasQualifier =
false;
9059 const CXXMethodDecl *
Member =
nullptr;
9060 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
9064 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
9066 return Error(Callee);
9068 HasQualifier = ME->hasQualifier();
9069 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
9071 const ValueDecl *D =
9075 Member = dyn_cast<CXXMethodDecl>(D);
9077 return Error(Callee);
9079 }
else if (
const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
9080 if (!Info.getLangOpts().CPlusPlus20)
9081 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
9085 return Error(Callee);
9092 if (!CalleeLV.getLValueOffset().isZero())
9093 return Error(Callee);
9094 if (CalleeLV.isNullPointer()) {
9095 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
9096 <<
const_cast<Expr *
>(
Callee);
9099 FD = dyn_cast_or_null<FunctionDecl>(
9100 CalleeLV.getLValueBase().dyn_cast<
const ValueDecl *>());
9102 return Error(Callee);
9105 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
9112 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
9113 if (OCE && OCE->isAssignmentOp()) {
9114 assert(Args.size() == 2 &&
"wrong number of arguments in assignment");
9115 Call = Info.CurrentCall->createCall(FD);
9116 bool HasThis =
false;
9117 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
9118 HasThis = MD->isImplicitObjectMemberFunction();
9126 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
9146 if (Info.getLangOpts().CPlusPlus20 && OCE &&
9147 OCE->getOperator() == OO_Equal && MD->
isTrivial() &&
9151 Args = Args.slice(1);
9157 const CXXRecordDecl *ClosureClass = MD->
getParent();
9159 ClosureClass->
captures().empty() &&
9160 "Number of captures must be zero for conversion to function-ptr");
9162 const CXXMethodDecl *LambdaCallOp =
9171 "A generic lambda's static-invoker function must be a "
9172 "template specialization");
9174 FunctionTemplateDecl *CallOpTemplate =
9176 llvm::FoldingSetInsertToken InsertToken;
9177 FunctionDecl *CorrespondingCallOpSpecialization =
9179 assert(CorrespondingCallOpSpecialization &&
9180 "We must always have a function call operator specialization "
9181 "that corresponds to our static invoker specialization");
9183 FD = CorrespondingCallOpSpecialization;
9192 return CallScope.destroy();
9202 Call = Info.CurrentCall->createCall(FD);
9208 SmallVector<QualType, 4> CovariantAdjustmentPath;
9210 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
9211 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
9214 CovariantAdjustmentPath);
9217 }
else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
9227 if (
auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
9228 assert(This &&
"no 'this' pointer for destructor call");
9230 Info.Ctx.getCanonicalTagType(DD->getParent())) &&
9231 CallScope.destroy();
9251 if (!CovariantAdjustmentPath.empty() &&
9253 CovariantAdjustmentPath))
9256 return CallScope.destroy();
9259 bool VisitCompoundLiteralExpr(
const CompoundLiteralExpr *E) {
9262 bool VisitInitListExpr(
const InitListExpr *E) {
9264 return DerivedZeroInitialization(E);
9266 return StmtVisitorTy::Visit(E->
getInit(0));
9269 bool VisitImplicitValueInitExpr(
const ImplicitValueInitExpr *E) {
9270 return DerivedZeroInitialization(E);
9272 bool VisitCXXScalarValueInitExpr(
const CXXScalarValueInitExpr *E) {
9273 return DerivedZeroInitialization(E);
9275 bool VisitCXXNullPtrLiteralExpr(
const CXXNullPtrLiteralExpr *E) {
9276 return DerivedZeroInitialization(E);
9280 bool VisitMemberExpr(
const MemberExpr *E) {
9281 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
9282 "missing temporary materialization conversion");
9283 assert(!E->
isArrow() &&
"missing call to bound member function?");
9291 const FieldDecl *FD = dyn_cast<FieldDecl>(E->
getMemberDecl());
9292 if (!FD)
return Error(E);
9296 "record / field mismatch");
9301 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
9302 SubobjectDesignator Designator(BaseTy);
9303 Designator.addDeclUnchecked(FD);
9307 DerivedSuccess(
Result, E);
9310 bool VisitExtVectorElementExpr(
const ExtVectorElementExpr *E) {
9316 SmallVector<uint32_t, 4> Indices;
9318 if (Indices.size() == 1) {
9320 return DerivedSuccess(Val.
getVectorElt(Indices[0]), E);
9323 SmallVector<APValue, 4> Elts;
9324 for (
unsigned I = 0; I < Indices.size(); ++I) {
9327 APValue VecResult(Elts.data(), Indices.size());
9328 return DerivedSuccess(VecResult, E);
9335 bool VisitCastExpr(
const CastExpr *E) {
9340 case CK_AtomicToNonAtomic: {
9347 return DerivedSuccess(AtomicVal, E);
9351 case CK_UserDefinedConversion:
9352 return StmtVisitorTy::Visit(E->
getSubExpr());
9354 case CK_HLSLArrayRValue: {
9360 return DerivedSuccess(Val, E);
9371 return DerivedSuccess(RVal, E);
9373 case CK_LValueToRValue: {
9382 return DerivedSuccess(RVal, E);
9384 case CK_LValueToRValueBitCast: {
9385 APValue DestValue, SourceValue;
9388 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
9390 return DerivedSuccess(DestValue, E);
9393 case CK_AddressSpaceConversion: {
9397 return DerivedSuccess(
Value, E);
9404 bool VisitUnaryPostInc(
const UnaryOperator *UO) {
9405 return VisitUnaryPostIncDec(UO);
9407 bool VisitUnaryPostDec(
const UnaryOperator *UO) {
9408 return VisitUnaryPostIncDec(UO);
9410 bool VisitUnaryPostIncDec(
const UnaryOperator *UO) {
9411 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9421 return DerivedSuccess(RVal, UO);
9424 bool VisitStmtExpr(
const StmtExpr *E) {
9427 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
9434 BlockScopeRAII Scope(Info);
9439 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
9441 Info.FFDiag((*BI)->getBeginLoc(),
9442 diag::note_constexpr_stmt_expr_unsupported);
9445 return this->Visit(FinalExpr) && Scope.destroy();
9451 if (ESR != ESR_Succeeded) {
9455 if (ESR != ESR_Failed)
9456 Info.FFDiag((*BI)->getBeginLoc(),
9457 diag::note_constexpr_stmt_expr_unsupported);
9462 llvm_unreachable(
"Return from function from the loop above.");
9465 bool VisitPackIndexingExpr(
const PackIndexingExpr *E) {
9470 void VisitIgnoredValue(
const Expr *E) {
9475 void VisitIgnoredBaseExpression(
const Expr *E) {
9478 if (Info.getLangOpts().MSVCCompat && !E->
HasSideEffects(Info.Ctx))
9480 VisitIgnoredValue(E);
9490template<
class Derived>
9491class LValueExprEvaluatorBase
9492 :
public ExprEvaluatorBase<Derived> {
9496 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
9497 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
9499 bool Success(APValue::LValueBase B) {
9504 bool evaluatePointer(
const Expr *E, LValue &
Result) {
9509 LValueExprEvaluatorBase(EvalInfo &Info, LValue &
Result,
bool InvalidBaseOK)
9511 InvalidBaseOK(InvalidBaseOK) {}
9514 Result.setFrom(this->Info.Ctx,
V);
9518 bool VisitMemberExpr(
const MemberExpr *E) {
9530 EvalOK = this->Visit(E->
getBase());
9541 if (
const FieldDecl *FD = dyn_cast<FieldDecl>(E->
getMemberDecl())) {
9544 "record / field mismatch");
9548 }
else if (
const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
9552 return this->
Error(E);
9564 bool VisitBinaryOperator(
const BinaryOperator *E) {
9567 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9575 bool VisitCastExpr(
const CastExpr *E) {
9578 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9580 case CK_DerivedToBase:
9581 case CK_UncheckedDerivedToBase:
9628class LValueExprEvaluator
9629 :
public LValueExprEvaluatorBase<LValueExprEvaluator> {
9631 LValueExprEvaluator(EvalInfo &Info, LValue &
Result,
bool InvalidBaseOK) :
9632 LValueExprEvaluatorBaseTy(Info,
Result, InvalidBaseOK) {}
9634 bool VisitVarDecl(
const Expr *E,
const VarDecl *VD);
9635 bool VisitUnaryPreIncDec(
const UnaryOperator *UO);
9637 bool VisitCallExpr(
const CallExpr *E);
9638 bool VisitDeclRefExpr(
const DeclRefExpr *E);
9639 bool VisitPredefinedExpr(
const PredefinedExpr *E) {
return Success(E); }
9640 bool VisitMaterializeTemporaryExpr(
const MaterializeTemporaryExpr *E);
9641 bool VisitCompoundLiteralExpr(
const CompoundLiteralExpr *E);
9642 bool VisitMemberExpr(
const MemberExpr *E);
9643 bool VisitStringLiteral(
const StringLiteral *E) {
9645 APValue::LValueBase(E, 0, Info.Ctx.getNextStringLiteralVersion()));
9647 bool VisitObjCEncodeExpr(
const ObjCEncodeExpr *E) {
return Success(E); }
9648 bool VisitCXXTypeidExpr(
const CXXTypeidExpr *E);
9649 bool VisitCXXUuidofExpr(
const CXXUuidofExpr *E);
9650 bool VisitArraySubscriptExpr(
const ArraySubscriptExpr *E);
9651 bool VisitExtVectorElementExpr(
const ExtVectorElementExpr *E);
9652 bool VisitUnaryDeref(
const UnaryOperator *E);
9653 bool VisitUnaryReal(
const UnaryOperator *E);
9654 bool VisitUnaryImag(
const UnaryOperator *E);
9655 bool VisitUnaryPreInc(
const UnaryOperator *UO) {
9656 return VisitUnaryPreIncDec(UO);
9658 bool VisitUnaryPreDec(
const UnaryOperator *UO) {
9659 return VisitUnaryPreIncDec(UO);
9661 bool VisitBinAssign(
const BinaryOperator *BO);
9662 bool VisitCompoundAssignOperator(
const CompoundAssignOperator *CAO);
9664 bool VisitCastExpr(
const CastExpr *E) {
9667 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9669 case CK_LValueBitCast:
9670 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
9671 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
9675 Result.Designator.setInvalid();
9678 case CK_BaseToDerived:
9695 bool LValueToRValueConversion) {
9699 assert(Info.CurrentCall->This ==
nullptr &&
9700 "This should not be set for a static call operator");
9708 if (
Self->getType()->isReferenceType()) {
9709 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments,
Self);
9711 Result.setFrom(Info.Ctx, *RefValue);
9713 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(
Self);
9714 CallStackFrame *Frame =
9715 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
9717 unsigned Version = Info.CurrentCall->Arguments.Version;
9718 Result.set({VD, Frame->Index, Version});
9721 Result = *Info.CurrentCall->This;
9731 if (LValueToRValueConversion) {
9735 Result.setFrom(Info.Ctx, RVal);
9746 bool InvalidBaseOK) {
9750 return LValueExprEvaluator(Info,
Result, InvalidBaseOK).Visit(E);
9753bool LValueExprEvaluator::VisitDeclRefExpr(
const DeclRefExpr *E) {
9754 const ValueDecl *D = E->
getDecl();
9766 if (Info.checkingPotentialConstantExpression())
9769 if (
auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(D)) {
9776 if (
isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl,
9777 UnnamedGlobalConstantDecl>(D))
9779 if (
const VarDecl *VD = dyn_cast<VarDecl>(D))
9780 return VisitVarDecl(E, VD);
9781 if (
const BindingDecl *BD = dyn_cast<BindingDecl>(D))
9782 return Visit(BD->getBinding());
9786bool LValueExprEvaluator::VisitVarDecl(
const Expr *E,
const VarDecl *VD) {
9787 CallStackFrame *Frame =
nullptr;
9788 unsigned Version = 0;
9796 CallStackFrame *CurrFrame = Info.CurrentCall;
9801 if (
auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
9802 if (CurrFrame->Arguments) {
9803 VD = CurrFrame->Arguments.getOrigParam(PVD);
9805 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
9806 Version = CurrFrame->Arguments.Version;
9810 Version = CurrFrame->getCurrentTemporaryVersion(VD);
9817 Result.set({VD, Frame->Index, Version});
9823 if (!Info.getLangOpts().CPlusPlus11) {
9824 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
9826 Info.Note(VD->
getLocation(), diag::note_declared_at);
9835 Result.AllowConstexprUnknown =
true;
9842bool LValueExprEvaluator::VisitCallExpr(
const CallExpr *E) {
9843 if (!IsConstantEvaluatedBuiltinCall(E))
9844 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9849 case Builtin::BIas_const:
9850 case Builtin::BIforward:
9851 case Builtin::BIforward_like:
9852 case Builtin::BImove:
9853 case Builtin::BImove_if_noexcept:
9855 return Visit(E->
getArg(0));
9859 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9862bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9863 const MaterializeTemporaryExpr *E) {
9871 for (
const Expr *E : CommaLHSs)
9880 if (Info.EvalMode == EvaluationMode::ConstantFold)
9887 Value = &Info.CurrentCall->createTemporary(
9903 for (
unsigned I = Adjustments.size(); I != 0; ) {
9905 switch (Adjustments[I].Kind) {
9910 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9916 Type = Adjustments[I].Field->getType();
9921 Adjustments[I].
Ptr.RHS))
9923 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9932LValueExprEvaluator::VisitCompoundLiteralExpr(
const CompoundLiteralExpr *E) {
9933 assert((!Info.getLangOpts().CPlusPlus || E->
isFileScope()) &&
9934 "lvalue compound literal in c++?");
9946 assert(!Info.getLangOpts().CPlusPlus);
9948 ScopeKind::Block,
Result);
9960bool LValueExprEvaluator::VisitCXXTypeidExpr(
const CXXTypeidExpr *E) {
9961 TypeInfoLValue TypeInfo;
9969 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9970 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9978 std::optional<DynamicType> DynType =
9983 TypeInfo = TypeInfoLValue(
9984 Info.Ctx.getCanonicalTagType(DynType->Type).getTypePtr());
9990bool LValueExprEvaluator::VisitCXXUuidofExpr(
const CXXUuidofExpr *E) {
9994bool LValueExprEvaluator::VisitMemberExpr(
const MemberExpr *E) {
9996 if (
const VarDecl *VD = dyn_cast<VarDecl>(E->
getMemberDecl())) {
9997 VisitIgnoredBaseExpression(E->
getBase());
9998 return VisitVarDecl(E, VD);
10002 if (
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->
getMemberDecl())) {
10003 if (MD->isStatic()) {
10004 VisitIgnoredBaseExpression(E->
getBase());
10010 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
10013bool LValueExprEvaluator::VisitExtVectorElementExpr(
10014 const ExtVectorElementExpr *E) {
10019 if (!Info.noteFailure())
10027 if (Indices.size() > 1)
10031 Result.setFrom(Info.Ctx, Val);
10035 const auto *VT = BaseType->
castAs<VectorType>();
10037 VT->getNumElements(), Indices[0]);
10043bool LValueExprEvaluator::VisitArraySubscriptExpr(
const ArraySubscriptExpr *E) {
10053 if (!Info.noteFailure())
10059 if (!Info.noteFailure())
10065 Result.setFrom(Info.Ctx, Val);
10067 VT->getNumElements(), Index.getZExtValue());
10075 for (
const Expr *SubExpr : {E->
getLHS(), E->
getRHS()}) {
10076 if (SubExpr == E->
getBase() ? !evaluatePointer(SubExpr,
Result)
10078 if (!Info.noteFailure())
10088bool LValueExprEvaluator::VisitUnaryDeref(
const UnaryOperator *E) {
10099 Info.noteUndefinedBehavior();
10102bool LValueExprEvaluator::VisitUnaryReal(
const UnaryOperator *E) {
10111bool LValueExprEvaluator::VisitUnaryImag(
const UnaryOperator *E) {
10113 "lvalue __imag__ on scalar?");
10120bool LValueExprEvaluator::VisitUnaryPreIncDec(
const UnaryOperator *UO) {
10121 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
10132bool LValueExprEvaluator::VisitCompoundAssignOperator(
10133 const CompoundAssignOperator *CAO) {
10134 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
10142 if (!Info.noteFailure())
10157bool LValueExprEvaluator::VisitBinAssign(
const BinaryOperator *E) {
10158 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
10166 if (!Info.noteFailure())
10174 if (Info.getLangOpts().CPlusPlus20 &&
10189 const LValue &LVal,
10191 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10192 "Can't get the size of a non alloc_size function");
10193 const auto *
Base = LVal.getLValueBase().get<
const Expr *>();
10195 std::optional<llvm::APInt> Size =
10196 CE->evaluateBytesReturnedByAllocSizeCall(Ctx);
10200 Result = std::move(*Size);
10219 dyn_cast_or_null<VarDecl>(
Base.dyn_cast<
const ValueDecl *>());
10224 if (!
Init ||
Init->getType().isNull())
10227 const Expr *E =
Init->IgnoreParens();
10228 if (!tryUnwrapAllocSizeCall(E))
10236 Result.addUnsizedArray(Info, E, Pointee);
10241class PointerExprEvaluator
10242 :
public ExprEvaluatorBase<PointerExprEvaluator> {
10244 bool InvalidBaseOK;
10246 bool Success(
const Expr *E) {
10251 bool evaluateLValue(
const Expr *E, LValue &
Result) {
10255 bool evaluatePointer(
const Expr *E, LValue &
Result) {
10259 bool visitNonBuiltinCallExpr(
const CallExpr *E);
10262 PointerExprEvaluator(EvalInfo &info, LValue &
Result,
bool InvalidBaseOK)
10264 InvalidBaseOK(InvalidBaseOK) {}
10270 bool ZeroInitialization(
const Expr *E) {
10275 bool VisitBinaryOperator(
const BinaryOperator *E);
10276 bool VisitCastExpr(
const CastExpr* E);
10277 bool VisitUnaryAddrOf(
const UnaryOperator *E);
10278 bool VisitObjCStringLiteral(
const ObjCStringLiteral *E)
10280 bool VisitObjCBoxedExpr(
const ObjCBoxedExpr *E) {
10283 if (Info.noteFailure())
10287 bool VisitObjCArrayLiteral(
const ObjCArrayLiteral *E) {
10290 bool VisitObjCDictionaryLiteral(
const ObjCDictionaryLiteral *E) {
10293 bool VisitAddrLabelExpr(
const AddrLabelExpr *E)
10295 bool VisitCallExpr(
const CallExpr *E);
10296 bool VisitBuiltinCallExpr(
const CallExpr *E,
unsigned BuiltinOp);
10297 bool VisitBlockExpr(
const BlockExpr *E) {
10302 bool VisitCXXThisExpr(
const CXXThisExpr *E) {
10303 auto DiagnoseInvalidUseOfThis = [&] {
10304 if (Info.getLangOpts().CPlusPlus11)
10305 Info.FFDiag(E, diag::note_constexpr_this) << E->
isImplicit();
10311 if (Info.checkingPotentialConstantExpression())
10314 bool IsExplicitLambda =
10316 if (!IsExplicitLambda) {
10317 if (!Info.CurrentCall->This) {
10318 DiagnoseInvalidUseOfThis();
10322 Result = *Info.CurrentCall->This;
10330 if (!Info.CurrentCall->LambdaThisCaptureField) {
10331 if (IsExplicitLambda && !Info.CurrentCall->This) {
10332 DiagnoseInvalidUseOfThis();
10341 Info, E,
Result, MD, Info.CurrentCall->LambdaThisCaptureField,
10347 bool VisitCXXNewExpr(
const CXXNewExpr *E);
10349 bool VisitSourceLocExpr(
const SourceLocExpr *E) {
10350 assert(!E->
isIntType() &&
"SourceLocExpr isn't a pointer type?");
10352 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.
getDefaultExpr());
10353 Result.setFrom(Info.Ctx, LValResult);
10357 bool VisitEmbedExpr(
const EmbedExpr *E) {
10358 llvm::report_fatal_error(
"Not yet implemented for ExprConstant.cpp");
10362 bool VisitSYCLUniqueStableNameExpr(
const SYCLUniqueStableNameExpr *E) {
10363 std::string ResultStr = E->
ComputeName(Info.Ctx);
10365 QualType CharTy = Info.Ctx.CharTy.withConst();
10366 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
10367 ResultStr.size() + 1);
10368 QualType ArrayTy = Info.Ctx.getConstantArrayType(
10369 CharTy, Size,
nullptr, ArraySizeModifier::Normal, 0);
10371 StringLiteral *SL =
10372 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
10375 evaluateLValue(SL,
Result);
10385 bool InvalidBaseOK) {
10388 return PointerExprEvaluator(Info,
Result, InvalidBaseOK).Visit(E);
10391bool PointerExprEvaluator::VisitBinaryOperator(
const BinaryOperator *E) {
10394 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10396 const Expr *PExp = E->
getLHS();
10397 const Expr *IExp = E->
getRHS();
10399 std::swap(PExp, IExp);
10401 bool EvalPtrOK = evaluatePointer(PExp,
Result);
10402 if (!EvalPtrOK && !Info.noteFailure())
10405 llvm::APSInt Offset;
10416bool PointerExprEvaluator::VisitUnaryAddrOf(
const UnaryOperator *E) {
10424 if (!Info.getLangOpts().CPlusPlus) {
10426 if (
const auto *Deref = dyn_cast<UnaryOperator>(Sub);
10427 Deref && Deref->getOpcode() == UO_Deref)
10428 return evaluatePointer(Deref->getSubExpr(),
Result);
10438 if (!FnII || !FnII->
isStr(
"current"))
10441 const auto *RD = dyn_cast<RecordDecl>(FD->
getParent());
10449bool PointerExprEvaluator::VisitCastExpr(
const CastExpr *E) {
10456 case CK_CPointerToObjCPointerCast:
10457 case CK_BlockPointerToObjCPointerCast:
10458 case CK_AnyPointerToBlockPointerCast:
10459 case CK_AddressSpaceConversion:
10460 if (!Visit(SubExpr))
10466 CCEDiag(E, diag::note_constexpr_invalid_cast)
10467 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10468 << Info.Ctx.getLangOpts().CPlusPlus;
10469 Result.Designator.setInvalid();
10477 bool HasValidResult = !
Result.InvalidBase && !
Result.Designator.Invalid &&
10479 bool VoidPtrCastMaybeOK =
10482 Info.Ctx.hasSimilarType(
Result.Designator.getType(Info.Ctx),
10491 if (VoidPtrCastMaybeOK &&
10492 (Info.getStdAllocatorCaller(
"allocate") ||
10494 Info.getLangOpts().CPlusPlus26)) {
10498 Info.getLangOpts().CPlusPlus) {
10499 if (HasValidResult)
10500 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
10501 << SubExpr->
getType() << Info.getLangOpts().CPlusPlus26
10502 <<
Result.Designator.getType(Info.Ctx).getCanonicalType()
10505 CCEDiag(E, diag::note_constexpr_invalid_cast)
10506 << diag::ConstexprInvalidCastKind::CastFrom
10509 CCEDiag(E, diag::note_constexpr_invalid_cast)
10510 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10511 << Info.Ctx.getLangOpts().CPlusPlus;
10512 Result.Designator.setInvalid();
10516 ZeroInitialization(E);
10519 case CK_DerivedToBase:
10520 case CK_UncheckedDerivedToBase:
10532 case CK_BaseToDerived:
10544 case CK_NullToPointer:
10546 return ZeroInitialization(E);
10548 case CK_IntegralToPointer: {
10549 CCEDiag(E, diag::note_constexpr_invalid_cast)
10550 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
10551 << Info.Ctx.getLangOpts().CPlusPlus;
10557 if (
Value.isInt()) {
10558 unsigned Size = Info.Ctx.getTypeSize(E->
getType());
10559 uint64_t N =
Value.getInt().extOrTrunc(Size).getZExtValue();
10560 if (N == Info.Ctx.getTargetNullPointerValue(E->
getType())) {
10563 Result.Base = (Expr *)
nullptr;
10564 Result.InvalidBase =
false;
10566 Result.Designator.setInvalid();
10567 Result.IsNullPtr =
false;
10575 if (!
Value.isLValue())
10584 case CK_ArrayToPointerDecay: {
10586 if (!evaluateLValue(SubExpr,
Result))
10590 SubExpr, SubExpr->
getType(), ScopeKind::FullExpression,
Result);
10595 auto *AT = Info.Ctx.getAsArrayType(SubExpr->
getType());
10596 if (
auto *CAT = dyn_cast<ConstantArrayType>(AT))
10597 Result.addArray(Info, E, CAT);
10599 Result.addUnsizedArray(Info, E, AT->getElementType());
10603 case CK_FunctionToPointerDecay:
10604 return evaluateLValue(SubExpr,
Result);
10606 case CK_LValueToRValue: {
10615 return InvalidBaseOK &&
10621 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10625 UnaryExprOrTypeTrait ExprKind) {
10629 T =
T.getNonReferenceType();
10631 if (
T.getQualifiers().hasUnaligned())
10634 const bool AlignOfReturnsPreferred =
10640 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
10643 else if (ExprKind == UETT_AlignOf)
10646 llvm_unreachable(
"GetAlignOfType on a non-alignment ExprKind");
10661 unsigned BuiltinOp) {
10685 switch (OwningTarget->
getTriple().getArch()) {
10686 case llvm::Triple::x86:
10687 case llvm::Triple::x86_64:
10700 UnaryExprOrTypeTrait ExprKind) {
10709 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10713 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10722 return Info.Ctx.getDeclAlign(VD);
10723 if (
const auto *E =
Value.Base.dyn_cast<
const Expr *>())
10734 EvalInfo &Info,
APSInt &Alignment) {
10737 if (Alignment < 0 || !Alignment.isPowerOf2()) {
10738 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
10741 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
10742 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
10743 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
10744 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
10745 << MaxValue << ForType << Alignment;
10751 APSInt(Alignment.zextOrTrunc(SrcWidth),
true);
10752 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
10753 "Alignment should not be changed by ext/trunc");
10754 Alignment = ExtAlignment;
10755 assert(Alignment.getBitWidth() == SrcWidth);
10760bool PointerExprEvaluator::visitNonBuiltinCallExpr(
const CallExpr *E) {
10761 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
10769 Result.addUnsizedArray(Info, E, PointeeTy);
10773bool PointerExprEvaluator::VisitCallExpr(
const CallExpr *E) {
10774 if (!IsConstantEvaluatedBuiltinCall(E))
10775 return visitNonBuiltinCallExpr(E);
10782 return T->isCharType() ||
T->isChar8Type();
10785bool PointerExprEvaluator::VisitBuiltinCallExpr(
const CallExpr *E,
10786 unsigned BuiltinOp) {
10790 switch (BuiltinOp) {
10791 case Builtin::BIaddressof:
10792 case Builtin::BI__addressof:
10793 case Builtin::BI__builtin_addressof:
10795 case Builtin::BI__builtin_assume_aligned: {
10802 LValue OffsetResult(
Result);
10814 int64_t AdditionalOffset = -Offset.getZExtValue();
10819 if (OffsetResult.Base) {
10822 if (BaseAlignment < Align) {
10823 Result.Designator.setInvalid();
10824 CCEDiag(E->
getArg(0), diag::note_constexpr_baa_insufficient_alignment)
10831 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
10832 Result.Designator.setInvalid();
10836 diag::note_constexpr_baa_insufficient_alignment)
10839 diag::note_constexpr_baa_value_insufficient_alignment))
10840 << OffsetResult.Offset.getQuantity() << Align.
getQuantity();
10846 case Builtin::BI__builtin_align_up:
10847 case Builtin::BI__builtin_align_down: {
10857 if (
Result.Offset.isZero())
10863 Info.FFDiag(E->
getArg(0), diag::note_constexpr_alignment_adjust)
10881 assert(Alignment.getBitWidth() <= 64 &&
10882 "Cannot handle > 64-bit address-space");
10883 uint64_t Alignment64 = Alignment.getZExtValue();
10885 BuiltinOp == Builtin::BI__builtin_align_down
10886 ? llvm::alignDown(
Result.Offset.getQuantity(), Alignment64)
10887 : llvm::alignTo(
Result.Offset.getQuantity(), Alignment64));
10893 Info.FFDiag(E->
getArg(0), diag::note_constexpr_alignment_adjust)
10897 case Builtin::BI__builtin_operator_new:
10899 case Builtin::BI__builtin_launder:
10901 case Builtin::BIstrchr:
10902 case Builtin::BIwcschr:
10903 case Builtin::BImemchr:
10904 case Builtin::BIwmemchr:
10905 if (Info.getLangOpts().CPlusPlus11)
10906 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10908 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10910 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10912 case Builtin::BI__builtin_strchr:
10913 case Builtin::BI__builtin_wcschr:
10914 case Builtin::BI__builtin_memchr:
10915 case Builtin::BI__builtin_char_memchr:
10916 case Builtin::BI__builtin_wmemchr: {
10917 if (!Visit(E->
getArg(0)))
10923 if (BuiltinOp != Builtin::BIstrchr &&
10924 BuiltinOp != Builtin::BIwcschr &&
10925 BuiltinOp != Builtin::BI__builtin_strchr &&
10926 BuiltinOp != Builtin::BI__builtin_wcschr) {
10930 MaxLength = N.getZExtValue();
10933 if (MaxLength == 0u)
10934 return ZeroInitialization(E);
10935 if (!
Result.checkNullPointerForFoldAccess(Info, E,
AK_Read) ||
10936 Result.Designator.Invalid)
10938 QualType CharTy =
Result.Designator.getType(Info.Ctx);
10939 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
10940 BuiltinOp == Builtin::BI__builtin_memchr;
10941 assert(IsRawByte ||
10942 Info.Ctx.hasSameUnqualifiedType(
10946 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
10952 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10953 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10959 bool StopAtNull =
false;
10960 switch (BuiltinOp) {
10961 case Builtin::BIstrchr:
10962 case Builtin::BI__builtin_strchr:
10965 case Builtin::BImemchr:
10966 case Builtin::BI__builtin_memchr:
10967 case Builtin::BI__builtin_char_memchr:
10971 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10974 case Builtin::BIwcschr:
10975 case Builtin::BI__builtin_wcschr:
10978 case Builtin::BIwmemchr:
10979 case Builtin::BI__builtin_wmemchr:
10981 DesiredVal = Desired.getZExtValue();
10985 for (; MaxLength; --MaxLength) {
10990 if (Char.
getInt().getZExtValue() == DesiredVal)
10992 if (StopAtNull && !Char.
getInt())
10998 return ZeroInitialization(E);
11001 case Builtin::BImemcpy:
11002 case Builtin::BImemmove:
11003 case Builtin::BIwmemcpy:
11004 case Builtin::BIwmemmove:
11005 if (Info.getLangOpts().CPlusPlus11)
11006 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11008 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
11010 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11012 case Builtin::BI__builtin_memcpy:
11013 case Builtin::BI__builtin_memmove:
11014 case Builtin::BI__builtin_wmemcpy:
11015 case Builtin::BI__builtin_wmemmove: {
11016 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
11017 BuiltinOp == Builtin::BIwmemmove ||
11018 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
11019 BuiltinOp == Builtin::BI__builtin_wmemmove;
11020 bool Move = BuiltinOp == Builtin::BImemmove ||
11021 BuiltinOp == Builtin::BIwmemmove ||
11022 BuiltinOp == Builtin::BI__builtin_memmove ||
11023 BuiltinOp == Builtin::BI__builtin_wmemmove;
11026 if (!Visit(E->
getArg(0)))
11037 assert(!N.isSigned() &&
"memcpy and friends take an unsigned size");
11047 if (!Src.Base || !Dest.Base) {
11049 (!Src.Base ? Src : Dest).moveInto(Val);
11050 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
11051 <<
Move << WChar << !!Src.Base
11055 if (Src.Designator.Invalid || Dest.Designator.Invalid)
11061 QualType
T = Dest.Designator.getType(Info.Ctx);
11062 QualType SrcT = Src.Designator.getType(Info.Ctx);
11063 if (!Info.Ctx.hasSameUnqualifiedType(
T, SrcT)) {
11065 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) <<
Move << SrcT <<
T;
11069 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) <<
Move <<
T;
11072 if (!
T.isTriviallyCopyableType(Info.Ctx)) {
11073 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) <<
Move <<
T;
11078 uint64_t TSize = Info.Ctx.getTypeSizeInChars(
T).getQuantity();
11083 llvm::APInt OrigN = N;
11084 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
11086 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
11096 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
11097 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
11098 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
11099 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
11100 <<
Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) <<
T
11104 uint64_t NElems = N.getZExtValue();
11110 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
11111 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
11112 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
11115 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
11123 }
else if (!Move && SrcOffset >= DestOffset &&
11124 SrcOffset - DestOffset < NBytes) {
11126 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
11155 QualType AllocType);
11158 const CXXConstructExpr *CCE,
11159 QualType AllocType);
11161bool PointerExprEvaluator::VisitCXXNewExpr(
const CXXNewExpr *E) {
11162 if (!Info.getLangOpts().CPlusPlus20)
11163 Info.CCEDiag(E, diag::note_constexpr_new);
11166 if (Info.SpeculativeEvaluationDepth)
11171 QualType TargetType = AllocType;
11173 bool IsNothrow =
false;
11174 bool IsPlacement =
false;
11190 if (OperatorNew->isReservedGlobalPlacementOperator()) {
11191 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
11192 (Info.CurrentCall->CanEvalMSConstexpr &&
11193 OperatorNew->hasAttr<MSConstexprAttr>())) {
11196 if (
Result.Designator.Invalid)
11199 IsPlacement =
true;
11201 Info.FFDiag(E, diag::note_constexpr_new_placement)
11206 Info.FFDiag(E, diag::note_constexpr_new_placement)
11209 }
else if (!OperatorNew
11210 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
11214 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
11217 }
else if (HasNothrowArg) {
11225 const InitListExpr *ResizedArrayILE =
nullptr;
11226 const CXXConstructExpr *ResizedArrayCCE =
nullptr;
11227 bool ValueInit =
false;
11229 if (std::optional<const Expr *> ArraySize = E->
getArraySize()) {
11230 const Expr *Stripped = *ArraySize;
11231 for (;
auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
11232 Stripped = ICE->getSubExpr())
11233 if (ICE->getCastKind() != CK_NoOp &&
11234 ICE->getCastKind() != CK_IntegralCast)
11247 return ZeroInitialization(E);
11249 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
11250 <<
ArrayBound << (*ArraySize)->getSourceRange();
11256 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
11261 return ZeroInitialization(E);
11273 }
else if (
auto *CCE = dyn_cast<CXXConstructExpr>(
Init)) {
11274 ResizedArrayCCE = CCE;
11276 auto *CAT = Info.Ctx.getAsConstantArrayType(
Init->getType());
11277 assert(CAT &&
"unexpected type for array initializer");
11281 llvm::APInt InitBound = CAT->
getSize().zext(Bits);
11282 llvm::APInt AllocBound =
ArrayBound.zext(Bits);
11283 if (InitBound.ugt(AllocBound)) {
11285 return ZeroInitialization(E);
11287 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
11288 <<
toString(AllocBound, 10,
false)
11290 << (*ArraySize)->getSourceRange();
11296 if (InitBound != AllocBound)
11300 AllocType = Info.Ctx.getConstantArrayType(AllocType,
ArrayBound,
nullptr,
11301 ArraySizeModifier::Normal, 0);
11311 "array allocation with non-array new");
11317 struct FindObjectHandler {
11320 QualType AllocType;
11324 typedef bool result_type;
11325 bool failed() {
return false; }
11326 bool checkConst(QualType QT) {
11328 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
11333 bool found(
APValue &Subobj, QualType SubobjType,
11334 APValue::LValueBase Base) {
11335 if (!checkConst(SubobjType))
11339 if (!Info.Ctx.hasSimilarType(SubobjType, AllocType)) {
11340 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
11341 << SubobjType << AllocType;
11348 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11351 bool found(APFloat &
Value, QualType SubobjType) {
11352 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
11355 } Handler = {Info, E, AllocType, AK,
nullptr};
11358 Result.Designator.MostDerivedIsArrayElement &&
11359 Result.Designator.Entries.back().getAsArrayIndex() == 0) {
11364 QualType AllocElementType =
11365 Info.Ctx.getAsArrayType(AllocType)->getElementType();
11366 if (Info.Ctx.hasSimilarType(AllocElementType,
11367 Result.Designator.MostDerivedType)) {
11369 Result.Designator.MostDerivedPathLength - 1);
11377 Val = Handler.Value;
11386 Val = Info.createHeapAlloc(E, AllocType,
Result);
11392 ImplicitValueInitExpr VIE(AllocType);
11395 }
else if (ResizedArrayILE) {
11399 }
else if (ResizedArrayCCE) {
11423class ReflectionEvaluator :
public ExprEvaluatorBase<ReflectionEvaluator> {
11425 using BaseType = ExprEvaluatorBase<ReflectionEvaluator>;
11438 bool VisitCXXReflectExpr(
const CXXReflectExpr *E);
11439 bool ZeroInitialization(
const Expr *E);
11442bool ReflectionEvaluator::VisitCXXReflectExpr(
const CXXReflectExpr *E) {
11444 case ReflectionKind::Null: {
11445 assert(
false &&
"null reflection can't be constructed from parsing a "
11446 "reflection operand");
11449 case ReflectionKind::Type: {
11451 return Success(ReflectionValue, E);
11454 assert(
false &&
"unknown or unimplemented reflection entities");
11458bool ReflectionEvaluator::ZeroInitialization(
const Expr *E) {
11467 return ReflectionEvaluator(Info,
Result).Visit(E);
11472 unsigned BuiltinOp,
11474 switch (BuiltinOp) {
11475 case Builtin::BI__builtin_meta_is_type: {
11485 llvm_unreachable(
"unknown metafunction builtin");
11494class MemberPointerExprEvaluator
11495 :
public ExprEvaluatorBase<MemberPointerExprEvaluator> {
11498 bool Success(
const ValueDecl *D) {
11504 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &
Result)
11511 bool ZeroInitialization(
const Expr *E) {
11512 return Success((
const ValueDecl*)
nullptr);
11515 bool VisitCastExpr(
const CastExpr *E);
11516 bool VisitUnaryAddrOf(
const UnaryOperator *E);
11524 return MemberPointerExprEvaluator(Info,
Result).Visit(E);
11527bool MemberPointerExprEvaluator::VisitCastExpr(
const CastExpr *E) {
11530 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11532 case CK_NullToMemberPointer:
11534 return ZeroInitialization(E);
11536 case CK_BaseToDerivedMemberPointer: {
11544 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
11546 PathI != PathE; ++PathI) {
11547 assert(!(*PathI)->isVirtual() &&
"memptr cast through vbase");
11548 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
11549 if (!
Result.castToDerived(Derived))
11553 ->
castAs<MemberPointerType>()
11554 ->getMostRecentCXXRecordDecl()))
11559 case CK_DerivedToBaseMemberPointer:
11563 PathE = E->
path_end(); PathI != PathE; ++PathI) {
11564 assert(!(*PathI)->isVirtual() &&
"memptr cast through vbase");
11565 const CXXRecordDecl *
Base = (*PathI)->getType()->getAsCXXRecordDecl();
11566 if (!
Result.castToBase(Base))
11573bool MemberPointerExprEvaluator::VisitUnaryAddrOf(
const UnaryOperator *E) {
11584 class RecordExprEvaluator
11585 :
public ExprEvaluatorBase<RecordExprEvaluator> {
11586 const LValue &
This;
11590 RecordExprEvaluator(EvalInfo &info,
const LValue &This,
APValue &
Result)
11597 bool ZeroInitialization(
const Expr *E) {
11598 return ZeroInitialization(E, E->
getType());
11600 bool ZeroInitialization(
const Expr *E, QualType
T);
11602 bool VisitCallExpr(
const CallExpr *E) {
11603 return handleCallExpr(E,
Result, &This);
11605 bool VisitCastExpr(
const CastExpr *E);
11606 bool VisitInitListExpr(
const InitListExpr *E);
11607 bool VisitCXXConstructExpr(
const CXXConstructExpr *E) {
11608 return VisitCXXConstructExpr(E, E->
getType());
11611 bool VisitCXXInheritedCtorInitExpr(
const CXXInheritedCtorInitExpr *E);
11612 bool VisitCXXConstructExpr(
const CXXConstructExpr *E, QualType
T);
11613 bool VisitCXXStdInitializerListExpr(
const CXXStdInitializerListExpr *E);
11614 bool VisitBinCmp(
const BinaryOperator *E);
11615 bool VisitTypeTraitExpr(
const TypeTraitExpr *E);
11616 bool VisitCXXParenListInitExpr(
const CXXParenListInitExpr *E);
11617 bool VisitCXXParenListOrInitListExpr(
const Expr *ExprToVisit,
11618 ArrayRef<Expr *> Args);
11619 bool VisitDesignatedInitUpdateExpr(
const DesignatedInitUpdateExpr *E);
11633 bool IsCompleteClass =
true) {
11634 assert(!RD->
isUnion() &&
"Expected non-union class type");
11638 unsigned NonVirtualBases = countNonVirtualBases(CD);
11650 unsigned Index = 0;
11652 for (
const auto &B : CD->
bases()) {
11656 LValue Subobject =
This;
11660 Result.getStructBase(Index),
11667 for (
const auto *I : RD->
fields()) {
11669 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
11672 LValue Subobject =
This;
11678 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
11682 if (CD &&
This.pointsToCompleteClass(CD)) {
11683 unsigned Index = 0;
11684 for (
const auto &B : CD->
vbases()) {
11686 LValue Subobject =
This;
11690 Result.getStructVirtualBase(Index),
11700bool RecordExprEvaluator::ZeroInitialization(
const Expr *E, QualType
T) {
11707 while (I != RD->
field_end() && (*I)->isUnnamedBitField())
11714 LValue Subobject =
This;
11718 ImplicitValueInitExpr VIE(I->getType());
11722 if (!Info.getLangOpts().CPlusPlus26) {
11723 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11724 CXXRD && CXXRD->getNumVBases()) {
11725 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
11733bool RecordExprEvaluator::VisitCastExpr(
const CastExpr *E) {
11736 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11738 case CK_ConstructorConversion:
11741 case CK_DerivedToBase:
11742 case CK_UncheckedDerivedToBase: {
11753 PathE = E->
path_end(); PathI != PathE; ++PathI) {
11754 assert(!(*PathI)->isVirtual() &&
"record rvalue with virtual base");
11755 const CXXRecordDecl *
Base = (*PathI)->getType()->getAsCXXRecordDecl();
11762 case CK_HLSLAggregateSplatCast: {
11782 case CK_HLSLElementwiseCast: {
11800 LValue Subobject =
This;
11807 if (
Field->isBitField()) {
11817bool RecordExprEvaluator::VisitInitListExpr(
const InitListExpr *E) {
11820 return VisitCXXParenListOrInitListExpr(E, E->
inits());
11823bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
11827 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
11828 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
11830 EvalInfo::EvaluatingConstructorRAII EvalObj(
11832 ObjectUnderConstruction{
This.getLValueBase(),
This.Designator.Entries},
11833 CXXRD && CXXRD->getNumBases());
11836 const FieldDecl *
Field;
11837 if (
auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
11838 Field = ILE->getInitializedFieldInUnion();
11839 }
else if (
auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
11840 Field = PLIE->getInitializedFieldInUnion();
11843 "Expression is neither an init list nor a C++ paren list");
11855 ImplicitValueInitExpr VIE(
Field->getType());
11856 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
11858 LValue Subobject =
This;
11863 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11867 if (
Field->isBitField())
11877 Result =
APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
11879 unsigned ElementNo = 0;
11883 if (CXXRD && CXXRD->getNumBases()) {
11884 for (
const auto &Base : CXXRD->bases()) {
11885 assert(ElementNo < Args.size() &&
"missing init for base class");
11886 const Expr *
Init = Args[ElementNo];
11888 LValue Subobject =
This;
11894 if (!Info.noteFailure())
11901 EvalObj.finishedConstructingBases();
11905 for (
const auto *Field : RD->
fields()) {
11908 if (
Field->isUnnamedBitField())
11911 LValue Subobject =
This;
11913 bool HaveInit = ElementNo < Args.size();
11918 Subobject, Field, &Layout))
11923 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy :
Field->getType());
11924 const Expr *
Init = HaveInit ? Args[ElementNo++] : &VIE;
11931 if (
Field->getType()->isIncompleteArrayType()) {
11932 if (
auto *CAT = Info.Ctx.getAsConstantArrayType(
Init->getType())) {
11936 Info.FFDiag(
Init, diag::note_constexpr_unsupported_flexible_array);
11943 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
11947 if (
Field->getType()->isReferenceType()) {
11951 if (!Info.noteFailure())
11956 (
Field->isBitField() &&
11958 if (!Info.noteFailure())
11964 EvalObj.finishedConstructingFields();
11969bool RecordExprEvaluator::VisitCXXConstructExpr(
const CXXConstructExpr *E,
11979 return ZeroInitialization(E,
T);
11999 const Expr *SrcObj = E->
getArg(0);
12001 assert(Info.Ctx.hasSameUnqualifiedType(E->
getType(), SrcObj->
getType()));
12002 if (
const MaterializeTemporaryExpr *ME =
12003 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
12004 return Visit(ME->getSubExpr());
12007 if (ZeroInit && !ZeroInitialization(E,
T))
12016bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
12017 const CXXInheritedCtorInitExpr *E) {
12018 if (!Info.CurrentCall) {
12019 assert(Info.checkingPotentialConstantExpression());
12040bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
12041 const CXXStdInitializerListExpr *E) {
12042 const ConstantArrayType *ArrayType =
12049 assert(ArrayType &&
"unexpected type for array initializer");
12052 Array.addArray(Info, E, ArrayType);
12060 assert(Field !=
Record->field_end() &&
12061 Info.Ctx.hasSameType(
Field->getType()->getPointeeType(),
12063 "Expected std::initializer_list first field to be const E *");
12065 assert(Field !=
Record->field_end() &&
12066 "Expected std::initializer_list to have two fields");
12068 if (Info.Ctx.hasSameType(
Field->getType(), Info.Ctx.getSizeType())) {
12073 assert(Info.Ctx.hasSameType(
Field->getType()->getPointeeType(),
12075 "Expected std::initializer_list second field to be const E *");
12083 assert(++Field ==
Record->field_end() &&
12084 "Expected std::initializer_list to only have two fields");
12089bool RecordExprEvaluator::VisitLambdaExpr(
const LambdaExpr *E) {
12094 const size_t NumFields = ClosureClass->
getNumFields();
12098 "The number of lambda capture initializers should equal the number of "
12099 "fields within the closure type");
12106 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
12107 for (
const auto *Field : ClosureClass->
fields()) {
12110 Expr *
const CurFieldInit = *CaptureInitIt++;
12117 LValue Subobject =
This;
12124 if (!Info.keepEvaluatingAfterFailure())
12132bool RecordExprEvaluator::VisitDesignatedInitUpdateExpr(
12133 const DesignatedInitUpdateExpr *E) {
12143 "can't evaluate expression as a record rvalue");
12144 return RecordExprEvaluator(Info,
This,
Result).Visit(E);
12155class TemporaryExprEvaluator
12156 :
public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
12158 TemporaryExprEvaluator(EvalInfo &Info, LValue &
Result) :
12159 LValueExprEvaluatorBaseTy(Info,
Result,
false) {}
12162 bool VisitConstructExpr(
const Expr *E) {
12168 bool VisitCastExpr(
const CastExpr *E) {
12171 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
12173 case CK_ConstructorConversion:
12177 bool VisitInitListExpr(
const InitListExpr *E) {
12178 return VisitConstructExpr(E);
12180 bool VisitCXXConstructExpr(
const CXXConstructExpr *E) {
12181 return VisitConstructExpr(E);
12183 bool VisitCallExpr(
const CallExpr *E) {
12184 return VisitConstructExpr(E);
12186 bool VisitCXXStdInitializerListExpr(
const CXXStdInitializerListExpr *E) {
12187 return VisitConstructExpr(E);
12190 return VisitConstructExpr(E);
12199 return TemporaryExprEvaluator(Info,
Result).Visit(E);
12207 class VectorExprEvaluator
12208 :
public ExprEvaluatorBase<VectorExprEvaluator> {
12215 bool Success(ArrayRef<APValue>
V,
const Expr *E) {
12216 assert(
V.size() == E->
getType()->
castAs<VectorType>()->getNumElements());
12222 assert(
V.isVector());
12226 bool ZeroInitialization(
const Expr *E);
12228 bool VisitUnaryReal(
const UnaryOperator *E)
12230 bool VisitCastExpr(
const CastExpr* E);
12231 bool VisitInitListExpr(
const InitListExpr *E);
12232 bool VisitUnaryImag(
const UnaryOperator *E);
12233 bool VisitBinaryOperator(
const BinaryOperator *E);
12234 bool VisitUnaryOperator(
const UnaryOperator *E);
12235 bool VisitCallExpr(
const CallExpr *E);
12236 bool VisitConvertVectorExpr(
const ConvertVectorExpr *E);
12237 bool VisitShuffleVectorExpr(
const ShuffleVectorExpr *E);
12246 "not a vector prvalue");
12247 return VectorExprEvaluator(Info,
Result).Visit(E);
12251 assert(Val.
isVector() &&
"expected vector APValue");
12255 llvm::APInt
Result(NumElts, 0);
12257 for (
unsigned I = 0; I < NumElts; ++I) {
12259 assert(Elt.
isInt() &&
"expected integer element in bool vector");
12261 if (Elt.
getInt().getBoolValue())
12268bool VectorExprEvaluator::VisitCastExpr(
const CastExpr *E) {
12269 const VectorType *VTy = E->
getType()->
castAs<VectorType>();
12273 QualType SETy = SE->
getType();
12276 case CK_VectorSplat: {
12282 Val =
APValue(std::move(IntResult));
12287 Val =
APValue(std::move(FloatResult));
12304 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
12305 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
12306 << Info.Ctx.getLangOpts().CPlusPlus;
12310 if (!handleRValueToRValueBitCast(Info,
Result, SVal, E))
12315 case CK_HLSLVectorTruncation: {
12320 for (
unsigned I = 0; I < NElts; I++)
12324 case CK_HLSLMatrixTruncation: {
12330 for (
unsigned Row = 0;
12332 for (
unsigned Col = 0;
12337 case CK_HLSLAggregateSplatCast: {
12354 case CK_HLSLElementwiseCast: {
12367 return Success(ResultEls, E);
12369 case CK_IntegralToFloating:
12370 case CK_FloatingToIntegral:
12371 case CK_IntegralCast:
12372 case CK_FloatingCast:
12373 case CK_FloatingToBoolean:
12374 case CK_IntegralToBoolean: {
12376 assert(SETy->
isVectorType() &&
"expected vector source type");
12382 QualType SrcEltTy = SETy->
castAs<VectorType>()->getElementType();
12387 for (
unsigned I = 0; I < NElts; ++I) {
12392 return Success(ResultEls, E);
12395 return ExprEvaluatorBaseTy::VisitCastExpr(E);
12400VectorExprEvaluator::VisitInitListExpr(
const InitListExpr *E) {
12417 unsigned CountInits = 0, CountElts = 0;
12418 while (CountElts < NumElements) {
12420 if (CountInits < NumInits
12426 for (
unsigned j = 0; j < vlen; j++)
12430 llvm::APSInt sInt(32);
12431 if (CountInits < NumInits) {
12435 sInt = Info.Ctx.MakeIntValue(0, EltTy);
12436 Elements.push_back(
APValue(sInt));
12439 llvm::APFloat f(0.0);
12440 if (CountInits < NumInits) {
12444 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
12445 Elements.push_back(
APValue(f));
12454VectorExprEvaluator::ZeroInitialization(
const Expr *E) {
12458 if (EltTy->isIntegerType())
12459 ZeroElement =
APValue(Info.Ctx.MakeIntValue(0, EltTy));
12462 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
12468bool VectorExprEvaluator::VisitUnaryImag(
const UnaryOperator *E) {
12470 return ZeroInitialization(E);
12473bool VectorExprEvaluator::VisitBinaryOperator(
const BinaryOperator *E) {
12475 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
12476 "Operation not supported on vector types");
12478 if (Op == BO_Comma)
12479 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12481 Expr *LHS = E->
getLHS();
12482 Expr *RHS = E->
getRHS();
12487 "Must both be vector types");
12490 assert(LHSType->
castAs<VectorType>()->getNumElements() ==
12492 RHSType->
castAs<VectorType>()->getNumElements() ==
12494 "All operands must be the same size.");
12498 bool LHSOK =
Evaluate(LHSValue, Info, LHS);
12499 if (!LHSOK && !Info.noteFailure())
12501 if (!
Evaluate(RHSValue, Info, RHS) || !LHSOK)
12523 "Vector can only be int or float type");
12531 "Vector operator ~ can only be int");
12532 Elt.
getInt().flipAllBits();
12542 "Vector can only be int or float type");
12548 EltResult.setAllBits();
12550 EltResult.clearAllBits();
12556 return std::nullopt;
12560bool VectorExprEvaluator::VisitUnaryOperator(
const UnaryOperator *E) {
12566 const QualType ResultEltTy = VD->getElementType();
12570 if (!
Evaluate(SubExprValue, Info, SubExpr))
12583 "Vector length doesn't match type?");
12586 for (
unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
12588 Info.Ctx, ResultEltTy, Op, SubExprValue.
getVectorElt(EltNum));
12591 ResultElements.push_back(*Elt);
12593 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
12604 DestTy,
Result.getFloat());
12620 DestTy,
Result.getInt());
12624 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
12625 << SourceTy << DestTy;
12630 llvm::function_ref<APInt(
const APSInt &)> PackFn) {
12639 assert(LHSVecLen != 0 && LHSVecLen == RHSVecLen &&
12640 "pack builtin LHSVecLen must equal to RHSVecLen");
12643 const unsigned SrcBits = Info.Ctx.getIntWidth(VT0->
getElementType());
12649 const unsigned SrcPerLane = 128 / SrcBits;
12650 const unsigned Lanes = LHSVecLen * SrcBits / 128;
12653 Out.reserve(LHSVecLen + RHSVecLen);
12655 for (
unsigned Lane = 0; Lane != Lanes; ++Lane) {
12656 unsigned base = Lane * SrcPerLane;
12657 for (
unsigned I = 0; I != SrcPerLane; ++I)
12660 for (
unsigned I = 0; I != SrcPerLane; ++I)
12671 llvm::function_ref<std::pair<unsigned, int>(
unsigned,
unsigned)>
12678 unsigned ShuffleMask = 0;
12680 bool IsVectorMask =
false;
12681 bool IsSingleOperand = (
Call->getNumArgs() == 2);
12683 if (IsSingleOperand) {
12686 IsVectorMask =
true;
12695 ShuffleMask =
static_cast<unsigned>(MaskImm.getZExtValue());
12705 IsVectorMask =
true;
12714 ShuffleMask =
static_cast<unsigned>(MaskImm.getZExtValue());
12725 ResultElements.reserve(NumElts);
12727 for (
unsigned DstIdx = 0; DstIdx != NumElts; ++DstIdx) {
12728 if (IsVectorMask) {
12729 ShuffleMask =
static_cast<unsigned>(
12730 MaskVector.getVectorElt(DstIdx).getInt().getZExtValue());
12732 auto [SrcVecIdx, SrcIdx] = GetSourceIndex(DstIdx, ShuffleMask);
12738 ResultElements.push_back(
12739 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy))));
12745 ResultElements.push_back(
APValue());
12748 const APValue &Src = (SrcVecIdx == 0) ? A : B;
12753 Out =
APValue(ResultElements.data(), ResultElements.size());
12759 if (OrigVal.isInfinity()) {
12760 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 0;
12763 if (OrigVal.isNaN()) {
12764 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << 1;
12768 APFloat Val = OrigVal;
12769 bool LosesInfo =
false;
12770 APFloat::opStatus Status = Val.convert(
12771 APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &LosesInfo);
12773 if (LosesInfo || Val.isDenormal()) {
12774 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic_strict);
12778 if (Status != APFloat::opOK) {
12779 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
12788 llvm::function_ref<APInt(
const APInt &,
uint64_t)> ShiftOp,
12789 llvm::function_ref<APInt(
const APInt &,
unsigned)> OverflowOp) {
12796 assert(
Call->getNumArgs() == 2);
12800 Call->getArg(1)->getType()->isVectorType());
12803 unsigned DestEltWidth = Source.getVectorElt(0).getInt().getBitWidth();
12804 unsigned DestLen = Source.getVectorLength();
12807 unsigned NumBitsInQWord = 64;
12808 unsigned NumCountElts = NumBitsInQWord / CountEltWidth;
12810 Result.reserve(DestLen);
12813 for (
unsigned EltIdx = 0; EltIdx != NumCountElts; ++EltIdx) {
12815 CountLQWord |= (Elt << (EltIdx * CountEltWidth));
12818 for (
unsigned EltIdx = 0; EltIdx != DestLen; ++EltIdx) {
12819 APInt Elt = Source.getVectorElt(EltIdx).getInt();
12820 if (CountLQWord < DestEltWidth) {
12822 APValue(
APSInt(ShiftOp(Elt, CountLQWord), IsDestUnsigned)));
12825 APValue(
APSInt(OverflowOp(Elt, DestEltWidth), IsDestUnsigned)));
12833 std::optional<APSInt> RoundingMode,
12835 APSInt DefaultMode(APInt(32, 4),
true);
12836 if (RoundingMode.value_or(DefaultMode) != 4)
12837 return std::nullopt;
12838 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
12839 B.isInfinity() || B.isDenormal())
12840 return std::nullopt;
12841 if (A.isZero() && B.isZero())
12843 return IsMin ? llvm::minimum(A, B) : llvm::maximum(A, B);
12846bool VectorExprEvaluator::VisitCallExpr(
const CallExpr *E) {
12847 if (!IsConstantEvaluatedBuiltinCall(E))
12848 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12852 auto EvaluateBinOpExpr =
12854 APValue SourceLHS, SourceRHS;
12860 QualType DestEltTy = DestTy->getElementType();
12861 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
12864 ResultElements.reserve(SourceLen);
12866 if (SourceRHS.
isInt()) {
12868 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12870 ResultElements.push_back(
12874 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
12877 ResultElements.push_back(
12884 auto EvaluateFpBinOpExpr =
12885 [&](llvm::function_ref<std::optional<APFloat>(
12886 const APFloat &,
const APFloat &, std::optional<APSInt>)>
12888 bool IsScalar =
false) {
12898 std::optional<APSInt> RoundingMode;
12903 RoundingMode = Imm;
12908 ResultElements.reserve(NumElems);
12910 for (
unsigned EltNum = 0; EltNum < NumElems; ++EltNum) {
12911 if (IsScalar && EltNum > 0) {
12917 std::optional<APFloat>
Result =
Fn(EltA, EltB, RoundingMode);
12925 auto EvaluateScalarFpRoundMaskBinOp =
12926 [&](llvm::function_ref<std::optional<APFloat>(
12927 const APFloat &,
const APFloat &, std::optional<APSInt>)>
12931 APSInt MaskVal, Rounding;
12942 ResultElements.reserve(NumElems);
12944 if (MaskVal.getZExtValue() & 1) {
12947 std::optional<APFloat>
Result =
Fn(EltA, EltB, Rounding);
12955 for (
unsigned I = 1; I < NumElems; ++I)
12961 auto EvalSelectScalar = [&](
unsigned Len) ->
bool {
12969 bool TakeA0 = (Mask.getZExtValue() & 1u) != 0;
12973 for (
unsigned I = 1; I < Len; ++I)
12975 APValue V(Res.data(), Res.size());
12979 auto EvalVectorDotProduct = [&](
bool IsSaturating) ->
bool {
12980 APValue Source, OperandA, OperandB;
12989 unsigned ElemsPerLane = NumOperandElems / NumSrcElems;
12994 Result.reserve(NumSrcElems);
12995 for (
unsigned I = 0; I != NumSrcElems; ++I) {
12997 DotProduct = DotProduct.extend(64);
12998 for (
unsigned J = 0; J != ElemsPerLane; ++J) {
13005 DotProduct += OpA * OpB;
13007 if (IsSaturating) {
13008 DotProduct =
APSInt(DotProduct.truncSSat(32),
false);
13010 DotProduct =
APSInt(DotProduct.trunc(32),
false);
13018 switch (BuiltinOp) {
13021 case Builtin::BI__builtin_elementwise_popcount:
13022 case Builtin::BI__builtin_elementwise_bitreverse: {
13027 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
13030 ResultElements.reserve(SourceLen);
13032 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13034 switch (BuiltinOp) {
13035 case Builtin::BI__builtin_elementwise_popcount:
13036 ResultElements.push_back(
APValue(
13037 APSInt(
APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
13040 case Builtin::BI__builtin_elementwise_bitreverse:
13041 ResultElements.push_back(
13048 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13050 case Builtin::BI__builtin_elementwise_abs: {
13055 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
13058 ResultElements.reserve(SourceLen);
13060 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13065 CurrentEle.getInt().
abs(),
13066 DestEltTy->isUnsignedIntegerOrEnumerationType()));
13067 ResultElements.push_back(Val);
13070 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13073 case Builtin::BI__builtin_elementwise_add_sat:
13074 return EvaluateBinOpExpr([](
const APSInt &LHS,
const APSInt &RHS) {
13075 return LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13078 case Builtin::BI__builtin_elementwise_sub_sat:
13079 return EvaluateBinOpExpr([](
const APSInt &LHS,
const APSInt &RHS) {
13080 return LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13083 case X86::BI__builtin_ia32_extract128i256:
13084 case X86::BI__builtin_ia32_vextractf128_pd256:
13085 case X86::BI__builtin_ia32_vextractf128_ps256:
13086 case X86::BI__builtin_ia32_vextractf128_si256: {
13087 APValue SourceVec, SourceImm;
13096 unsigned RetLen = RetVT->getNumElements();
13097 unsigned Idx = SourceImm.
getInt().getZExtValue() & 1;
13100 ResultElements.reserve(RetLen);
13102 for (
unsigned I = 0; I < RetLen; I++)
13103 ResultElements.push_back(SourceVec.
getVectorElt(Idx * RetLen + I));
13108 case clang::X86::BI__builtin_ia32_cvtmask2b128:
13109 case clang::X86::BI__builtin_ia32_cvtmask2b256:
13110 case clang::X86::BI__builtin_ia32_cvtmask2b512:
13111 case clang::X86::BI__builtin_ia32_cvtmask2w128:
13112 case clang::X86::BI__builtin_ia32_cvtmask2w256:
13113 case clang::X86::BI__builtin_ia32_cvtmask2w512:
13114 case clang::X86::BI__builtin_ia32_cvtmask2d128:
13115 case clang::X86::BI__builtin_ia32_cvtmask2d256:
13116 case clang::X86::BI__builtin_ia32_cvtmask2d512:
13117 case clang::X86::BI__builtin_ia32_cvtmask2q128:
13118 case clang::X86::BI__builtin_ia32_cvtmask2q256:
13119 case clang::X86::BI__builtin_ia32_cvtmask2q512: {
13125 QualType VecTy = E->
getType();
13126 const VectorType *VT = VecTy->
castAs<VectorType>();
13129 unsigned ElemWidth = Info.Ctx.getTypeSize(ElemTy);
13132 for (
unsigned I = 0; I != VectorLen; ++I) {
13133 bool BitSet = Mask[I];
13134 APSInt ElemVal(ElemWidth,
false);
13136 ElemVal.setAllBits();
13138 Elems.push_back(
APValue(ElemVal));
13143 case X86::BI__builtin_ia32_extracti32x4_256_mask:
13144 case X86::BI__builtin_ia32_extractf32x4_256_mask:
13145 case X86::BI__builtin_ia32_extracti32x4_mask:
13146 case X86::BI__builtin_ia32_extractf32x4_mask:
13147 case X86::BI__builtin_ia32_extracti32x8_mask:
13148 case X86::BI__builtin_ia32_extractf32x8_mask:
13149 case X86::BI__builtin_ia32_extracti64x2_256_mask:
13150 case X86::BI__builtin_ia32_extractf64x2_256_mask:
13151 case X86::BI__builtin_ia32_extracti64x2_512_mask:
13152 case X86::BI__builtin_ia32_extractf64x2_512_mask:
13153 case X86::BI__builtin_ia32_extracti64x4_mask:
13154 case X86::BI__builtin_ia32_extractf64x4_mask: {
13165 unsigned RetLen = RetVT->getNumElements();
13170 unsigned Lanes = SrcLen / RetLen;
13171 unsigned Lane =
static_cast<unsigned>(Imm.getZExtValue() % Lanes);
13172 unsigned Base = Lane * RetLen;
13175 ResultElements.reserve(RetLen);
13176 for (
unsigned I = 0; I < RetLen; ++I) {
13178 ResultElements.push_back(SourceVec.
getVectorElt(Base + I));
13182 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13185 case clang::X86::BI__builtin_ia32_pavgb128:
13186 case clang::X86::BI__builtin_ia32_pavgw128:
13187 case clang::X86::BI__builtin_ia32_pavgb256:
13188 case clang::X86::BI__builtin_ia32_pavgw256:
13189 case clang::X86::BI__builtin_ia32_pavgb512:
13190 case clang::X86::BI__builtin_ia32_pavgw512:
13191 return EvaluateBinOpExpr(llvm::APIntOps::avgCeilU);
13193 case clang::X86::BI__builtin_ia32_pmulhrsw128:
13194 case clang::X86::BI__builtin_ia32_pmulhrsw256:
13195 case clang::X86::BI__builtin_ia32_pmulhrsw512:
13196 return EvaluateBinOpExpr([](
const APSInt &LHS,
const APSInt &RHS) {
13197 return (llvm::APIntOps::mulsExtended(LHS, RHS).ashr(14) + 1)
13198 .extractBits(16, 1);
13201 case clang::X86::BI__builtin_ia32_psadbw128:
13202 case clang::X86::BI__builtin_ia32_psadbw256:
13203 case clang::X86::BI__builtin_ia32_psadbw512: {
13204 APValue SourceLHS, SourceRHS;
13212 assert((SourceLen % 8) == 0);
13215 QualType DestEltTy = DestTy->getElementType();
13216 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13218 ResultElements.reserve(SourceLen / 8);
13220 for (
unsigned Lane = 0; Lane != SourceLen; Lane += 8) {
13222 for (
unsigned I = 0; I != 8; ++I) {
13225 Sum += llvm::APIntOps::abdu(LHS, RHS).zext(64);
13227 ResultElements.push_back(
APValue(
APSInt(Sum, DestUnsigned)));
13230 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13233 case clang::X86::BI__builtin_ia32_pmaddubsw128:
13234 case clang::X86::BI__builtin_ia32_pmaddubsw256:
13235 case clang::X86::BI__builtin_ia32_pmaddubsw512:
13236 case clang::X86::BI__builtin_ia32_pmaddwd128:
13237 case clang::X86::BI__builtin_ia32_pmaddwd256:
13238 case clang::X86::BI__builtin_ia32_pmaddwd512: {
13239 APValue SourceLHS, SourceRHS;
13245 QualType DestEltTy = DestTy->getElementType();
13247 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13249 ResultElements.reserve(SourceLen / 2);
13251 for (
unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13256 unsigned BitWidth = 2 * LoLHS.getBitWidth();
13258 switch (BuiltinOp) {
13259 case clang::X86::BI__builtin_ia32_pmaddubsw128:
13260 case clang::X86::BI__builtin_ia32_pmaddubsw256:
13261 case clang::X86::BI__builtin_ia32_pmaddubsw512:
13262 ResultElements.push_back(
APValue(
13263 APSInt((LoLHS.zext(BitWidth) * LoRHS.sext(BitWidth))
13264 .sadd_sat((HiLHS.zext(BitWidth) * HiRHS.sext(BitWidth))),
13267 case clang::X86::BI__builtin_ia32_pmaddwd128:
13268 case clang::X86::BI__builtin_ia32_pmaddwd256:
13269 case clang::X86::BI__builtin_ia32_pmaddwd512:
13270 ResultElements.push_back(
13271 APValue(
APSInt((LoLHS.sext(BitWidth) * LoRHS.sext(BitWidth)) +
13272 (HiLHS.sext(BitWidth) * HiRHS.sext(BitWidth)),
13278 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13281 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v16hi:
13282 case clang::X86::BI__builtin_ia32_bmacor16x16x16_v32hi:
13283 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi:
13284 case clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi: {
13295 APValue SourceA, SourceB, SourceC;
13302 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v16hi ||
13304 clang::X86::BI__builtin_ia32_bmacxor16x16x16_v32hi;
13307 assert(SourceLen % 16 == 0 &&
"BMM operates on 256-bit lanes of 16 x i16");
13309 QualType DestEltTy = DestTy->getElementType();
13310 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13313 for (
unsigned Lane = 0; Lane != SourceLen; Lane += 16) {
13314 for (
unsigned I = 0; I != 16; ++I) {
13319 for (
unsigned J = 0; J != 16; ++J) {
13323 unsigned Bit = (Dst >> J) & 1u;
13324 for (
unsigned K = 0; K != 16; ++K) {
13328 unsigned Product = ((A >> K) & 1u) & ((B >> J) & 1u);
13329 Bit = IsXor ? (Bit ^ Product) : (Bit | Product);
13333 ResultElements[Lane + I] =
13337 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13340 case clang::X86::BI__builtin_ia32_dbpsadbw128:
13341 case clang::X86::BI__builtin_ia32_dbpsadbw256:
13342 case clang::X86::BI__builtin_ia32_dbpsadbw512: {
13343 APValue SourceA, SourceB, SourceImm;
13350 constexpr unsigned LaneSize = 16;
13351 unsigned Imm = SourceImm.
getInt().getZExtValue();
13354 QualType DestEltTy = DestTy->getElementType();
13355 bool DestUnsigned = DestEltTy->isUnsignedIntegerOrEnumerationType();
13357 ResultElements.reserve(SourceLen / 2);
13363 for (
unsigned I = 0; I < SourceLen; I += LaneSize) {
13364 for (
unsigned J = 0; J < 4; ++J) {
13365 unsigned Part = (Imm >> (2 * J)) & 3;
13366 for (
unsigned K = 0; K < 4; ++K) {
13367 Shuffled[I + 4 * J + K] =
static_cast<uint8_t>(
13368 SourceB.
getVectorElt(I + 4 * Part + K).getInt().getZExtValue());
13376 unsigned Size = SourceLen / 2;
13377 for (
unsigned I = 0; I <
Size; I += 4) {
13378 unsigned Sad[4] = {0, 0, 0, 0};
13379 for (
unsigned J = 0; J < 4; ++J) {
13381 SourceA.
getVectorElt(2 * I + J).getInt().getZExtValue());
13383 SourceA.
getVectorElt(2 * I + J + 4).getInt().getZExtValue());
13384 uint8_t B0 = Shuffled[2 * I + J];
13385 uint8_t B1 = Shuffled[2 * I + J + 1];
13386 uint8_t B2 = Shuffled[2 * I + J + 2];
13387 uint8_t B3 = Shuffled[2 * I + J + 3];
13388 Sad[0] += (A1 > B0) ? (A1 - B0) : (B0 - A1);
13389 Sad[1] += (A1 > B1) ? (A1 - B1) : (B1 - A1);
13390 Sad[2] += (A2 > B2) ? (A2 - B2) : (B2 - A2);
13391 Sad[3] += (A2 > B3) ? (A2 - B3) : (B3 - A2);
13393 for (
unsigned R = 0;
R < 4; ++
R)
13394 ResultElements.push_back(
13398 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13401 case clang::X86::BI__builtin_ia32_mpsadbw128:
13402 case clang::X86::BI__builtin_ia32_mpsadbw256: {
13410 constexpr unsigned LaneSize = 16;
13411 assert((SourceLen == LaneSize || SourceLen == 2 * LaneSize) &&
13412 "MPSADBW operates on 128-bit or 256-bit vectors");
13413 unsigned NumLanes = SourceLen / LaneSize;
13414 unsigned Imm = SourceImm.getZExtValue();
13416 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
13419 ResultElements.reserve(SourceLen / 2);
13421 for (
unsigned Lane = 0; Lane != NumLanes; ++Lane) {
13422 unsigned Ctrl = (Imm >> (3 * Lane)) & 0x7;
13423 unsigned AOff = ((Ctrl >> 2) & 1) * 4;
13424 unsigned BOff = (Ctrl & 3) * 4;
13425 for (
unsigned J = 0; J != 8; ++J) {
13427 for (
unsigned K = 0; K != 4; ++K) {
13436 Sad += (A > B) ? (A - B) : (B - A);
13441 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13444 case clang::X86::BI__builtin_ia32_pmulhuw128:
13445 case clang::X86::BI__builtin_ia32_pmulhuw256:
13446 case clang::X86::BI__builtin_ia32_pmulhuw512:
13447 return EvaluateBinOpExpr(llvm::APIntOps::mulhu);
13449 case clang::X86::BI__builtin_ia32_pmulhw128:
13450 case clang::X86::BI__builtin_ia32_pmulhw256:
13451 case clang::X86::BI__builtin_ia32_pmulhw512:
13452 return EvaluateBinOpExpr(llvm::APIntOps::mulhs);
13454 case clang::X86::BI__builtin_ia32_psllv2di:
13455 case clang::X86::BI__builtin_ia32_psllv4di:
13456 case clang::X86::BI__builtin_ia32_psllv4si:
13457 case clang::X86::BI__builtin_ia32_psllv8di:
13458 case clang::X86::BI__builtin_ia32_psllv8hi:
13459 case clang::X86::BI__builtin_ia32_psllv8si:
13460 case clang::X86::BI__builtin_ia32_psllv16hi:
13461 case clang::X86::BI__builtin_ia32_psllv16si:
13462 case clang::X86::BI__builtin_ia32_psllv32hi:
13463 case clang::X86::BI__builtin_ia32_psllwi128:
13464 case clang::X86::BI__builtin_ia32_pslldi128:
13465 case clang::X86::BI__builtin_ia32_psllqi128:
13466 case clang::X86::BI__builtin_ia32_psllwi256:
13467 case clang::X86::BI__builtin_ia32_pslldi256:
13468 case clang::X86::BI__builtin_ia32_psllqi256:
13469 case clang::X86::BI__builtin_ia32_psllwi512:
13470 case clang::X86::BI__builtin_ia32_pslldi512:
13471 case clang::X86::BI__builtin_ia32_psllqi512:
13472 return EvaluateBinOpExpr([](
const APSInt &LHS,
const APSInt &RHS) {
13473 if (RHS.uge(LHS.getBitWidth())) {
13474 return APInt::getZero(LHS.getBitWidth());
13476 return LHS.shl(RHS.getZExtValue());
13479 case clang::X86::BI__builtin_ia32_psrav4si:
13480 case clang::X86::BI__builtin_ia32_psrav8di:
13481 case clang::X86::BI__builtin_ia32_psrav8hi:
13482 case clang::X86::BI__builtin_ia32_psrav8si:
13483 case clang::X86::BI__builtin_ia32_psrav16hi:
13484 case clang::X86::BI__builtin_ia32_psrav16si:
13485 case clang::X86::BI__builtin_ia32_psrav32hi:
13486 case clang::X86::BI__builtin_ia32_psravq128:
13487 case clang::X86::BI__builtin_ia32_psravq256:
13488 case clang::X86::BI__builtin_ia32_psrawi128:
13489 case clang::X86::BI__builtin_ia32_psradi128:
13490 case clang::X86::BI__builtin_ia32_psraqi128:
13491 case clang::X86::BI__builtin_ia32_psrawi256:
13492 case clang::X86::BI__builtin_ia32_psradi256:
13493 case clang::X86::BI__builtin_ia32_psraqi256:
13494 case clang::X86::BI__builtin_ia32_psrawi512:
13495 case clang::X86::BI__builtin_ia32_psradi512:
13496 case clang::X86::BI__builtin_ia32_psraqi512:
13497 return EvaluateBinOpExpr([](
const APSInt &LHS,
const APSInt &RHS) {
13498 if (RHS.uge(LHS.getBitWidth())) {
13499 return LHS.ashr(LHS.getBitWidth() - 1);
13501 return LHS.ashr(RHS.getZExtValue());
13504 case clang::X86::BI__builtin_ia32_psrlv2di:
13505 case clang::X86::BI__builtin_ia32_psrlv4di:
13506 case clang::X86::BI__builtin_ia32_psrlv4si:
13507 case clang::X86::BI__builtin_ia32_psrlv8di:
13508 case clang::X86::BI__builtin_ia32_psrlv8hi:
13509 case clang::X86::BI__builtin_ia32_psrlv8si:
13510 case clang::X86::BI__builtin_ia32_psrlv16hi:
13511 case clang::X86::BI__builtin_ia32_psrlv16si:
13512 case clang::X86::BI__builtin_ia32_psrlv32hi:
13513 case clang::X86::BI__builtin_ia32_psrlwi128:
13514 case clang::X86::BI__builtin_ia32_psrldi128:
13515 case clang::X86::BI__builtin_ia32_psrlqi128:
13516 case clang::X86::BI__builtin_ia32_psrlwi256:
13517 case clang::X86::BI__builtin_ia32_psrldi256:
13518 case clang::X86::BI__builtin_ia32_psrlqi256:
13519 case clang::X86::BI__builtin_ia32_psrlwi512:
13520 case clang::X86::BI__builtin_ia32_psrldi512:
13521 case clang::X86::BI__builtin_ia32_psrlqi512:
13522 return EvaluateBinOpExpr([](
const APSInt &LHS,
const APSInt &RHS) {
13523 if (RHS.uge(LHS.getBitWidth())) {
13524 return APInt::getZero(LHS.getBitWidth());
13526 return LHS.lshr(RHS.getZExtValue());
13528 case X86::BI__builtin_ia32_packsswb128:
13529 case X86::BI__builtin_ia32_packsswb256:
13530 case X86::BI__builtin_ia32_packsswb512:
13531 case X86::BI__builtin_ia32_packssdw128:
13532 case X86::BI__builtin_ia32_packssdw256:
13533 case X86::BI__builtin_ia32_packssdw512:
13535 return APSInt(Src).truncSSat(Src.getBitWidth() / 2);
13537 case X86::BI__builtin_ia32_packusdw128:
13538 case X86::BI__builtin_ia32_packusdw256:
13539 case X86::BI__builtin_ia32_packusdw512:
13540 case X86::BI__builtin_ia32_packuswb128:
13541 case X86::BI__builtin_ia32_packuswb256:
13542 case X86::BI__builtin_ia32_packuswb512:
13544 return APSInt(Src).truncSSatU(Src.getBitWidth() / 2);
13546 case clang::X86::BI__builtin_ia32_selectss_128:
13547 return EvalSelectScalar(4);
13548 case clang::X86::BI__builtin_ia32_selectsd_128:
13549 return EvalSelectScalar(2);
13550 case clang::X86::BI__builtin_ia32_selectsh_128:
13551 case clang::X86::BI__builtin_ia32_selectsbf_128:
13552 return EvalSelectScalar(8);
13553 case clang::X86::BI__builtin_ia32_pmuldq128:
13554 case clang::X86::BI__builtin_ia32_pmuldq256:
13555 case clang::X86::BI__builtin_ia32_pmuldq512:
13556 case clang::X86::BI__builtin_ia32_pmuludq128:
13557 case clang::X86::BI__builtin_ia32_pmuludq256:
13558 case clang::X86::BI__builtin_ia32_pmuludq512: {
13559 APValue SourceLHS, SourceRHS;
13566 ResultElements.reserve(SourceLen / 2);
13568 for (
unsigned EltNum = 0; EltNum < SourceLen; EltNum += 2) {
13572 switch (BuiltinOp) {
13573 case clang::X86::BI__builtin_ia32_pmuludq128:
13574 case clang::X86::BI__builtin_ia32_pmuludq256:
13575 case clang::X86::BI__builtin_ia32_pmuludq512:
13576 ResultElements.push_back(
13577 APValue(
APSInt(llvm::APIntOps::muluExtended(LHS, RHS),
true)));
13579 case clang::X86::BI__builtin_ia32_pmuldq128:
13580 case clang::X86::BI__builtin_ia32_pmuldq256:
13581 case clang::X86::BI__builtin_ia32_pmuldq512:
13582 ResultElements.push_back(
13583 APValue(
APSInt(llvm::APIntOps::mulsExtended(LHS, RHS),
false)));
13588 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13591 case X86::BI__builtin_ia32_vpmadd52luq128:
13592 case X86::BI__builtin_ia32_vpmadd52luq256:
13593 case X86::BI__builtin_ia32_vpmadd52luq512: {
13602 ResultElements.reserve(ALen);
13604 for (
unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13607 APInt CElt =
C.getVectorElt(EltNum).getInt().trunc(52);
13608 APSInt ResElt(AElt + (BElt * CElt).zext(64),
false);
13609 ResultElements.push_back(
APValue(ResElt));
13612 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13614 case X86::BI__builtin_ia32_vpmadd52huq128:
13615 case X86::BI__builtin_ia32_vpmadd52huq256:
13616 case X86::BI__builtin_ia32_vpmadd52huq512: {
13625 ResultElements.reserve(ALen);
13627 for (
unsigned EltNum = 0; EltNum < ALen; EltNum += 1) {
13630 APInt CElt =
C.getVectorElt(EltNum).getInt().trunc(52);
13631 APSInt ResElt(AElt + llvm::APIntOps::mulhu(BElt, CElt).zext(64),
false);
13632 ResultElements.push_back(
APValue(ResElt));
13635 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13638 case clang::X86::BI__builtin_ia32_vprotbi:
13639 case clang::X86::BI__builtin_ia32_vprotdi:
13640 case clang::X86::BI__builtin_ia32_vprotqi:
13641 case clang::X86::BI__builtin_ia32_vprotwi:
13642 case clang::X86::BI__builtin_ia32_prold128:
13643 case clang::X86::BI__builtin_ia32_prold256:
13644 case clang::X86::BI__builtin_ia32_prold512:
13645 case clang::X86::BI__builtin_ia32_prolq128:
13646 case clang::X86::BI__builtin_ia32_prolq256:
13647 case clang::X86::BI__builtin_ia32_prolq512:
13648 return EvaluateBinOpExpr(
13649 [](
const APSInt &LHS,
const APSInt &RHS) {
return LHS.rotl(RHS); });
13651 case clang::X86::BI__builtin_ia32_prord128:
13652 case clang::X86::BI__builtin_ia32_prord256:
13653 case clang::X86::BI__builtin_ia32_prord512:
13654 case clang::X86::BI__builtin_ia32_prorq128:
13655 case clang::X86::BI__builtin_ia32_prorq256:
13656 case clang::X86::BI__builtin_ia32_prorq512:
13657 return EvaluateBinOpExpr(
13658 [](
const APSInt &LHS,
const APSInt &RHS) {
return LHS.rotr(RHS); });
13660 case Builtin::BI__builtin_elementwise_max:
13661 case Builtin::BI__builtin_elementwise_min: {
13662 APValue SourceLHS, SourceRHS;
13667 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
13674 ResultElements.reserve(SourceLen);
13676 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13679 switch (BuiltinOp) {
13680 case Builtin::BI__builtin_elementwise_max:
13681 ResultElements.push_back(
13685 case Builtin::BI__builtin_elementwise_min:
13686 ResultElements.push_back(
13693 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13695 case X86::BI__builtin_ia32_vpshldd128:
13696 case X86::BI__builtin_ia32_vpshldd256:
13697 case X86::BI__builtin_ia32_vpshldd512:
13698 case X86::BI__builtin_ia32_vpshldq128:
13699 case X86::BI__builtin_ia32_vpshldq256:
13700 case X86::BI__builtin_ia32_vpshldq512:
13701 case X86::BI__builtin_ia32_vpshldw128:
13702 case X86::BI__builtin_ia32_vpshldw256:
13703 case X86::BI__builtin_ia32_vpshldw512: {
13704 APValue SourceHi, SourceLo, SourceAmt;
13710 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
13713 ResultElements.reserve(SourceLen);
13716 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13719 APInt R = llvm::APIntOps::fshl(Hi, Lo, Amt);
13720 ResultElements.push_back(
13724 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13726 case X86::BI__builtin_ia32_vpshrdd128:
13727 case X86::BI__builtin_ia32_vpshrdd256:
13728 case X86::BI__builtin_ia32_vpshrdd512:
13729 case X86::BI__builtin_ia32_vpshrdq128:
13730 case X86::BI__builtin_ia32_vpshrdq256:
13731 case X86::BI__builtin_ia32_vpshrdq512:
13732 case X86::BI__builtin_ia32_vpshrdw128:
13733 case X86::BI__builtin_ia32_vpshrdw256:
13734 case X86::BI__builtin_ia32_vpshrdw512: {
13736 APValue SourceHi, SourceLo, SourceAmt;
13742 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
13745 ResultElements.reserve(SourceLen);
13748 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13751 APInt R = llvm::APIntOps::fshr(Hi, Lo, Amt);
13752 ResultElements.push_back(
13756 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13758 case X86::BI__builtin_ia32_compressdf128_mask:
13759 case X86::BI__builtin_ia32_compressdf256_mask:
13760 case X86::BI__builtin_ia32_compressdf512_mask:
13761 case X86::BI__builtin_ia32_compressdi128_mask:
13762 case X86::BI__builtin_ia32_compressdi256_mask:
13763 case X86::BI__builtin_ia32_compressdi512_mask:
13764 case X86::BI__builtin_ia32_compresshi128_mask:
13765 case X86::BI__builtin_ia32_compresshi256_mask:
13766 case X86::BI__builtin_ia32_compresshi512_mask:
13767 case X86::BI__builtin_ia32_compressqi128_mask:
13768 case X86::BI__builtin_ia32_compressqi256_mask:
13769 case X86::BI__builtin_ia32_compressqi512_mask:
13770 case X86::BI__builtin_ia32_compresssf128_mask:
13771 case X86::BI__builtin_ia32_compresssf256_mask:
13772 case X86::BI__builtin_ia32_compresssf512_mask:
13773 case X86::BI__builtin_ia32_compresssi128_mask:
13774 case X86::BI__builtin_ia32_compresssi256_mask:
13775 case X86::BI__builtin_ia32_compresssi512_mask: {
13786 ResultElements.reserve(NumElts);
13788 for (
unsigned I = 0; I != NumElts; ++I) {
13792 for (
unsigned I = ResultElements.size(); I != NumElts; ++I) {
13796 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13798 case X86::BI__builtin_ia32_expanddf128_mask:
13799 case X86::BI__builtin_ia32_expanddf256_mask:
13800 case X86::BI__builtin_ia32_expanddf512_mask:
13801 case X86::BI__builtin_ia32_expanddi128_mask:
13802 case X86::BI__builtin_ia32_expanddi256_mask:
13803 case X86::BI__builtin_ia32_expanddi512_mask:
13804 case X86::BI__builtin_ia32_expandhi128_mask:
13805 case X86::BI__builtin_ia32_expandhi256_mask:
13806 case X86::BI__builtin_ia32_expandhi512_mask:
13807 case X86::BI__builtin_ia32_expandqi128_mask:
13808 case X86::BI__builtin_ia32_expandqi256_mask:
13809 case X86::BI__builtin_ia32_expandqi512_mask:
13810 case X86::BI__builtin_ia32_expandsf128_mask:
13811 case X86::BI__builtin_ia32_expandsf256_mask:
13812 case X86::BI__builtin_ia32_expandsf512_mask:
13813 case X86::BI__builtin_ia32_expandsi128_mask:
13814 case X86::BI__builtin_ia32_expandsi256_mask:
13815 case X86::BI__builtin_ia32_expandsi512_mask: {
13826 ResultElements.reserve(NumElts);
13828 unsigned SourceIdx = 0;
13829 for (
unsigned I = 0; I != NumElts; ++I) {
13831 ResultElements.push_back(Source.
getVectorElt(SourceIdx++));
13835 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13837 case X86::BI__builtin_ia32_vpconflictsi_128:
13838 case X86::BI__builtin_ia32_vpconflictsi_256:
13839 case X86::BI__builtin_ia32_vpconflictsi_512:
13840 case X86::BI__builtin_ia32_vpconflictdi_128:
13841 case X86::BI__builtin_ia32_vpconflictdi_256:
13842 case X86::BI__builtin_ia32_vpconflictdi_512: {
13850 ResultElements.reserve(SourceLen);
13853 bool DestUnsigned =
13854 VecT->getElementType()->isUnsignedIntegerOrEnumerationType();
13856 for (
unsigned I = 0; I != SourceLen; ++I) {
13859 APInt ConflictMask(EltI.
getInt().getBitWidth(), 0);
13860 for (
unsigned J = 0; J != I; ++J) {
13862 ConflictMask.setBitVal(J, EltI.
getInt() == EltJ.
getInt());
13864 ResultElements.push_back(
APValue(
APSInt(ConflictMask, DestUnsigned)));
13866 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13868 case X86::BI__builtin_ia32_blendpd:
13869 case X86::BI__builtin_ia32_blendpd256:
13870 case X86::BI__builtin_ia32_blendps:
13871 case X86::BI__builtin_ia32_blendps256:
13872 case X86::BI__builtin_ia32_pblendw128:
13873 case X86::BI__builtin_ia32_pblendw256:
13874 case X86::BI__builtin_ia32_pblendd128:
13875 case X86::BI__builtin_ia32_pblendd256: {
13876 APValue SourceF, SourceT, SourceC;
13885 ResultElements.reserve(SourceLen);
13886 for (
unsigned EltNum = 0; EltNum != SourceLen; ++EltNum) {
13889 ResultElements.push_back(
C[EltNum % 8] ?
T : F);
13892 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13895 case X86::BI__builtin_ia32_psignb128:
13896 case X86::BI__builtin_ia32_psignb256:
13897 case X86::BI__builtin_ia32_psignw128:
13898 case X86::BI__builtin_ia32_psignw256:
13899 case X86::BI__builtin_ia32_psignd128:
13900 case X86::BI__builtin_ia32_psignd256:
13901 return EvaluateBinOpExpr([](
const APInt &AElem,
const APInt &BElem) {
13902 if (BElem.isZero())
13903 return APInt::getZero(AElem.getBitWidth());
13904 if (BElem.isNegative())
13909 case X86::BI__builtin_ia32_blendvpd:
13910 case X86::BI__builtin_ia32_blendvpd256:
13911 case X86::BI__builtin_ia32_blendvps:
13912 case X86::BI__builtin_ia32_blendvps256:
13913 case X86::BI__builtin_ia32_pblendvb128:
13914 case X86::BI__builtin_ia32_pblendvb256: {
13916 APValue SourceF, SourceT, SourceC;
13924 ResultElements.reserve(SourceLen);
13926 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13930 APInt M =
C.isInt() ? (
APInt)
C.getInt() :
C.getFloat().bitcastToAPInt();
13931 ResultElements.push_back(M.isNegative() ?
T : F);
13934 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13936 case X86::BI__builtin_ia32_selectb_128:
13937 case X86::BI__builtin_ia32_selectb_256:
13938 case X86::BI__builtin_ia32_selectb_512:
13939 case X86::BI__builtin_ia32_selectw_128:
13940 case X86::BI__builtin_ia32_selectw_256:
13941 case X86::BI__builtin_ia32_selectw_512:
13942 case X86::BI__builtin_ia32_selectd_128:
13943 case X86::BI__builtin_ia32_selectd_256:
13944 case X86::BI__builtin_ia32_selectd_512:
13945 case X86::BI__builtin_ia32_selectq_128:
13946 case X86::BI__builtin_ia32_selectq_256:
13947 case X86::BI__builtin_ia32_selectq_512:
13948 case X86::BI__builtin_ia32_selectph_128:
13949 case X86::BI__builtin_ia32_selectph_256:
13950 case X86::BI__builtin_ia32_selectph_512:
13951 case X86::BI__builtin_ia32_selectpbf_128:
13952 case X86::BI__builtin_ia32_selectpbf_256:
13953 case X86::BI__builtin_ia32_selectpbf_512:
13954 case X86::BI__builtin_ia32_selectps_128:
13955 case X86::BI__builtin_ia32_selectps_256:
13956 case X86::BI__builtin_ia32_selectps_512:
13957 case X86::BI__builtin_ia32_selectpd_128:
13958 case X86::BI__builtin_ia32_selectpd_256:
13959 case X86::BI__builtin_ia32_selectpd_512: {
13961 APValue SourceMask, SourceLHS, SourceRHS;
13970 ResultElements.reserve(SourceLen);
13972 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
13975 ResultElements.push_back(Mask[EltNum] ? LHS : RHS);
13978 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
13981 case X86::BI__builtin_ia32_cvtsd2ss: {
13994 Elements.push_back(ResultVal);
13997 for (
unsigned I = 1; I < NumEltsA; ++I) {
14003 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: {
14004 APValue VecA, VecB, VecSrc, MaskValue;
14012 unsigned Mask = MaskValue.
getInt().getZExtValue();
14020 Elements.push_back(ResultVal);
14026 for (
unsigned I = 1; I < NumEltsA; ++I) {
14032 case X86::BI__builtin_ia32_cvtpd2ps:
14033 case X86::BI__builtin_ia32_cvtpd2ps256:
14034 case X86::BI__builtin_ia32_cvtpd2ps_mask:
14035 case X86::BI__builtin_ia32_cvtpd2ps512_mask: {
14037 const auto BuiltinID = BuiltinOp;
14038 bool IsMasked = (BuiltinID == X86::BI__builtin_ia32_cvtpd2ps_mask ||
14039 BuiltinID == X86::BI__builtin_ia32_cvtpd2ps512_mask);
14046 unsigned Mask = 0xFFFFFFFF;
14047 bool NeedsMerge =
false;
14052 Mask = MaskValue.
getInt().getZExtValue();
14053 auto NumEltsResult = E->
getType()->
getAs<VectorType>()->getNumElements();
14054 for (
unsigned I = 0; I < NumEltsResult; ++I) {
14055 if (!((Mask >> I) & 1)) {
14066 unsigned NumEltsResult =
14070 for (
unsigned I = 0; I < NumEltsResult; ++I) {
14071 if (IsMasked && !((Mask >> I) & 1)) {
14079 if (I >= NumEltsInput) {
14080 Elements.push_back(
APValue(APFloat::getZero(APFloat::IEEEsingle())));
14089 Elements.push_back(ResultVal);
14094 case X86::BI__builtin_ia32_shufps:
14095 case X86::BI__builtin_ia32_shufps256:
14096 case X86::BI__builtin_ia32_shufps512: {
14100 [](
unsigned DstIdx,
14101 unsigned ShuffleMask) -> std::pair<unsigned, int> {
14102 constexpr unsigned LaneBits = 128u;
14103 unsigned NumElemPerLane = LaneBits / 32;
14104 unsigned NumSelectableElems = NumElemPerLane / 2;
14105 unsigned BitsPerElem = 2;
14106 unsigned IndexMask = (1u << BitsPerElem) - 1;
14107 unsigned MaskBits = 8;
14108 unsigned Lane = DstIdx / NumElemPerLane;
14109 unsigned ElemInLane = DstIdx % NumElemPerLane;
14110 unsigned LaneOffset = Lane * NumElemPerLane;
14111 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14112 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
14113 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
14114 return {SrcIdx,
static_cast<int>(LaneOffset + Index)};
14119 case X86::BI__builtin_ia32_shufpd:
14120 case X86::BI__builtin_ia32_shufpd256:
14121 case X86::BI__builtin_ia32_shufpd512: {
14125 [](
unsigned DstIdx,
14126 unsigned ShuffleMask) -> std::pair<unsigned, int> {
14127 constexpr unsigned LaneBits = 128u;
14128 unsigned NumElemPerLane = LaneBits / 64;
14129 unsigned NumSelectableElems = NumElemPerLane / 2;
14130 unsigned BitsPerElem = 1;
14131 unsigned IndexMask = (1u << BitsPerElem) - 1;
14132 unsigned MaskBits = 8;
14133 unsigned Lane = DstIdx / NumElemPerLane;
14134 unsigned ElemInLane = DstIdx % NumElemPerLane;
14135 unsigned LaneOffset = Lane * NumElemPerLane;
14136 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14137 unsigned SrcIdx = (ElemInLane < NumSelectableElems) ? 0 : 1;
14138 unsigned Index = (ShuffleMask >> BitIndex) & IndexMask;
14139 return {SrcIdx,
static_cast<int>(LaneOffset + Index)};
14144 case X86::BI__builtin_ia32_insertps128: {
14148 [](
unsigned DstIdx,
unsigned Mask) -> std::pair<unsigned, int> {
14150 if ((Mask & (1 << DstIdx)) != 0) {
14155 unsigned SrcElem = (Mask >> 6) & 0x3;
14156 unsigned DstElem = (Mask >> 4) & 0x3;
14157 if (DstIdx == DstElem) {
14159 return {1,
static_cast<int>(SrcElem)};
14162 return {0,
static_cast<int>(DstIdx)};
14168 case X86::BI__builtin_ia32_pshufb128:
14169 case X86::BI__builtin_ia32_pshufb256:
14170 case X86::BI__builtin_ia32_pshufb512: {
14174 [](
unsigned DstIdx,
14175 unsigned ShuffleMask) -> std::pair<unsigned, int> {
14178 return std::make_pair(0, -1);
14180 unsigned LaneBase = (DstIdx / 16) * 16;
14181 unsigned SrcOffset = Ctlb & 0x0F;
14182 unsigned SrcIdx = LaneBase + SrcOffset;
14183 return std::make_pair(0,
static_cast<int>(SrcIdx));
14189 case X86::BI__builtin_ia32_pshuflw:
14190 case X86::BI__builtin_ia32_pshuflw256:
14191 case X86::BI__builtin_ia32_pshuflw512: {
14195 [](
unsigned DstIdx,
unsigned Mask) -> std::pair<unsigned, int> {
14196 constexpr unsigned LaneBits = 128u;
14197 constexpr unsigned ElemBits = 16u;
14198 constexpr unsigned LaneElts = LaneBits / ElemBits;
14199 constexpr unsigned HalfSize = 4;
14200 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
14201 unsigned LaneIdx = DstIdx % LaneElts;
14202 if (LaneIdx < HalfSize) {
14203 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
14204 return std::make_pair(0,
static_cast<int>(LaneBase + Sel));
14206 return std::make_pair(0,
static_cast<int>(DstIdx));
14212 case X86::BI__builtin_ia32_pshufhw:
14213 case X86::BI__builtin_ia32_pshufhw256:
14214 case X86::BI__builtin_ia32_pshufhw512: {
14218 [](
unsigned DstIdx,
unsigned Mask) -> std::pair<unsigned, int> {
14219 constexpr unsigned LaneBits = 128u;
14220 constexpr unsigned ElemBits = 16u;
14221 constexpr unsigned LaneElts = LaneBits / ElemBits;
14222 constexpr unsigned HalfSize = 4;
14223 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
14224 unsigned LaneIdx = DstIdx % LaneElts;
14225 if (LaneIdx >= HalfSize) {
14226 unsigned Rel = LaneIdx - HalfSize;
14227 unsigned Sel = (Mask >> (2 * Rel)) & 0x3;
14228 return std::make_pair(
14229 0,
static_cast<int>(LaneBase + HalfSize + Sel));
14231 return std::make_pair(0,
static_cast<int>(DstIdx));
14237 case X86::BI__builtin_ia32_pshufd:
14238 case X86::BI__builtin_ia32_pshufd256:
14239 case X86::BI__builtin_ia32_pshufd512:
14240 case X86::BI__builtin_ia32_vpermilps:
14241 case X86::BI__builtin_ia32_vpermilps256:
14242 case X86::BI__builtin_ia32_vpermilps512: {
14246 [](
unsigned DstIdx,
unsigned Mask) -> std::pair<unsigned, int> {
14247 constexpr unsigned LaneBits = 128u;
14248 constexpr unsigned ElemBits = 32u;
14249 constexpr unsigned LaneElts = LaneBits / ElemBits;
14250 unsigned LaneBase = (DstIdx / LaneElts) * LaneElts;
14251 unsigned LaneIdx = DstIdx % LaneElts;
14252 unsigned Sel = (Mask >> (2 * LaneIdx)) & 0x3;
14253 return std::make_pair(0,
static_cast<int>(LaneBase + Sel));
14259 case X86::BI__builtin_ia32_vpermilvarpd:
14260 case X86::BI__builtin_ia32_vpermilvarpd256:
14261 case X86::BI__builtin_ia32_vpermilvarpd512: {
14265 [](
unsigned DstIdx,
unsigned Mask) -> std::pair<unsigned, int> {
14266 unsigned NumElemPerLane = 2;
14267 unsigned Lane = DstIdx / NumElemPerLane;
14268 unsigned Offset = Mask & 0b10 ? 1 : 0;
14269 return std::make_pair(
14270 0,
static_cast<int>(Lane * NumElemPerLane + Offset));
14276 case X86::BI__builtin_ia32_vpermilpd:
14277 case X86::BI__builtin_ia32_vpermilpd256:
14278 case X86::BI__builtin_ia32_vpermilpd512: {
14281 unsigned NumElemPerLane = 2;
14282 unsigned BitsPerElem = 1;
14283 unsigned MaskBits = 8;
14284 unsigned IndexMask = 0x1;
14285 unsigned Lane = DstIdx / NumElemPerLane;
14286 unsigned LaneOffset = Lane * NumElemPerLane;
14287 unsigned BitIndex = (DstIdx * BitsPerElem) % MaskBits;
14288 unsigned Index = (Control >> BitIndex) & IndexMask;
14289 return std::make_pair(0,
static_cast<int>(LaneOffset + Index));
14295 case X86::BI__builtin_ia32_permdf256:
14296 case X86::BI__builtin_ia32_permdi256: {
14301 unsigned Index = (Control >> (2 * DstIdx)) & 0x3;
14302 return std::make_pair(0,
static_cast<int>(Index));
14308 case X86::BI__builtin_ia32_vpermilvarps:
14309 case X86::BI__builtin_ia32_vpermilvarps256:
14310 case X86::BI__builtin_ia32_vpermilvarps512: {
14314 [](
unsigned DstIdx,
unsigned Mask) -> std::pair<unsigned, int> {
14315 unsigned NumElemPerLane = 4;
14316 unsigned Lane = DstIdx / NumElemPerLane;
14317 unsigned Offset = Mask & 0b11;
14318 return std::make_pair(
14319 0,
static_cast<int>(Lane * NumElemPerLane + Offset));
14325 case X86::BI__builtin_ia32_vpmultishiftqb128:
14326 case X86::BI__builtin_ia32_vpmultishiftqb256:
14327 case X86::BI__builtin_ia32_vpmultishiftqb512: {
14335 unsigned NumBytesInQWord = 8;
14336 unsigned NumBitsInByte = 8;
14338 unsigned NumQWords = NumBytes / NumBytesInQWord;
14340 Result.reserve(NumBytes);
14342 for (
unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
14343 APInt BQWord(64, 0);
14344 for (
unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14345 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14347 BQWord.insertBits(
APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
14350 for (
unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14351 unsigned Idx = QWordId * NumBytesInQWord + ByteIdx;
14355 for (
unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
14356 Byte.setBitVal(BitIdx, BQWord[(Ctrl + BitIdx) & 0x3F]);
14364 case X86::BI__builtin_ia32_phminposuw128: {
14371 unsigned ElemBitWidth = Info.Ctx.getTypeSize(ElemQT);
14373 APInt MinIndex(ElemBitWidth, 0);
14375 for (
unsigned I = 1; I != SourceLen; ++I) {
14377 if (MinVal.ugt(Val)) {
14386 ->isUnsignedIntegerOrEnumerationType();
14389 Result.reserve(SourceLen);
14391 Result.emplace_back(
APSInt(MinIndex, ResultUnsigned));
14392 for (
unsigned I = 0; I != SourceLen - 2; ++I) {
14398 case X86::BI__builtin_ia32_psraq128:
14399 case X86::BI__builtin_ia32_psraq256:
14400 case X86::BI__builtin_ia32_psraq512:
14401 case X86::BI__builtin_ia32_psrad128:
14402 case X86::BI__builtin_ia32_psrad256:
14403 case X86::BI__builtin_ia32_psrad512:
14404 case X86::BI__builtin_ia32_psraw128:
14405 case X86::BI__builtin_ia32_psraw256:
14406 case X86::BI__builtin_ia32_psraw512: {
14410 [](
const APInt &Elt,
uint64_t Count) {
return Elt.ashr(Count); },
14411 [](
const APInt &Elt,
unsigned Width) {
14412 return Elt.ashr(Width - 1);
14418 case X86::BI__builtin_ia32_psllq128:
14419 case X86::BI__builtin_ia32_psllq256:
14420 case X86::BI__builtin_ia32_psllq512:
14421 case X86::BI__builtin_ia32_pslld128:
14422 case X86::BI__builtin_ia32_pslld256:
14423 case X86::BI__builtin_ia32_pslld512:
14424 case X86::BI__builtin_ia32_psllw128:
14425 case X86::BI__builtin_ia32_psllw256:
14426 case X86::BI__builtin_ia32_psllw512: {
14430 [](
const APInt &Elt,
uint64_t Count) {
return Elt.shl(Count); },
14431 [](
const APInt &Elt,
unsigned Width) {
14432 return APInt::getZero(Width);
14438 case X86::BI__builtin_ia32_psrlq128:
14439 case X86::BI__builtin_ia32_psrlq256:
14440 case X86::BI__builtin_ia32_psrlq512:
14441 case X86::BI__builtin_ia32_psrld128:
14442 case X86::BI__builtin_ia32_psrld256:
14443 case X86::BI__builtin_ia32_psrld512:
14444 case X86::BI__builtin_ia32_psrlw128:
14445 case X86::BI__builtin_ia32_psrlw256:
14446 case X86::BI__builtin_ia32_psrlw512: {
14450 [](
const APInt &Elt,
uint64_t Count) {
return Elt.lshr(Count); },
14451 [](
const APInt &Elt,
unsigned Width) {
14452 return APInt::getZero(Width);
14458 case X86::BI__builtin_ia32_pternlogd128_mask:
14459 case X86::BI__builtin_ia32_pternlogd256_mask:
14460 case X86::BI__builtin_ia32_pternlogd512_mask:
14461 case X86::BI__builtin_ia32_pternlogq128_mask:
14462 case X86::BI__builtin_ia32_pternlogq256_mask:
14463 case X86::BI__builtin_ia32_pternlogq512_mask: {
14464 APValue AValue, BValue, CValue, ImmValue, UValue;
14472 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14478 ResultElements.reserve(ResultLen);
14480 for (
unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14486 unsigned BitWidth = ALane.getBitWidth();
14487 APInt ResLane(BitWidth, 0);
14489 for (
unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14490 unsigned ABit = ALane[Bit];
14491 unsigned BBit = BLane[Bit];
14492 unsigned CBit = CLane[Bit];
14494 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14495 ResLane.setBitVal(Bit, Imm[Idx]);
14497 ResultElements.push_back(
APValue(
APSInt(ResLane, DestUnsigned)));
14499 ResultElements.push_back(
APValue(
APSInt(ALane, DestUnsigned)));
14502 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14504 case X86::BI__builtin_ia32_pternlogd128_maskz:
14505 case X86::BI__builtin_ia32_pternlogd256_maskz:
14506 case X86::BI__builtin_ia32_pternlogd512_maskz:
14507 case X86::BI__builtin_ia32_pternlogq128_maskz:
14508 case X86::BI__builtin_ia32_pternlogq256_maskz:
14509 case X86::BI__builtin_ia32_pternlogq512_maskz: {
14510 APValue AValue, BValue, CValue, ImmValue, UValue;
14518 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14524 ResultElements.reserve(ResultLen);
14526 for (
unsigned EltNum = 0; EltNum < ResultLen; ++EltNum) {
14531 unsigned BitWidth = ALane.getBitWidth();
14532 APInt ResLane(BitWidth, 0);
14535 for (
unsigned Bit = 0; Bit < BitWidth; ++Bit) {
14536 unsigned ABit = ALane[Bit];
14537 unsigned BBit = BLane[Bit];
14538 unsigned CBit = CLane[Bit];
14540 unsigned Idx = (ABit << 2) | (BBit << 1) | CBit;
14541 ResLane.setBitVal(Bit, Imm[Idx]);
14544 ResultElements.push_back(
APValue(
APSInt(ResLane, DestUnsigned)));
14546 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14549 case Builtin::BI__builtin_elementwise_clzg:
14550 case Builtin::BI__builtin_elementwise_ctzg: {
14552 std::optional<APValue> Fallback;
14559 Fallback = FallbackTmp;
14562 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14565 ResultElements.reserve(SourceLen);
14567 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14572 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
14574 Builtin::BI__builtin_elementwise_ctzg);
14577 ResultElements.push_back(Fallback->getVectorElt(EltNum));
14580 switch (BuiltinOp) {
14581 case Builtin::BI__builtin_elementwise_clzg:
14582 ResultElements.push_back(
APValue(
14583 APSInt(
APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countl_zero()),
14586 case Builtin::BI__builtin_elementwise_ctzg:
14587 ResultElements.push_back(
APValue(
14588 APSInt(
APInt(Info.Ctx.getIntWidth(DestEltTy), LHS.countr_zero()),
14594 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14597 case Builtin::BI__builtin_elementwise_fma: {
14598 APValue SourceX, SourceY, SourceZ;
14606 ResultElements.reserve(SourceLen);
14608 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14613 (void)
Result.fusedMultiplyAdd(Y, Z, RM);
14616 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14619 case clang::X86::BI__builtin_ia32_phaddw128:
14620 case clang::X86::BI__builtin_ia32_phaddw256:
14621 case clang::X86::BI__builtin_ia32_phaddd128:
14622 case clang::X86::BI__builtin_ia32_phaddd256:
14623 case clang::X86::BI__builtin_ia32_phaddsw128:
14624 case clang::X86::BI__builtin_ia32_phaddsw256:
14626 case clang::X86::BI__builtin_ia32_phsubw128:
14627 case clang::X86::BI__builtin_ia32_phsubw256:
14628 case clang::X86::BI__builtin_ia32_phsubd128:
14629 case clang::X86::BI__builtin_ia32_phsubd256:
14630 case clang::X86::BI__builtin_ia32_phsubsw128:
14631 case clang::X86::BI__builtin_ia32_phsubsw256: {
14632 APValue SourceLHS, SourceRHS;
14636 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14640 unsigned EltBits = Info.Ctx.getIntWidth(DestEltTy);
14641 unsigned EltsPerLane = 128 / EltBits;
14643 ResultElements.reserve(NumElts);
14645 for (
unsigned LaneStart = 0; LaneStart != NumElts;
14646 LaneStart += EltsPerLane) {
14647 for (
unsigned I = 0; I != EltsPerLane; I += 2) {
14650 switch (BuiltinOp) {
14651 case clang::X86::BI__builtin_ia32_phaddw128:
14652 case clang::X86::BI__builtin_ia32_phaddw256:
14653 case clang::X86::BI__builtin_ia32_phaddd128:
14654 case clang::X86::BI__builtin_ia32_phaddd256: {
14655 APSInt Res(LHSA + LHSB, DestUnsigned);
14656 ResultElements.push_back(
APValue(Res));
14659 case clang::X86::BI__builtin_ia32_phaddsw128:
14660 case clang::X86::BI__builtin_ia32_phaddsw256: {
14661 APSInt Res(LHSA.sadd_sat(LHSB));
14662 ResultElements.push_back(
APValue(Res));
14665 case clang::X86::BI__builtin_ia32_phsubw128:
14666 case clang::X86::BI__builtin_ia32_phsubw256:
14667 case clang::X86::BI__builtin_ia32_phsubd128:
14668 case clang::X86::BI__builtin_ia32_phsubd256: {
14669 APSInt Res(LHSA - LHSB, DestUnsigned);
14670 ResultElements.push_back(
APValue(Res));
14673 case clang::X86::BI__builtin_ia32_phsubsw128:
14674 case clang::X86::BI__builtin_ia32_phsubsw256: {
14675 APSInt Res(LHSA.ssub_sat(LHSB));
14676 ResultElements.push_back(
APValue(Res));
14681 for (
unsigned I = 0; I != EltsPerLane; I += 2) {
14684 switch (BuiltinOp) {
14685 case clang::X86::BI__builtin_ia32_phaddw128:
14686 case clang::X86::BI__builtin_ia32_phaddw256:
14687 case clang::X86::BI__builtin_ia32_phaddd128:
14688 case clang::X86::BI__builtin_ia32_phaddd256: {
14689 APSInt Res(RHSA + RHSB, DestUnsigned);
14690 ResultElements.push_back(
APValue(Res));
14693 case clang::X86::BI__builtin_ia32_phaddsw128:
14694 case clang::X86::BI__builtin_ia32_phaddsw256: {
14695 APSInt Res(RHSA.sadd_sat(RHSB));
14696 ResultElements.push_back(
APValue(Res));
14699 case clang::X86::BI__builtin_ia32_phsubw128:
14700 case clang::X86::BI__builtin_ia32_phsubw256:
14701 case clang::X86::BI__builtin_ia32_phsubd128:
14702 case clang::X86::BI__builtin_ia32_phsubd256: {
14703 APSInt Res(RHSA - RHSB, DestUnsigned);
14704 ResultElements.push_back(
APValue(Res));
14707 case clang::X86::BI__builtin_ia32_phsubsw128:
14708 case clang::X86::BI__builtin_ia32_phsubsw256: {
14709 APSInt Res(RHSA.ssub_sat(RHSB));
14710 ResultElements.push_back(
APValue(Res));
14716 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14718 case clang::X86::BI__builtin_ia32_haddpd:
14719 case clang::X86::BI__builtin_ia32_haddps:
14720 case clang::X86::BI__builtin_ia32_haddps256:
14721 case clang::X86::BI__builtin_ia32_haddpd256:
14722 case clang::X86::BI__builtin_ia32_hsubpd:
14723 case clang::X86::BI__builtin_ia32_hsubps:
14724 case clang::X86::BI__builtin_ia32_hsubps256:
14725 case clang::X86::BI__builtin_ia32_hsubpd256: {
14726 APValue SourceLHS, SourceRHS;
14732 ResultElements.reserve(NumElts);
14734 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14735 unsigned EltBits = Info.Ctx.getTypeSize(DestEltTy);
14736 unsigned NumLanes = NumElts * EltBits / 128;
14737 unsigned NumElemsPerLane = NumElts / NumLanes;
14738 unsigned HalfElemsPerLane = NumElemsPerLane / 2;
14740 for (
unsigned L = 0; L != NumElts; L += NumElemsPerLane) {
14741 for (
unsigned I = 0; I != HalfElemsPerLane; ++I) {
14744 switch (BuiltinOp) {
14745 case clang::X86::BI__builtin_ia32_haddpd:
14746 case clang::X86::BI__builtin_ia32_haddps:
14747 case clang::X86::BI__builtin_ia32_haddps256:
14748 case clang::X86::BI__builtin_ia32_haddpd256:
14749 LHSA.add(LHSB, RM);
14751 case clang::X86::BI__builtin_ia32_hsubpd:
14752 case clang::X86::BI__builtin_ia32_hsubps:
14753 case clang::X86::BI__builtin_ia32_hsubps256:
14754 case clang::X86::BI__builtin_ia32_hsubpd256:
14755 LHSA.subtract(LHSB, RM);
14758 ResultElements.push_back(
APValue(LHSA));
14760 for (
unsigned I = 0; I != HalfElemsPerLane; ++I) {
14763 switch (BuiltinOp) {
14764 case clang::X86::BI__builtin_ia32_haddpd:
14765 case clang::X86::BI__builtin_ia32_haddps:
14766 case clang::X86::BI__builtin_ia32_haddps256:
14767 case clang::X86::BI__builtin_ia32_haddpd256:
14768 RHSA.add(RHSB, RM);
14770 case clang::X86::BI__builtin_ia32_hsubpd:
14771 case clang::X86::BI__builtin_ia32_hsubps:
14772 case clang::X86::BI__builtin_ia32_hsubps256:
14773 case clang::X86::BI__builtin_ia32_hsubpd256:
14774 RHSA.subtract(RHSB, RM);
14777 ResultElements.push_back(
APValue(RHSA));
14780 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14782 case clang::X86::BI__builtin_ia32_addsubpd:
14783 case clang::X86::BI__builtin_ia32_addsubps:
14784 case clang::X86::BI__builtin_ia32_addsubpd256:
14785 case clang::X86::BI__builtin_ia32_addsubps256: {
14788 APValue SourceLHS, SourceRHS;
14794 ResultElements.reserve(NumElems);
14797 for (
unsigned I = 0; I != NumElems; ++I) {
14802 LHS.subtract(RHS, RM);
14807 ResultElements.push_back(
APValue(LHS));
14809 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14811 case clang::X86::BI__builtin_ia32_pclmulqdq128:
14812 case clang::X86::BI__builtin_ia32_pclmulqdq256:
14813 case clang::X86::BI__builtin_ia32_pclmulqdq512: {
14817 APValue SourceLHS, SourceRHS;
14827 bool SelectUpperA = (Imm8 & 0x01) != 0;
14828 bool SelectUpperB = (Imm8 & 0x10) != 0;
14832 ResultElements.reserve(NumElems);
14833 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14837 for (
unsigned Lane = 0; Lane < NumElems; Lane += 2) {
14846 APInt A = SelectUpperA ? A1 : A0;
14847 APInt B = SelectUpperB ? B1 : B0;
14850 APInt A128 = A.zext(128);
14851 APInt B128 = B.zext(128);
14854 APInt Result = llvm::APIntOps::clmul(A128, B128);
14857 APSInt ResultLow(
Result.extractBits(64, 0), DestUnsigned);
14858 APSInt ResultHigh(
Result.extractBits(64, 64), DestUnsigned);
14860 ResultElements.push_back(
APValue(ResultLow));
14861 ResultElements.push_back(
APValue(ResultHigh));
14864 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14866 case Builtin::BI__builtin_elementwise_clmul:
14867 return EvaluateBinOpExpr(llvm::APIntOps::clmul);
14868 case Builtin::BI__builtin_elementwise_pext:
14869 return EvaluateBinOpExpr(llvm::APIntOps::pext);
14870 case Builtin::BI__builtin_elementwise_pdep:
14871 return EvaluateBinOpExpr(llvm::APIntOps::pdep);
14872 case Builtin::BI__builtin_elementwise_fshl:
14873 case Builtin::BI__builtin_elementwise_fshr: {
14874 APValue SourceHi, SourceLo, SourceShift;
14880 QualType DestEltTy = E->
getType()->
castAs<VectorType>()->getElementType();
14886 ResultElements.reserve(SourceLen);
14887 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
14891 switch (BuiltinOp) {
14892 case Builtin::BI__builtin_elementwise_fshl:
14893 ResultElements.push_back(
APValue(
14894 APSInt(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned())));
14896 case Builtin::BI__builtin_elementwise_fshr:
14897 ResultElements.push_back(
APValue(
14898 APSInt(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned())));
14903 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
14906 case X86::BI__builtin_ia32_shuf_f32x4_256:
14907 case X86::BI__builtin_ia32_shuf_i32x4_256:
14908 case X86::BI__builtin_ia32_shuf_f64x2_256:
14909 case X86::BI__builtin_ia32_shuf_i64x2_256:
14910 case X86::BI__builtin_ia32_shuf_f32x4:
14911 case X86::BI__builtin_ia32_shuf_i32x4:
14912 case X86::BI__builtin_ia32_shuf_f64x2:
14913 case X86::BI__builtin_ia32_shuf_i64x2: {
14927 unsigned ElemBits = Info.Ctx.getTypeSize(ElemQT);
14928 unsigned LaneBits = 128u;
14929 unsigned NumLanes = (NumElems * ElemBits) / LaneBits;
14930 unsigned NumElemsPerLane = LaneBits / ElemBits;
14934 ResultElements.reserve(DstLen);
14939 [NumLanes, NumElemsPerLane](
unsigned DstIdx,
unsigned ShuffleMask)
14940 -> std::pair<unsigned, int> {
14942 unsigned BitsPerElem = NumLanes / 2;
14943 unsigned IndexMask = (1u << BitsPerElem) - 1;
14944 unsigned Lane = DstIdx / NumElemsPerLane;
14945 unsigned SrcIdx = (Lane < NumLanes / 2) ? 0 : 1;
14946 unsigned BitIdx = BitsPerElem * Lane;
14947 unsigned SrcLaneIdx = (ShuffleMask >> BitIdx) & IndexMask;
14948 unsigned ElemInLane = DstIdx % NumElemsPerLane;
14949 unsigned IdxToPick = SrcLaneIdx * NumElemsPerLane + ElemInLane;
14950 return {SrcIdx, IdxToPick};
14956 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14957 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14958 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi:
14959 case X86::BI__builtin_ia32_vgf2p8affineqb_v16qi:
14960 case X86::BI__builtin_ia32_vgf2p8affineqb_v32qi:
14961 case X86::BI__builtin_ia32_vgf2p8affineqb_v64qi: {
14973 bool IsInverse =
false;
14974 switch (BuiltinOp) {
14975 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v16qi:
14976 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v32qi:
14977 case X86::BI__builtin_ia32_vgf2p8affineinvqb_v64qi: {
14982 unsigned NumBitsInByte = 8;
14983 unsigned NumBytesInQWord = 8;
14984 unsigned NumBitsInQWord = 64;
14986 unsigned NumQWords = NumBytes / NumBytesInQWord;
14988 Result.reserve(NumBytes);
14991 for (
unsigned QWordIdx = 0; QWordIdx != NumQWords; ++QWordIdx) {
14993 APInt XQWord(NumBitsInQWord, 0);
14994 APInt AQWord(NumBitsInQWord, 0);
14995 for (
unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
14996 unsigned Idx = QWordIdx * NumBytesInQWord + ByteIdx;
14997 APInt XByte =
X.getVectorElt(Idx).getInt();
14999 XQWord.insertBits(XByte, ByteIdx * NumBitsInByte);
15000 AQWord.insertBits(AByte, ByteIdx * NumBitsInByte);
15003 for (
unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
15005 XQWord.lshr(ByteIdx * NumBitsInByte).getLoBits(8).getZExtValue();
15014 case X86::BI__builtin_ia32_vgf2p8mulb_v16qi:
15015 case X86::BI__builtin_ia32_vgf2p8mulb_v32qi:
15016 case X86::BI__builtin_ia32_vgf2p8mulb_v64qi: {
15027 Result.reserve(NumBytes);
15029 for (
unsigned ByteIdx = 0; ByteIdx != NumBytes; ++ByteIdx) {
15039 case X86::BI__builtin_ia32_insertf32x4_256:
15040 case X86::BI__builtin_ia32_inserti32x4_256:
15041 case X86::BI__builtin_ia32_insertf64x2_256:
15042 case X86::BI__builtin_ia32_inserti64x2_256:
15043 case X86::BI__builtin_ia32_insertf32x4:
15044 case X86::BI__builtin_ia32_inserti32x4:
15045 case X86::BI__builtin_ia32_insertf64x2_512:
15046 case X86::BI__builtin_ia32_inserti64x2_512:
15047 case X86::BI__builtin_ia32_insertf32x8:
15048 case X86::BI__builtin_ia32_inserti32x8:
15049 case X86::BI__builtin_ia32_insertf64x4:
15050 case X86::BI__builtin_ia32_inserti64x4:
15051 case X86::BI__builtin_ia32_vinsertf128_ps256:
15052 case X86::BI__builtin_ia32_vinsertf128_pd256:
15053 case X86::BI__builtin_ia32_vinsertf128_si256:
15054 case X86::BI__builtin_ia32_insert128i256: {
15055 APValue SourceDst, SourceSub;
15067 assert(SubLen != 0 && DstLen != 0 && (DstLen % SubLen) == 0);
15068 unsigned NumLanes = DstLen / SubLen;
15069 unsigned LaneIdx = (Imm.getZExtValue() % NumLanes) * SubLen;
15072 ResultElements.reserve(DstLen);
15074 for (
unsigned EltNum = 0; EltNum < DstLen; ++EltNum) {
15075 if (EltNum >= LaneIdx && EltNum < LaneIdx + SubLen)
15076 ResultElements.push_back(SourceSub.
getVectorElt(EltNum - LaneIdx));
15078 ResultElements.push_back(SourceDst.
getVectorElt(EltNum));
15081 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
15084 case clang::X86::BI__builtin_ia32_vec_set_v4hi:
15085 case clang::X86::BI__builtin_ia32_vec_set_v16qi:
15086 case clang::X86::BI__builtin_ia32_vec_set_v8hi:
15087 case clang::X86::BI__builtin_ia32_vec_set_v4si:
15088 case clang::X86::BI__builtin_ia32_vec_set_v2di:
15089 case clang::X86::BI__builtin_ia32_vec_set_v32qi:
15090 case clang::X86::BI__builtin_ia32_vec_set_v16hi:
15091 case clang::X86::BI__builtin_ia32_vec_set_v8si:
15092 case clang::X86::BI__builtin_ia32_vec_set_v4di: {
15100 QualType ElemTy = E->
getType()->
castAs<VectorType>()->getElementType();
15101 unsigned ElemWidth = Info.Ctx.getIntWidth(ElemTy);
15103 Scalar.setIsUnsigned(ElemUnsigned);
15109 static_cast<unsigned>(IndexAPS.getZExtValue() & (NumElems - 1));
15112 Elems.reserve(NumElems);
15113 for (
unsigned ElemNum = 0; ElemNum != NumElems; ++ElemNum)
15114 Elems.push_back(ElemNum == Index ? ElemAV : VecVal.
getVectorElt(ElemNum));
15119 case X86::BI__builtin_ia32_pslldqi128_byteshift:
15120 case X86::BI__builtin_ia32_pslldqi256_byteshift:
15121 case X86::BI__builtin_ia32_pslldqi512_byteshift: {
15125 [](
unsigned DstIdx,
unsigned Shift) -> std::pair<unsigned, int> {
15126 unsigned LaneBase = (DstIdx / 16) * 16;
15127 unsigned LaneIdx = DstIdx % 16;
15128 if (LaneIdx < Shift)
15129 return std::make_pair(0, -1);
15131 return std::make_pair(
15132 0,
static_cast<int>(LaneBase + LaneIdx - Shift));
15138 case X86::BI__builtin_ia32_psrldqi128_byteshift:
15139 case X86::BI__builtin_ia32_psrldqi256_byteshift:
15140 case X86::BI__builtin_ia32_psrldqi512_byteshift: {
15144 [](
unsigned DstIdx,
unsigned Shift) -> std::pair<unsigned, int> {
15145 unsigned LaneBase = (DstIdx / 16) * 16;
15146 unsigned LaneIdx = DstIdx % 16;
15147 if (LaneIdx + Shift < 16)
15148 return std::make_pair(
15149 0,
static_cast<int>(LaneBase + LaneIdx + Shift));
15151 return std::make_pair(0, -1);
15157 case X86::BI__builtin_ia32_palignr128:
15158 case X86::BI__builtin_ia32_palignr256:
15159 case X86::BI__builtin_ia32_palignr512: {
15163 unsigned VecIdx = 1;
15166 int Lane = DstIdx / 16;
15167 int Offset = DstIdx % 16;
15170 unsigned ShiftedIdx = Offset + (
Shift & 0xFF);
15171 if (ShiftedIdx < 16) {
15172 ElemIdx = ShiftedIdx + (Lane * 16);
15173 }
else if (ShiftedIdx < 32) {
15175 ElemIdx = (ShiftedIdx - 16) + (Lane * 16);
15178 return std::pair<unsigned, int>{VecIdx, ElemIdx};
15183 case X86::BI__builtin_ia32_alignd128:
15184 case X86::BI__builtin_ia32_alignd256:
15185 case X86::BI__builtin_ia32_alignd512:
15186 case X86::BI__builtin_ia32_alignq128:
15187 case X86::BI__builtin_ia32_alignq256:
15188 case X86::BI__builtin_ia32_alignq512: {
15190 unsigned NumElems = E->
getType()->
castAs<VectorType>()->getNumElements();
15192 [NumElems](
unsigned DstIdx,
unsigned Shift) {
15193 unsigned Imm =
Shift & 0xFF;
15194 unsigned EffectiveShift = Imm & (NumElems - 1);
15195 unsigned SourcePos = DstIdx + EffectiveShift;
15196 unsigned VecIdx = SourcePos < NumElems ? 1 : 0;
15197 unsigned ElemIdx = SourcePos & (NumElems - 1);
15199 return std::pair<unsigned, int>{
15200 VecIdx,
static_cast<int>(ElemIdx)};
15205 case X86::BI__builtin_ia32_permvarsi256:
15206 case X86::BI__builtin_ia32_permvarsf256:
15207 case X86::BI__builtin_ia32_permvardf512:
15208 case X86::BI__builtin_ia32_permvardi512:
15209 case X86::BI__builtin_ia32_permvarhi128: {
15212 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15213 int Offset = ShuffleMask & 0x7;
15214 return std::pair<unsigned, int>{0, Offset};
15219 case X86::BI__builtin_ia32_permvarqi128:
15220 case X86::BI__builtin_ia32_permvarhi256:
15221 case X86::BI__builtin_ia32_permvarsi512:
15222 case X86::BI__builtin_ia32_permvarsf512: {
15225 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15226 int Offset = ShuffleMask & 0xF;
15227 return std::pair<unsigned, int>{0, Offset};
15232 case X86::BI__builtin_ia32_permvardi256:
15233 case X86::BI__builtin_ia32_permvardf256: {
15236 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15237 int Offset = ShuffleMask & 0x3;
15238 return std::pair<unsigned, int>{0, Offset};
15243 case X86::BI__builtin_ia32_permvarqi256:
15244 case X86::BI__builtin_ia32_permvarhi512: {
15247 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15248 int Offset = ShuffleMask & 0x1F;
15249 return std::pair<unsigned, int>{0, Offset};
15254 case X86::BI__builtin_ia32_permvarqi512: {
15257 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15258 int Offset = ShuffleMask & 0x3F;
15259 return std::pair<unsigned, int>{0, Offset};
15264 case X86::BI__builtin_ia32_vpermi2varq128:
15265 case X86::BI__builtin_ia32_vpermi2varpd128: {
15268 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15269 int Offset = ShuffleMask & 0x1;
15270 unsigned SrcIdx = (ShuffleMask >> 1) & 0x1;
15271 return std::pair<unsigned, int>{SrcIdx, Offset};
15276 case X86::BI__builtin_ia32_vpermi2vard128:
15277 case X86::BI__builtin_ia32_vpermi2varps128:
15278 case X86::BI__builtin_ia32_vpermi2varq256:
15279 case X86::BI__builtin_ia32_vpermi2varpd256: {
15282 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15283 int Offset = ShuffleMask & 0x3;
15284 unsigned SrcIdx = (ShuffleMask >> 2) & 0x1;
15285 return std::pair<unsigned, int>{SrcIdx, Offset};
15290 case X86::BI__builtin_ia32_vpermi2varhi128:
15291 case X86::BI__builtin_ia32_vpermi2vard256:
15292 case X86::BI__builtin_ia32_vpermi2varps256:
15293 case X86::BI__builtin_ia32_vpermi2varq512:
15294 case X86::BI__builtin_ia32_vpermi2varpd512: {
15297 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15298 int Offset = ShuffleMask & 0x7;
15299 unsigned SrcIdx = (ShuffleMask >> 3) & 0x1;
15300 return std::pair<unsigned, int>{SrcIdx, Offset};
15305 case X86::BI__builtin_ia32_vpermi2varqi128:
15306 case X86::BI__builtin_ia32_vpermi2varhi256:
15307 case X86::BI__builtin_ia32_vpermi2vard512:
15308 case X86::BI__builtin_ia32_vpermi2varps512: {
15311 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15312 int Offset = ShuffleMask & 0xF;
15313 unsigned SrcIdx = (ShuffleMask >> 4) & 0x1;
15314 return std::pair<unsigned, int>{SrcIdx, Offset};
15319 case X86::BI__builtin_ia32_vpermi2varqi256:
15320 case X86::BI__builtin_ia32_vpermi2varhi512: {
15323 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15324 int Offset = ShuffleMask & 0x1F;
15325 unsigned SrcIdx = (ShuffleMask >> 5) & 0x1;
15326 return std::pair<unsigned, int>{SrcIdx, Offset};
15331 case X86::BI__builtin_ia32_vpermi2varqi512: {
15334 [](
unsigned DstIdx,
unsigned ShuffleMask) {
15335 int Offset = ShuffleMask & 0x3F;
15336 unsigned SrcIdx = (ShuffleMask >> 6) & 0x1;
15337 return std::pair<unsigned, int>{SrcIdx, Offset};
15343 case clang::X86::BI__builtin_ia32_minps:
15344 case clang::X86::BI__builtin_ia32_minpd:
15345 case clang::X86::BI__builtin_ia32_minps256:
15346 case clang::X86::BI__builtin_ia32_minpd256:
15347 case clang::X86::BI__builtin_ia32_minps512:
15348 case clang::X86::BI__builtin_ia32_minpd512:
15349 case clang::X86::BI__builtin_ia32_minph128:
15350 case clang::X86::BI__builtin_ia32_minph256:
15351 case clang::X86::BI__builtin_ia32_minph512:
15352 return EvaluateFpBinOpExpr(
15353 [](
const APFloat &A,
const APFloat &B,
15354 std::optional<APSInt>) -> std::optional<APFloat> {
15355 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15356 B.isInfinity() || B.isDenormal())
15357 return std::nullopt;
15358 if (A.isZero() && B.isZero())
15360 return llvm::minimum(A, B);
15363 case clang::X86::BI__builtin_ia32_minss:
15364 case clang::X86::BI__builtin_ia32_minsd:
15365 return EvaluateFpBinOpExpr(
15366 [](
const APFloat &A,
const APFloat &B,
15367 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15372 case clang::X86::BI__builtin_ia32_minsd_round_mask:
15373 case clang::X86::BI__builtin_ia32_minss_round_mask:
15374 case clang::X86::BI__builtin_ia32_minsh_round_mask:
15375 case clang::X86::BI__builtin_ia32_maxsd_round_mask:
15376 case clang::X86::BI__builtin_ia32_maxss_round_mask:
15377 case clang::X86::BI__builtin_ia32_maxsh_round_mask: {
15378 bool IsMin = BuiltinOp == clang::X86::BI__builtin_ia32_minsd_round_mask ||
15379 BuiltinOp == clang::X86::BI__builtin_ia32_minss_round_mask ||
15380 BuiltinOp == clang::X86::BI__builtin_ia32_minsh_round_mask;
15381 return EvaluateScalarFpRoundMaskBinOp(
15382 [IsMin](
const APFloat &A,
const APFloat &B,
15383 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15388 case clang::X86::BI__builtin_ia32_maxps:
15389 case clang::X86::BI__builtin_ia32_maxpd:
15390 case clang::X86::BI__builtin_ia32_maxps256:
15391 case clang::X86::BI__builtin_ia32_maxpd256:
15392 case clang::X86::BI__builtin_ia32_maxps512:
15393 case clang::X86::BI__builtin_ia32_maxpd512:
15394 case clang::X86::BI__builtin_ia32_maxph128:
15395 case clang::X86::BI__builtin_ia32_maxph256:
15396 case clang::X86::BI__builtin_ia32_maxph512:
15397 return EvaluateFpBinOpExpr(
15398 [](
const APFloat &A,
const APFloat &B,
15399 std::optional<APSInt>) -> std::optional<APFloat> {
15400 if (A.isNaN() || A.isInfinity() || A.isDenormal() || B.isNaN() ||
15401 B.isInfinity() || B.isDenormal())
15402 return std::nullopt;
15403 if (A.isZero() && B.isZero())
15405 return llvm::maximum(A, B);
15408 case clang::X86::BI__builtin_ia32_maxss:
15409 case clang::X86::BI__builtin_ia32_maxsd:
15410 return EvaluateFpBinOpExpr(
15411 [](
const APFloat &A,
const APFloat &B,
15412 std::optional<APSInt> RoundingMode) -> std::optional<APFloat> {
15417 case clang::X86::BI__builtin_ia32_vcvtps2ph:
15418 case clang::X86::BI__builtin_ia32_vcvtps2ph256: {
15428 unsigned SrcNumElems = SrcVTy->getNumElements();
15430 unsigned DstNumElems = DstVTy->getNumElements();
15431 QualType DstElemTy = DstVTy->getElementType();
15433 const llvm::fltSemantics &HalfSem =
15434 Info.Ctx.getFloatTypeSemantics(Info.Ctx.HalfTy);
15436 int ImmVal = Imm.getZExtValue();
15437 bool UseMXCSR = (ImmVal & 4) != 0;
15438 bool IsFPConstrained =
15441 llvm::RoundingMode RM;
15443 switch (ImmVal & 3) {
15445 RM = llvm::RoundingMode::NearestTiesToEven;
15448 RM = llvm::RoundingMode::TowardNegative;
15451 RM = llvm::RoundingMode::TowardPositive;
15454 RM = llvm::RoundingMode::TowardZero;
15457 llvm_unreachable(
"Invalid immediate rounding mode");
15460 RM = llvm::RoundingMode::NearestTiesToEven;
15464 ResultElements.reserve(DstNumElems);
15466 for (
unsigned I = 0; I < SrcNumElems; ++I) {
15470 APFloat::opStatus St = SrcVal.convert(HalfSem, RM, &LostInfo);
15472 if (UseMXCSR && IsFPConstrained && St != APFloat::opOK) {
15473 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
15477 APSInt DstInt(SrcVal.bitcastToAPInt(),
15479 ResultElements.push_back(
APValue(DstInt));
15482 if (DstNumElems > SrcNumElems) {
15483 APSInt Zero = Info.Ctx.MakeIntValue(0, DstElemTy);
15484 for (
unsigned I = SrcNumElems; I < DstNumElems; ++I) {
15489 return Success(ResultElements, E);
15491 case X86::BI__builtin_ia32_vperm2f128_pd256:
15492 case X86::BI__builtin_ia32_vperm2f128_ps256:
15493 case X86::BI__builtin_ia32_vperm2f128_si256:
15494 case X86::BI__builtin_ia32_permti256: {
15495 unsigned NumElements =
15497 unsigned PreservedBitsCnt = NumElements >> 2;
15501 [PreservedBitsCnt](
unsigned DstIdx,
unsigned ShuffleMask) {
15502 unsigned ControlBitsCnt = DstIdx >> PreservedBitsCnt << 2;
15503 unsigned ControlBits = ShuffleMask >> ControlBitsCnt;
15505 if (ControlBits & 0b1000)
15506 return std::make_pair(0u, -1);
15508 unsigned SrcVecIdx = (ControlBits & 0b10) >> 1;
15509 unsigned PreservedBitsMask = (1 << PreservedBitsCnt) - 1;
15510 int SrcIdx = ((ControlBits & 0b1) << PreservedBitsCnt) |
15511 (DstIdx & PreservedBitsMask);
15512 return std::make_pair(SrcVecIdx, SrcIdx);
15517 case X86::BI__builtin_ia32_vpdpwssd128:
15518 case X86::BI__builtin_ia32_vpdpwssd256:
15519 case X86::BI__builtin_ia32_vpdpwssd512:
15520 case X86::BI__builtin_ia32_vpdpbusd128:
15521 case X86::BI__builtin_ia32_vpdpbusd256:
15522 case X86::BI__builtin_ia32_vpdpbusd512:
15523 return EvalVectorDotProduct(
false);
15524 case X86::BI__builtin_ia32_vpdpwssds128:
15525 case X86::BI__builtin_ia32_vpdpwssds256:
15526 case X86::BI__builtin_ia32_vpdpwssds512:
15527 case X86::BI__builtin_ia32_vpdpbusds128:
15528 case X86::BI__builtin_ia32_vpdpbusds256:
15529 case X86::BI__builtin_ia32_vpdpbusds512:
15530 return EvalVectorDotProduct(
true);
15531 case X86::BI__builtin_ia32_cvtpd2dq:
15532 case X86::BI__builtin_ia32_cvtps2dq:
15533 case X86::BI__builtin_ia32_cvttpd2dq:
15534 case X86::BI__builtin_ia32_cvttps2dq:
15535 case X86::BI__builtin_ia32_cvtpd2dq256:
15536 case X86::BI__builtin_ia32_cvtps2dq256:
15537 case X86::BI__builtin_ia32_cvttpd2dq256:
15538 case X86::BI__builtin_ia32_cvttps2dq256: {
15545 bool isUnsigned = EltTy->isUnsignedIntegerType();
15546 unsigned BitWidth = Info.Ctx.getIntWidth(EltTy);
15552 for (
unsigned i = 0; i != NumDstElems; ++i) {
15553 if (i < NumSrcElems) {
15555 llvm::APSInt IntResult(BitWidth,
isUnsigned);
15556 bool IsExact =
false;
15559 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
15563 ResultElts.push_back(
APValue(IntResult));
15568 return Success(ResultElts, E);
15573bool VectorExprEvaluator::VisitConvertVectorExpr(
const ConvertVectorExpr *E) {
15579 QualType DestTy = E->
getType()->
castAs<VectorType>()->getElementType();
15580 QualType SourceTy = SourceVecType->
castAs<VectorType>()->getElementType();
15586 ResultElements.reserve(SourceLen);
15587 for (
unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
15592 ResultElements.push_back(std::move(Elt));
15595 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
15600 APValue const &VecVal2,
unsigned EltNum,
15602 unsigned const TotalElementsInInputVector1 = VecVal1.
getVectorLength();
15603 unsigned const TotalElementsInInputVector2 = VecVal2.
getVectorLength();
15613 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
15619 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
15620 llvm_unreachable(
"Out of bounds shuffle index");
15622 if (
index >= TotalElementsInInputVector1)
15629bool VectorExprEvaluator::VisitShuffleVectorExpr(
const ShuffleVectorExpr *E) {
15634 const Expr *Vec1 = E->
getExpr(0);
15638 const Expr *Vec2 = E->
getExpr(1);
15642 VectorType
const *DestVecTy = E->
getType()->
castAs<VectorType>();
15648 ResultElements.reserve(TotalElementsInOutputVector);
15649 for (
unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
15653 ResultElements.push_back(std::move(Elt));
15656 return Success(
APValue(ResultElements.data(), ResultElements.size()), E);
15664class MatrixExprEvaluator :
public ExprEvaluatorBase<MatrixExprEvaluator> {
15671 bool Success(ArrayRef<APValue> M,
const Expr *E) {
15673 assert(M.size() == CMTy->getNumElementsFlattened());
15675 Result =
APValue(M.data(), CMTy->getNumRows(), CMTy->getNumColumns());
15679 assert(M.
isMatrix() &&
"expected matrix");
15684 bool VisitCastExpr(
const CastExpr *E);
15685 bool VisitInitListExpr(
const InitListExpr *E);
15691 "not a matrix prvalue");
15692 return MatrixExprEvaluator(Info,
Result).Visit(E);
15695bool MatrixExprEvaluator::VisitCastExpr(
const CastExpr *E) {
15696 const auto *MT = E->
getType()->
castAs<ConstantMatrixType>();
15697 unsigned NumRows = MT->getNumRows();
15698 unsigned NumCols = MT->getNumColumns();
15699 unsigned NElts = NumRows * NumCols;
15700 QualType EltTy = MT->getElementType();
15704 case CK_HLSLAggregateSplatCast: {
15719 case CK_HLSLElementwiseCast: {
15732 return Success(ResultEls, E);
15735 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15739bool MatrixExprEvaluator::VisitInitListExpr(
const InitListExpr *E) {
15740 const auto *MT = E->
getType()->
castAs<ConstantMatrixType>();
15741 QualType EltTy = MT->getElementType();
15743 assert(E->
getNumInits() == MT->getNumElementsFlattened() &&
15744 "Expected number of elements in initializer list to match the number "
15745 "of matrix elements");
15748 Elements.reserve(MT->getNumElementsFlattened());
15753 for (
unsigned I = 0, N = MT->getNumElementsFlattened(); I < N; ++I) {
15754 if (EltTy->isIntegerType()) {
15755 llvm::APSInt IntVal;
15758 Elements.push_back(
APValue(IntVal));
15760 llvm::APFloat FloatVal(0.0);
15763 Elements.push_back(
APValue(FloatVal));
15775 class ArrayExprEvaluator
15776 :
public ExprEvaluatorBase<ArrayExprEvaluator> {
15777 const LValue &
This;
15781 ArrayExprEvaluator(EvalInfo &Info,
const LValue &This,
APValue &
Result)
15785 assert(
V.isArray() &&
"expected array");
15790 bool ZeroInitialization(
const Expr *E) {
15791 const ConstantArrayType *CAT =
15792 Info.Ctx.getAsConstantArrayType(E->
getType());
15806 if (!
Result.hasArrayFiller())
15810 LValue Subobject =
This;
15811 Subobject.addArray(Info, E, CAT);
15816 bool VisitCallExpr(
const CallExpr *E) {
15817 return handleCallExpr(E,
Result, &This);
15819 bool VisitCastExpr(
const CastExpr *E);
15820 bool VisitInitListExpr(
const InitListExpr *E,
15821 QualType AllocType = QualType());
15822 bool VisitArrayInitLoopExpr(
const ArrayInitLoopExpr *E);
15823 bool VisitCXXConstructExpr(
const CXXConstructExpr *E);
15824 bool VisitCXXConstructExpr(
const CXXConstructExpr *E,
15825 const LValue &Subobject,
15827 bool VisitStringLiteral(
const StringLiteral *E,
15828 QualType AllocType = QualType()) {
15832 bool VisitCXXParenListInitExpr(
const CXXParenListInitExpr *E);
15833 bool VisitCXXParenListOrInitListExpr(
const Expr *ExprToVisit,
15834 ArrayRef<Expr *> Args,
15835 const Expr *ArrayFiller,
15836 QualType AllocType = QualType());
15837 bool VisitDesignatedInitUpdateExpr(
const DesignatedInitUpdateExpr *E);
15845 "not an array prvalue");
15846 return ArrayExprEvaluator(Info,
This,
Result).Visit(E);
15854 "not an array prvalue");
15855 return ArrayExprEvaluator(Info,
This,
Result)
15856 .VisitInitListExpr(ILE, AllocType);
15865 "not an array prvalue");
15866 return ArrayExprEvaluator(Info,
This,
Result)
15867 .VisitCXXConstructExpr(CCE,
This, &
Result, AllocType);
15876 if (
const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
15877 for (
unsigned I = 0, E = ILE->
getNumInits(); I != E; ++I) {
15882 if (ILE->hasArrayFiller() &&
15891bool ArrayExprEvaluator::VisitCastExpr(
const CastExpr *E) {
15896 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15897 case CK_HLSLAggregateSplatCast: {
15917 case CK_HLSLElementwiseCast: {
15934bool ArrayExprEvaluator::VisitInitListExpr(
const InitListExpr *E,
15935 QualType AllocType) {
15936 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15949 return VisitStringLiteral(SL, AllocType);
15954 "transparent array list initialization is not string literal init?");
15960bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
15962 QualType AllocType) {
15963 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
15968 unsigned NumEltsToInit = Args.size();
15973 if (NumEltsToInit != NumElts &&
15975 NumEltsToInit = NumElts;
15978 for (
auto *
Init : Args) {
15979 if (
auto *EmbedS = dyn_cast<EmbedExpr>(
Init->IgnoreParenImpCasts()))
15980 NumEltsToInit += EmbedS->getDataElementCount() - 1;
15983 if (NumEltsToInit > NumElts)
15984 NumEltsToInit = NumElts;
15988 if (
Result.hasValue() && NumEltsToInit <
Result.getArrayInitializedElts())
15989 NumEltsToInit =
Result.getArrayInitializedElts();
15992 LLVM_DEBUG(llvm::dbgs() <<
"The number of elements to initialize: "
15993 << NumEltsToInit <<
".\n");
15995 if (!
Result.hasValue()) {
15996 Result =
APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
15997 }
else if (
Result.getArrayInitializedElts() != NumEltsToInit) {
16008 APValue NewResult =
APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
16010 unsigned NumOldElts =
Result.getArrayInitializedElts();
16011 for (
unsigned I = 0; I < NumOldElts; ++I) {
16013 std::move(
Result.getArrayInitializedElt(I));
16016 for (
unsigned I =
Result.getArrayInitializedElts(); I < NumEltsToInit; ++I)
16020 Result = std::move(NewResult);
16023 LValue Subobject =
This;
16024 Subobject.addArray(Info, ExprToVisit, CAT);
16025 auto Eval = [&](
const Expr *
Init,
unsigned ArrayIndex) {
16026 if (
Init->isValueDependent())
16035 Subobject,
Init) ||
16038 if (!Info.noteFailure())
16044 unsigned ArrayIndex = 0;
16047 for (
unsigned Index = 0; Index != NumEltsToInit; ++Index) {
16048 const Expr *
Init = Index < Args.size() ? Args[Index] : ArrayFiller;
16049 if (ArrayIndex >= NumEltsToInit)
16051 if (
auto *EmbedS = dyn_cast<EmbedExpr>(
Init->IgnoreParenImpCasts())) {
16052 StringLiteral *SL = EmbedS->getDataStringLiteral();
16053 for (
unsigned I = EmbedS->getStartingElementPos(),
16054 N = EmbedS->getDataElementCount();
16055 I != EmbedS->getStartingElementPos() + N; ++I) {
16061 const FPOptions FPO =
16062 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
16067 Result.getArrayInitializedElt(ArrayIndex) =
APValue(FValue);
16072 if (!Eval(
Init, ArrayIndex))
16078 if (!
Result.hasArrayFiller())
16083 assert(ArrayFiller &&
"no array filler for incomplete init list");
16089bool ArrayExprEvaluator::VisitArrayInitLoopExpr(
const ArrayInitLoopExpr *E) {
16092 !
Evaluate(Info.CurrentCall->createTemporary(
16095 ScopeKind::FullExpression, CommonLV),
16104 Result =
APValue(APValue::UninitArray(), Elements, Elements);
16106 LValue Subobject =
This;
16107 Subobject.addArray(Info, E, CAT);
16110 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
16119 FullExpressionRAII Scope(Info);
16125 if (!Info.noteFailure())
16137bool ArrayExprEvaluator::VisitCXXConstructExpr(
const CXXConstructExpr *E) {
16138 return VisitCXXConstructExpr(E, This, &
Result, E->
getType());
16141bool ArrayExprEvaluator::VisitCXXConstructExpr(
const CXXConstructExpr *E,
16142 const LValue &Subobject,
16145 bool HadZeroInit =
Value->hasValue();
16147 if (
const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
Type)) {
16154 HadZeroInit &&
Value->hasArrayFiller() ?
Value->getArrayFiller()
16157 *
Value =
APValue(APValue::UninitArray(), 0, FinalSize);
16158 if (FinalSize == 0)
16164 LValue ArrayElt = Subobject;
16165 ArrayElt.addArray(Info, E, CAT);
16171 for (
const unsigned N : {1u, FinalSize}) {
16172 unsigned OldElts =
Value->getArrayInitializedElts();
16177 APValue NewValue(APValue::UninitArray(), N, FinalSize);
16178 for (
unsigned I = 0; I < OldElts; ++I)
16179 NewValue.getArrayInitializedElt(I).swap(
16180 Value->getArrayInitializedElt(I));
16181 Value->swap(NewValue);
16184 for (
unsigned I = OldElts; I < N; ++I)
16185 Value->getArrayInitializedElt(I) = Filler;
16187 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
16190 APValue &FirstResult =
Value->getArrayInitializedElt(0);
16191 for (
unsigned I = OldElts; I < FinalSize; ++I)
16192 Value->getArrayInitializedElt(I) = FirstResult;
16194 for (
unsigned I = OldElts; I < N; ++I) {
16195 if (!VisitCXXConstructExpr(E, ArrayElt,
16196 &
Value->getArrayInitializedElt(I),
16203 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
16204 !Info.keepEvaluatingAfterFailure())
16213 if (!
Type->isRecordType())
16216 return RecordExprEvaluator(Info, Subobject, *
Value)
16217 .VisitCXXConstructExpr(E,
Type);
16220bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
16221 const CXXParenListInitExpr *E) {
16223 "Expression result is not a constant array type");
16225 return VisitCXXParenListOrInitListExpr(E, E->
getInitExprs(),
16229bool ArrayExprEvaluator::VisitDesignatedInitUpdateExpr(
16230 const DesignatedInitUpdateExpr *E) {
16245class IntExprEvaluator
16246 :
public ExprEvaluatorBase<IntExprEvaluator> {
16249 IntExprEvaluator(EvalInfo &info,
APValue &result)
16250 : ExprEvaluatorBaseTy(
info),
Result(result) {}
16254 "Invalid evaluation result.");
16256 "Invalid evaluation result.");
16257 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->
getType()) &&
16258 "Invalid evaluation result.");
16262 bool Success(
const llvm::APSInt &SI,
const Expr *E) {
16268 "Invalid evaluation result.");
16269 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->
getType()) &&
16270 "Invalid evaluation result.");
16272 Result.getInt().setIsUnsigned(
16276 bool Success(
const llvm::APInt &I,
const Expr *E) {
16282 "Invalid evaluation result.");
16290 bool Success(CharUnits Size,
const Expr *E) {
16297 if (
V.isLValue() ||
V.isAddrLabelDiff() ||
V.isIndeterminate() ||
16298 V.allowConstexprUnknown()) {
16305 bool ZeroInitialization(
const Expr *E) {
return Success(0, E); }
16307 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
16314 bool VisitIntegerLiteral(
const IntegerLiteral *E) {
16317 bool VisitCharacterLiteral(
const CharacterLiteral *E) {
16321 bool CheckReferencedDecl(
const Expr *E,
const Decl *D);
16322 bool VisitDeclRefExpr(
const DeclRefExpr *E) {
16323 if (CheckReferencedDecl(E, E->
getDecl()))
16326 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
16328 bool VisitMemberExpr(
const MemberExpr *E) {
16330 VisitIgnoredBaseExpression(E->
getBase());
16334 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
16337 bool VisitCallExpr(
const CallExpr *E);
16338 bool VisitBuiltinCallExpr(
const CallExpr *E,
unsigned BuiltinOp);
16339 bool VisitBinaryOperator(
const BinaryOperator *E);
16340 bool VisitOffsetOfExpr(
const OffsetOfExpr *E);
16341 bool VisitUnaryOperator(
const UnaryOperator *E);
16343 bool VisitCastExpr(
const CastExpr* E);
16344 bool VisitUnaryExprOrTypeTraitExpr(
const UnaryExprOrTypeTraitExpr *E);
16346 bool VisitCXXBoolLiteralExpr(
const CXXBoolLiteralExpr *E) {
16350 bool VisitObjCBoolLiteralExpr(
const ObjCBoolLiteralExpr *E) {
16354 bool VisitArrayInitIndexExpr(
const ArrayInitIndexExpr *E) {
16355 if (Info.ArrayInitIndex ==
uint64_t(-1)) {
16361 return Success(Info.ArrayInitIndex, E);
16365 bool VisitGNUNullExpr(
const GNUNullExpr *E) {
16366 return ZeroInitialization(E);
16369 bool VisitTypeTraitExpr(
const TypeTraitExpr *E) {
16378 bool VisitArrayTypeTraitExpr(
const ArrayTypeTraitExpr *E) {
16382 bool VisitExpressionTraitExpr(
const ExpressionTraitExpr *E) {
16386 bool VisitOpenACCAsteriskSizeExpr(
const OpenACCAsteriskSizeExpr *E) {
16393 bool VisitUnaryReal(
const UnaryOperator *E);
16394 bool VisitUnaryImag(
const UnaryOperator *E);
16396 bool VisitCXXNoexceptExpr(
const CXXNoexceptExpr *E);
16397 bool VisitSizeOfPackExpr(
const SizeOfPackExpr *E);
16398 bool VisitSourceLocExpr(
const SourceLocExpr *E);
16399 bool VisitConceptSpecializationExpr(
const ConceptSpecializationExpr *E);
16404class FixedPointExprEvaluator
16405 :
public ExprEvaluatorBase<FixedPointExprEvaluator> {
16409 FixedPointExprEvaluator(EvalInfo &info,
APValue &result)
16410 : ExprEvaluatorBaseTy(
info),
Result(result) {}
16412 bool Success(
const llvm::APInt &I,
const Expr *E) {
16414 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->
getType())), E);
16419 APFixedPoint(
Value, Info.Ctx.getFixedPointSemantics(E->
getType())), E);
16423 return Success(
V.getFixedPoint(), E);
16426 bool Success(
const APFixedPoint &
V,
const Expr *E) {
16428 assert(
V.getWidth() == Info.Ctx.getIntWidth(E->
getType()) &&
16429 "Invalid evaluation result.");
16434 bool ZeroInitialization(
const Expr *E) {
16442 bool VisitFixedPointLiteral(
const FixedPointLiteral *E) {
16446 bool VisitCastExpr(
const CastExpr *E);
16447 bool VisitUnaryOperator(
const UnaryOperator *E);
16448 bool VisitBinaryOperator(
const BinaryOperator *E);
16464 return IntExprEvaluator(Info,
Result).Visit(E);
16472 if (!Val.
isInt()) {
16475 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16482bool IntExprEvaluator::VisitSourceLocExpr(
const SourceLocExpr *E) {
16484 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.
getDefaultExpr());
16493 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
16508 auto FXSema = Info.Ctx.getFixedPointSemantics(E->
getType());
16512 Result = APFixedPoint(Val, FXSema);
16523bool IntExprEvaluator::CheckReferencedDecl(
const Expr* E,
const Decl* D) {
16525 if (
const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
16527 bool SameSign = (ECD->getInitVal().isSigned()
16529 bool SameWidth = (ECD->getInitVal().
getBitWidth()
16530 == Info.Ctx.getIntWidth(E->
getType()));
16531 if (SameSign && SameWidth)
16532 return Success(ECD->getInitVal(), E);
16536 llvm::APSInt Val = ECD->getInitVal();
16538 Val.setIsSigned(!ECD->getInitVal().isSigned());
16540 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->
getType()));
16551 assert(!
T->isDependentType() &&
"unexpected dependent type");
16556#define TYPE(ID, BASE)
16557#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
16558#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
16559#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
16560#include "clang/AST/TypeNodes.inc"
16562 case Type::DeducedTemplateSpecialization:
16563 llvm_unreachable(
"unexpected non-canonical or dependent type");
16565 case Type::Builtin:
16567#define BUILTIN_TYPE(ID, SINGLETON_ID)
16568#define SIGNED_TYPE(ID, SINGLETON_ID) \
16569 case BuiltinType::ID: return GCCTypeClass::Integer;
16570#define FLOATING_TYPE(ID, SINGLETON_ID) \
16571 case BuiltinType::ID: return GCCTypeClass::RealFloat;
16572#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
16573 case BuiltinType::ID: break;
16574#include "clang/AST/BuiltinTypes.def"
16575 case BuiltinType::Void:
16578 case BuiltinType::Bool:
16581 case BuiltinType::Char_U:
16582 case BuiltinType::UChar:
16583 case BuiltinType::WChar_U:
16584 case BuiltinType::Char8:
16585 case BuiltinType::Char16:
16586 case BuiltinType::Char32:
16587 case BuiltinType::UShort:
16588 case BuiltinType::UInt:
16589 case BuiltinType::ULong:
16590 case BuiltinType::ULongLong:
16591 case BuiltinType::UInt128:
16594 case BuiltinType::UShortAccum:
16595 case BuiltinType::UAccum:
16596 case BuiltinType::ULongAccum:
16597 case BuiltinType::UShortFract:
16598 case BuiltinType::UFract:
16599 case BuiltinType::ULongFract:
16600 case BuiltinType::SatUShortAccum:
16601 case BuiltinType::SatUAccum:
16602 case BuiltinType::SatULongAccum:
16603 case BuiltinType::SatUShortFract:
16604 case BuiltinType::SatUFract:
16605 case BuiltinType::SatULongFract:
16608 case BuiltinType::NullPtr:
16610 case BuiltinType::ObjCId:
16611 case BuiltinType::ObjCClass:
16612 case BuiltinType::ObjCSel:
16613#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16614 case BuiltinType::Id:
16615#include "clang/Basic/OpenCLImageTypes.def"
16616#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16617 case BuiltinType::Id:
16618#include "clang/Basic/OpenCLExtensionTypes.def"
16619 case BuiltinType::OCLSampler:
16620 case BuiltinType::OCLEvent:
16621 case BuiltinType::OCLClkEvent:
16622 case BuiltinType::OCLQueue:
16623 case BuiltinType::OCLReserveID:
16624#define SVE_TYPE(Name, Id, SingletonId) \
16625 case BuiltinType::Id:
16626#include "clang/Basic/AArch64ACLETypes.def"
16627#define PPC_VECTOR_TYPE(Name, Id, Size) \
16628 case BuiltinType::Id:
16629#include "clang/Basic/PPCTypes.def"
16630#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16631#include "clang/Basic/RISCVVTypes.def"
16632#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16633#include "clang/Basic/WebAssemblyReferenceTypes.def"
16634#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
16635#include "clang/Basic/AMDGPUTypes.def"
16636#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16637#include "clang/Basic/HLSLIntangibleTypes.def"
16638#define HLSL_PACKED_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16639#include "clang/Basic/HLSLPackedTypes.def"
16640#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
16641#include "clang/Basic/SPIRVTypes.def"
16642 case BuiltinType::MetaInfo:
16645 case BuiltinType::Dependent:
16646 llvm_unreachable(
"unexpected dependent type");
16648 llvm_unreachable(
"unexpected placeholder type");
16653 case Type::Pointer:
16654 case Type::ConstantArray:
16655 case Type::VariableArray:
16656 case Type::IncompleteArray:
16657 case Type::FunctionNoProto:
16658 case Type::FunctionProto:
16659 case Type::ArrayParameter:
16662 case Type::MemberPointer:
16667 case Type::Complex:
16680 case Type::ExtVector:
16683 case Type::BlockPointer:
16684 case Type::ConstantMatrix:
16685 case Type::ObjCObject:
16686 case Type::ObjCInterface:
16687 case Type::ObjCObjectPointer:
16689 case Type::HLSLAttributedResource:
16690 case Type::HLSLInlineSpirv:
16691 case Type::OverflowBehavior:
16699 case Type::LValueReference:
16700 case Type::RValueReference:
16701 llvm_unreachable(
"invalid type for expression");
16704 llvm_unreachable(
"unexpected type class");
16729 if (
Base.isNull()) {
16732 }
else if (
const Expr *E =
Base.dyn_cast<
const Expr *>()) {
16751 SpeculativeEvaluationRAII SpeculativeEval(Info);
16756 FoldConstant Fold(Info,
true);
16774 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
16775 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
16776 ArgType->isNullPtrType()) {
16779 Fold.keepDiagnostics();
16788 return V.hasValue();
16799 if (
const VarDecl *VD = dyn_cast<VarDecl>(D))
16823 const auto *Cast = dyn_cast<CastExpr>(NoParens);
16824 if (Cast ==
nullptr)
16829 auto CastKind = Cast->getCastKind();
16831 CastKind != CK_AddressSpaceConversion)
16834 const auto *SubExpr = Cast->getSubExpr();
16856 assert(!LVal.Designator.Invalid);
16858 auto IsLastOrInvalidFieldDecl = [&Ctx](
const FieldDecl *FD) {
16866 auto &
Base = LVal.getLValueBase();
16867 if (
auto *ME = dyn_cast_or_null<MemberExpr>(
Base.dyn_cast<
const Expr *>())) {
16868 if (
auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
16869 if (!IsLastOrInvalidFieldDecl(FD))
16871 }
else if (
auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
16872 for (
auto *FD : IFD->chain()) {
16881 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
16885 if (BaseType->isIncompleteArrayType())
16891 for (
unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
16892 const auto &Entry = LVal.Designator.Entries[I];
16893 if (BaseType->isArrayType()) {
16899 uint64_t Index = Entry.getAsArrayIndex();
16903 }
else if (BaseType->isAnyComplexType()) {
16904 const auto *CT = BaseType->castAs<
ComplexType>();
16905 uint64_t Index = Entry.getAsArrayIndex();
16908 BaseType = CT->getElementType();
16909 }
else if (
auto *FD = getAsField(Entry)) {
16910 if (!IsLastOrInvalidFieldDecl(FD))
16914 assert(getAsBaseClass(Entry) &&
"Expecting cast to a base class");
16926 if (LVal.Designator.Invalid)
16929 if (!LVal.Designator.Entries.empty())
16930 return LVal.Designator.isMostDerivedAnUnsizedArray();
16932 if (!LVal.InvalidBase)
16944 const SubobjectDesignator &
Designator = LVal.Designator;
16956 auto isFlexibleArrayMember = [&] {
16958 FAMKind StrictFlexArraysLevel =
16961 if (
Designator.isMostDerivedAnUnsizedArray())
16964 if (StrictFlexArraysLevel == FAMKind::Default)
16967 if (
Designator.getMostDerivedArraySize() == 0 &&
16968 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
16971 if (
Designator.getMostDerivedArraySize() == 1 &&
16972 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
16978 return LVal.InvalidBase &&
16980 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
16988 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
16989 if (
Int.ugt(CharUnitsMax))
16999 if (!
T.isNull() &&
T->isStructureType() &&
17000 T->castAsRecordDecl()->hasFlexibleArrayMember())
17001 if (
const auto *
V = LV.getLValueBase().dyn_cast<
const ValueDecl *>())
17002 if (
const auto *VD = dyn_cast<VarDecl>(
V))
17014 unsigned Type,
const LValue &LVal,
17033 if (!(
Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
17035 if (
Type == 3 && !DetermineForCompleteObject)
17038 llvm::APInt APEndOffset;
17039 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
17043 if (LVal.InvalidBase)
17047 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
17053 const SubobjectDesignator &
Designator = LVal.Designator;
17065 llvm::APInt APEndOffset;
17066 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
17078 if (!CheckedHandleSizeof(
Designator.MostDerivedType, BytesPerElem))
17089 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
17091 ElemsRemaining =
Designator.isOnePastTheEnd() ? 0 : 1;
17094 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
17104static std::optional<uint64_t>
17106 bool IsDynamic =
false) {
17114 SpeculativeEvaluationRAII SpeculativeEval(Info);
17115 IgnoreSideEffectsRAII Fold(Info);
17122 return std::nullopt;
17123 LVal.setFrom(Info.Ctx, RVal);
17126 return std::nullopt;
17131 if (LVal.getLValueOffset().isNegative())
17146 const auto *FD = ME ? dyn_cast<FieldDecl>(ME->getMemberDecl()) :
nullptr;
17148 return std::nullopt;
17153 return std::nullopt;
17157 if (EndOffset <= LVal.getLValueOffset())
17159 return (EndOffset - LVal.getLValueOffset()).
getQuantity();
17162bool IntExprEvaluator::VisitCallExpr(
const CallExpr *E) {
17163 if (!IsConstantEvaluatedBuiltinCall(E))
17164 return ExprEvaluatorBaseTy::VisitCallExpr(E);
17181 Info.FFDiag(E->
getArg(0));
17187 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
17188 "Bit widths must be the same");
17205 if (!Ptr.checkNullPointerForFoldAccess(Info, E,
AK_Read) ||
17206 Ptr.Designator.Invalid)
17209 if (Ptr.Designator.isMostDerivedAnUnsizedArray())
17216 if (PtrAlign < RequiredAlign) {
17217 Info.FFDiag(E, diag::note_constexpr_load8_unaligned)
17224 QualType CharTy = Ptr.Designator.getType(Info.Ctx);
17225 unsigned ByteWidth = Info.Ctx.getTypeSize(E->
getType()) / 8;
17226 uint64_t RemainingElems = Ptr.Designator.validIndexAdjustments().second;
17227 if (ByteWidth > RemainingElems) {
17228 uint64_t ArrayIndex = Ptr.Designator.MostDerivedIsArrayElement
17229 ? Ptr.Designator.Entries.back().getAsArrayIndex()
17230 : (
uint64_t)Ptr.Designator.IsOnePastTheEnd;
17231 APSInt Index = APSInt::get(ArrayIndex + ByteWidth - 1);
17232 Ptr.Designator.diagnosePointerArithmetic(Info, E, Index);
17240 LValue BytePtr = Ptr;
17241 for (
unsigned I = 0; I < ByteWidth; ++I) {
17245 unsigned Shift = 8 * (IsBE ? ByteWidth - I - 1 : I);
17246 ResultBits |= ByteVal.
getInt().getZExtValue() << Shift;
17247 if (I + 1 < ByteWidth)
17253 Result =
APSInt(APInt(ByteWidth * 8, ResultBits), !IsSigned);
17257bool IntExprEvaluator::VisitBuiltinCallExpr(
const CallExpr *E,
17258 unsigned BuiltinOp) {
17259 if (Info.Ctx.BuiltinInfo.isReflectionMetafunctionBuiltin(BuiltinOp)) {
17266 auto EvalTestOp = [&](llvm::function_ref<
bool(
const APInt &,
const APInt &)>
17268 APValue SourceLHS, SourceRHS;
17276 unsigned LaneWidth = Info.Ctx.getTypeSize(ElemQT);
17278 APInt AWide(LaneWidth * SourceLen, 0);
17279 APInt BWide(LaneWidth * SourceLen, 0);
17281 for (
unsigned I = 0; I != SourceLen; ++I) {
17284 if (ElemQT->isIntegerType()) {
17287 }
else if (ElemQT->isFloatingType()) {
17295 AWide.insertBits(ALane, I * LaneWidth);
17296 BWide.insertBits(BLane, I * LaneWidth);
17301 auto HandleMaskBinOp =
17314 auto HandleCRC32 = [&](
unsigned DataBytes) ->
bool {
17320 uint64_t CRCVal = CRC.getZExtValue();
17324 static const uint32_t CRC32C_POLY = 0x82F63B78;
17327 static_cast<uint32_t>(CRCVal), DataVal, DataBytes, CRC32C_POLY);
17332 switch (BuiltinOp) {
17336 case X86::BI__builtin_ia32_crc32qi:
17337 return HandleCRC32(1);
17338 case X86::BI__builtin_ia32_crc32hi:
17339 return HandleCRC32(2);
17340 case X86::BI__builtin_ia32_crc32si:
17341 return HandleCRC32(4);
17342 case X86::BI__builtin_ia32_crc32di:
17343 return HandleCRC32(8);
17345 case Builtin::BI__builtin_dynamic_object_size:
17346 case Builtin::BI__builtin_object_size: {
17350 if (TypeValue < 0 || TypeValue > 3) {
17351 Info.FFDiag(E->
getArg(1), diag::note_constexpr_builtin_arg_out_of_range)
17352 << TypeValue << 0 << 3;
17355 unsigned Type = TypeValue.getZExtValue();
17357 bool IsDynamic = BuiltinOp == Builtin::BI__builtin_dynamic_object_size;
17358 if (std::optional<uint64_t> Size =
17367 switch (Info.EvalMode) {
17368 case EvaluationMode::ConstantExpression:
17369 case EvaluationMode::ConstantFold:
17370 case EvaluationMode::IgnoreSideEffects:
17373 case EvaluationMode::ConstantExpressionUnevaluated:
17378 llvm_unreachable(
"unexpected EvalMode");
17381 case Builtin::BI__builtin_os_log_format_buffer_size: {
17382 analyze_os_log::OSLogBufferLayout Layout;
17387 case Builtin::BI__builtin_is_aligned: {
17395 Ptr.setFrom(Info.Ctx, Src);
17398 if (
Ptr.Offset.isZero())
17401 Info.FFDiag(E->
getArg(0), diag::note_constexpr_alignment_compute)
17413 assert(Alignment.isPowerOf2());
17426 Info.FFDiag(E->
getArg(0), diag::note_constexpr_alignment_compute)
17430 assert(Src.
isInt());
17431 return Success((Src.
getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
17433 case Builtin::BI__builtin_align_up: {
17441 APSInt((Src.
getInt() + (Alignment - 1)) & ~(Alignment - 1),
17442 Src.
getInt().isUnsigned());
17443 assert(AlignedVal.getBitWidth() == Src.
getInt().getBitWidth());
17444 return Success(AlignedVal, E);
17446 case Builtin::BI__builtin_align_down: {
17455 assert(AlignedVal.getBitWidth() == Src.
getInt().getBitWidth());
17456 return Success(AlignedVal, E);
17459 case Builtin::BI__builtin_bitreverseg:
17460 case Builtin::BI__builtin_bitreverse8:
17461 case Builtin::BI__builtin_bitreverse16:
17462 case Builtin::BI__builtin_bitreverse32:
17463 case Builtin::BI__builtin_bitreverse64:
17464 case Builtin::BI__builtin_elementwise_bitreverse: {
17469 return Success(Val.reverseBits(), E);
17471 case Builtin::BI__builtin_bswapg:
17472 case Builtin::BI__builtin_bswap16:
17473 case Builtin::BI__builtin_bswap32:
17474 case Builtin::BI__builtin_bswap64:
17475 case Builtin::BIstdc_memreverse8u8:
17476 case Builtin::BIstdc_memreverse8u16:
17477 case Builtin::BIstdc_memreverse8u32:
17478 case Builtin::BIstdc_memreverse8u64: {
17482 if (Val.getBitWidth() == 8 || Val.getBitWidth() == 1)
17485 return Success(Val.byteSwap(), E);
17488 case Builtin::BIstdc_load8_leu8:
17489 case Builtin::BIstdc_load8_leu16:
17490 case Builtin::BIstdc_load8_leu32:
17491 case Builtin::BIstdc_load8_leu64:
17492 case Builtin::BIstdc_load8_les8:
17493 case Builtin::BIstdc_load8_les16:
17494 case Builtin::BIstdc_load8_les32:
17495 case Builtin::BIstdc_load8_les64: {
17503 case Builtin::BIstdc_load8_aligned_leu8:
17504 case Builtin::BIstdc_load8_aligned_leu16:
17505 case Builtin::BIstdc_load8_aligned_leu32:
17506 case Builtin::BIstdc_load8_aligned_leu64:
17507 case Builtin::BIstdc_load8_aligned_les8:
17508 case Builtin::BIstdc_load8_aligned_les16:
17509 case Builtin::BIstdc_load8_aligned_les32:
17510 case Builtin::BIstdc_load8_aligned_les64: {
17517 case Builtin::BIstdc_load8_beu8:
17518 case Builtin::BIstdc_load8_beu16:
17519 case Builtin::BIstdc_load8_beu32:
17520 case Builtin::BIstdc_load8_beu64:
17521 case Builtin::BIstdc_load8_bes8:
17522 case Builtin::BIstdc_load8_bes16:
17523 case Builtin::BIstdc_load8_bes32:
17524 case Builtin::BIstdc_load8_bes64: {
17531 case Builtin::BIstdc_load8_aligned_beu8:
17532 case Builtin::BIstdc_load8_aligned_beu16:
17533 case Builtin::BIstdc_load8_aligned_beu32:
17534 case Builtin::BIstdc_load8_aligned_beu64:
17535 case Builtin::BIstdc_load8_aligned_bes8:
17536 case Builtin::BIstdc_load8_aligned_bes16:
17537 case Builtin::BIstdc_load8_aligned_bes32:
17538 case Builtin::BIstdc_load8_aligned_bes64: {
17545 case Builtin::BI__builtin_classify_type:
17548 case Builtin::BI__builtin_clrsb:
17549 case Builtin::BI__builtin_clrsbl:
17550 case Builtin::BI__builtin_clrsbll: {
17555 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
17558 case Builtin::BI__builtin_clz:
17559 case Builtin::BI__builtin_clzl:
17560 case Builtin::BI__builtin_clzll:
17561 case Builtin::BI__builtin_clzs:
17562 case Builtin::BI__builtin_clzg:
17563 case Builtin::BI__builtin_elementwise_clzg:
17564 case Builtin::BI__lzcnt16:
17565 case Builtin::BI__lzcnt:
17566 case Builtin::BI__lzcnt64: {
17577 std::optional<APSInt> Fallback;
17578 if ((BuiltinOp == Builtin::BI__builtin_clzg ||
17579 BuiltinOp == Builtin::BI__builtin_elementwise_clzg) &&
17584 Fallback = FallbackTemp;
17589 return Success(*Fallback, E);
17594 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
17595 BuiltinOp != Builtin::BI__lzcnt &&
17596 BuiltinOp != Builtin::BI__lzcnt64;
17598 if (BuiltinOp == Builtin::BI__builtin_elementwise_clzg) {
17599 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17603 if (ZeroIsUndefined)
17607 return Success(Val.countl_zero(), E);
17610 case Builtin::BI__builtin_constant_p: {
17611 const Expr *Arg = E->
getArg(0);
17620 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
17624 case Builtin::BI__noop:
17628 case Builtin::BI__builtin_is_constant_evaluated: {
17629 const auto *
Callee = Info.CurrentCall->getCallee();
17630 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
17631 (Info.CallStackDepth == 1 ||
17632 (Info.CallStackDepth == 2 &&
Callee->isInStdNamespace() &&
17633 Callee->getIdentifier() &&
17634 Callee->getIdentifier()->isStr(
"is_constant_evaluated")))) {
17636 if (Info.EvalStatus.Diag)
17637 Info.report((Info.CallStackDepth == 1)
17639 : Info.CurrentCall->getCallRange().getBegin(),
17640 diag::warn_is_constant_evaluated_always_true_constexpr)
17641 << (Info.CallStackDepth == 1 ?
"__builtin_is_constant_evaluated"
17642 :
"std::is_constant_evaluated");
17645 return Success(Info.InConstantContext, E);
17648 case Builtin::BI__builtin_is_within_lifetime:
17649 if (
auto result = EvaluateBuiltinIsWithinLifetime(*
this, E))
17653 case Builtin::BI__builtin_ctz:
17654 case Builtin::BI__builtin_ctzl:
17655 case Builtin::BI__builtin_ctzll:
17656 case Builtin::BI__builtin_ctzs:
17657 case Builtin::BI__builtin_ctzg:
17658 case Builtin::BI__builtin_elementwise_ctzg: {
17669 std::optional<APSInt> Fallback;
17670 if ((BuiltinOp == Builtin::BI__builtin_ctzg ||
17671 BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) &&
17676 Fallback = FallbackTemp;
17681 return Success(*Fallback, E);
17683 if (BuiltinOp == Builtin::BI__builtin_elementwise_ctzg) {
17684 Info.FFDiag(E, diag::note_constexpr_countzeroes_zero)
17690 return Success(Val.countr_zero(), E);
17693 case Builtin::BI__builtin_eh_return_data_regno: {
17695 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
17699 case Builtin::BI__builtin_elementwise_abs: {
17704 return Success(Val.abs(), E);
17707 case Builtin::BI__builtin_expect:
17708 case Builtin::BI__builtin_expect_with_probability:
17709 return Visit(E->
getArg(0));
17711 case Builtin::BI__builtin_ptrauth_string_discriminator: {
17718 case Builtin::BI__builtin_infer_alloc_token: {
17724 E, diag::note_constexpr_infer_alloc_token_type_inference_failed);
17727 return Error(E, diag::note_constexpr_infer_alloc_token_no_metadata);
17729 Info.getLangOpts().AllocTokenMode.value_or(llvm::DefaultAllocTokenMode);
17730 uint64_t BitWidth = Info.Ctx.getTypeSize(Info.Ctx.getSizeType());
17731 auto MaxTokensOpt = Info.getLangOpts().AllocTokenMax;
17733 MaxTokensOpt.value_or(0) ? *MaxTokensOpt : (~0ULL >> (64 - BitWidth));
17734 auto MaybeToken = llvm::getAllocToken(Mode, *ATMD, MaxTokens);
17736 return Error(E, diag::note_constexpr_infer_alloc_token_unsupported_mode);
17737 return Success(llvm::APInt(BitWidth, *MaybeToken), E);
17740 case Builtin::BI__builtin_ffs:
17741 case Builtin::BI__builtin_ffsl:
17742 case Builtin::BI__builtin_ffsll: {
17747 unsigned N = Val.countr_zero();
17748 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
17751 case Builtin::BI__builtin_fpclassify: {
17756 switch (Val.getCategory()) {
17757 case APFloat::fcNaN: Arg = 0;
break;
17758 case APFloat::fcInfinity: Arg = 1;
break;
17759 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2;
break;
17760 case APFloat::fcZero: Arg = 4;
break;
17762 return Visit(E->
getArg(Arg));
17765 case Builtin::BI__builtin_isinf_sign: {
17768 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
17771 case Builtin::BI__builtin_isinf: {
17774 Success(Val.isInfinity() ? 1 : 0, E);
17777 case Builtin::BI__builtin_isfinite: {
17780 Success(Val.isFinite() ? 1 : 0, E);
17783 case Builtin::BI__builtin_isnan: {
17786 Success(Val.isNaN() ? 1 : 0, E);
17789 case Builtin::BI__builtin_isnormal: {
17792 Success(Val.isNormal() ? 1 : 0, E);
17795 case Builtin::BI__builtin_issubnormal: {
17798 Success(Val.isDenormal() ? 1 : 0, E);
17801 case Builtin::BI__builtin_iszero: {
17804 Success(Val.isZero() ? 1 : 0, E);
17807 case Builtin::BI__builtin_signbit:
17808 case Builtin::BI__builtin_signbitf:
17809 case Builtin::BI__builtin_signbitl: {
17812 Success(Val.isNegative() ? 1 : 0, E);
17815 case Builtin::BI__builtin_isgreater:
17816 case Builtin::BI__builtin_isgreaterequal:
17817 case Builtin::BI__builtin_isless:
17818 case Builtin::BI__builtin_islessequal:
17819 case Builtin::BI__builtin_islessgreater:
17820 case Builtin::BI__builtin_isunordered: {
17829 switch (BuiltinOp) {
17830 case Builtin::BI__builtin_isgreater:
17832 case Builtin::BI__builtin_isgreaterequal:
17834 case Builtin::BI__builtin_isless:
17836 case Builtin::BI__builtin_islessequal:
17838 case Builtin::BI__builtin_islessgreater: {
17839 APFloat::cmpResult cmp = LHS.compare(RHS);
17840 return cmp == APFloat::cmpResult::cmpLessThan ||
17841 cmp == APFloat::cmpResult::cmpGreaterThan;
17843 case Builtin::BI__builtin_isunordered:
17844 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
17846 llvm_unreachable(
"Unexpected builtin ID: Should be a floating "
17847 "point comparison function");
17855 case Builtin::BI__builtin_issignaling: {
17858 Success(Val.isSignaling() ? 1 : 0, E);
17861 case Builtin::BI__builtin_isfpclass: {
17865 unsigned Test =
static_cast<llvm::FPClassTest
>(MaskVal.getZExtValue());
17868 Success((Val.classify() & Test) ? 1 : 0, E);
17871 case Builtin::BI__builtin_parity:
17872 case Builtin::BI__builtin_parityl:
17873 case Builtin::BI__builtin_parityll: {
17878 return Success(Val.popcount() % 2, E);
17881 case Builtin::BI__builtin_abs:
17882 case Builtin::BI__builtin_labs:
17883 case Builtin::BI__builtin_llabs: {
17887 if (Val ==
APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
17890 if (Val.isNegative())
17895 case Builtin::BI__builtin_popcount:
17896 case Builtin::BI__builtin_popcountl:
17897 case Builtin::BI__builtin_popcountll:
17898 case Builtin::BI__builtin_popcountg:
17899 case Builtin::BI__builtin_elementwise_popcount:
17900 case Builtin::BI__popcnt16:
17901 case Builtin::BI__popcnt:
17902 case Builtin::BI__popcnt64: {
17913 return Success(Val.popcount(), E);
17916 case Builtin::BI__builtin_rotateleft8:
17917 case Builtin::BI__builtin_rotateleft16:
17918 case Builtin::BI__builtin_rotateleft32:
17919 case Builtin::BI__builtin_rotateleft64:
17920 case Builtin::BI__builtin_rotateright8:
17921 case Builtin::BI__builtin_rotateright16:
17922 case Builtin::BI__builtin_rotateright32:
17923 case Builtin::BI__builtin_rotateright64:
17924 case Builtin::BI__builtin_stdc_rotate_left:
17925 case Builtin::BI__builtin_stdc_rotate_right:
17926 case Builtin::BIstdc_rotate_left_uc:
17927 case Builtin::BIstdc_rotate_left_us:
17928 case Builtin::BIstdc_rotate_left_ui:
17929 case Builtin::BIstdc_rotate_left_ul:
17930 case Builtin::BIstdc_rotate_left_ull:
17931 case Builtin::BIstdc_rotate_right_uc:
17932 case Builtin::BIstdc_rotate_right_us:
17933 case Builtin::BIstdc_rotate_right_ui:
17934 case Builtin::BIstdc_rotate_right_ul:
17935 case Builtin::BIstdc_rotate_right_ull:
17936 case Builtin::BI_rotl8:
17937 case Builtin::BI_rotl16:
17938 case Builtin::BI_rotl:
17939 case Builtin::BI_lrotl:
17940 case Builtin::BI_rotl64:
17941 case Builtin::BI_rotr8:
17942 case Builtin::BI_rotr16:
17943 case Builtin::BI_rotr:
17944 case Builtin::BI_lrotr:
17945 case Builtin::BI_rotr64: {
17953 switch (BuiltinOp) {
17954 case Builtin::BI__builtin_rotateright8:
17955 case Builtin::BI__builtin_rotateright16:
17956 case Builtin::BI__builtin_rotateright32:
17957 case Builtin::BI__builtin_rotateright64:
17958 case Builtin::BI__builtin_stdc_rotate_right:
17959 case Builtin::BIstdc_rotate_right_uc:
17960 case Builtin::BIstdc_rotate_right_us:
17961 case Builtin::BIstdc_rotate_right_ui:
17962 case Builtin::BIstdc_rotate_right_ul:
17963 case Builtin::BIstdc_rotate_right_ull:
17964 case Builtin::BI_rotr8:
17965 case Builtin::BI_rotr16:
17966 case Builtin::BI_rotr:
17967 case Builtin::BI_lrotr:
17968 case Builtin::BI_rotr64:
17977 case Builtin::BIstdc_leading_zeros_uc:
17978 case Builtin::BIstdc_leading_zeros_us:
17979 case Builtin::BIstdc_leading_zeros_ui:
17980 case Builtin::BIstdc_leading_zeros_ul:
17981 case Builtin::BIstdc_leading_zeros_ull:
17982 case Builtin::BIstdc_leading_ones_uc:
17983 case Builtin::BIstdc_leading_ones_us:
17984 case Builtin::BIstdc_leading_ones_ui:
17985 case Builtin::BIstdc_leading_ones_ul:
17986 case Builtin::BIstdc_leading_ones_ull:
17987 case Builtin::BIstdc_trailing_zeros_uc:
17988 case Builtin::BIstdc_trailing_zeros_us:
17989 case Builtin::BIstdc_trailing_zeros_ui:
17990 case Builtin::BIstdc_trailing_zeros_ul:
17991 case Builtin::BIstdc_trailing_zeros_ull:
17992 case Builtin::BIstdc_trailing_ones_uc:
17993 case Builtin::BIstdc_trailing_ones_us:
17994 case Builtin::BIstdc_trailing_ones_ui:
17995 case Builtin::BIstdc_trailing_ones_ul:
17996 case Builtin::BIstdc_trailing_ones_ull:
17997 case Builtin::BIstdc_first_leading_zero_uc:
17998 case Builtin::BIstdc_first_leading_zero_us:
17999 case Builtin::BIstdc_first_leading_zero_ui:
18000 case Builtin::BIstdc_first_leading_zero_ul:
18001 case Builtin::BIstdc_first_leading_zero_ull:
18002 case Builtin::BIstdc_first_leading_one_uc:
18003 case Builtin::BIstdc_first_leading_one_us:
18004 case Builtin::BIstdc_first_leading_one_ui:
18005 case Builtin::BIstdc_first_leading_one_ul:
18006 case Builtin::BIstdc_first_leading_one_ull:
18007 case Builtin::BIstdc_first_trailing_zero_uc:
18008 case Builtin::BIstdc_first_trailing_zero_us:
18009 case Builtin::BIstdc_first_trailing_zero_ui:
18010 case Builtin::BIstdc_first_trailing_zero_ul:
18011 case Builtin::BIstdc_first_trailing_zero_ull:
18012 case Builtin::BIstdc_first_trailing_one_uc:
18013 case Builtin::BIstdc_first_trailing_one_us:
18014 case Builtin::BIstdc_first_trailing_one_ui:
18015 case Builtin::BIstdc_first_trailing_one_ul:
18016 case Builtin::BIstdc_first_trailing_one_ull:
18017 case Builtin::BIstdc_count_zeros_uc:
18018 case Builtin::BIstdc_count_zeros_us:
18019 case Builtin::BIstdc_count_zeros_ui:
18020 case Builtin::BIstdc_count_zeros_ul:
18021 case Builtin::BIstdc_count_zeros_ull:
18022 case Builtin::BIstdc_count_ones_uc:
18023 case Builtin::BIstdc_count_ones_us:
18024 case Builtin::BIstdc_count_ones_ui:
18025 case Builtin::BIstdc_count_ones_ul:
18026 case Builtin::BIstdc_count_ones_ull:
18027 case Builtin::BIstdc_has_single_bit_uc:
18028 case Builtin::BIstdc_has_single_bit_us:
18029 case Builtin::BIstdc_has_single_bit_ui:
18030 case Builtin::BIstdc_has_single_bit_ul:
18031 case Builtin::BIstdc_has_single_bit_ull:
18032 case Builtin::BIstdc_bit_width_uc:
18033 case Builtin::BIstdc_bit_width_us:
18034 case Builtin::BIstdc_bit_width_ui:
18035 case Builtin::BIstdc_bit_width_ul:
18036 case Builtin::BIstdc_bit_width_ull:
18037 case Builtin::BIstdc_bit_floor_uc:
18038 case Builtin::BIstdc_bit_floor_us:
18039 case Builtin::BIstdc_bit_floor_ui:
18040 case Builtin::BIstdc_bit_floor_ul:
18041 case Builtin::BIstdc_bit_floor_ull:
18042 case Builtin::BIstdc_bit_ceil_uc:
18043 case Builtin::BIstdc_bit_ceil_us:
18044 case Builtin::BIstdc_bit_ceil_ui:
18045 case Builtin::BIstdc_bit_ceil_ul:
18046 case Builtin::BIstdc_bit_ceil_ull:
18047 case Builtin::BI__builtin_stdc_leading_zeros:
18048 case Builtin::BI__builtin_stdc_leading_ones:
18049 case Builtin::BI__builtin_stdc_trailing_zeros:
18050 case Builtin::BI__builtin_stdc_trailing_ones:
18051 case Builtin::BI__builtin_stdc_first_leading_zero:
18052 case Builtin::BI__builtin_stdc_first_leading_one:
18053 case Builtin::BI__builtin_stdc_first_trailing_zero:
18054 case Builtin::BI__builtin_stdc_first_trailing_one:
18055 case Builtin::BI__builtin_stdc_count_zeros:
18056 case Builtin::BI__builtin_stdc_count_ones:
18057 case Builtin::BI__builtin_stdc_has_single_bit:
18058 case Builtin::BI__builtin_stdc_bit_width:
18059 case Builtin::BI__builtin_stdc_bit_floor:
18060 case Builtin::BI__builtin_stdc_bit_ceil: {
18065 unsigned BitWidth = Val.getBitWidth();
18066 const unsigned ResBitWidth = Info.Ctx.getIntWidth(E->
getType());
18068 switch (BuiltinOp) {
18069 case Builtin::BIstdc_leading_zeros_uc:
18070 case Builtin::BIstdc_leading_zeros_us:
18071 case Builtin::BIstdc_leading_zeros_ui:
18072 case Builtin::BIstdc_leading_zeros_ul:
18073 case Builtin::BIstdc_leading_zeros_ull:
18074 case Builtin::BI__builtin_stdc_leading_zeros:
18075 return Success(
APInt(ResBitWidth, Val.countl_zero()), E);
18076 case Builtin::BIstdc_leading_ones_uc:
18077 case Builtin::BIstdc_leading_ones_us:
18078 case Builtin::BIstdc_leading_ones_ui:
18079 case Builtin::BIstdc_leading_ones_ul:
18080 case Builtin::BIstdc_leading_ones_ull:
18081 case Builtin::BI__builtin_stdc_leading_ones:
18082 return Success(
APInt(ResBitWidth, Val.countl_one()), E);
18083 case Builtin::BIstdc_trailing_zeros_uc:
18084 case Builtin::BIstdc_trailing_zeros_us:
18085 case Builtin::BIstdc_trailing_zeros_ui:
18086 case Builtin::BIstdc_trailing_zeros_ul:
18087 case Builtin::BIstdc_trailing_zeros_ull:
18088 case Builtin::BI__builtin_stdc_trailing_zeros:
18089 return Success(
APInt(ResBitWidth, Val.countr_zero()), E);
18090 case Builtin::BIstdc_trailing_ones_uc:
18091 case Builtin::BIstdc_trailing_ones_us:
18092 case Builtin::BIstdc_trailing_ones_ui:
18093 case Builtin::BIstdc_trailing_ones_ul:
18094 case Builtin::BIstdc_trailing_ones_ull:
18095 case Builtin::BI__builtin_stdc_trailing_ones:
18096 return Success(
APInt(ResBitWidth, Val.countr_one()), E);
18097 case Builtin::BIstdc_first_leading_zero_uc:
18098 case Builtin::BIstdc_first_leading_zero_us:
18099 case Builtin::BIstdc_first_leading_zero_ui:
18100 case Builtin::BIstdc_first_leading_zero_ul:
18101 case Builtin::BIstdc_first_leading_zero_ull:
18102 case Builtin::BI__builtin_stdc_first_leading_zero:
18104 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countl_one() + 1), E);
18105 case Builtin::BIstdc_first_leading_one_uc:
18106 case Builtin::BIstdc_first_leading_one_us:
18107 case Builtin::BIstdc_first_leading_one_ui:
18108 case Builtin::BIstdc_first_leading_one_ul:
18109 case Builtin::BIstdc_first_leading_one_ull:
18110 case Builtin::BI__builtin_stdc_first_leading_one:
18112 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countl_zero() + 1), E);
18113 case Builtin::BIstdc_first_trailing_zero_uc:
18114 case Builtin::BIstdc_first_trailing_zero_us:
18115 case Builtin::BIstdc_first_trailing_zero_ui:
18116 case Builtin::BIstdc_first_trailing_zero_ul:
18117 case Builtin::BIstdc_first_trailing_zero_ull:
18118 case Builtin::BI__builtin_stdc_first_trailing_zero:
18120 APInt(ResBitWidth, Val.isAllOnes() ? 0 : Val.countr_one() + 1), E);
18121 case Builtin::BIstdc_first_trailing_one_uc:
18122 case Builtin::BIstdc_first_trailing_one_us:
18123 case Builtin::BIstdc_first_trailing_one_ui:
18124 case Builtin::BIstdc_first_trailing_one_ul:
18125 case Builtin::BIstdc_first_trailing_one_ull:
18126 case Builtin::BI__builtin_stdc_first_trailing_one:
18128 APInt(ResBitWidth, Val.isZero() ? 0 : Val.countr_zero() + 1), E);
18129 case Builtin::BIstdc_count_zeros_uc:
18130 case Builtin::BIstdc_count_zeros_us:
18131 case Builtin::BIstdc_count_zeros_ui:
18132 case Builtin::BIstdc_count_zeros_ul:
18133 case Builtin::BIstdc_count_zeros_ull:
18134 case Builtin::BI__builtin_stdc_count_zeros: {
18135 APInt Cnt(ResBitWidth, BitWidth - Val.popcount());
18138 case Builtin::BIstdc_count_ones_uc:
18139 case Builtin::BIstdc_count_ones_us:
18140 case Builtin::BIstdc_count_ones_ui:
18141 case Builtin::BIstdc_count_ones_ul:
18142 case Builtin::BIstdc_count_ones_ull:
18143 case Builtin::BI__builtin_stdc_count_ones: {
18144 APInt Cnt(ResBitWidth, Val.popcount());
18147 case Builtin::BIstdc_has_single_bit_uc:
18148 case Builtin::BIstdc_has_single_bit_us:
18149 case Builtin::BIstdc_has_single_bit_ui:
18150 case Builtin::BIstdc_has_single_bit_ul:
18151 case Builtin::BIstdc_has_single_bit_ull:
18152 case Builtin::BI__builtin_stdc_has_single_bit: {
18153 APInt Res(ResBitWidth, Val.popcount() == 1 ? 1 : 0);
18156 case Builtin::BIstdc_bit_width_uc:
18157 case Builtin::BIstdc_bit_width_us:
18158 case Builtin::BIstdc_bit_width_ui:
18159 case Builtin::BIstdc_bit_width_ul:
18160 case Builtin::BIstdc_bit_width_ull:
18161 case Builtin::BI__builtin_stdc_bit_width:
18162 return Success(
APInt(ResBitWidth, BitWidth - Val.countl_zero()), E);
18163 case Builtin::BIstdc_bit_floor_uc:
18164 case Builtin::BIstdc_bit_floor_us:
18165 case Builtin::BIstdc_bit_floor_ui:
18166 case Builtin::BIstdc_bit_floor_ul:
18167 case Builtin::BIstdc_bit_floor_ull:
18168 case Builtin::BI__builtin_stdc_bit_floor: {
18171 unsigned Exp = BitWidth - Val.countl_zero() - 1;
18173 APSInt(APInt::getOneBitSet(BitWidth, Exp),
true), E);
18175 case Builtin::BIstdc_bit_ceil_uc:
18176 case Builtin::BIstdc_bit_ceil_us:
18177 case Builtin::BIstdc_bit_ceil_ui:
18178 case Builtin::BIstdc_bit_ceil_ul:
18179 case Builtin::BIstdc_bit_ceil_ull:
18180 case Builtin::BI__builtin_stdc_bit_ceil: {
18183 APInt ValMinusOne = Val - 1;
18184 unsigned LZ = ValMinusOne.countl_zero();
18188 APInt Result = APInt::getOneBitSet(BitWidth, BitWidth - LZ);
18192 llvm_unreachable(
"Unknown stdc builtin");
18196 case Builtin::BI__builtin_elementwise_add_sat: {
18202 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
18205 case Builtin::BI__builtin_elementwise_sub_sat: {
18211 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
18214 case Builtin::BI__builtin_elementwise_max: {
18223 case Builtin::BI__builtin_elementwise_min: {
18232 case Builtin::BI__builtin_elementwise_clmul: {
18241 case Builtin::BI__builtin_elementwise_fshl:
18242 case Builtin::BI__builtin_elementwise_fshr: {
18249 switch (BuiltinOp) {
18250 case Builtin::BI__builtin_elementwise_fshl: {
18251 APSInt Result(llvm::APIntOps::fshl(Hi, Lo, Shift), Hi.isUnsigned());
18254 case Builtin::BI__builtin_elementwise_fshr: {
18255 APSInt Result(llvm::APIntOps::fshr(Hi, Lo, Shift), Hi.isUnsigned());
18259 llvm_unreachable(
"Fully covered switch above");
18261 case Builtin::BIstrlen:
18262 case Builtin::BIwcslen:
18264 if (Info.getLangOpts().CPlusPlus11)
18265 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
18267 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
18269 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
18271 case Builtin::BI__builtin_strlen:
18272 case Builtin::BI__builtin_wcslen: {
18275 if (std::optional<uint64_t> StrLen =
18281 case Builtin::BIstrcmp:
18282 case Builtin::BIwcscmp:
18283 case Builtin::BIstrncmp:
18284 case Builtin::BIwcsncmp:
18285 case Builtin::BImemcmp:
18286 case Builtin::BIbcmp:
18287 case Builtin::BIwmemcmp:
18289 if (Info.getLangOpts().CPlusPlus11)
18290 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
18292 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
18294 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
18296 case Builtin::BI__builtin_strcmp:
18297 case Builtin::BI__builtin_wcscmp:
18298 case Builtin::BI__builtin_strncmp:
18299 case Builtin::BI__builtin_wcsncmp:
18300 case Builtin::BI__builtin_memcmp:
18301 case Builtin::BI__builtin_bcmp:
18302 case Builtin::BI__builtin_wmemcmp: {
18303 LValue String1, String2;
18309 if (BuiltinOp != Builtin::BIstrcmp &&
18310 BuiltinOp != Builtin::BIwcscmp &&
18311 BuiltinOp != Builtin::BI__builtin_strcmp &&
18312 BuiltinOp != Builtin::BI__builtin_wcscmp) {
18316 MaxLength = N.getZExtValue();
18320 if (MaxLength == 0u)
18323 if (!String1.checkNullPointerForFoldAccess(Info, E,
AK_Read) ||
18324 !String2.checkNullPointerForFoldAccess(Info, E,
AK_Read) ||
18325 String1.Designator.Invalid || String2.Designator.Invalid)
18328 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
18329 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
18331 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
18332 BuiltinOp == Builtin::BIbcmp ||
18333 BuiltinOp == Builtin::BI__builtin_memcmp ||
18334 BuiltinOp == Builtin::BI__builtin_bcmp;
18336 assert(IsRawByte ||
18337 (Info.Ctx.hasSameUnqualifiedType(
18339 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
18346 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
18347 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
18352 const auto &ReadCurElems = [&](
APValue &Char1,
APValue &Char2) {
18355 Char1.
isInt() && Char2.isInt();
18357 const auto &AdvanceElems = [&] {
18363 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
18364 BuiltinOp != Builtin::BIwmemcmp &&
18365 BuiltinOp != Builtin::BI__builtin_memcmp &&
18366 BuiltinOp != Builtin::BI__builtin_bcmp &&
18367 BuiltinOp != Builtin::BI__builtin_wmemcmp);
18368 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
18369 BuiltinOp == Builtin::BIwcsncmp ||
18370 BuiltinOp == Builtin::BIwmemcmp ||
18371 BuiltinOp == Builtin::BI__builtin_wcscmp ||
18372 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
18373 BuiltinOp == Builtin::BI__builtin_wmemcmp;
18375 for (; MaxLength; --MaxLength) {
18377 if (!ReadCurElems(Char1, Char2))
18385 if (StopAtNull && !Char1.
getInt())
18387 assert(!(StopAtNull && !Char2.
getInt()));
18388 if (!AdvanceElems())
18395 case Builtin::BI__atomic_always_lock_free:
18396 case Builtin::BI__atomic_is_lock_free:
18397 case Builtin::BI__c11_atomic_is_lock_free: {
18413 if (
Size.isPowerOfTwo()) {
18415 unsigned InlineWidthBits =
18416 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
18417 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
18418 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
18424 const Expr *PtrArg = E->
getArg(1);
18430 IntResult.isAligned(
Size.getAsAlign()))
18434 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
18437 if (ICE->getCastKind() == CK_BitCast)
18438 PtrArg = ICE->getSubExpr();
18441 if (
auto PtrTy = PtrArg->
getType()->
getAs<PointerType>()) {
18444 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
18452 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
18455 case Builtin::BI__builtin_addcb:
18456 case Builtin::BI__builtin_addcs:
18457 case Builtin::BI__builtin_addc:
18458 case Builtin::BI__builtin_addcl:
18459 case Builtin::BI__builtin_addcll:
18460 case Builtin::BI__builtin_subcb:
18461 case Builtin::BI__builtin_subcs:
18462 case Builtin::BI__builtin_subc:
18463 case Builtin::BI__builtin_subcl:
18464 case Builtin::BI__builtin_subcll: {
18465 LValue CarryOutLValue;
18477 bool FirstOverflowed =
false;
18478 bool SecondOverflowed =
false;
18479 switch (BuiltinOp) {
18481 llvm_unreachable(
"Invalid value for BuiltinOp");
18482 case Builtin::BI__builtin_addcb:
18483 case Builtin::BI__builtin_addcs:
18484 case Builtin::BI__builtin_addc:
18485 case Builtin::BI__builtin_addcl:
18486 case Builtin::BI__builtin_addcll:
18488 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
18490 case Builtin::BI__builtin_subcb:
18491 case Builtin::BI__builtin_subcs:
18492 case Builtin::BI__builtin_subc:
18493 case Builtin::BI__builtin_subcl:
18494 case Builtin::BI__builtin_subcll:
18496 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
18502 CarryOut = (
uint64_t)(FirstOverflowed | SecondOverflowed);
18508 case Builtin::BI__builtin_add_overflow:
18509 case Builtin::BI__builtin_sub_overflow:
18510 case Builtin::BI__builtin_mul_overflow:
18511 case Builtin::BI__builtin_sadd_overflow:
18512 case Builtin::BI__builtin_uadd_overflow:
18513 case Builtin::BI__builtin_uaddl_overflow:
18514 case Builtin::BI__builtin_uaddll_overflow:
18515 case Builtin::BI__builtin_usub_overflow:
18516 case Builtin::BI__builtin_usubl_overflow:
18517 case Builtin::BI__builtin_usubll_overflow:
18518 case Builtin::BI__builtin_umul_overflow:
18519 case Builtin::BI__builtin_umull_overflow:
18520 case Builtin::BI__builtin_umulll_overflow:
18521 case Builtin::BI__builtin_saddl_overflow:
18522 case Builtin::BI__builtin_saddll_overflow:
18523 case Builtin::BI__builtin_ssub_overflow:
18524 case Builtin::BI__builtin_ssubl_overflow:
18525 case Builtin::BI__builtin_ssubll_overflow:
18526 case Builtin::BI__builtin_smul_overflow:
18527 case Builtin::BI__builtin_smull_overflow:
18528 case Builtin::BI__builtin_smulll_overflow: {
18529 LValue ResultLValue;
18539 bool DidOverflow =
false;
18542 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18543 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18544 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18545 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
18547 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
18549 uint64_t LHSSize = LHS.getBitWidth();
18550 uint64_t RHSSize = RHS.getBitWidth();
18551 uint64_t ResultSize = Info.Ctx.getIntWidth(ResultType);
18552 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
18558 if (IsSigned && !AllSigned)
18561 LHS =
APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
18562 RHS =
APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
18567 switch (BuiltinOp) {
18569 llvm_unreachable(
"Invalid value for BuiltinOp");
18570 case Builtin::BI__builtin_add_overflow:
18571 case Builtin::BI__builtin_sadd_overflow:
18572 case Builtin::BI__builtin_saddl_overflow:
18573 case Builtin::BI__builtin_saddll_overflow:
18574 case Builtin::BI__builtin_uadd_overflow:
18575 case Builtin::BI__builtin_uaddl_overflow:
18576 case Builtin::BI__builtin_uaddll_overflow:
18577 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
18578 : LHS.uadd_ov(RHS, DidOverflow);
18580 case Builtin::BI__builtin_sub_overflow:
18581 case Builtin::BI__builtin_ssub_overflow:
18582 case Builtin::BI__builtin_ssubl_overflow:
18583 case Builtin::BI__builtin_ssubll_overflow:
18584 case Builtin::BI__builtin_usub_overflow:
18585 case Builtin::BI__builtin_usubl_overflow:
18586 case Builtin::BI__builtin_usubll_overflow:
18587 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
18588 : LHS.usub_ov(RHS, DidOverflow);
18590 case Builtin::BI__builtin_mul_overflow:
18591 case Builtin::BI__builtin_smul_overflow:
18592 case Builtin::BI__builtin_smull_overflow:
18593 case Builtin::BI__builtin_smulll_overflow:
18594 case Builtin::BI__builtin_umul_overflow:
18595 case Builtin::BI__builtin_umull_overflow:
18596 case Builtin::BI__builtin_umulll_overflow:
18597 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
18598 : LHS.umul_ov(RHS, DidOverflow);
18607 APSInt Temp =
Result.extOrTrunc(Info.Ctx.getIntWidth(ResultType));
18612 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
18613 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
18614 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
18615 if (!APSInt::isSameValue(Temp,
Result))
18616 DidOverflow =
true;
18623 return Success(DidOverflow, E);
18626 case Builtin::BI__builtin_reduce_add:
18627 case Builtin::BI__builtin_reduce_mul:
18628 case Builtin::BI__builtin_reduce_and:
18629 case Builtin::BI__builtin_reduce_or:
18630 case Builtin::BI__builtin_reduce_xor:
18631 case Builtin::BI__builtin_reduce_min:
18632 case Builtin::BI__builtin_reduce_max: {
18639 for (
unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
18640 switch (BuiltinOp) {
18643 case Builtin::BI__builtin_reduce_add: {
18646 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
18650 case Builtin::BI__builtin_reduce_mul: {
18653 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
18657 case Builtin::BI__builtin_reduce_and: {
18661 case Builtin::BI__builtin_reduce_or: {
18665 case Builtin::BI__builtin_reduce_xor: {
18669 case Builtin::BI__builtin_reduce_min: {
18673 case Builtin::BI__builtin_reduce_max: {
18683 case clang::X86::BI__builtin_ia32_addcarryx_u32:
18684 case clang::X86::BI__builtin_ia32_addcarryx_u64:
18685 case clang::X86::BI__builtin_ia32_subborrow_u32:
18686 case clang::X86::BI__builtin_ia32_subborrow_u64: {
18687 LValue ResultLValue;
18688 APSInt CarryIn, LHS, RHS;
18696 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
18697 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
18699 unsigned BitWidth = LHS.getBitWidth();
18700 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
18703 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
18704 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
18706 APInt Result = ExResult.extractBits(BitWidth, 0);
18707 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
18715 case clang::X86::BI__builtin_ia32_movmskps:
18716 case clang::X86::BI__builtin_ia32_movmskpd:
18717 case clang::X86::BI__builtin_ia32_pmovmskb128:
18718 case clang::X86::BI__builtin_ia32_pmovmskb256:
18719 case clang::X86::BI__builtin_ia32_movmskps256:
18720 case clang::X86::BI__builtin_ia32_movmskpd256: {
18727 unsigned ResultLen = Info.Ctx.getTypeSize(
18731 for (
unsigned I = 0; I != SourceLen; ++I) {
18733 if (ElemQT->isIntegerType()) {
18735 }
else if (ElemQT->isRealFloatingType()) {
18740 Result.setBitVal(I, Elem.isNegative());
18745 case clang::X86::BI__builtin_ia32_bextr_u32:
18746 case clang::X86::BI__builtin_ia32_bextr_u64:
18747 case clang::X86::BI__builtin_ia32_bextri_u32:
18748 case clang::X86::BI__builtin_ia32_bextri_u64: {
18754 unsigned BitWidth = Val.getBitWidth();
18756 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
18757 Length = Length > BitWidth ? BitWidth : Length;
18760 if (Length == 0 || Shift >= BitWidth)
18764 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
18768 case clang::X86::BI__builtin_ia32_bzhi_si:
18769 case clang::X86::BI__builtin_ia32_bzhi_di: {
18775 unsigned BitWidth = Val.getBitWidth();
18776 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
18777 if (Index < BitWidth)
18778 Val.clearHighBits(BitWidth - Index);
18782 case clang::X86::BI__builtin_ia32_ktestcqi:
18783 case clang::X86::BI__builtin_ia32_ktestchi:
18784 case clang::X86::BI__builtin_ia32_ktestcsi:
18785 case clang::X86::BI__builtin_ia32_ktestcdi: {
18791 return Success((~A & B) == 0, E);
18794 case clang::X86::BI__builtin_ia32_ktestzqi:
18795 case clang::X86::BI__builtin_ia32_ktestzhi:
18796 case clang::X86::BI__builtin_ia32_ktestzsi:
18797 case clang::X86::BI__builtin_ia32_ktestzdi: {
18803 return Success((A & B) == 0, E);
18806 case clang::X86::BI__builtin_ia32_kortestcqi:
18807 case clang::X86::BI__builtin_ia32_kortestchi:
18808 case clang::X86::BI__builtin_ia32_kortestcsi:
18809 case clang::X86::BI__builtin_ia32_kortestcdi: {
18815 return Success(~(A | B) == 0, E);
18818 case clang::X86::BI__builtin_ia32_kortestzqi:
18819 case clang::X86::BI__builtin_ia32_kortestzhi:
18820 case clang::X86::BI__builtin_ia32_kortestzsi:
18821 case clang::X86::BI__builtin_ia32_kortestzdi: {
18827 return Success((A | B) == 0, E);
18830 case clang::X86::BI__builtin_ia32_kunpckhi:
18831 case clang::X86::BI__builtin_ia32_kunpckdi:
18832 case clang::X86::BI__builtin_ia32_kunpcksi: {
18840 unsigned BW = A.getBitWidth();
18841 APSInt Result(A.trunc(BW / 2).concat(B.trunc(BW / 2)), A.isUnsigned());
18845 case clang::X86::BI__builtin_ia32_lzcnt_u16:
18846 case clang::X86::BI__builtin_ia32_lzcnt_u32:
18847 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
18851 return Success(Val.countLeadingZeros(), E);
18854 case clang::X86::BI__builtin_ia32_tzcnt_u16:
18855 case clang::X86::BI__builtin_ia32_tzcnt_u32:
18856 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
18860 return Success(Val.countTrailingZeros(), E);
18863 case Builtin::BI__builtin_elementwise_pdep: {
18868 return Success(llvm::APIntOps::pdep(Val, Msk), E);
18871 case Builtin::BI__builtin_elementwise_pext: {
18876 return Success(llvm::APIntOps::pext(Val, Msk), E);
18879 case X86::BI__builtin_ia32_ptestz128:
18880 case X86::BI__builtin_ia32_ptestz256:
18881 case X86::BI__builtin_ia32_vtestzps:
18882 case X86::BI__builtin_ia32_vtestzps256:
18883 case X86::BI__builtin_ia32_vtestzpd:
18884 case X86::BI__builtin_ia32_vtestzpd256: {
18886 [](
const APInt &A,
const APInt &B) {
return (A & B) == 0; });
18888 case X86::BI__builtin_ia32_ptestc128:
18889 case X86::BI__builtin_ia32_ptestc256:
18890 case X86::BI__builtin_ia32_vtestcps:
18891 case X86::BI__builtin_ia32_vtestcps256:
18892 case X86::BI__builtin_ia32_vtestcpd:
18893 case X86::BI__builtin_ia32_vtestcpd256: {
18895 [](
const APInt &A,
const APInt &B) {
return (~A & B) == 0; });
18897 case X86::BI__builtin_ia32_ptestnzc128:
18898 case X86::BI__builtin_ia32_ptestnzc256:
18899 case X86::BI__builtin_ia32_vtestnzcps:
18900 case X86::BI__builtin_ia32_vtestnzcps256:
18901 case X86::BI__builtin_ia32_vtestnzcpd:
18902 case X86::BI__builtin_ia32_vtestnzcpd256: {
18903 return EvalTestOp([](
const APInt &A,
const APInt &B) {
18904 return ((A & B) != 0) && ((~A & B) != 0);
18907 case X86::BI__builtin_ia32_kandqi:
18908 case X86::BI__builtin_ia32_kandhi:
18909 case X86::BI__builtin_ia32_kandsi:
18910 case X86::BI__builtin_ia32_kanddi: {
18911 return HandleMaskBinOp(
18912 [](
const APSInt &LHS,
const APSInt &RHS) {
return LHS & RHS; });
18915 case X86::BI__builtin_ia32_kandnqi:
18916 case X86::BI__builtin_ia32_kandnhi:
18917 case X86::BI__builtin_ia32_kandnsi:
18918 case X86::BI__builtin_ia32_kandndi: {
18919 return HandleMaskBinOp(
18920 [](
const APSInt &LHS,
const APSInt &RHS) {
return ~LHS & RHS; });
18923 case X86::BI__builtin_ia32_korqi:
18924 case X86::BI__builtin_ia32_korhi:
18925 case X86::BI__builtin_ia32_korsi:
18926 case X86::BI__builtin_ia32_kordi: {
18927 return HandleMaskBinOp(
18928 [](
const APSInt &LHS,
const APSInt &RHS) {
return LHS | RHS; });
18931 case X86::BI__builtin_ia32_kxnorqi:
18932 case X86::BI__builtin_ia32_kxnorhi:
18933 case X86::BI__builtin_ia32_kxnorsi:
18934 case X86::BI__builtin_ia32_kxnordi: {
18935 return HandleMaskBinOp(
18936 [](
const APSInt &LHS,
const APSInt &RHS) {
return ~(LHS ^ RHS); });
18939 case X86::BI__builtin_ia32_kxorqi:
18940 case X86::BI__builtin_ia32_kxorhi:
18941 case X86::BI__builtin_ia32_kxorsi:
18942 case X86::BI__builtin_ia32_kxordi: {
18943 return HandleMaskBinOp(
18944 [](
const APSInt &LHS,
const APSInt &RHS) {
return LHS ^ RHS; });
18947 case X86::BI__builtin_ia32_knotqi:
18948 case X86::BI__builtin_ia32_knothi:
18949 case X86::BI__builtin_ia32_knotsi:
18950 case X86::BI__builtin_ia32_knotdi: {
18958 case X86::BI__builtin_ia32_kaddqi:
18959 case X86::BI__builtin_ia32_kaddhi:
18960 case X86::BI__builtin_ia32_kaddsi:
18961 case X86::BI__builtin_ia32_kadddi: {
18962 return HandleMaskBinOp(
18963 [](
const APSInt &LHS,
const APSInt &RHS) {
return LHS + RHS; });
18966 case X86::BI__builtin_ia32_kmovb:
18967 case X86::BI__builtin_ia32_kmovw:
18968 case X86::BI__builtin_ia32_kmovd:
18969 case X86::BI__builtin_ia32_kmovq: {
18976 case X86::BI__builtin_ia32_kshiftliqi:
18977 case X86::BI__builtin_ia32_kshiftlihi:
18978 case X86::BI__builtin_ia32_kshiftlisi:
18979 case X86::BI__builtin_ia32_kshiftlidi: {
18980 return HandleMaskBinOp([](
const APSInt &LHS,
const APSInt &RHS) {
18981 unsigned Amt = RHS.getZExtValue() & 0xFF;
18982 if (Amt >= LHS.getBitWidth())
18983 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18984 return APSInt(LHS.shl(Amt), LHS.isUnsigned());
18988 case X86::BI__builtin_ia32_kshiftriqi:
18989 case X86::BI__builtin_ia32_kshiftrihi:
18990 case X86::BI__builtin_ia32_kshiftrisi:
18991 case X86::BI__builtin_ia32_kshiftridi: {
18992 return HandleMaskBinOp([](
const APSInt &LHS,
const APSInt &RHS) {
18993 unsigned Amt = RHS.getZExtValue() & 0xFF;
18994 if (Amt >= LHS.getBitWidth())
18995 return APSInt(APInt::getZero(LHS.getBitWidth()), LHS.isUnsigned());
18996 return APSInt(LHS.lshr(Amt), LHS.isUnsigned());
19000 case clang::X86::BI__builtin_ia32_vec_ext_v4hi:
19001 case clang::X86::BI__builtin_ia32_vec_ext_v16qi:
19002 case clang::X86::BI__builtin_ia32_vec_ext_v8hi:
19003 case clang::X86::BI__builtin_ia32_vec_ext_v4si:
19004 case clang::X86::BI__builtin_ia32_vec_ext_v2di:
19005 case clang::X86::BI__builtin_ia32_vec_ext_v32qi:
19006 case clang::X86::BI__builtin_ia32_vec_ext_v16hi:
19007 case clang::X86::BI__builtin_ia32_vec_ext_v8si:
19008 case clang::X86::BI__builtin_ia32_vec_ext_v4di: {
19015 unsigned Idx =
static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
19019 case clang::X86::BI__builtin_ia32_cvtb2mask128:
19020 case clang::X86::BI__builtin_ia32_cvtb2mask256:
19021 case clang::X86::BI__builtin_ia32_cvtb2mask512:
19022 case clang::X86::BI__builtin_ia32_cvtw2mask128:
19023 case clang::X86::BI__builtin_ia32_cvtw2mask256:
19024 case clang::X86::BI__builtin_ia32_cvtw2mask512:
19025 case clang::X86::BI__builtin_ia32_cvtd2mask128:
19026 case clang::X86::BI__builtin_ia32_cvtd2mask256:
19027 case clang::X86::BI__builtin_ia32_cvtd2mask512:
19028 case clang::X86::BI__builtin_ia32_cvtq2mask128:
19029 case clang::X86::BI__builtin_ia32_cvtq2mask256:
19030 case clang::X86::BI__builtin_ia32_cvtq2mask512: {
19037 unsigned RetWidth = Info.Ctx.getIntWidth(E->
getType());
19038 llvm::APInt Bits(RetWidth, 0);
19040 for (
unsigned ElemNum = 0; ElemNum != VectorLen; ++ElemNum) {
19042 unsigned MSB = A[A.getBitWidth() - 1];
19043 Bits.setBitVal(ElemNum, MSB);
19046 APSInt RetMask(Bits,
true);
19050 case clang::X86::BI__builtin_ia32_cmpb128_mask:
19051 case clang::X86::BI__builtin_ia32_cmpw128_mask:
19052 case clang::X86::BI__builtin_ia32_cmpd128_mask:
19053 case clang::X86::BI__builtin_ia32_cmpq128_mask:
19054 case clang::X86::BI__builtin_ia32_cmpb256_mask:
19055 case clang::X86::BI__builtin_ia32_cmpw256_mask:
19056 case clang::X86::BI__builtin_ia32_cmpd256_mask:
19057 case clang::X86::BI__builtin_ia32_cmpq256_mask:
19058 case clang::X86::BI__builtin_ia32_cmpb512_mask:
19059 case clang::X86::BI__builtin_ia32_cmpw512_mask:
19060 case clang::X86::BI__builtin_ia32_cmpd512_mask:
19061 case clang::X86::BI__builtin_ia32_cmpq512_mask:
19062 case clang::X86::BI__builtin_ia32_ucmpb128_mask:
19063 case clang::X86::BI__builtin_ia32_ucmpw128_mask:
19064 case clang::X86::BI__builtin_ia32_ucmpd128_mask:
19065 case clang::X86::BI__builtin_ia32_ucmpq128_mask:
19066 case clang::X86::BI__builtin_ia32_ucmpb256_mask:
19067 case clang::X86::BI__builtin_ia32_ucmpw256_mask:
19068 case clang::X86::BI__builtin_ia32_ucmpd256_mask:
19069 case clang::X86::BI__builtin_ia32_ucmpq256_mask:
19070 case clang::X86::BI__builtin_ia32_ucmpb512_mask:
19071 case clang::X86::BI__builtin_ia32_ucmpw512_mask:
19072 case clang::X86::BI__builtin_ia32_ucmpd512_mask:
19073 case clang::X86::BI__builtin_ia32_ucmpq512_mask: {
19077 (BuiltinOp >= clang::X86::BI__builtin_ia32_ucmpb128_mask &&
19078 BuiltinOp <= clang::X86::BI__builtin_ia32_ucmpw512_mask);
19091 unsigned RetWidth = Mask.getBitWidth();
19093 APSInt RetMask(llvm::APInt(RetWidth, 0),
true);
19095 for (
unsigned ElemNum = 0; ElemNum < VectorLen; ++ElemNum) {
19100 switch (
Opcode.getExtValue() & 0x7) {
19105 Result = IsUnsigned ? A.ult(B) : A.slt(B);
19108 Result = IsUnsigned ? A.ule(B) : A.sle(B);
19117 Result = IsUnsigned ? A.uge(B) : A.sge(B);
19120 Result = IsUnsigned ? A.ugt(B) : A.sgt(B);
19127 RetMask.setBitVal(ElemNum, Mask[ElemNum] &&
Result);
19132 case X86::BI__builtin_ia32_cvtss2si:
19133 case X86::BI__builtin_ia32_cvtsd2si:
19134 case X86::BI__builtin_ia32_cvttss2si:
19135 case X86::BI__builtin_ia32_cvttsd2si:
19136 case X86::BI__builtin_ia32_cvtss2si64:
19137 case X86::BI__builtin_ia32_cvtsd2si64:
19138 case X86::BI__builtin_ia32_cvttss2si64:
19139 case X86::BI__builtin_ia32_cvttsd2si64: {
19144 assert(ArgVal.
isVector() &&
"Expected a vector argument");
19146 unsigned BitWidth = Info.Ctx.getIntWidth(E->
getType());
19149 llvm::APSInt IntResult(BitWidth,
isUnsigned);
19150 bool IsExact =
false;
19153 FloatElem.convertToInteger(IntResult, llvm::APFloat::rmTowardZero,
19158 return Success(IntResult, E);
19160 case X86::BI__builtin_ia32_vpshufbitqmb128_mask:
19161 case X86::BI__builtin_ia32_vpshufbitqmb256_mask:
19162 case X86::BI__builtin_ia32_vpshufbitqmb512_mask: {
19175 unsigned NumBytesInQWord = 8;
19176 unsigned NumBitsInByte = 8;
19178 unsigned NumQWords = NumBytes / NumBytesInQWord;
19179 unsigned RetWidth = ZeroMask.getBitWidth();
19180 APSInt RetMask(llvm::APInt(RetWidth, 0),
true);
19182 for (
unsigned QWordId = 0; QWordId != NumQWords; ++QWordId) {
19183 APInt SourceQWord(64, 0);
19184 for (
unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
19188 SourceQWord.insertBits(
APInt(8, Byte & 0xFF), ByteIdx * NumBitsInByte);
19191 for (
unsigned ByteIdx = 0; ByteIdx != NumBytesInQWord; ++ByteIdx) {
19192 unsigned SelIdx = QWordId * NumBytesInQWord + ByteIdx;
19195 if (ZeroMask[SelIdx]) {
19196 RetMask.setBitVal(SelIdx, SourceQWord[M]);
19208 const LValue &LV) {
19211 if (!LV.getLValueBase())
19216 if (!LV.getLValueDesignator().Invalid &&
19217 !LV.getLValueDesignator().isOnePastTheEnd())
19227 if (LV.getLValueDesignator().Invalid)
19233 return LV.getLValueOffset() == Size;
19243class DataRecursiveIntBinOpEvaluator {
19244 struct EvalResult {
19246 bool Failed =
false;
19248 EvalResult() =
default;
19250 void swap(EvalResult &RHS) {
19252 Failed = RHS.Failed;
19253 RHS.Failed =
false;
19259 EvalResult LHSResult;
19260 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind }
Kind;
19263 Job(Job &&) =
default;
19265 void startSpeculativeEval(EvalInfo &Info) {
19266 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
19270 SpeculativeEvaluationRAII SpecEvalRAII;
19273 SmallVector<Job, 16> Queue;
19275 IntExprEvaluator &IntEval;
19280 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval,
APValue &
Result)
19281 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(
Result) { }
19287 static bool shouldEnqueue(
const BinaryOperator *E) {
19294 bool Traverse(
const BinaryOperator *E) {
19296 EvalResult PrevResult;
19297 while (!Queue.empty())
19298 process(PrevResult);
19300 if (PrevResult.Failed)
return false;
19302 FinalResult.
swap(PrevResult.Val);
19313 bool Error(
const Expr *E) {
19314 return IntEval.Error(E);
19317 return IntEval.Error(E, D);
19320 OptionalDiagnostic CCEDiag(
const Expr *E,
diag::kind D) {
19321 return Info.CCEDiag(E, D);
19325 bool VisitBinOpLHSOnly(EvalResult &LHSResult,
const BinaryOperator *E,
19326 bool &SuppressRHSDiags);
19328 bool VisitBinOp(
const EvalResult &LHSResult,
const EvalResult &RHSResult,
19331 void EvaluateExpr(
const Expr *E, EvalResult &
Result) {
19337 void process(EvalResult &
Result);
19339 void enqueue(
const Expr *E) {
19341 Queue.resize(Queue.size()+1);
19342 Queue.back().E = E;
19343 Queue.back().Kind = Job::AnyExprKind;
19349bool DataRecursiveIntBinOpEvaluator::
19350 VisitBinOpLHSOnly(EvalResult &LHSResult,
const BinaryOperator *E,
19351 bool &SuppressRHSDiags) {
19354 if (LHSResult.Failed)
19355 return Info.noteSideEffect();
19364 if (LHSAsBool == (E->
getOpcode() == BO_LOr)) {
19365 Success(LHSAsBool, E, LHSResult.Val);
19369 LHSResult.Failed =
true;
19373 if (!Info.noteSideEffect())
19379 SuppressRHSDiags =
true;
19388 if (LHSResult.Failed && !Info.noteFailure())
19399 assert(!LVal.
hasLValuePath() &&
"have designator for integer lvalue");
19401 uint64_t Offset64 = Offset.getQuantity();
19402 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
19404 : Offset64 + Index64);
19407bool DataRecursiveIntBinOpEvaluator::
19408 VisitBinOp(
const EvalResult &LHSResult,
const EvalResult &RHSResult,
19411 if (RHSResult.Failed)
19418 bool lhsResult, rhsResult;
19433 if (rhsResult == (E->
getOpcode() == BO_LOr))
19444 if (LHSResult.Failed || RHSResult.Failed)
19447 const APValue &LHSVal = LHSResult.Val;
19448 const APValue &RHSVal = RHSResult.Val;
19472 if (!LHSExpr || !RHSExpr)
19474 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
19475 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
19476 if (!LHSAddrExpr || !RHSAddrExpr)
19501void DataRecursiveIntBinOpEvaluator::process(EvalResult &
Result) {
19502 Job &job = Queue.back();
19504 switch (job.Kind) {
19505 case Job::AnyExprKind: {
19506 if (
const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
19507 if (shouldEnqueue(Bop)) {
19508 job.Kind = Job::BinOpKind;
19509 enqueue(Bop->getLHS());
19514 EvaluateExpr(job.E,
Result);
19519 case Job::BinOpKind: {
19521 bool SuppressRHSDiags =
false;
19522 if (!VisitBinOpLHSOnly(
Result, Bop, SuppressRHSDiags)) {
19526 if (SuppressRHSDiags)
19527 job.startSpeculativeEval(Info);
19528 job.LHSResult.swap(
Result);
19529 job.Kind = Job::BinOpVisitedLHSKind;
19534 case Job::BinOpVisitedLHSKind: {
19538 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop,
Result.Val);
19544 llvm_unreachable(
"Invalid Job::Kind!");
19548enum class CmpResult {
19557template <
class SuccessCB,
class AfterCB>
19560 SuccessCB &&
Success, AfterCB &&DoAfter) {
19565 "unsupported binary expression evaluation");
19567 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
19581 if (!LHSOK && !Info.noteFailure())
19586 return Success(CmpResult::Less, E);
19588 return Success(CmpResult::Greater, E);
19589 return Success(CmpResult::Equal, E);
19593 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
19594 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
19597 if (!LHSOK && !Info.noteFailure())
19602 return Success(CmpResult::Less, E);
19604 return Success(CmpResult::Greater, E);
19605 return Success(CmpResult::Equal, E);
19609 ComplexValue LHS, RHS;
19618 LHS.makeComplexFloat();
19619 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
19624 if (!LHSOK && !Info.noteFailure())
19630 RHS.makeComplexFloat();
19631 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
19635 if (LHS.isComplexFloat()) {
19636 APFloat::cmpResult CR_r =
19637 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
19638 APFloat::cmpResult CR_i =
19639 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
19640 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
19641 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19643 assert(IsEquality &&
"invalid complex comparison");
19644 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
19645 LHS.getComplexIntImag() == RHS.getComplexIntImag();
19646 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
19652 APFloat RHS(0.0), LHS(0.0);
19655 if (!LHSOK && !Info.noteFailure())
19662 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
19663 if (!Info.InConstantContext &&
19664 APFloatCmpResult == APFloat::cmpUnordered &&
19667 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
19670 auto GetCmpRes = [&]() {
19671 switch (APFloatCmpResult) {
19672 case APFloat::cmpEqual:
19673 return CmpResult::Equal;
19674 case APFloat::cmpLessThan:
19675 return CmpResult::Less;
19676 case APFloat::cmpGreaterThan:
19677 return CmpResult::Greater;
19678 case APFloat::cmpUnordered:
19679 return CmpResult::Unordered;
19681 llvm_unreachable(
"Unrecognised APFloat::cmpResult enum");
19683 return Success(GetCmpRes(), E);
19687 LValue LHSValue, RHSValue;
19690 if (!LHSOK && !Info.noteFailure())
19701 if (Info.checkingPotentialConstantExpression() &&
19702 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
19704 auto DiagComparison = [&] (
unsigned DiagID,
bool Reversed =
false) {
19705 std::string LHS = LHSValue.toString(Info.Ctx, E->
getLHS()->
getType());
19706 std::string RHS = RHSValue.toString(Info.Ctx, E->
getRHS()->
getType());
19707 Info.FFDiag(E, DiagID)
19714 return DiagComparison(
19715 diag::note_constexpr_pointer_comparison_unspecified);
19721 if ((!LHSValue.Base && !LHSValue.Offset.
isZero()) ||
19722 (!RHSValue.Base && !RHSValue.Offset.
isZero()))
19723 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
19737 return DiagComparison(diag::note_constexpr_literal_comparison);
19739 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
19744 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
19748 if (LHSValue.Base && LHSValue.Offset.
isZero() &&
19750 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19752 if (RHSValue.Base && RHSValue.Offset.
isZero() &&
19754 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
19760 return DiagComparison(
19761 diag::note_constexpr_pointer_comparison_zero_sized);
19762 if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
19763 return DiagComparison(
19764 diag::note_constexpr_pointer_comparison_unspecified);
19766 return Success(CmpResult::Unequal, E);
19769 CharUnits LHSOffset = LHSValue.getLValueOffset();
19770 CharUnits RHSOffset = RHSValue.getLValueOffset();
19772 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
19773 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
19783 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
19784 bool WasArrayIndex;
19787 :
getType(LHSValue.Base).getNonReferenceType(),
19788 LHSDesignator, RHSDesignator, WasArrayIndex);
19795 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
19796 Mismatch < RHSDesignator.Entries.size()) {
19797 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
19798 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
19800 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
19802 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19803 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
19806 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
19807 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
19812 diag::note_constexpr_pointer_comparison_differing_access)
19820 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
19823 assert(PtrSize <= 64 &&
"Unexpected pointer width");
19824 uint64_t Mask = ~0ULL >> (64 - PtrSize);
19825 CompareLHS &= Mask;
19826 CompareRHS &= Mask;
19831 if (!LHSValue.Base.
isNull() && IsRelational) {
19835 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
19836 uint64_t OffsetLimit = Size.getQuantity();
19837 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
19841 if (CompareLHS < CompareRHS)
19842 return Success(CmpResult::Less, E);
19843 if (CompareLHS > CompareRHS)
19844 return Success(CmpResult::Greater, E);
19845 return Success(CmpResult::Equal, E);
19849 assert(IsEquality &&
"unexpected member pointer operation");
19852 MemberPtr LHSValue, RHSValue;
19855 if (!LHSOK && !Info.noteFailure())
19863 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
19864 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19865 << LHSValue.getDecl();
19868 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
19869 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
19870 << RHSValue.getDecl();
19877 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
19878 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
19879 return Success(
Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19884 if (
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
19885 if (MD->isVirtual())
19886 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19887 if (
const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
19888 if (MD->isVirtual())
19889 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
19895 bool Equal = LHSValue == RHSValue;
19896 return Success(
Equal ? CmpResult::Equal : CmpResult::Unequal, E);
19901 assert(RHSTy->
isNullPtrType() &&
"missing pointer conversion");
19909 return Success(CmpResult::Equal, E);
19914 llvm::FoldingSetNodeID LID, RID;
19924 return Success(CmpResult::Equal, E);
19926 return Success(CmpResult::Unequal, E);
19936 Info.Ctx.CompCategories.getInfoForType(E->
getType());
19945 ConstantExprKind::Normal);
19948bool RecordExprEvaluator::VisitBinCmp(
const BinaryOperator *E) {
19952 auto OnSuccess = [&](CmpResult CR,
const BinaryOperator *E) {
19955 case CmpResult::Unequal:
19956 llvm_unreachable(
"should never produce Unequal for three-way comparison");
19957 case CmpResult::Less:
19958 CCR = ComparisonCategoryResult::Less;
19960 case CmpResult::Equal:
19961 CCR = ComparisonCategoryResult::Equal;
19963 case CmpResult::Greater:
19964 CCR = ComparisonCategoryResult::Greater;
19966 case CmpResult::Unordered:
19967 CCR = ComparisonCategoryResult::Unordered;
19973 return ExprEvaluatorBaseTy::VisitBinCmp(E);
19977bool RecordExprEvaluator::VisitTypeTraitExpr(
const TypeTraitExpr *E) {
19982 "expected a strong_ordering type trait with a stored value");
19989bool RecordExprEvaluator::VisitCXXParenListInitExpr(
19990 const CXXParenListInitExpr *E) {
19991 return VisitCXXParenListOrInitListExpr(E, E->
getInitExprs());
19994bool IntExprEvaluator::VisitBinaryOperator(
const BinaryOperator *E) {
19999 if (!Info.noteFailure())
20003 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
20004 return DataRecursiveIntBinOpEvaluator(*
this,
Result).Traverse(E);
20008 "DataRecursiveIntBinOpEvaluator should have handled integral types");
20013 auto OnSuccess = [&](CmpResult CR,
const BinaryOperator *E) {
20014 assert((CR != CmpResult::Unequal || E->
isEqualityOp()) &&
20015 "should only produce Unequal for equality comparisons");
20016 bool IsEqual = CR == CmpResult::Equal,
20017 IsLess = CR == CmpResult::Less,
20018 IsGreater = CR == CmpResult::Greater;
20022 llvm_unreachable(
"unsupported binary operator");
20025 return Success(IsEqual == (Op == BO_EQ), E);
20029 return Success(IsGreater, E);
20031 return Success(IsEqual || IsLess, E);
20033 return Success(IsEqual || IsGreater, E);
20037 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20046 LValue LHSValue, RHSValue;
20049 if (!LHSOK && !Info.noteFailure())
20058 if (Info.checkingPotentialConstantExpression() &&
20059 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
20062 const Expr *LHSExpr = LHSValue.Base.
dyn_cast<
const Expr *>();
20063 const Expr *RHSExpr = RHSValue.Base.
dyn_cast<
const Expr *>();
20065 auto DiagArith = [&](
unsigned DiagID) {
20066 std::string LHS = LHSValue.toString(Info.Ctx, E->
getLHS()->
getType());
20067 std::string RHS = RHSValue.toString(Info.Ctx, E->
getRHS()->
getType());
20068 Info.FFDiag(E, DiagID) << LHS << RHS;
20069 if (LHSExpr && LHSExpr == RHSExpr)
20071 diag::note_constexpr_repeated_literal_eval)
20076 if (!LHSExpr || !RHSExpr)
20077 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
20080 return DiagArith(diag::note_constexpr_literal_arith);
20082 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
20083 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
20084 if (!LHSAddrExpr || !RHSAddrExpr)
20092 CharUnits LHSOffset = LHSValue.getLValueOffset();
20093 CharUnits RHSOffset = RHSValue.getLValueOffset();
20095 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
20096 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
20102 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
20105 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
20110 CharUnits ElementSize;
20117 if (ElementSize.
isZero()) {
20118 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
20135 APSInt TrueResult = (LHS - RHS) / ElemSize;
20138 if (
Result.extend(65) != TrueResult &&
20144 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20149bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
20150 const UnaryExprOrTypeTraitExpr *E) {
20152 case UETT_PreferredAlignOf:
20153 case UETT_AlignOf: {
20162 case UETT_PtrAuthTypeDiscriminator: {
20168 case UETT_VecStep: {
20172 unsigned n = Ty->
castAs<VectorType>()->getNumElements();
20184 case UETT_DataSizeOf:
20185 case UETT_SizeOf: {
20189 if (
const ReferenceType *Ref = SrcTy->
getAs<ReferenceType>())
20200 case UETT_OpenMPRequiredSimdAlign:
20203 Info.Ctx.toCharUnitsFromBits(
20207 case UETT_VectorElements: {
20211 if (
const auto *VT = Ty->
getAs<VectorType>())
20215 if (Info.InConstantContext)
20216 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
20221 case UETT_CountOf: {
20227 if (
const auto *CAT =
20237 const auto *VAT = Info.Ctx.getAsVariableArrayType(Ty);
20239 if (VAT->getElementType()->isArrayType()) {
20242 if (!VAT->getSizeExpr()) {
20247 std::optional<APSInt> Res =
20248 VAT->getSizeExpr()->getIntegerConstantExpr(Info.Ctx);
20253 static_cast<unsigned>(Info.Ctx.getTypeSize(Info.Ctx.getSizeType())),
20254 Res->getZExtValue()};
20266 llvm_unreachable(
"unknown expr/type trait");
20269bool IntExprEvaluator::VisitOffsetOfExpr(
const OffsetOfExpr *OOE) {
20270 Info.Ctx.recordOffsetOfEvaluation(OOE);
20276 for (
unsigned i = 0; i != n; ++i) {
20284 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
20288 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
20291 if (IdxResult.isNegative() || IdxResult.getActiveBits() > 63)
20293 int64_t IdxVal = IdxResult.getExtValue();
20296 ElemSize > std::numeric_limits<int64_t>::max() / IdxVal)
20297 return Error(OOE, diag::note_constexpr_offsetof_overflow);
20298 int64_t Offset = IdxVal * ElemSize;
20299 if (
Result.getQuantity() > std::numeric_limits<int64_t>::max() - Offset)
20300 return Error(OOE, diag::note_constexpr_offsetof_overflow);
20306 FieldDecl *MemberDecl = ON.
getField();
20311 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
20313 assert(i < RL.
getFieldCount() &&
"offsetof field in wrong type");
20320 llvm_unreachable(
"dependent __builtin_offsetof");
20323 CXXBaseSpecifier *BaseSpec = ON.
getBase();
20332 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
20335 CurrentType = BaseSpec->
getType();
20349bool IntExprEvaluator::VisitUnaryOperator(
const UnaryOperator *E) {
20369 if (Info.checkingForUndefinedBehavior())
20370 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
20371 diag::warn_integer_constant_overflow)
20399bool IntExprEvaluator::VisitCastExpr(
const CastExpr *E) {
20401 QualType DestType = E->
getType();
20402 QualType SrcType = SubExpr->
getType();
20405 case CK_BaseToDerived:
20406 case CK_DerivedToBase:
20407 case CK_UncheckedDerivedToBase:
20410 case CK_ArrayToPointerDecay:
20411 case CK_FunctionToPointerDecay:
20412 case CK_NullToPointer:
20413 case CK_NullToMemberPointer:
20414 case CK_BaseToDerivedMemberPointer:
20415 case CK_DerivedToBaseMemberPointer:
20416 case CK_ReinterpretMemberPointer:
20417 case CK_ConstructorConversion:
20418 case CK_IntegralToPointer:
20420 case CK_VectorSplat:
20421 case CK_IntegralToFloating:
20422 case CK_FloatingCast:
20423 case CK_CPointerToObjCPointerCast:
20424 case CK_BlockPointerToObjCPointerCast:
20425 case CK_AnyPointerToBlockPointerCast:
20426 case CK_ObjCObjectLValueCast:
20427 case CK_FloatingRealToComplex:
20428 case CK_FloatingComplexToReal:
20429 case CK_FloatingComplexCast:
20430 case CK_FloatingComplexToIntegralComplex:
20431 case CK_IntegralRealToComplex:
20432 case CK_IntegralComplexCast:
20433 case CK_IntegralComplexToFloatingComplex:
20434 case CK_BuiltinFnToFnPtr:
20435 case CK_ZeroToOCLOpaqueType:
20436 case CK_NonAtomicToAtomic:
20437 case CK_AddressSpaceConversion:
20438 case CK_IntToOCLSampler:
20439 case CK_FloatingToFixedPoint:
20440 case CK_FixedPointToFloating:
20441 case CK_FixedPointCast:
20442 case CK_IntegralToFixedPoint:
20443 case CK_MatrixCast:
20444 case CK_HLSLAggregateSplatCast:
20445 llvm_unreachable(
"invalid cast kind for integral value");
20448 case CK_LValueBitCast:
20449 case CK_ARCProduceObject:
20450 case CK_ARCConsumeObject:
20451 case CK_ARCReclaimReturnedObject:
20452 case CK_ARCExtendBlockObject:
20453 case CK_CopyAndAutoreleaseBlockObject:
20456 case CK_UserDefinedConversion:
20457 case CK_LValueToRValue:
20458 case CK_AtomicToNonAtomic:
20460 case CK_LValueToRValueBitCast:
20461 case CK_HLSLArrayRValue:
20462 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20466 if (!
Evaluate(Src, Info, SubExpr))
20469 if (!handleRValueToRValueBitCast(Info, Dst, Src, E))
20474 case CK_MemberPointerToBoolean:
20475 case CK_PointerToBoolean:
20476 case CK_IntegralToBoolean:
20477 case CK_FloatingToBoolean:
20478 case CK_BooleanToSignedIntegral:
20479 case CK_FloatingComplexToBoolean:
20480 case CK_IntegralComplexToBoolean: {
20485 if (BoolResult && E->
getCastKind() == CK_BooleanToSignedIntegral)
20487 return Success(IntResult, E);
20490 case CK_FixedPointToIntegral: {
20491 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
20495 llvm::APSInt
Result = Src.convertToInt(
20496 Info.Ctx.getIntWidth(DestType),
20503 case CK_FixedPointToBoolean: {
20506 if (!
Evaluate(Val, Info, SubExpr))
20511 case CK_IntegralCast: {
20512 if (!Visit(SubExpr))
20522 if (
Result.isAddrLabelDiff()) {
20523 unsigned DestBits = Info.Ctx.getTypeSize(DestType);
20524 return DestBits >= 32 && DestBits <= Info.Ctx.getTypeSize(SrcType);
20527 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
20530 if (Info.Ctx.getLangOpts().CPlusPlus && DestType->
isEnumeralType()) {
20542 if (!ED->isFixed()) {
20546 ED->getValueRange(
Max,
Min);
20549 if (ED->getNumNegativeBits() &&
20550 (
Max.slt(
Result.getInt().getSExtValue()) ||
20551 Min.sgt(
Result.getInt().getSExtValue())))
20552 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20553 << llvm::toString(
Result.getInt(), 10) <<
Min.getSExtValue()
20554 <<
Max.getSExtValue() << ED;
20555 else if (!ED->getNumNegativeBits() &&
20556 Max.ult(
Result.getInt().getZExtValue()))
20557 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
20558 << llvm::toString(
Result.getInt(), 10) <<
Min.getZExtValue()
20559 <<
Max.getZExtValue() << ED;
20567 case CK_PointerToIntegral: {
20568 CCEDiag(E, diag::note_constexpr_invalid_cast_ptrtoint)
20569 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
20576 if (LV.getLValueBase()) {
20577 CCEDiag(E, diag::note_constexpr_has_lvalue) << E->
getSourceRange();
20582 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
20585 LV.Designator.setInvalid();
20593 if (!
V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
20594 llvm_unreachable(
"Can't cast this!");
20599 case CK_IntegralComplexToReal: {
20603 return Success(
C.getComplexIntReal(), E);
20606 case CK_FloatingToIntegral: {
20616 case CK_HLSLVectorTruncation: {
20622 case CK_HLSLMatrixTruncation: {
20628 case CK_HLSLElementwiseCast: {
20641 return Success(ResultVal, E);
20645 llvm_unreachable(
"unknown cast resulting in integral value");
20648bool IntExprEvaluator::VisitUnaryReal(
const UnaryOperator *E) {
20653 if (!LV.isComplexInt())
20655 return Success(LV.getComplexIntReal(), E);
20661bool IntExprEvaluator::VisitUnaryImag(
const UnaryOperator *E) {
20666 if (!LV.isComplexInt())
20668 return Success(LV.getComplexIntImag(), E);
20675bool IntExprEvaluator::VisitSizeOfPackExpr(
const SizeOfPackExpr *E) {
20679bool IntExprEvaluator::VisitCXXNoexceptExpr(
const CXXNoexceptExpr *E) {
20683bool IntExprEvaluator::VisitConceptSpecializationExpr(
20684 const ConceptSpecializationExpr *E) {
20688bool IntExprEvaluator::VisitRequiresExpr(
const RequiresExpr *E) {
20692bool FixedPointExprEvaluator::VisitUnaryOperator(
const UnaryOperator *E) {
20702 if (!
Result.isFixedPoint())
20705 APFixedPoint Negated =
Result.getFixedPoint().negate(&Overflowed);
20719bool FixedPointExprEvaluator::VisitCastExpr(
const CastExpr *E) {
20721 QualType DestType = E->
getType();
20723 "Expected destination type to be a fixed point type");
20724 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
20727 case CK_FixedPointCast: {
20728 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->
getType()));
20732 APFixedPoint
Result = Src.convert(DestFXSema, &Overflowed);
20734 if (Info.checkingForUndefinedBehavior())
20735 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
20736 diag::warn_fixedpoint_constant_overflow)
20743 case CK_IntegralToFixedPoint: {
20749 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
20750 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20753 if (Info.checkingForUndefinedBehavior())
20754 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
20755 diag::warn_fixedpoint_constant_overflow)
20756 << IntResult.toString() << E->
getType();
20761 return Success(IntResult, E);
20763 case CK_FloatingToFixedPoint: {
20769 APFixedPoint
Result = APFixedPoint::getFromFloatValue(
20770 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
20773 if (Info.checkingForUndefinedBehavior())
20774 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
20775 diag::warn_fixedpoint_constant_overflow)
20784 case CK_LValueToRValue:
20785 return ExprEvaluatorBaseTy::VisitCastExpr(E);
20791bool FixedPointExprEvaluator::VisitBinaryOperator(
const BinaryOperator *E) {
20793 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
20795 const Expr *LHS = E->
getLHS();
20796 const Expr *RHS = E->
getRHS();
20798 Info.Ctx.getFixedPointSemantics(E->
getType());
20800 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->
getType()));
20803 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->
getType()));
20807 bool OpOverflow =
false, ConversionOverflow =
false;
20808 APFixedPoint
Result(LHSFX.getSemantics());
20811 Result = LHSFX.add(RHSFX, &OpOverflow)
20812 .convert(ResultFXSema, &ConversionOverflow);
20816 Result = LHSFX.sub(RHSFX, &OpOverflow)
20817 .convert(ResultFXSema, &ConversionOverflow);
20821 Result = LHSFX.mul(RHSFX, &OpOverflow)
20822 .convert(ResultFXSema, &ConversionOverflow);
20826 if (RHSFX.getValue() == 0) {
20827 Info.FFDiag(E, diag::note_expr_divide_by_zero);
20830 Result = LHSFX.div(RHSFX, &OpOverflow)
20831 .convert(ResultFXSema, &ConversionOverflow);
20837 llvm::APSInt RHSVal = RHSFX.getValue();
20840 LHSSema.getWidth() - (
unsigned)LHSSema.hasUnsignedPadding();
20841 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
20845 if (RHSVal.isNegative())
20846 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
20847 else if (Amt != RHSVal)
20848 Info.CCEDiag(E, diag::note_constexpr_large_shift)
20849 << RHSVal << E->
getType() << ShiftBW;
20852 Result = LHSFX.shl(Amt, &OpOverflow);
20854 Result = LHSFX.shr(Amt, &OpOverflow);
20860 if (OpOverflow || ConversionOverflow) {
20861 if (Info.checkingForUndefinedBehavior())
20862 Info.Ctx.getDiagnostics().Report(E->
getExprLoc(),
20863 diag::warn_fixedpoint_constant_overflow)
20876class FloatExprEvaluator
20877 :
public ExprEvaluatorBase<FloatExprEvaluator> {
20880 FloatExprEvaluator(EvalInfo &info, APFloat &result)
20881 : ExprEvaluatorBaseTy(
info),
Result(result) {}
20888 bool ZeroInitialization(
const Expr *E) {
20889 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->
getType()));
20893 bool VisitCallExpr(
const CallExpr *E);
20895 bool VisitUnaryOperator(
const UnaryOperator *E);
20896 bool VisitBinaryOperator(
const BinaryOperator *E);
20897 bool VisitFloatingLiteral(
const FloatingLiteral *E);
20898 bool VisitCastExpr(
const CastExpr *E);
20900 bool VisitUnaryReal(
const UnaryOperator *E);
20901 bool VisitUnaryImag(
const UnaryOperator *E);
20910 return FloatExprEvaluator(Info,
Result).Visit(E);
20917 llvm::APFloat &
Result) {
20922 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
20928 fill = llvm::APInt(32, 0);
20929 else if (S->
getString().getAsInteger(0, fill))
20932 if (Context.getTargetInfo().isNan2008()) {
20934 Result = llvm::APFloat::getSNaN(Sem,
false, &fill);
20936 Result = llvm::APFloat::getQNaN(Sem,
false, &fill);
20944 Result = llvm::APFloat::getQNaN(Sem,
false, &fill);
20946 Result = llvm::APFloat::getSNaN(Sem,
false, &fill);
20952bool FloatExprEvaluator::VisitCallExpr(
const CallExpr *E) {
20953 if (!IsConstantEvaluatedBuiltinCall(E))
20954 return ExprEvaluatorBaseTy::VisitCallExpr(E);
20958 switch (BuiltinOp) {
20962 case Builtin::BI__builtin_huge_val:
20963 case Builtin::BI__builtin_huge_valf:
20964 case Builtin::BI__builtin_huge_vall:
20965 case Builtin::BI__builtin_huge_valf16:
20966 case Builtin::BI__builtin_huge_valf128:
20967 case Builtin::BI__builtin_inf:
20968 case Builtin::BI__builtin_inff:
20969 case Builtin::BI__builtin_infl:
20970 case Builtin::BI__builtin_inff16:
20971 case Builtin::BI__builtin_inff128: {
20972 const llvm::fltSemantics &Sem =
20973 Info.Ctx.getFloatTypeSemantics(E->
getType());
20974 Result = llvm::APFloat::getInf(Sem);
20978 case Builtin::BI__builtin_nans:
20979 case Builtin::BI__builtin_nansf:
20980 case Builtin::BI__builtin_nansl:
20981 case Builtin::BI__builtin_nansf16:
20982 case Builtin::BI__builtin_nansf128:
20988 case Builtin::BI__builtin_nan:
20989 case Builtin::BI__builtin_nanf:
20990 case Builtin::BI__builtin_nanl:
20991 case Builtin::BI__builtin_nanf16:
20992 case Builtin::BI__builtin_nanf128:
21000 case Builtin::BI__builtin_elementwise_abs:
21001 case Builtin::BI__builtin_fabs:
21002 case Builtin::BI__builtin_fabsf:
21003 case Builtin::BI__builtin_fabsl:
21004 case Builtin::BI__builtin_fabsf128:
21013 if (
Result.isNegative())
21017 case Builtin::BI__arithmetic_fence:
21024 case Builtin::BI__builtin_copysign:
21025 case Builtin::BI__builtin_copysignf:
21026 case Builtin::BI__builtin_copysignl:
21027 case Builtin::BI__builtin_copysignf128: {
21036 case Builtin::BI__builtin_fmax:
21037 case Builtin::BI__builtin_fmaxf:
21038 case Builtin::BI__builtin_fmaxl:
21039 case Builtin::BI__builtin_fmaxf16:
21040 case Builtin::BI__builtin_fmaxf128: {
21049 case Builtin::BI__builtin_fmin:
21050 case Builtin::BI__builtin_fminf:
21051 case Builtin::BI__builtin_fminl:
21052 case Builtin::BI__builtin_fminf16:
21053 case Builtin::BI__builtin_fminf128: {
21062 case Builtin::BI__builtin_fmaximum_num:
21063 case Builtin::BI__builtin_fmaximum_numf:
21064 case Builtin::BI__builtin_fmaximum_numl:
21065 case Builtin::BI__builtin_fmaximum_numf16:
21066 case Builtin::BI__builtin_fmaximum_numf128: {
21075 case Builtin::BI__builtin_fminimum_num:
21076 case Builtin::BI__builtin_fminimum_numf:
21077 case Builtin::BI__builtin_fminimum_numl:
21078 case Builtin::BI__builtin_fminimum_numf16:
21079 case Builtin::BI__builtin_fminimum_numf128: {
21088 case Builtin::BI__builtin_elementwise_fma: {
21093 APFloat SourceY(0.), SourceZ(0.);
21099 (void)
Result.fusedMultiplyAdd(SourceY, SourceZ, RM);
21103 case clang::X86::BI__builtin_ia32_vec_ext_v4sf: {
21110 unsigned Idx =
static_cast<unsigned>(IdxAPS.getZExtValue() & (N - 1));
21116bool FloatExprEvaluator::VisitUnaryReal(
const UnaryOperator *E) {
21128bool FloatExprEvaluator::VisitUnaryImag(
const UnaryOperator *E) {
21138 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->
getType());
21139 Result = llvm::APFloat::getZero(Sem);
21143bool FloatExprEvaluator::VisitUnaryOperator(
const UnaryOperator *E) {
21145 default:
return Error(E);
21159bool FloatExprEvaluator::VisitBinaryOperator(
const BinaryOperator *E) {
21161 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21165 if (!LHSOK && !Info.noteFailure())
21171bool FloatExprEvaluator::VisitFloatingLiteral(
const FloatingLiteral *E) {
21176bool FloatExprEvaluator::VisitCastExpr(
const CastExpr *E) {
21181 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21183 case CK_HLSLAggregateSplatCast:
21184 llvm_unreachable(
"invalid cast kind for floating value");
21186 case CK_IntegralToFloating: {
21189 Info.Ctx.getLangOpts());
21195 case CK_FixedPointToFloating: {
21196 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->
getType()));
21200 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->
getType()));
21204 case CK_FloatingCast: {
21205 if (!Visit(SubExpr))
21211 case CK_FloatingComplexToReal: {
21215 Result =
V.getComplexFloatReal();
21218 case CK_HLSLVectorTruncation: {
21224 case CK_HLSLMatrixTruncation: {
21230 case CK_HLSLElementwiseCast: {
21244 return Success(ResultVal, E);
21254class ComplexExprEvaluator
21255 :
public ExprEvaluatorBase<ComplexExprEvaluator> {
21259 ComplexExprEvaluator(EvalInfo &info, ComplexValue &
Result)
21267 bool ZeroInitialization(
const Expr *E);
21273 bool VisitImaginaryLiteral(
const ImaginaryLiteral *E);
21274 bool VisitCastExpr(
const CastExpr *E);
21275 bool VisitBinaryOperator(
const BinaryOperator *E);
21276 bool VisitUnaryOperator(
const UnaryOperator *E);
21277 bool VisitInitListExpr(
const InitListExpr *E);
21278 bool VisitCallExpr(
const CallExpr *E);
21286 return ComplexExprEvaluator(Info,
Result).Visit(E);
21289bool ComplexExprEvaluator::ZeroInitialization(
const Expr *E) {
21290 QualType ElemTy = E->
getType()->
castAs<ComplexType>()->getElementType();
21292 Result.makeComplexFloat();
21293 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
21297 Result.makeComplexInt();
21298 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
21305bool ComplexExprEvaluator::VisitImaginaryLiteral(
const ImaginaryLiteral *E) {
21309 Result.makeComplexFloat();
21318 "Unexpected imaginary literal.");
21320 Result.makeComplexInt();
21325 Result.IntReal =
APSInt(Imag.getBitWidth(), !Imag.isSigned());
21330bool ComplexExprEvaluator::VisitCastExpr(
const CastExpr *E) {
21334 case CK_BaseToDerived:
21335 case CK_DerivedToBase:
21336 case CK_UncheckedDerivedToBase:
21339 case CK_ArrayToPointerDecay:
21340 case CK_FunctionToPointerDecay:
21341 case CK_NullToPointer:
21342 case CK_NullToMemberPointer:
21343 case CK_BaseToDerivedMemberPointer:
21344 case CK_DerivedToBaseMemberPointer:
21345 case CK_MemberPointerToBoolean:
21346 case CK_ReinterpretMemberPointer:
21347 case CK_ConstructorConversion:
21348 case CK_IntegralToPointer:
21349 case CK_PointerToIntegral:
21350 case CK_PointerToBoolean:
21352 case CK_VectorSplat:
21353 case CK_IntegralCast:
21354 case CK_BooleanToSignedIntegral:
21355 case CK_IntegralToBoolean:
21356 case CK_IntegralToFloating:
21357 case CK_FloatingToIntegral:
21358 case CK_FloatingToBoolean:
21359 case CK_FloatingCast:
21360 case CK_CPointerToObjCPointerCast:
21361 case CK_BlockPointerToObjCPointerCast:
21362 case CK_AnyPointerToBlockPointerCast:
21363 case CK_ObjCObjectLValueCast:
21364 case CK_FloatingComplexToReal:
21365 case CK_FloatingComplexToBoolean:
21366 case CK_IntegralComplexToReal:
21367 case CK_IntegralComplexToBoolean:
21368 case CK_ARCProduceObject:
21369 case CK_ARCConsumeObject:
21370 case CK_ARCReclaimReturnedObject:
21371 case CK_ARCExtendBlockObject:
21372 case CK_CopyAndAutoreleaseBlockObject:
21373 case CK_BuiltinFnToFnPtr:
21374 case CK_ZeroToOCLOpaqueType:
21375 case CK_NonAtomicToAtomic:
21376 case CK_AddressSpaceConversion:
21377 case CK_IntToOCLSampler:
21378 case CK_FloatingToFixedPoint:
21379 case CK_FixedPointToFloating:
21380 case CK_FixedPointCast:
21381 case CK_FixedPointToBoolean:
21382 case CK_FixedPointToIntegral:
21383 case CK_IntegralToFixedPoint:
21384 case CK_MatrixCast:
21385 case CK_HLSLVectorTruncation:
21386 case CK_HLSLMatrixTruncation:
21387 case CK_HLSLElementwiseCast:
21388 case CK_HLSLAggregateSplatCast:
21389 llvm_unreachable(
"invalid cast kind for complex value");
21391 case CK_LValueToRValue:
21392 case CK_AtomicToNonAtomic:
21394 case CK_LValueToRValueBitCast:
21395 case CK_HLSLArrayRValue:
21396 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21399 case CK_LValueBitCast:
21400 case CK_UserDefinedConversion:
21403 case CK_FloatingRealToComplex: {
21408 Result.makeComplexFloat();
21413 case CK_FloatingComplexCast: {
21417 QualType To = E->
getType()->
castAs<ComplexType>()->getElementType();
21425 case CK_FloatingComplexToIntegralComplex: {
21429 QualType To = E->
getType()->
castAs<ComplexType>()->getElementType();
21432 Result.makeComplexInt();
21439 case CK_IntegralRealToComplex: {
21444 Result.makeComplexInt();
21445 Result.IntImag =
APSInt(Real.getBitWidth(), !Real.isSigned());
21449 case CK_IntegralComplexCast: {
21453 QualType To = E->
getType()->
castAs<ComplexType>()->getElementType();
21462 case CK_IntegralComplexToFloatingComplex: {
21467 Info.Ctx.getLangOpts());
21468 QualType To = E->
getType()->
castAs<ComplexType>()->getElementType();
21471 Result.makeComplexFloat();
21473 To,
Result.FloatReal) &&
21479 llvm_unreachable(
"unknown cast resulting in complex value");
21485 0x00, 0x01, 0x8d, 0xf6, 0xcb, 0x52, 0x7b, 0xd1, 0xe8, 0x4f, 0x29, 0xc0,
21486 0xb0, 0xe1, 0xe5, 0xc7, 0x74, 0xb4, 0xaa, 0x4b, 0x99, 0x2b, 0x60, 0x5f,
21487 0x58, 0x3f, 0xfd, 0xcc, 0xff, 0x40, 0xee, 0xb2, 0x3a, 0x6e, 0x5a, 0xf1,
21488 0x55, 0x4d, 0xa8, 0xc9, 0xc1, 0x0a, 0x98, 0x15, 0x30, 0x44, 0xa2, 0xc2,
21489 0x2c, 0x45, 0x92, 0x6c, 0xf3, 0x39, 0x66, 0x42, 0xf2, 0x35, 0x20, 0x6f,
21490 0x77, 0xbb, 0x59, 0x19, 0x1d, 0xfe, 0x37, 0x67, 0x2d, 0x31, 0xf5, 0x69,
21491 0xa7, 0x64, 0xab, 0x13, 0x54, 0x25, 0xe9, 0x09, 0xed, 0x5c, 0x05, 0xca,
21492 0x4c, 0x24, 0x87, 0xbf, 0x18, 0x3e, 0x22, 0xf0, 0x51, 0xec, 0x61, 0x17,
21493 0x16, 0x5e, 0xaf, 0xd3, 0x49, 0xa6, 0x36, 0x43, 0xf4, 0x47, 0x91, 0xdf,
21494 0x33, 0x93, 0x21, 0x3b, 0x79, 0xb7, 0x97, 0x85, 0x10, 0xb5, 0xba, 0x3c,
21495 0xb6, 0x70, 0xd0, 0x06, 0xa1, 0xfa, 0x81, 0x82, 0x83, 0x7e, 0x7f, 0x80,
21496 0x96, 0x73, 0xbe, 0x56, 0x9b, 0x9e, 0x95, 0xd9, 0xf7, 0x02, 0xb9, 0xa4,
21497 0xde, 0x6a, 0x32, 0x6d, 0xd8, 0x8a, 0x84, 0x72, 0x2a, 0x14, 0x9f, 0x88,
21498 0xf9, 0xdc, 0x89, 0x9a, 0xfb, 0x7c, 0x2e, 0xc3, 0x8f, 0xb8, 0x65, 0x48,
21499 0x26, 0xc8, 0x12, 0x4a, 0xce, 0xe7, 0xd2, 0x62, 0x0c, 0xe0, 0x1f, 0xef,
21500 0x11, 0x75, 0x78, 0x71, 0xa5, 0x8e, 0x76, 0x3d, 0xbd, 0xbc, 0x86, 0x57,
21501 0x0b, 0x28, 0x2f, 0xa3, 0xda, 0xd4, 0xe4, 0x0f, 0xa9, 0x27, 0x53, 0x04,
21502 0x1b, 0xfc, 0xac, 0xe6, 0x7a, 0x07, 0xae, 0x63, 0xc5, 0xdb, 0xe2, 0xea,
21503 0x94, 0x8b, 0xc4, 0xd5, 0x9d, 0xf8, 0x90, 0x6b, 0xb1, 0x0d, 0xd6, 0xeb,
21504 0xc6, 0x0e, 0xcf, 0xad, 0x08, 0x4e, 0xd7, 0xe3, 0x5d, 0x50, 0x1e, 0xb3,
21505 0x5b, 0x23, 0x38, 0x34, 0x68, 0x46, 0x03, 0x8c, 0xdd, 0x9c, 0x7d, 0xa0,
21506 0xcd, 0x1a, 0x41, 0x1c};
21508 return GFInv[Byte];
21513 unsigned NumBitsInByte = 8;
21516 for (
uint32_t BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21518 AQword.lshr((7 -
static_cast<int32_t>(BitIdx)) * NumBitsInByte)
21525 Product = AByte & XByte;
21530 for (
unsigned PBitIdx = 0; PBitIdx != NumBitsInByte; ++PBitIdx) {
21531 Parity = Parity ^ ((Product >> PBitIdx) & 0x1);
21534 uint8_t Temp = Imm[BitIdx] ? 1 : 0;
21535 RetByte |= (Temp ^ Parity) << BitIdx;
21545 unsigned NumBitsInByte = 8;
21546 for (
unsigned BitIdx = 0; BitIdx != NumBitsInByte; ++BitIdx) {
21547 if ((BByte >> BitIdx) & 0x1) {
21548 TWord = TWord ^ (AByte << BitIdx);
21556 for (
int32_t BitIdx = 14; BitIdx > 7; --BitIdx) {
21557 if ((TWord >> BitIdx) & 0x1) {
21558 TWord = TWord ^ (0x11B << (BitIdx - 8));
21561 return (TWord & 0xFF);
21565 APFloat &ResR, APFloat &ResI) {
21571 APFloat AC = A *
C;
21572 APFloat BD = B * D;
21573 APFloat AD = A * D;
21574 APFloat BC = B *
C;
21577 if (ResR.isNaN() && ResI.isNaN()) {
21578 bool Recalc =
false;
21579 if (A.isInfinity() || B.isInfinity()) {
21580 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21582 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21585 C = APFloat::copySign(APFloat(
C.getSemantics()),
C);
21587 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21590 if (
C.isInfinity() || D.isInfinity()) {
21591 C = APFloat::copySign(APFloat(
C.getSemantics(),
C.isInfinity() ? 1 : 0),
21593 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21596 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21598 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21601 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
21602 BC.isInfinity())) {
21604 A = APFloat::copySign(APFloat(A.getSemantics()), A);
21606 B = APFloat::copySign(APFloat(B.getSemantics()), B);
21608 C = APFloat::copySign(APFloat(
C.getSemantics()),
C);
21610 D = APFloat::copySign(APFloat(D.getSemantics()), D);
21614 ResR = APFloat::getInf(A.getSemantics()) * (A *
C - B * D);
21615 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B *
C);
21621 APFloat &ResR, APFloat &ResI) {
21628 APFloat MaxCD = maxnum(
abs(
C),
abs(D));
21629 if (MaxCD.isFinite()) {
21630 DenomLogB =
ilogb(MaxCD);
21631 C =
scalbn(
C, -DenomLogB, APFloat::rmNearestTiesToEven);
21632 D =
scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
21634 APFloat Denom =
C *
C + D * D;
21636 scalbn((A *
C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21638 scalbn((B *
C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
21639 if (ResR.isNaN() && ResI.isNaN()) {
21640 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
21641 ResR = APFloat::getInf(ResR.getSemantics(),
C.isNegative()) * A;
21642 ResI = APFloat::getInf(ResR.getSemantics(),
C.isNegative()) * B;
21643 }
else if ((A.isInfinity() || B.isInfinity()) &&
C.isFinite() &&
21645 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
21647 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
21649 ResR = APFloat::getInf(ResR.getSemantics()) * (A *
C + B * D);
21650 ResI = APFloat::getInf(ResI.getSemantics()) * (B *
C - A * D);
21651 }
else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
21652 C = APFloat::copySign(APFloat(
C.getSemantics(),
C.isInfinity() ? 1 : 0),
21654 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
21656 ResR = APFloat::getZero(ResR.getSemantics()) * (A *
C + B * D);
21657 ResI = APFloat::getZero(ResI.getSemantics()) * (B *
C - A * D);
21664 APSInt NormAmt = Amount;
21665 unsigned BitWidth =
Value.getBitWidth();
21666 unsigned AmtBitWidth = NormAmt.getBitWidth();
21667 if (BitWidth == 1) {
21669 NormAmt =
APSInt(APInt(AmtBitWidth, 0), NormAmt.isUnsigned());
21670 }
else if (BitWidth == 2) {
21675 APSInt(APInt(AmtBitWidth, NormAmt[0] ? 1 : 0), NormAmt.isUnsigned());
21678 if (AmtBitWidth > BitWidth) {
21679 Divisor = llvm::APInt(AmtBitWidth, BitWidth);
21681 Divisor = llvm::APInt(BitWidth, BitWidth);
21682 if (AmtBitWidth < BitWidth) {
21683 NormAmt = NormAmt.extend(BitWidth);
21688 if (NormAmt.isSigned()) {
21689 NormAmt =
APSInt(NormAmt.srem(Divisor),
false);
21690 if (NormAmt.isNegative()) {
21691 APSInt SignedDivisor(Divisor,
false);
21692 NormAmt += SignedDivisor;
21695 NormAmt =
APSInt(NormAmt.urem(Divisor),
true);
21702bool ComplexExprEvaluator::VisitBinaryOperator(
const BinaryOperator *E) {
21704 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
21708 bool LHSReal =
false, RHSReal =
false;
21716 Result.makeComplexFloat();
21720 LHSOK = Visit(E->
getLHS());
21722 if (!LHSOK && !Info.noteFailure())
21728 APFloat &Real = RHS.FloatReal;
21731 RHS.makeComplexFloat();
21732 RHS.FloatImag =
APFloat(Real.getSemantics());
21736 assert(!(LHSReal && RHSReal) &&
21737 "Cannot have both operands of a complex operation be real.");
21739 default:
return Error(E);
21741 if (
Result.isComplexFloat()) {
21742 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
21743 APFloat::rmNearestTiesToEven);
21745 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21747 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
21748 APFloat::rmNearestTiesToEven);
21750 Result.getComplexIntReal() += RHS.getComplexIntReal();
21751 Result.getComplexIntImag() += RHS.getComplexIntImag();
21755 if (
Result.isComplexFloat()) {
21756 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
21757 APFloat::rmNearestTiesToEven);
21759 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
21760 Result.getComplexFloatImag().changeSign();
21761 }
else if (!RHSReal) {
21762 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
21763 APFloat::rmNearestTiesToEven);
21766 Result.getComplexIntReal() -= RHS.getComplexIntReal();
21767 Result.getComplexIntImag() -= RHS.getComplexIntImag();
21771 if (
Result.isComplexFloat()) {
21776 ComplexValue LHS =
Result;
21777 APFloat &A = LHS.getComplexFloatReal();
21778 APFloat &B = LHS.getComplexFloatImag();
21779 APFloat &
C = RHS.getComplexFloatReal();
21780 APFloat &D = RHS.getComplexFloatImag();
21784 assert(!RHSReal &&
"Cannot have two real operands for a complex op!");
21792 }
else if (RHSReal) {
21804 ComplexValue LHS =
Result;
21805 Result.getComplexIntReal() =
21806 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
21807 LHS.getComplexIntImag() * RHS.getComplexIntImag());
21808 Result.getComplexIntImag() =
21809 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
21810 LHS.getComplexIntImag() * RHS.getComplexIntReal());
21814 if (
Result.isComplexFloat()) {
21819 ComplexValue LHS =
Result;
21820 APFloat &A = LHS.getComplexFloatReal();
21821 APFloat &B = LHS.getComplexFloatImag();
21822 APFloat &
C = RHS.getComplexFloatReal();
21823 APFloat &D = RHS.getComplexFloatImag();
21837 B = APFloat::getZero(A.getSemantics());
21842 ComplexValue LHS =
Result;
21843 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
21844 RHS.getComplexIntImag() * RHS.getComplexIntImag();
21846 return Error(E, diag::note_expr_divide_by_zero);
21848 Result.getComplexIntReal() =
21849 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
21850 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
21851 Result.getComplexIntImag() =
21852 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
21853 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
21861bool ComplexExprEvaluator::VisitUnaryOperator(
const UnaryOperator *E) {
21875 if (
Result.isComplexFloat()) {
21876 Result.getComplexFloatReal().changeSign();
21877 Result.getComplexFloatImag().changeSign();
21880 Result.getComplexIntReal() = -
Result.getComplexIntReal();
21881 Result.getComplexIntImag() = -
Result.getComplexIntImag();
21885 if (
Result.isComplexFloat())
21886 Result.getComplexFloatImag().changeSign();
21888 Result.getComplexIntImag() = -
Result.getComplexIntImag();
21893bool ComplexExprEvaluator::VisitInitListExpr(
const InitListExpr *E) {
21896 Result.makeComplexFloat();
21902 Result.makeComplexInt();
21910 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
21913bool ComplexExprEvaluator::VisitCallExpr(
const CallExpr *E) {
21914 if (!IsConstantEvaluatedBuiltinCall(E))
21915 return ExprEvaluatorBaseTy::VisitCallExpr(E);
21918 case Builtin::BI__builtin_complex:
21919 Result.makeComplexFloat();
21937class AtomicExprEvaluator :
21938 public ExprEvaluatorBase<AtomicExprEvaluator> {
21939 const LValue *
This;
21942 AtomicExprEvaluator(EvalInfo &Info,
const LValue *This,
APValue &
Result)
21950 bool ZeroInitialization(
const Expr *E) {
21951 ImplicitValueInitExpr VIE(
21959 bool VisitCastExpr(
const CastExpr *E) {
21962 return ExprEvaluatorBaseTy::VisitCastExpr(E);
21963 case CK_NullToPointer:
21965 return ZeroInitialization(E);
21966 case CK_NonAtomicToAtomic:
21978 return AtomicExprEvaluator(Info,
This,
Result).Visit(E);
21987class VoidExprEvaluator
21988 :
public ExprEvaluatorBase<VoidExprEvaluator> {
21990 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
21994 bool ZeroInitialization(
const Expr *E) {
return true; }
21996 bool VisitCastExpr(
const CastExpr *E) {
21999 return ExprEvaluatorBaseTy::VisitCastExpr(E);
22006 bool VisitCallExpr(
const CallExpr *E) {
22007 if (!IsConstantEvaluatedBuiltinCall(E))
22008 return ExprEvaluatorBaseTy::VisitCallExpr(E);
22011 case Builtin::BI__assume:
22012 case Builtin::BI__builtin_assume:
22016 case Builtin::BI__builtin_operator_delete:
22019 case Builtin::BIstdc_memreverse8:
22020 case Builtin::BI__builtin_stdc_memreverse8: {
22024 uint64_t NElems = N.getZExtValue();
22030 if (!
Ptr.checkNullPointerForFoldAccess(Info, E,
AK_Assign) ||
22031 Ptr.Designator.Invalid)
22034 QualType CharTy =
Ptr.Designator.getType(Info.Ctx);
22035 uint64_t RemainingElems =
Ptr.Designator.validIndexAdjustments().second;
22036 if (NElems > RemainingElems) {
22038 Ptr.Designator.MostDerivedIsArrayElement
22039 ?
Ptr.Designator.Entries.back().getAsArrayIndex()
22042 APSInt::getUnsigned(llvm::SaturatingAdd(ArrayIndex, NElems - 1));
22043 Ptr.Designator.diagnosePointerArithmetic(Info, E, Index);
22073 bool VisitCXXDeleteExpr(
const CXXDeleteExpr *E);
22077bool VoidExprEvaluator::VisitCXXDeleteExpr(
const CXXDeleteExpr *E) {
22079 if (Info.SpeculativeEvaluationDepth)
22083 if (!OperatorDelete
22084 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
22085 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
22095 if (
Pointer.Designator.Invalid)
22099 if (
Pointer.isNullPointer()) {
22103 if (!Info.getLangOpts().CPlusPlus20)
22104 Info.CCEDiag(E, diag::note_constexpr_new);
22110 E->
isArrayForm() ? DynAllocKind::ArrayNew : DynAllocKind::New);
22113 QualType AllocType =
Pointer.Base.getDynamicAllocType();
22119 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
22128 if (VirtualDelete &&
22130 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
22131 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
22138 (*Alloc)->Value, AllocType))
22141 if (!Info.HeapAllocs.erase(
Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
22146 Info.FFDiag(E, diag::note_constexpr_double_delete);
22156 return VoidExprEvaluator(Info).Visit(E);
22168 if (E->
isGLValue() ||
T->isFunctionType()) {
22173 }
else if (
T->isVectorType()) {
22176 }
else if (
T->isConstantMatrixType()) {
22179 }
else if (
T->isIntegralOrEnumerationType()) {
22180 if (!IntExprEvaluator(Info,
Result).Visit(E))
22182 }
else if (
T->isMetaInfoType()) {
22185 }
else if (
T->hasPointerRepresentation()) {
22190 }
else if (
T->isRealFloatingType()) {
22191 llvm::APFloat F(0.0);
22195 }
else if (
T->isAnyComplexType()) {
22200 }
else if (
T->isFixedPointType()) {
22201 if (!FixedPointExprEvaluator(Info,
Result).Visit(E))
return false;
22202 }
else if (
T->isMemberPointerType()) {
22208 }
else if (
T->isArrayType()) {
22211 Info.CurrentCall->createTemporary(E,
T, ScopeKind::FullExpression, LV);
22215 }
else if (
T->isRecordType()) {
22218 Info.CurrentCall->createTemporary(E,
T, ScopeKind::FullExpression, LV);
22222 }
else if (
T->isVoidType()) {
22223 if (!Info.getLangOpts().CPlusPlus11)
22224 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
22228 }
else if (
T->isAtomicType()) {
22229 QualType Unqual =
T.getAtomicUnqualifiedType();
22233 E, Unqual, ScopeKind::FullExpression, LV);
22241 }
else if (Info.getLangOpts().CPlusPlus11) {
22242 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->
getType();
22245 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
22256 const Expr *E,
bool AllowNonLiteralTypes) {
22272 if (
T->isArrayType())
22274 else if (
T->isRecordType())
22276 else if (
T->isAtomicType()) {
22277 QualType Unqual =
T.getAtomicUnqualifiedType();
22291 assert(!Info.Ctx.getLangOpts().EnableNewConstInterp);
22305 LV.setFrom(Info.Ctx,
Result);
22312 ConstantExprKind::Normal) &&
22320 if (
const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
22322 APValue(
APSInt(L->getValue(), L->getType()->isUnsignedIntegerType()));
22327 if (
const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
22333 if (
const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
22339 if (
const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
22345 if (
const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
22346 if (CE->hasAPValueResult()) {
22347 APValue APV = CE->getAPValueResult();
22349 Result = std::move(APV);
22421 bool InConstantContext) {
22423 "Expression evaluator can't be called on a dependent expression.");
22437 Info.InConstantContext = InConstantContext;
22438 return ::EvaluateAsRValue(E,
Result, Ctx, Info);
22447 bool InConstantContext)
const {
22448 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsRValue");
22449 return ::doEvaluateAsRValue(
this,
Result, Ctx,
nullptr,
22450 InConstantContext);
22456 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsMandatedConstantRValue");
22457 return ::doEvaluateAsRValue(
this,
Result, Ctx, &SProxy,
22462 bool InConstantContext)
const {
22464 "Expression evaluator can't be called on a dependent expression.");
22465 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsBooleanCondition");
22473 bool InConstantContext)
const {
22475 "Expression evaluator can't be called on a dependent expression.");
22477 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsInt");
22479 if (!
getType()->isIntegralOrEnumerationType())
22493 if (!
Result.Val.isInt() ||
22499 EvalInfo Info(Ctx,
nullptr,
Result,
22501 Info.InConstantContext = InConstantContext;
22502 return ::EvaluateAsInt(
this,
Result, Ctx, AllowSideEffects, Info);
22507 bool InConstantContext)
const {
22509 "Expression evaluator can't be called on a dependent expression.");
22510 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsFixedPoint");
22512 if (!
getType()->isFixedPointType())
22523 if (!
Result.Val.isFixedPoint() ||
22530 EvalInfo Info(Ctx,
nullptr,
Result,
22532 Info.InConstantContext = InConstantContext;
22533 return ::EvaluateAsFixedPoint(
this,
Result, Ctx, AllowSideEffects, Info);
22538 bool InConstantContext)
const {
22540 "Expression evaluator can't be called on a dependent expression.");
22542 if (!
getType()->isRealFloatingType())
22545 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsFloat");
22557 bool InConstantContext)
const {
22559 "Expression evaluator can't be called on a dependent expression.");
22561 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsLValue");
22571 Info.InConstantContext = InConstantContext;
22575 if (!
EvaluateLValue(
this, LV, Info) || !Info.discardCleanups() ||
22576 Result.HasSideEffects ||
22579 ConstantExprKind::Normal, CheckedTemps))
22582 LV.moveInto(
Result.Val);
22590 bool IsConstantDestruction) {
22591 EvalInfo Info(Ctx, SProxy, EStatus,
22594 Info.setEvaluatingDecl(
Base, DestroyedValue,
22595 EvalInfo::EvaluatingDeclKind::Dtor);
22596 Info.InConstantContext = IsConstantDestruction;
22605 if (!Info.discardCleanups())
22606 llvm_unreachable(
"Unhandled cleanup; missing full expression marker?");
22615 "Expression evaluator can't be called on a dependent expression.");
22632 EvalInfo Info(Ctx, SProxy,
Result, EM);
22633 Info.InConstantContext =
true;
22637 if (Kind == ConstantExprKind::ClassTemplateArgument)
22653 FullExpressionRAII
Scope(Info);
22658 if (!Info.discardCleanups())
22659 llvm_unreachable(
"Unhandled cleanup; missing full expression marker?");
22661 if (
Result.HasSideEffects ||
22670 if (Kind == ConstantExprKind::ClassTemplateArgument &&
22673 Result.HasSideEffects)) {
22685 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsConstantExpr");
22686 return ::doEvaluateConstantExpr(
Result, Ctx,
nullptr,
this, Kind);
22693 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateAsMandatedConstantExpr");
22694 return ::doEvaluateConstantExpr(
Result, Ctx, &SProxy,
this, Kind);
22700 bool IsConstantInitialization) {
22702 "Expression evaluator can't be called on a dependent expression.");
22703 assert(VD &&
"Need a valid VarDecl");
22706 (IsConstantInitialization &&
22721 EvalInfo Info(Ctx, SProxy, EStatus, EvalMode);
22722 Info.setEvaluatingDecl(VD, EStatus.
Val);
22723 Info.InConstantContext = IsConstantInitialization;
22738 FullExpressionRAII
Scope(Info);
22747 Info.performLifetimeExtension();
22749 if (!Info.discardCleanups())
22750 llvm_unreachable(
"Unhandled cleanup; missing full expression marker?");
22753 ConstantExprKind::Normal) &&
22759 bool IsConstantInitialization)
const {
22760 llvm::TimeTraceScope TimeScope(
"EvaluateAsInitializer", [&] {
22762 llvm::raw_string_ostream OS(Name);
22767 return ::doEvaluateInitializer(Ctx,
nullptr, VD,
this, EStatus,
22768 IsConstantInitialization);
22775 llvm::TimeTraceScope TimeScope(
"EvaluateAsMandatedConstantInitializer", [&] {
22777 llvm::raw_string_ostream OS(Name);
22782 return ::doEvaluateInitializer(Ctx, &SProxy, VD,
this, EStatus,
22787 bool IsConstantDestruction,
22805 EStatus.
Diag = &Notes;
22823 std::move(DestroyedValue)))
22830 VD->
getLocation(), EStatus, IsConstantDestruction) ||
22844 return ::doEvaluateDestruction(
this,
nullptr,
22845 IsConstantDestruction, Notes);
22854 return ::doEvaluateDestruction(
this, &SProxy, IsConstantDestruction, Notes);
22861 "Expression evaluator can't be called on a dependent expression.");
22870 "Expression evaluator can't be called on a dependent expression.");
22872 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateKnownConstInt");
22878 assert(EVResult.Val.isInt() &&
"Expression did not evaluate to integer");
22879 return EVResult.Val.getInt();
22886 [[maybe_unused]]
bool Result =
22888 assert(
Result &&
"Could not evaluate expression");
22889 assert(EVResult.Val.isInt() &&
"Expression did not evaluate to integer");
22891 return EVResult.Val.getInt();
22894 EvalInfo Info(Ctx,
nullptr, EVResult,
22896 Info.InConstantContext =
true;
22900 assert(
Result &&
"Could not evaluate expression");
22901 assert(EVResult.Val.isInt() &&
"Expression did not evaluate to integer");
22903 return EVResult.Val.getInt();
22909 "Expression evaluator can't be called on a dependent expression.");
22911 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateKnownConstIntCheckOverflow");
22913 EVResult.Diag =
Diag;
22918 assert(EVResult.Val.isInt() &&
"Expression did not evaluate to integer");
22919 return EVResult.Val.getInt();
22927 [[maybe_unused]]
bool Result =
22929 assert(
Result &&
"Could not evaluate expression");
22930 assert(EVResult.Val.isInt() &&
"Expression did not evaluate to integer");
22932 return EVResult.Val.getInt();
22935 EvalInfo Info(Ctx,
nullptr, EVResult,
22937 Info.InConstantContext =
true;
22938 Info.CheckingForUndefinedBehavior =
true;
22942 assert(
Result &&
"Could not evaluate expression");
22943 assert(EVResult.Val.isInt() &&
"Expression did not evaluate to integer");
22945 return EVResult.Val.getInt();
22950 "Expression evaluator can't be called on a dependent expression.");
22952 ExprTimeTraceScope TimeScope(
this, Ctx,
"EvaluateForOverflow");
22966 EvalInfo Info(Ctx,
nullptr, EVResult,
22968 Info.CheckingForUndefinedBehavior =
true;
22973 assert(
Val.isLValue());
22999 IK_ICEIfUnevaluated,
23015static ICEDiag
Worst(ICEDiag A, ICEDiag B) {
return A.Kind >= B.Kind ? A : B; }
23031 EvalInfo Info(Ctx,
nullptr, Status,
23034 Info.InConstantContext =
true;
23043 assert(!E->
isValueDependent() &&
"Should not see value dependent exprs!");
23048#define ABSTRACT_STMT(Node)
23049#define STMT(Node, Base) case Expr::Node##Class:
23050#define EXPR(Node, Base)
23051#include "clang/AST/StmtNodes.inc"
23052 case Expr::PredefinedExprClass:
23053 case Expr::FloatingLiteralClass:
23054 case Expr::ImaginaryLiteralClass:
23055 case Expr::StringLiteralClass:
23056 case Expr::ArraySubscriptExprClass:
23057 case Expr::MatrixSingleSubscriptExprClass:
23058 case Expr::MatrixSubscriptExprClass:
23059 case Expr::ArraySectionExprClass:
23060 case Expr::OMPArrayShapingExprClass:
23061 case Expr::OMPIteratorExprClass:
23062 case Expr::CompoundAssignOperatorClass:
23063 case Expr::CompoundLiteralExprClass:
23064 case Expr::ExtVectorElementExprClass:
23065 case Expr::MatrixElementExprClass:
23066 case Expr::DesignatedInitExprClass:
23067 case Expr::ArrayInitLoopExprClass:
23068 case Expr::ArrayInitIndexExprClass:
23069 case Expr::NoInitExprClass:
23070 case Expr::DesignatedInitUpdateExprClass:
23071 case Expr::ImplicitValueInitExprClass:
23072 case Expr::ParenListExprClass:
23073 case Expr::VAArgExprClass:
23074 case Expr::AddrLabelExprClass:
23075 case Expr::StmtExprClass:
23076 case Expr::CXXMemberCallExprClass:
23077 case Expr::CUDAKernelCallExprClass:
23078 case Expr::CXXAddrspaceCastExprClass:
23079 case Expr::CXXDynamicCastExprClass:
23080 case Expr::CXXTypeidExprClass:
23081 case Expr::CXXUuidofExprClass:
23082 case Expr::MSPropertyRefExprClass:
23083 case Expr::MSPropertySubscriptExprClass:
23084 case Expr::CXXNullPtrLiteralExprClass:
23085 case Expr::UserDefinedLiteralClass:
23086 case Expr::CXXThisExprClass:
23087 case Expr::CXXThrowExprClass:
23088 case Expr::CXXNewExprClass:
23089 case Expr::CXXDeleteExprClass:
23090 case Expr::CXXPseudoDestructorExprClass:
23091 case Expr::UnresolvedLookupExprClass:
23092 case Expr::RecoveryExprClass:
23093 case Expr::DependentScopeDeclRefExprClass:
23094 case Expr::DependentTemplateIdExprClass:
23095 case Expr::CXXConstructExprClass:
23096 case Expr::CXXInheritedCtorInitExprClass:
23097 case Expr::CXXStdInitializerListExprClass:
23098 case Expr::CXXBindTemporaryExprClass:
23099 case Expr::ExprWithCleanupsClass:
23100 case Expr::CXXTemporaryObjectExprClass:
23101 case Expr::CXXUnresolvedConstructExprClass:
23102 case Expr::CXXDependentScopeMemberExprClass:
23103 case Expr::UnresolvedMemberExprClass:
23104 case Expr::ObjCStringLiteralClass:
23105 case Expr::ObjCBoxedExprClass:
23106 case Expr::ObjCArrayLiteralClass:
23107 case Expr::ObjCDictionaryLiteralClass:
23108 case Expr::ObjCEncodeExprClass:
23109 case Expr::ObjCMessageExprClass:
23110 case Expr::ObjCSelectorExprClass:
23111 case Expr::ObjCProtocolExprClass:
23112 case Expr::ObjCIvarRefExprClass:
23113 case Expr::ObjCPropertyRefExprClass:
23114 case Expr::ObjCSubscriptRefExprClass:
23115 case Expr::ObjCIsaExprClass:
23116 case Expr::ObjCAvailabilityCheckExprClass:
23117 case Expr::ShuffleVectorExprClass:
23118 case Expr::ConvertVectorExprClass:
23119 case Expr::BlockExprClass:
23121 case Expr::OpaqueValueExprClass:
23122 case Expr::PackExpansionExprClass:
23123 case Expr::SubstNonTypeTemplateParmPackExprClass:
23124 case Expr::FunctionParmPackExprClass:
23125 case Expr::AsTypeExprClass:
23126 case Expr::ObjCIndirectCopyRestoreExprClass:
23127 case Expr::MaterializeTemporaryExprClass:
23128 case Expr::PseudoObjectExprClass:
23129 case Expr::AtomicExprClass:
23130 case Expr::LambdaExprClass:
23131 case Expr::CXXFoldExprClass:
23132 case Expr::CoawaitExprClass:
23133 case Expr::DependentCoawaitExprClass:
23134 case Expr::CoyieldExprClass:
23135 case Expr::SYCLUniqueStableNameExprClass:
23136 case Expr::CXXParenListInitExprClass:
23137 case Expr::HLSLOutArgExprClass:
23138 case Expr::CXXExpansionSelectExprClass:
23141 case Expr::MemberExprClass: {
23144 while (
const auto *M = dyn_cast<MemberExpr>(ME)) {
23147 ME = M->getBase()->IgnoreParenImpCasts();
23149 const auto *DRE = dyn_cast<DeclRefExpr>(ME);
23151 if (
const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
23159 case Expr::InitListExprClass: {
23170 case Expr::SizeOfPackExprClass:
23171 case Expr::GNUNullExprClass:
23172 case Expr::SourceLocExprClass:
23173 case Expr::EmbedExprClass:
23174 case Expr::OpenACCAsteriskSizeExprClass:
23177 case Expr::PackIndexingExprClass:
23180 case Expr::SubstNonTypeTemplateParmExprClass:
23184 case Expr::ConstantExprClass:
23187 case Expr::ParenExprClass:
23189 case Expr::GenericSelectionExprClass:
23191 case Expr::IntegerLiteralClass:
23192 case Expr::FixedPointLiteralClass:
23193 case Expr::CharacterLiteralClass:
23194 case Expr::ObjCBoolLiteralExprClass:
23195 case Expr::CXXBoolLiteralExprClass:
23196 case Expr::CXXScalarValueInitExprClass:
23197 case Expr::TypeTraitExprClass:
23198 case Expr::ConceptSpecializationExprClass:
23199 case Expr::RequiresExprClass:
23200 case Expr::ArrayTypeTraitExprClass:
23201 case Expr::ExpressionTraitExprClass:
23202 case Expr::CXXNoexceptExprClass:
23203 case Expr::CXXReflectExprClass:
23205 case Expr::CallExprClass:
23206 case Expr::CXXOperatorCallExprClass: {
23215 case Expr::CXXRewrittenBinaryOperatorClass:
23218 case Expr::DeclRefExprClass: {
23232 const VarDecl *VD = dyn_cast<VarDecl>(D);
23239 case Expr::UnaryOperatorClass: {
23262 llvm_unreachable(
"invalid unary operator class");
23264 case Expr::OffsetOfExprClass: {
23273 case Expr::UnaryExprOrTypeTraitExprClass: {
23275 if ((Exp->
getKind() == UETT_SizeOf) &&
23278 if (Exp->
getKind() == UETT_CountOf) {
23285 if (VAT->getElementType()->isArrayType())
23297 case Expr::BinaryOperatorClass: {
23342 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
23345 return ICEDiag(IK_ICEIfUnevaluated, E->
getBeginLoc());
23346 if (REval.isSigned() && REval.isAllOnes()) {
23348 if (LEval.isMinSignedValue())
23349 return ICEDiag(IK_ICEIfUnevaluated, E->
getBeginLoc());
23357 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
23358 return ICEDiag(IK_ICEIfUnevaluated, E->
getBeginLoc());
23364 return Worst(LHSResult, RHSResult);
23370 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
23380 return Worst(LHSResult, RHSResult);
23383 llvm_unreachable(
"invalid binary operator kind");
23385 case Expr::ImplicitCastExprClass:
23386 case Expr::CStyleCastExprClass:
23387 case Expr::CXXFunctionalCastExprClass:
23388 case Expr::CXXStaticCastExprClass:
23389 case Expr::CXXReinterpretCastExprClass:
23390 case Expr::CXXConstCastExprClass:
23391 case Expr::ObjCBridgedCastExprClass: {
23398 APSInt IgnoredVal(DestWidth, !DestSigned);
23403 if (FL->getValue().convertToInteger(IgnoredVal,
23404 llvm::APFloat::rmTowardZero,
23405 &Ignored) & APFloat::opInvalidOp)
23411 case CK_LValueToRValue:
23412 case CK_AtomicToNonAtomic:
23413 case CK_NonAtomicToAtomic:
23415 case CK_IntegralToBoolean:
23416 case CK_IntegralCast:
23422 case Expr::BinaryConditionalOperatorClass: {
23425 if (CommonResult.Kind == IK_NotICE)
return CommonResult;
23427 if (FalseResult.Kind == IK_NotICE)
return FalseResult;
23428 if (CommonResult.Kind == IK_ICEIfUnevaluated)
return CommonResult;
23429 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
23431 return FalseResult;
23433 case Expr::ConditionalOperatorClass: {
23441 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
23444 if (CondResult.Kind == IK_NotICE)
23450 if (TrueResult.Kind == IK_NotICE)
23452 if (FalseResult.Kind == IK_NotICE)
23453 return FalseResult;
23454 if (CondResult.Kind == IK_ICEIfUnevaluated)
23456 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
23462 return FalseResult;
23465 case Expr::CXXDefaultArgExprClass:
23467 case Expr::CXXDefaultInitExprClass:
23469 case Expr::ChooseExprClass: {
23472 case Expr::BuiltinBitCastExprClass: {
23473 if (!checkBitCastConstexprEligibility(
nullptr, Ctx,
cast<CastExpr>(E)))
23479 llvm_unreachable(
"Invalid StmtClass!");
23485 llvm::APSInt *
Value,
23486 bool AllowRelaxedEval =
false) {
23503 "Expression evaluator can't be called on a dependent expression.");
23505 ExprTimeTraceScope TimeScope(
this, Ctx,
"isIntegerConstantExpr");
23511 if (D.Kind != IK_ICE)
23516std::optional<llvm::APSInt>
23518 bool AllowRelaxedEval)
const {
23521 return std::nullopt;
23529 return std::nullopt;
23533 return std::nullopt;
23547 llvm_unreachable(
"ICE cannot be evaluated!");
23552 EvalInfo Info(Ctx,
nullptr, Status,
23554 Info.InConstantContext =
true;
23557 llvm_unreachable(
"ICE cannot be evaluated!");
23564 "Expression evaluator can't be called on a dependent expression.");
23566 return CheckICE(
this, Ctx).Kind == IK_ICE;
23570 bool AllowRelaxedEval)
const {
23572 "Expression evaluator can't be called on a dependent expression.");
23585 Status.ExtendedDiag = AllowRelaxedEval ? &MSRelaxedDiag :
nullptr;
23594 EvalInfo Info(Ctx,
nullptr, Status,
23600 Info.discardCleanups() && !Status.HasSideEffects;
23602 return IsConstExpr && !Status.DiagEmitted;
23610 "Expression evaluator can't be called on a dependent expression.");
23612 llvm::TimeTraceScope TimeScope(
"EvaluateWithSubstitution", [&] {
23614 llvm::raw_string_ostream OS(Name);
23626 if (std::optional<bool> BoolResult =
23628 Args,
This,
this)) {
23635 EvalInfo Info(Ctx,
nullptr, Status,
23637 Info.InConstantContext =
true;
23640 const LValue *ThisPtr =
nullptr;
23643 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
23644 assert(MD &&
"Don't provide `this` for non-methods.");
23645 assert(MD->isImplicitObjectMemberFunction() &&
23646 "Don't provide `this` for methods without an implicit object.");
23648 if (!
This->isValueDependent() &&
23650 !Info.EvalStatus.HasSideEffects)
23651 ThisPtr = &ThisVal;
23655 Info.EvalStatus.HasSideEffects =
false;
23658 CallRef
Call = Info.CurrentCall->createCall(Callee);
23661 unsigned Idx = I - Args.begin();
23662 if (Idx >= Callee->getNumParams())
23664 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
23665 if ((*I)->isValueDependent() ||
23667 Info.EvalStatus.HasSideEffects) {
23669 if (
APValue *Slot = Info.getParamSlot(
Call, PVD))
23675 Info.EvalStatus.HasSideEffects =
false;
23680 Info.discardCleanups();
23681 Info.EvalStatus.HasSideEffects =
false;
23684 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
This,
23687 FullExpressionRAII
Scope(Info);
23689 !Info.EvalStatus.HasSideEffects;
23701 llvm::TimeTraceScope TimeScope(
"isPotentialConstantExpr", [&] {
23703 llvm::raw_string_ostream OS(Name);
23711 Status.
Diag = &Diags;
23714 if (Ctx.getLangOpts().EnableNewConstInterp) {
23719 Ctx.getInterpContext().isPotentialConstantExpr(Settings, FD);
23720 return Diags.empty();
23723 EvalInfo Info(Ctx,
nullptr, Status,
23725 Info.InConstantContext =
true;
23726 Info.CheckingPotentialConstantExpression =
true;
23736 This.set({&VIE, Info.CurrentCall->Index});
23744 Info.setEvaluatingDecl(
This.getLValueBase(), Scratch);
23750 &VIE, Args, CallRef(), FD->
getBody(), Info, Scratch,
23754 return Diags.empty();
23762 "Expression evaluator can't be called on a dependent expression.");
23766 Status.
Diag = &Diags;
23774 return Diags.empty();
23777 EvalInfo Info(Ctx,
nullptr, Status,
23779 Info.InConstantContext =
true;
23780 Info.CheckingPotentialConstantExpression =
true;
23784 nullptr, CallRef());
23788 return Diags.empty();
23792 unsigned Type)
const {
23793 if (!
getType()->isPointerType())
23794 return std::nullopt;
23808static std::optional<uint64_t>
23810 std::string *StringResult) {
23812 return std::nullopt;
23817 return std::nullopt;
23820 if (
const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
23821 String.getLValueBase().dyn_cast<
const Expr *>())) {
23826 if (StringResult) {
23828 Str = Str.substr(
Off, *ZeroIndex);
23829 *StringResult = Str;
23832 return ZeroIndex.
value_or(Str.size());
23839 for (
uint64_t Strlen = 0; ; ++Strlen) {
23843 return std::nullopt;
23846 else if (StringResult)
23847 StringResult->push_back(Char.
getInt().getExtValue());
23849 return std::nullopt;
23855 std::string StringResult;
23861 return std::nullopt;
23862 return StringResult;
23867 return StringResult;
23868 return std::nullopt;
23871template <
typename T>
23873 const Expr *SizeExpression,
23874 const Expr *PtrExpression,
23886 Info.InConstantContext =
true;
23889 FullExpressionRAII
Scope(Info);
23894 uint64_t Size = SizeValue.getZExtValue();
23897 if constexpr (std::is_same_v<APValue, T>)
23900 if (Size <
Result.max_size())
23907 for (
uint64_t I = 0; I < Size; ++I) {
23913 if constexpr (std::is_same_v<APValue, T>) {
23914 Result.getArrayInitializedElt(I) = std::move(Char);
23918 assert(
C.getBitWidth() <= 8 &&
23919 "string element not representable in char");
23921 Result.push_back(
static_cast<char>(
C.getExtValue()));
23932 const Expr *SizeExpression,
23937 PtrExpression, Ctx, SProxy, Status);
23941 const Expr *SizeExpression,
23946 PtrExpression, Ctx, SProxy, Status);
23962struct IsWithinLifetimeHandler {
23965 using result_type = std::optional<bool>;
23966 std::optional<bool> failed() {
return std::nullopt; }
23967 template <
typename T>
23968 std::optional<bool> found(
T &Subobj,
QualType SubobjType,
23972 template <
typename T>
23973 std::optional<bool> found(
T &Subobj, QualType SubobjType) {
23978std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
23979 const CallExpr *E) {
23980 EvalInfo &Info = IEE.Info;
23985 if (!Info.InConstantContext)
23986 return std::nullopt;
23988 const Expr *Arg = E->
getArg(0);
23990 return std::nullopt;
23993 return std::nullopt;
23995 if (Val.allowConstexprUnknown())
23999 bool CalledFromStd =
false;
24000 const auto *
Callee = Info.CurrentCall->getCallee();
24001 if (Callee &&
Callee->isInStdNamespace()) {
24002 const IdentifierInfo *Identifier =
Callee->getIdentifier();
24003 CalledFromStd = Identifier && Identifier->
isStr(
"is_within_lifetime");
24005 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
24007 diag::err_invalid_is_within_lifetime)
24008 << (CalledFromStd ?
"std::is_within_lifetime"
24009 :
"__builtin_is_within_lifetime")
24011 return std::nullopt;
24021 if (Val.isNullPointer() || Val.getLValueBase().isNull())
24023 QualType
T = Val.getLValueBase().getType();
24025 "Pointers to functions should have been typed as function pointers "
24026 "which would have been rejected earlier");
24029 if (Val.getLValueDesignator().isOnePastTheEnd())
24031 assert(Val.getLValueDesignator().isValidSubobject() &&
24032 "Unchecked case for valid subobject");
24036 CompleteObject CO =
24040 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
24045 IsWithinLifetimeHandler handler{Info};
24046 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isUnsigned(SValBuilder &SVB, NonLoc Value)
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
static uint32_t getBitWidth(const Expr *E)
static Decl::Kind getKind(const Decl *D)
bool isTemplateArgument(ConstantExprKind Kind)
bool isOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
bool isForManglingOnly(ConstantExprKind Kind)
Determines whether the given kind of constant expression is only ever used for name mangling.
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
@ PointerToMemberFunction
static bool isRead(AccessKinds AK)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of access valid on an indeterminate object value?
static unsigned elementwiseSize(EvalInfo &Info, QualType BaseTy)
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps, bool IsCompleteClass=true)
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool evalPackBuiltin(const CallExpr *E, EvalInfo &Info, APValue &Result, llvm::function_ref< APInt(const APSInt &)> PackFn)
static bool EvaluateReflection(const Expr *E, APValue &Result, EvalInfo &Info)
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool hlslElementwiseCastHelper(EvalInfo &Info, const Expr *E, QualType DestTy, SmallVectorImpl< APValue > &SrcVals, SmallVectorImpl< QualType > &SrcTypes)
static bool ShouldPropagateBreakContinue(EvalInfo &Info, const Stmt *LoopOrSwitch, ArrayRef< BlockScopeRAII * > Scopes, EvalStmtResult &ESR)
Helper to implement named break/continue.
static bool doEvaluateAsRValue(const Expr *E, Expr::EvalResult &Result, const ASTContext &Ctx, SemaProxy *SProxy, bool InConstantContext)
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
std::optional< APFloat > EvalScalarMinMaxFp(const APFloat &A, const APFloat &B, std::optional< APSInt > RoundingMode, bool IsMin)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static llvm::APInt ConvertBoolVectorToInt(const APValue &Val)
static bool flattenAPValue(EvalInfo &Info, const Expr *E, APValue Value, QualType BaseTy, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &Types, unsigned Size)
static bool hlslAggSplatHelper(EvalInfo &Info, const Expr *E, APValue &SrcVal, QualType &SrcTy)
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
unsigned ConvertBuiltinIDToX86BuiltinID(const ASTContext &Ctx, unsigned BuiltinOp)
Convert a builtin ID to the canonical x86 builtin ID the constant evaluators dispatch on in their x86...
static bool ConvertDoubleToFloatStrict(EvalInfo &Info, const Expr *E, APFloat OrigVal, APValue &Result)
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static bool checkFloatingPointResultForConstantFolding(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given floating-point evaluation result is allowed for compile-time constant folding duri...
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAllocKind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool handleElementwiseCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &SrcTypes, SmallVectorImpl< QualType > &DestTypes, SmallVectorImpl< APValue > &Results)
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid)....
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool EvaluateDecompositionDeclInit(EvalInfo &Info, const DecompositionDecl *DD)
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static bool constructAggregate(EvalInfo &Info, const FPOptions FPO, const Expr *E, APValue &Result, QualType ResultType, SmallVectorImpl< APValue > &Elements, SmallVectorImpl< QualType > &ElTypes)
static bool doEvaluateDestruction(const VarDecl *VD, SemaProxy *SProxy, bool IsConstantDestruction, SmallVectorImpl< PartialDiagnosticAt > &Notes)
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool evalShuffleGeneric(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< std::pair< unsigned, int >(unsigned, unsigned)> GetSourceIndex)
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleLValueDirectVirtualBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
static void expandVector(APValue &Vec, unsigned NumElements)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool IsOpaqueConstantCall(const LValue &LVal)
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
static std::optional< uint64_t > EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info, std::string *StringResult=nullptr)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static void TryInstantiateFunctionBeforeCall(const FunctionDecl *FD, EvalInfo &Info, SourceLocation Loc)
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static bool EvaluateDecl(EvalInfo &Info, const Decl *D, bool EvaluateConditionDecl=false)
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool doEvaluateInitializer(const ASTContext &Ctx, SemaProxy *SProxy, const VarDecl *VD, const Expr *E, Expr::EvalResult &EStatus, bool IsConstantInitialization)
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T, bool IsCompleteClass=true)
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static bool EvaluateComparisonResult(EvalInfo &Info, const Expr *E, ComparisonCategoryResult CCR, APValue &Result)
static bool EvaluateMatrix(const Expr *E, APValue &Result, EvalInfo &Info)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout....
bool isGlobalLValue(const ValueDecl *D, const Expr *E)
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue. In some cases, the in-place evaluati...
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result, bool IsCompleteClass=true)
Perform zero-initialization on an object of non-union class type. C++11 [dcl.init]p5: To zero-initial...
static bool EvaluateDestruction(const ASTContext &Ctx, SemaProxy *SProxy, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, bool AllowRelaxedEval=false)
Evaluate an expression as a C++11 integral constant expression.
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue. This can be legitimately called on expressions which are not glv...
static bool EvaluateReflectionMetafunctionBuiltin(EvalInfo &Info, const CallExpr *E, unsigned BuiltinOp, APValue &Result)
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result, bool IsCompleteClass=true)
Evaluate a constructor call.
static bool FastEvaluateAsRValue(const Expr *Exp, APValue &Result, const ASTContext &Ctx, bool &IsConst)
static bool doEvaluateConstantExpr(Expr::EvalResult &Result, const ASTContext &Ctx, SemaProxy *SProxy, const Expr *E, ConstantExprKind Kind)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static bool evalShiftWithCount(EvalInfo &Info, const CallExpr *Call, APValue &Out, llvm::function_ref< APInt(const APInt &, uint64_t)> ShiftOp, llvm::function_ref< APInt(const APInt &, unsigned)> OverflowOp)
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false, LValue *ObjectArg=nullptr)
Evaluate the arguments to a function call.
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const LValue &LVal, llvm::APInt &Result)
Convenience function. LVal's base must be a call to an alloc_size function.
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool EvaluateInitForDeclOfReferenceType(EvalInfo &Info, const ValueDecl *D, const Expr *Init, LValue &Result, APValue &Val)
Evaluates the initializer of a reference.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
bool FunctionDefinitionCanBeLazilyInstantiated(const FunctionDecl *FD)
Whether we can instantiate FD during constant evaluation.
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned. Fails if the conversion would ...
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false, APValue **EvaluatedArg=nullptr)
llvm::SmallPtrSet< const MaterializeTemporaryExpr *, 8 > CheckedTemporaries
Materialized temporaries that we've already checked to determine if they're initializsed by a constan...
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static bool MaybeEvaluateDeferredVarDeclInit(EvalInfo &Info, const VarDecl *VD)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static bool EvaluateCharRangeAsStringImpl(const Expr *, T &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, SemaProxy &SProxy, Expr::EvalResult &Status)
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool handleDefaultInitValue(QualType T, APValue &Result, bool IsCompleteClass=true)
Get the value to use for a default-initialized object of type T.
static bool EvaluateStdcLoad8(EvalInfo &Info, const CallExpr *E, bool IsBE, bool IsAligned, APSInt &Result)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static std::optional< uint64_t > tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, bool IsDynamic=false)
Tries to evaluate the __builtin_object_size for E.
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *ObjectArg, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
uint8_t GFNIMul(uint8_t AByte, uint8_t BByte)
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
uint8_t GFNIMultiplicativeInverse(uint8_t Byte)
uint8_t GFNIAffine(uint8_t XByte, const APInt &AQword, const APSInt &Imm, bool Inverse)
APSInt NormalizeRotateAmount(const APSInt &Value, const APSInt &Amount)
Result
Implement __builtin_bit_cast and related operations.
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const Pointer &Ptr, bool InvalidBase)
Does Ptr point to the last object AND to a flexible array member?
static bool isModification(AccessKinds AK)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ long long abs(long long __n)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
a trap message and trap category.
llvm::APInt getValue() const
unsigned getVersion() const
QualType getDynamicAllocType() const
QualType getTypeInfoType() const
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
A non-discriminated union of a base, field, or array index.
BaseOrMemberType getAsBaseOrMember() const
static LValuePathEntry ArrayIndex(uint64_t Index)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
bool hasArrayFiller() const
const LValueBase getLValueBase() const
APValue & getArrayInitializedElt(unsigned I)
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
APValue & getStructField(unsigned i)
unsigned getMatrixNumColumns() const
const FieldDecl * getUnionField() const
APSInt & getComplexIntImag()
bool isComplexInt() const
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
ValueKind getKind() const
ReflectionKind getReflectionOperandKind() const
APValue & getStructVirtualBase(unsigned i)
unsigned getArrayInitializedElts() const
static APValue IndeterminateValue()
void Profile(llvm::FoldingSetNodeID &ID) const
profile this value.
unsigned getStructNumBases() const
APFixedPoint & getFixedPoint()
bool hasLValuePath() const
const ValueDecl * getMemberPointerDecl() const
APValue & getUnionValue()
CharUnits & getLValueOffset()
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
bool isComplexFloat() const
APValue & getVectorElt(unsigned I)
APValue & getArrayFiller()
unsigned getVectorLength() const
void setUnion(const FieldDecl *Field, const APValue &Value)
bool isIndeterminate() const
unsigned getMatrixNumRows() const
unsigned getArraySize() const
bool allowConstexprUnknown() const
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
bool isFixedPoint() const
APValue & getMatrixElt(unsigned Idx)
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
@ None
There is no such object (it's outside its lifetime).
APSInt & getComplexIntReal()
APFloat & getComplexFloatImag()
APFloat & getComplexFloatReal()
APValue & getStructBase(unsigned i)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
const LangOptions & getLangOpts() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
const TargetInfo * getAuxTargetInfo() const
interp::Context & getInterpContext() const
Returns the clang bytecode interpreter context.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
LabelDecl * getLabel() const
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Expr * getSubExpr() const
Get the initializer to use for each array element.
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
uint64_t getValue() const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Attr - This represents one attribute.
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isLogicalOp(Opcode Opc)
static bool isRelationalOp(Opcode Opc)
static bool isComparisonOp(Opcode Opc)
static Opcode getOpForCompoundAssignment(Opcode Opc)
SourceLocation getExprLoc() const
static bool isAdditiveOp(Opcode Opc)
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
static bool isAssignmentOp(Opcode Opc)
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
static bool isEqualityOp(Opcode Opc)
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
const BlockDecl * getBlockDecl() const
bool isAuxBuiltinID(unsigned ID) const
Return true if the builtin ID belongs exclusively to the AuxTarget, and false if it belongs to both p...
unsigned getAuxBuiltinID(unsigned ID) const
Return real builtin ID (i.e.
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a base class of a C++ class.
SourceLocation getBeginLoc() const LLVM_READONLY
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
QualType getType() const
Retrieves the type of the base class.
const Expr * getSubExpr() const
Represents a call to a C++ constructor.
bool isElidable() const
Whether this construction is elidable.
Expr * getArg(unsigned Arg)
Return the specified argument.
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
SourceLocation getBeginLoc() const LLVM_READONLY
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Represents a C++ constructor within a class.
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Expr * getExpr()
Get the initialization expression that will be used.
FunctionDecl * getOperatorDelete() const
bool isGlobalDelete() const
Represents a C++ destructor within a class.
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
DeclStmt * getBeginStmt()
DeclStmt * getLoopVarStmt()
DeclStmt * getRangeStmt()
SourceLocation getBeginLoc() const LLVM_READONLY
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Represents a static or instance method of a struct/union/class.
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
QualType getAllocatedType() const
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Expr * getPlacementArg(unsigned I)
unsigned getNumPlacementArgs() const
SourceRange getSourceRange() const
FunctionDecl * getOperatorNew() const
Expr * getInitializer()
The initializer of this new-expression.
MutableArrayRef< Expr * > getInitExprs()
Represents a C++ struct/union/class.
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
unsigned getNumBases() const
Retrieves the number of base classes of this class.
base_class_range vbases()
capture_const_range captures() const
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
ReflectionKind getKind() const
const void * getOpaqueValue() const
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
bool isTypeOperand() const
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Expr * getExprOperand() const
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
MSGuidDecl * getGuidDecl() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
const AllocSizeAttr * getCalleeAllocSizeAttr() const
Try to get the alloc_size attribute of the callee. May return null.
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Expr ** getArgs()
Retrieve the call arguments.
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CaseStmt - Represent a case statement.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
path_iterator path_begin()
unsigned path_size() const
CastKind getCastKind() const
const FieldDecl * getTargetUnionField() const
const CXXBaseSpecifier *const * path_const_iterator
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operation.
This is an opaque type for sizes expressed in character units.
bool isPowerOfTwo() const
Test whether the quantity is a power of two.
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
bool isZero() const
Test whether the quantity equals zero.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits One()
Construct a CharUnits quantity of one.
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
unsigned getValue() const
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
QualType getElementType() const
CompoundAssignOperator - For compound assignments (e.g.
QualType getComputationLHSType() const
CompoundLiteralExpr - [C99 6.5.2.5].
bool hasStaticStorage() const
APValue & getOrCreateStaticValue(ASTContext &Ctx) const
const Expr * getInitializer() const
CompoundStmt - This represents a group of statements like { stmt stmt }.
Stmt *const * const_body_iterator
body_iterator body_begin()
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
ConditionalOperator - The ?
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Represents the canonical version of C arrays with a specified constant size.
unsigned getSizeBitWidth() const
Return the bit width of the size type.
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
bool isZeroSize() const
Return true if the size is zero.
const Expr * getSizeExpr() const
Return a pointer to the size expression.
llvm::APInt getSize() const
Return the constant array size as an APInt.
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
APValue getAPValueResult() const
bool hasAPValueResult() const
Represents a concrete matrix type with constant number of rows and columns.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Represents the current source location and context used to determine the value of the source location...
const Expr * getDefaultExpr() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
A reference to a declared variable, function, enum, etc.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Decl - This represents one declaration (or definition), e.g.
bool isInStdNamespace() const
ASTContext & getASTContext() const LLVM_READONLY
bool isInvalidDecl() const
SourceLocation getLocation() const
DeclContext * getDeclContext()
AccessSpecifier getAccess() const
bool isAnyOperatorNew() const
A decomposition declaration.
auto flat_bindings() const
InitListExpr * getUpdater() const
Designator - A designator in a C99 designated initializer.
DoStmt - This represents a 'do/while' stmt.
Symbolic representation of a dynamic allocation.
static uintptr_t getMaxIndex()
unsigned getIndex() const
DynAllocKind getAllocKind() const
const Expr * getBase() const
ChildElementIter< false > begin()
ExplicitCastExpr - An explicit cast written in the source code.
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
This represents one expression.
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
bool EvaluateAsMandatedConstantInitializer(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy, const VarDecl *VD) const
Evaluate an expression that is required by the language to be a constant expression.
bool isValueDependent() const
Determines whether the value of this expression depends on.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool EvaluateAsMandatedConstantExpr(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required by the language to be a constant expression.
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue &Result, bool AllowRelaxedEval=false) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
bool EvaluateAsMandatedConstantRValue(EvalResult &Result, const ASTContext &Ctx, SemaProxy &SProxy) const
Evaluate an expression that is required by the language to be a constant expression,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsInitializer(const ASTContext &Ctx, const VarDecl *VD, EvalResult &Result, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, SemaProxy &SProxy, EvalResult &Status) const
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
bool isFPConstrained() const
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
bool isBitField() const
Determines whether this field is a bitfield.
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
llvm::APFloat getValue() const
ForStmt - This represents a 'for (init;cond;inc)' stmt.
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
const Expr * getSubExpr() const
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
bool hasCXXExplicitFunctionObjectParameter() const
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
bool isImplicitlyInstantiable() const
Determines whether this function is a function template specialization or a member of a class templat...
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
bool isDefaulted() const
Whether this function is defaulted.
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
Expr * getResultExpr()
Return the result expression of this controlling expression.
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
bool isNonNegatedConsteval() const
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
const Expr * getSubExpr() const
Represents an implicitly-generated value initialization of an object of a given type.
Represents a field injected from an anonymous union/struct into the parent scope.
ArrayRef< NamedDecl * > chain() const
Describes an C or C++ initializer list.
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
bool isStringLiteralInit() const
Is this an initializer for an array of characters, initialized by a string literal or an @encode?
unsigned getNumInits() const
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
const Expr * getInit(unsigned Init) const
ArrayRef< Expr * > inits() const
capture_init_iterator capture_init_end()
Retrieve the iterator pointing one past the last initialization argument for this lambda expression.
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
StrictFlexArraysLevelKind
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompatibleWith(ClangABI Version) const
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
APValue * getOrCreateValue(bool MayCreate) const
Get the storage for the constant value of a materialized temporary of static storage duration.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
bool isExpressibleAsConstantInitializer() const
Expr * getIndexExpr(unsigned Idx)
const OffsetOfNode & getComponent(unsigned Idx) const
TypeSourceInfo * getTypeSourceInfo() const
unsigned getNumComponents() const
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
FieldDecl * getField() const
For a field offsetof node, returns the field.
@ Array
An index into an array.
@ Identifier
A field in a dependent type, known only by its name.
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Kind getKind() const
Determine what kind of offsetof node this is.
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Expr * getSelectedExpr() const
const Expr * getSubExpr() const
Represents a parameter to a function.
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
bool isExplicitObjectParameter() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
StringLiteral * getFunctionName()
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
ArrayRef< Expr * > semantics()
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
QualType withConst() const
void addConst()
Add the const type qualifier to this QualType.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
void removeLocalVolatile()
void addVolatile()
Add the volatile type qualifier to this QualType.
bool isConstQualified() const
Determine whether this type is const-qualified.
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
bool isWrapType() const
Returns true if it is a OverflowBehaviorType of Wrap kind.
Represents a struct/union/class.
unsigned getNumFields() const
Returns the number of fields (non-static data members) in this record.
field_iterator field_end() const
field_range fields() const
specific_decl_iterator< FieldDecl > field_iterator
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
field_iterator field_begin() const
bool isSatisfied() const
Whether or not the requires clause is satisfied.
SourceLocation getLocation() const
std::string ComputeName(ASTContext &Context) const
Scope - A scope is a transient data structure that is used while parsing the program.
Classes implementing SemaProxy present a restricted view of the (possibly mutating) actions and queri...
virtual void instantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function)=0
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
llvm::APSInt getShuffleMaskIdx(unsigned N) const
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
unsigned getPackLength() const
Retrieve the length of the parameter pack.
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
std::string printToString(const SourceManager &SM) const
CompoundStmt * getSubStmt()
Stmt - This represents one statement.
StmtClass getStmtClass() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
UnsignedOrNone findZeroCodeUnit(unsigned StartIndex=0) const
Scan the string literal contents for a code unit with value 0.
unsigned getLength() const
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
StringRef getBytes() const
Allow access to clients that need the byte representation, such as ASTWriterStmt::VisitStringLiteral(...
StringRef getString() const
Expr * getReplacement() const
const SwitchCase * getNextSwitchCase() const
SwitchStmt - This represents a 'switch' stmt.
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
SwitchCase * getSwitchCaseList()
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Exposes information about the current target.
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getLongLongAlign() const
unsigned getLongDoubleAlign() const
unsigned size() const
Retrieve the number of template arguments in this template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
@ Type
The template argument is a type.
Symbolic representation of typeid(T) for some type T.
QualType getType() const
Return the type wrapped by this type source info.
bool getBoolValue() const
bool isStoredAsComparisonResult() const
const APValue & getAPValue() const
bool isStoredAsBoolean() const
The base class of the type hierarchy.
bool isBooleanType() const
bool isFunctionReferenceType() const
bool isMFloat8Type() const
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
bool isPackedVectorBoolType(const ASTContext &ctx) const
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
bool isIncompleteArrayType() const
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isConstantArrayType() const
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isVoidPointerType() const
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
bool isFunctionPointerType() const
bool isCountAttributedType() const
bool isConstantMatrixType() const
bool isPointerType() const
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isEnumeralType() const
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
bool isVariableArrayType() const
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
bool isExtVectorBoolType() const
bool isMemberDataPointerType() const
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
RecordDecl * castAsRecordDecl() const
bool isAnyComplexType() const
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
bool isMemberPointerType() const
bool isAtomicType() const
bool isComplexIntegerType() const
bool isStdByteType() const
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
bool isObjectType() const
Determine whether this type is an object type.
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
bool isMetaInfoType() const
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isFunctionType() const
bool isVectorType() const
bool isRealFloatingType() const
Floating point categories.
bool isFloatingType() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
bool isAnyPointerType() const
TypeClass getTypeClass() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isNullPtrType() const
bool isRecordType() const
bool isSizelessVectorType() const
Returns true for all scalable vector types.
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
QualType getArgumentType() const
SourceLocation getBeginLoc() const LLVM_READONLY
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
bool isArgumentType() const
UnaryExprOrTypeTrait getKind() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
SourceLocation getExprLoc() const
Expr * getSubExpr() const
static bool isIncrementOp(Opcode Op)
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Represents a variable declaration or definition.
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
bool evaluateConstantDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes, SemaProxy &SProxy) const
Evaluate the destruction of a variable that is required by the language to have constant destruction.
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
const APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or nullptr if the value is not yet...
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
bool isCXXForRangeImplicitVar() const
Whether this variable is the implicit '__range' variable in C++ range-based for loops.
ThreadStorageClassSpecifier getTSCSpec() const
const Expr * getInit() const
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Expr * getSizeExpr() const
Represents a GCC generic vector type.
unsigned getNumElements() const
QualType getElementType() const
WhileStmt - This represents a 'while' stmt.
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
std::optional< uint64_t > tryEvaluateObjectSize(const EvalSettings &Settings, const Expr *E, unsigned Kind, bool IsDynamic)
If.
bool evaluateString(const EvalSettings &Settings, const Expr *E, std::string &Result)
Evaluate.
bool evaluateDestruction(const EvalSettings &Settings, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
std::optional< bool > evaluateWithSubstitution(const EvalSettings &Settings, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
bool evaluate(const EvalSettings &Settings, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
bool evaluateAsInitializer(const EvalSettings &Settings, const VarDecl *VD, const Expr *Init, APValue &Result)
Evaluates a toplevel initializer.
bool evaluateAsRValue(const EvalSettings &Settings, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
bool evaluateCharRange(const EvalSettings &Settings, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
std::optional< uint64_t > evaluateStrlen(const EvalSettings &Settings, const Expr *E)
Evalute.
void isPotentialConstantExprUnevaluated(const EvalSettings &Settings, const Expr *E, const FunctionDecl *FD)
Base class for stack frames, shared between VM and walker.
Interface for the VM to interact with the AST walker's context.
Defines the clang::TargetInfo interface.
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
static const FunctionDecl * getCallee(const CXXConstructExpr &D)
uint32_t Literal
Literals are represented as positive integers.
unsigned kind
All of the diagnostics that can be emitted by the frontend.