1//===------- Interp.cpp - Interpreter for the constexpr VM ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Interp.h"
10#include "Compiler.h"
11#include "Function.h"
12#include "InterpFrame.h"
13#include "InterpShared.h"
14#include "InterpStack.h"
15#include "Opcode.h"
16#include "PrimType.h"
17#include "Program.h"
18#include "State.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/SemaProxy.h"
25#include "clang/Basic/DiagnosticSema.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/ADT/StringExtras.h"
29
30using namespace clang;
31using namespace clang::interp;
32
33#if __has_cpp_attribute(clang::musttail)
34#define MUSTTAIL [[clang::musttail]]
35#elif __has_cpp_attribute(msvc::musttail)
36#define MUSTTAIL [[msvc::musttail]]
37#elif __has_attribute(musttail)
38#define MUSTTAIL __attribute__((musttail))
39#endif
40
41// On MSVC, musttail does not guarantee tail calls in debug mode.
42// We disable it on MSVC generally since it doesn't seem to be able
43// to handle the way we use tailcalls.
44// MIPS and PPC can't tail-call external calls, which is a problem for
45// InterpNext.
46#if defined(_MSC_VER) || defined(__powerpc__) || !defined(MUSTTAIL) || \
47 defined(__i386__) || defined(__sparc__) || defined(__mips__)
48#undef MUSTTAIL
49#define MUSTTAIL
50#define USE_TAILCALLS 0
51#else
52#define USE_TAILCALLS 1
53#endif
54
55// FIXME: Code duplication with Pointer.cpp
56static bool validType(QualType T) {
57 if (const RecordDecl *RD = T->getAsRecordDecl())
58 return ASTContext::hasLayout(D: RD);
59 return !T->isDependentType() && !T->isUndeducedAutoType() &&
60 !T->isSpecificBuiltinType(K: BuiltinType::UnknownAny) &&
61 !T->isIncompleteType();
62}
63
64PRESERVE_NONE static bool RetValue(InterpState &S) {
65 llvm::report_fatal_error(reason: "Interpreter cannot return values");
66}
67
68//===----------------------------------------------------------------------===//
69// Jmp, Jt, Jf
70//===----------------------------------------------------------------------===//
71
72static bool Jmp(InterpState &S, CodePtr OpPC, int32_t Offset) {
73 S.PC += Offset;
74 return S.noteStep(OpPC);
75}
76
77static bool Jt(InterpState &S, CodePtr OpPC, int32_t Offset) {
78 if (S.Stk.pop<bool>()) {
79 S.PC += Offset;
80 return S.noteStep(OpPC);
81 }
82 return true;
83}
84
85static bool Jf(InterpState &S, CodePtr OpPC, int32_t Offset) {
86 if (!S.Stk.pop<bool>()) {
87 S.PC += Offset;
88 return S.noteStep(OpPC);
89 }
90 return true;
91}
92
93static void diagnoseMissingInitializer(InterpState &S, CodePtr OpPC,
94 const ValueDecl *VD) {
95 const SourceInfo &E = S.Current->getSource(PC: OpPC);
96 S.FFDiag(SI: E, DiagId: diag::note_constexpr_var_init_unknown, ExtraNotes: 1) << VD;
97 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at) << VD->getSourceRange();
98}
99
100static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
101 const ValueDecl *VD,
102 AccessKinds AK = AK_Read);
103static bool diagnoseUnknownDecl(InterpState &S, CodePtr OpPC,
104 const ValueDecl *D, AccessKinds AK = AK_Read) {
105 // This function tries pretty hard to produce a good diagnostic. Just skip
106 // that if nobody will see it anyway. This should be handled in the caller.
107 assert(S.diagnosing());
108
109 if (isa<ParmVarDecl>(Val: D)) {
110 if (D->getType()->isReferenceType()) {
111 if (S.inConstantContext() && S.getLangOpts().CPlusPlus &&
112 !S.getLangOpts().CPlusPlus11) {
113 diagnoseNonConstVariable(S, OpPC, VD: D);
114 return false;
115 }
116 }
117
118 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
119 if (S.getLangOpts().CPlusPlus23 && D->getType()->isReferenceType()) {
120 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_access_unknown_variable, ExtraNotes: 1)
121 << AK_Read << D;
122 S.Note(Loc: D->getLocation(), DiagId: diag::note_declared_at) << D->getSourceRange();
123 } else if (S.getLangOpts().CPlusPlus11) {
124 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_function_param_value_unknown, ExtraNotes: 1) << D;
125 S.Note(Loc: D->getLocation(), DiagId: diag::note_declared_at) << D->getSourceRange();
126 } else {
127 S.FFDiag(SI: Loc);
128 }
129 return false;
130 }
131
132 if (!D->getType().isConstQualified()) {
133 diagnoseNonConstVariable(S, OpPC, VD: D, AK);
134 } else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
135 if (!VD->getAnyInitializer()) {
136 diagnoseMissingInitializer(S, OpPC, VD);
137 } else {
138 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
139 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD;
140 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
141 }
142 }
143
144 return false;
145}
146
147static bool isModification(AccessKinds AK) {
148 return AK == AK_Assign || AK == AK_Increment || AK == AK_Decrement ||
149 AK == AK_Construct || AK == AK_Destroy;
150}
151
152static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
153 const ValueDecl *VD, AccessKinds AK) {
154 if (!S.diagnosing())
155 return;
156
157 if (!S.getLangOpts().CPlusPlus) {
158 S.FFDiag(SI: S.Current->getSource(PC: OpPC));
159 return;
160 }
161
162 if (const auto *VarD = dyn_cast<VarDecl>(Val: VD);
163 VarD && VarD->isCXXForRangeImplicitVar()) {
164 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
165 DiagId: diag::note_constexpr_ltor_for_range_var)
166 << VarD;
167 return;
168 }
169
170 if (const auto *VarD = dyn_cast<VarDecl>(Val: VD);
171 VarD && VarD->getType().isConstQualified() &&
172 (VarD->isConstexpr() || !VarD->getType()->isArrayType()) &&
173 !VarD->getAnyInitializer()) {
174 diagnoseMissingInitializer(S, OpPC, VD);
175 return;
176 }
177
178 // Rather random, but this is to match the diagnostic output of the current
179 // interpreter.
180 if (isa<ObjCIvarDecl>(Val: VD))
181 return;
182
183 if (VD->getType()->isIntegralOrEnumerationType()) {
184 SourceInfo Loc = S.Current->getSource(PC: OpPC);
185 if (isModification(AK)) {
186 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_modify_global);
187 } else {
188 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_ltor_non_const_int, ExtraNotes: 1) << VD;
189 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
190 }
191 return;
192 }
193
194 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
195 DiagId: S.getLangOpts().CPlusPlus11 ? diag::note_constexpr_ltor_non_constexpr
196 : diag::note_constexpr_ltor_non_integral,
197 ExtraNotes: 1)
198 << VD << VD->getType();
199 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
200}
201
202static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Block *B) {
203 if (auto ID = B->getDeclID()) {
204 if (!B->isGlobal())
205 return true;
206
207 if (S.P.getCurrentDecl() == ID)
208 return true;
209
210 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC), DiagId: diag::note_constexpr_modify_global);
211 return false;
212 }
213 return true;
214}
215
216namespace clang {
217namespace interp {
218
219static void noteValueLocation(InterpState &S, const Block *B) {
220 const Descriptor *Desc = B->getDescriptor();
221
222 if (B->isDynamic())
223 S.Note(Loc: Desc->getLocation(), DiagId: diag::note_constexpr_dynamic_alloc_here);
224 else if (B->isTemporary())
225 S.Note(Loc: Desc->getLocation(), DiagId: diag::note_constexpr_temporary_here);
226 else
227 S.Note(Loc: Desc->getLocation(), DiagId: diag::note_declared_at);
228}
229
230void noteValueLocation(InterpState &S, const Pointer &Ptr) {
231 if (Ptr.isBlockPointer()) {
232 noteValueLocation(S, B: Ptr.block());
233 return;
234 }
235
236 if (Ptr.isOpaquePointer())
237 S.Note(Loc: Ptr.asOpaquePointer().Base.getLocation(), DiagId: diag::note_declared_at);
238
239 if (Ptr.isStringPointer())
240 S.Note(Loc: Ptr.asStringPointer().getLiteral(),
241 DiagId: diag::note_constexpr_temporary_here);
242}
243
244static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Block *B,
245 AccessKinds AK) {
246 if (B->getDeclID()) {
247 if (!(B->isGlobal() && B->isTemporary()))
248 return true;
249
250 const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(
251 Val: B->getDescriptor()->asExpr());
252 if (!MTE)
253 return true;
254
255 // FIXME(perf): Since we do this check on every Load from a static
256 // temporary, it might make sense to cache the value of the
257 // isUsableInConstantExpressions call.
258 if (S.checkingConstantDestruction() ||
259 (B->getEvalID() != S.EvalID &&
260 !MTE->isUsableInConstantExpressions(Context: S.getASTContext()))) {
261 const SourceInfo &E = S.Current->getSource(PC: OpPC);
262 S.FFDiag(SI: E, DiagId: diag::note_constexpr_access_static_temporary, ExtraNotes: 1) << AK;
263 noteValueLocation(S, B);
264 return false;
265 }
266 }
267
268 return true;
269}
270static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
271 AccessKinds AK) {
272 if (!Ptr.isBlockPointer())
273 return true;
274 return CheckTemporary(S, OpPC, B: Ptr.block(), AK);
275}
276
277PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
278 PrimType PT);
279
280bool diagnoseShiftFailure(InterpState &S, CodePtr OpPC, ShiftFailure Failure,
281 const APSInt *Value, unsigned Bits) {
282 switch (Failure) {
283 case ShiftFailure::NegativeCount:
284 assert(Value);
285 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_negative_shift)
286 << *Value;
287 break;
288 case ShiftFailure::TooLarge: {
289 assert(Value);
290 const Expr *E = S.Current->getExpr(PC: OpPC);
291 S.CCEDiag(E, DiagId: diag::note_constexpr_large_shift)
292 << *Value << E->getType() << Bits;
293 break;
294 }
295 case ShiftFailure::NegativeLeftOperand:
296 assert(Value);
297 S.CCEDiag(E: S.Current->getExpr(PC: OpPC), DiagId: diag::note_constexpr_lshift_of_negative)
298 << *Value;
299 break;
300 case ShiftFailure::DiscardsBits:
301 S.CCEDiag(E: S.Current->getExpr(PC: OpPC), DiagId: diag::note_constexpr_lshift_discards);
302 break;
303 }
304 return S.noteUndefinedBehavior();
305}
306
307bool diagnoseArrayIndex(InterpState &S, CodePtr OpPC, const APSInt &Index,
308 std::optional<uint64_t> NumElems, bool IsArray) {
309 if (IsArray)
310 assert(NumElems);
311
312 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_array_index)
313 << Index << /*non-array=*/!IsArray << NumElems.value_or(u: 0u);
314 return false;
315}
316
317void cleanupAfterFunctionCall(InterpState &S, const Function *Func) {
318 assert(S.Current);
319 assert(Func);
320
321 // Pop variadic parameter values from the stack.
322 if (S.Current->Caller && Func->isVariadic()) {
323 unsigned VariadicArgSize =
324 S.Current->getArgSize() - S.Current->getFunction()->getArgSize();
325 unsigned TargetStackSize = S.Stk.size() - VariadicArgSize;
326 while (S.Stk.size() != TargetStackSize) {
327 S.Stk.discardSlow();
328 }
329 }
330
331 // And in any case, remove the fixed parameters (the non-variadic ones)
332 // at the end.
333 for (const Function::ParamDescriptor &PDesc : Func->args_reverse())
334 TYPE_SWITCH(PDesc.T, S.Stk.discard<T>());
335
336 if (Func->hasImplicitThisPointer())
337 S.Stk.discard<Pointer>();
338 if (Func->hasRVO())
339 S.Stk.discard<Pointer>();
340}
341
342bool CheckBCPResult(InterpState &S, const Pointer &Ptr) {
343 if (Ptr.isDummy())
344 return false;
345 if (Ptr.isZero())
346 return true;
347 if (Ptr.isFunctionPointer())
348 return false;
349 if (Ptr.isIntegralPointer())
350 return true;
351 if (Ptr.isTypeidPointer())
352 return true;
353
354 if (Ptr.getType()->isAnyComplexType())
355 return true;
356
357 if (const Expr *Base = Ptr.getRootExpr())
358 return isa<StringLiteral>(Val: Base) && Ptr.getIndex() == 0;
359 return false;
360}
361
362static bool CheckActive(InterpState &S, CodePtr OpPC, PtrView Ptr,
363 AccessKinds AK, bool WillActivate = false) {
364 if (Ptr.isActive())
365 return true;
366
367 assert(Ptr.inUnion());
368
369 // Find the outermost union.
370 PtrView U = Ptr.getBase();
371 PtrView C = Ptr;
372 while (!U.isRoot() && !U.isActive()) {
373 // A little arbitrary, but this is what the current interpreter does.
374 // See the AnonymousUnion test in test/AST/ByteCode/unions.cpp.
375 // GCC's output is more similar to what we would get without
376 // this condition.
377 if (U.getRecord() && U.getRecord()->isAnonymousUnion())
378 break;
379
380 C = U;
381 U = U.getBase();
382 }
383 assert(C.isField());
384 assert(C.getBase() == U);
385
386 // Consider:
387 // union U {
388 // struct {
389 // int x;
390 // int y;
391 // } a;
392 // }
393 //
394 // When activating x, we will also activate a. If we now try to read
395 // from y, we will get to CheckActive, because y is not active. In that
396 // case, our U will be a (not a union). We return here and let later code
397 // handle this.
398 if (!U.getFieldDesc()->isUnion())
399 return true;
400
401 // When we will activate Ptr, check that none of the unions in its path have a
402 // non-trivial default constructor.
403 if (WillActivate) {
404 bool Fails = false;
405 PtrView It = Ptr;
406 while (!It.isRoot() && !It.isActive()) {
407 if (const Record *R = It.getRecord(); R && R->isUnion()) {
408 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: R->getDecl());
409 CXXRD && !CXXRD->hasTrivialDefaultConstructor()) {
410 Fails = true;
411 break;
412 }
413 }
414 It = It.getBase();
415 }
416 if (!Fails)
417 return true;
418 }
419
420 // Get the inactive field descriptor.
421 assert(!C.isActive());
422 const FieldDecl *InactiveField = C.getField();
423 assert(InactiveField);
424
425 // Find the active field of the union.
426 const Record *R = U.getRecord();
427 assert(R && R->isUnion() && "Not a union");
428
429 const FieldDecl *ActiveField = nullptr;
430 for (const Record::Field &F : R->fields()) {
431 PtrView Field = U.atField(Offset: F.Offset);
432 if (Field.isActive()) {
433 ActiveField = Field.getField();
434 break;
435 }
436 }
437
438 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
439 DiagId: diag::note_constexpr_access_inactive_union_member)
440 << AK << InactiveField << !ActiveField << ActiveField;
441 return false;
442}
443
444static bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
445 AccessKinds AK, bool WillActivate = false) {
446 if (!Ptr.isBlockPointer())
447 return true;
448 return CheckActive(S, OpPC, Ptr: Ptr.view(), AK, WillActivate);
449}
450
451static bool CheckExtern(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
452 if (!Ptr.isExtern())
453 return true;
454
455 if (!Ptr.isPastEnd() &&
456 (Ptr.isInitialized() ||
457 (Ptr.getDeclDesc()->asVarDecl() == S.EvaluatingDecl)))
458 return true;
459
460 if (S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus &&
461 Ptr.isConst())
462 return false;
463
464 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
465 if (!Ptr.isConstexprUnknown() || !S.checkingPotentialConstantExpression())
466 diagnoseNonConstVariable(S, OpPC, VD);
467 return false;
468}
469
470static bool CheckExtern(InterpState &S, CodePtr OpPC, const Block *B) {
471 if (!B->isExtern())
472 return true;
473 return CheckExtern(S, OpPC, Ptr: Pointer(const_cast<Block *>(B)));
474}
475
476bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
477 if (!Ptr.isUnknownSizeArray())
478 return true;
479 const SourceInfo &E = S.Current->getSource(PC: OpPC);
480 S.FFDiag(SI: E, DiagId: diag::note_constexpr_unsized_array_indexed);
481 return false;
482}
483
484bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
485 AccessKinds AK) {
486 if (Ptr.isZero()) {
487 const auto Loc = S.Current->getSource(PC: OpPC);
488
489 if (Ptr.isField())
490 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_null_subobject) << CSK_Field;
491 else
492 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_access_null) << AK;
493
494 return false;
495 }
496
497 if (!Ptr.isLive()) {
498 if (Ptr.isDynamic()) {
499 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
500 DiagId: diag::note_constexpr_access_deleted_object)
501 << AK;
502 } else if (!S.checkingPotentialConstantExpression()) {
503 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_uninit)
504 << AK << /*uninitialized=*/false << S.Current->getRange(PC: OpPC);
505 noteValueLocation(S, Ptr);
506 }
507
508 return false;
509 }
510
511 return true;
512}
513
514bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc,
515 AccessKinds AK) {
516 assert(Desc);
517
518 const auto *D = Desc->asVarDecl();
519 if (S.checkingConstantDestruction(VD: D)) {
520 // If we're checking for a constant destructor for this variable, we can
521 // only read from it if it is constant.
522 if (D->getType().isConstQualified())
523 return true;
524 } else if (!D || D == S.EvaluatingDecl || D->isConstexpr())
525 return true;
526
527 // If we're evaluating the initializer for a constexpr variable in C23, we may
528 // only read other contexpr variables. Abort here since this one isn't
529 // constexpr.
530 if (const auto *VD = S.EvaluatingDecl;
531 VD && VD->isConstexpr() && S.getLangOpts().C23)
532 return Invalid(S, OpPC);
533
534 QualType T = D->getType();
535 bool IsConstant = T.isConstant(Ctx: S.getASTContext());
536 if (T->isIntegralOrEnumerationType()) {
537 if (!IsConstant) {
538 diagnoseNonConstVariable(S, OpPC, VD: D, AK);
539 return false;
540 }
541 return true;
542 }
543
544 if (IsConstant) {
545 if (S.getLangOpts().CPlusPlus) {
546 S.CCEDiag(Loc: S.Current->getLocation(PC: OpPC),
547 DiagId: S.getLangOpts().CPlusPlus11
548 ? diag::note_constexpr_ltor_non_constexpr
549 : diag::note_constexpr_ltor_non_integral,
550 ExtraNotes: 1)
551 << D << T;
552 S.Note(Loc: D->getLocation(), DiagId: diag::note_declared_at);
553 } else {
554 S.CCEDiag(Loc: S.Current->getLocation(PC: OpPC));
555 }
556 return true;
557 }
558
559 if (T->isPointerOrReferenceType()) {
560 if (!T->getPointeeType().isConstant(Ctx: S.getASTContext()) ||
561 !S.getLangOpts().CPlusPlus11) {
562 diagnoseNonConstVariable(S, OpPC, VD: D, AK);
563 return false;
564 }
565 return true;
566 }
567
568 diagnoseNonConstVariable(S, OpPC, VD: D, AK);
569 return false;
570}
571
572static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
573 AccessKinds AK = AK_Read) {
574 if (S.checkingConstantDestruction(Ptr))
575 return CheckConstant(S, OpPC, Desc: Ptr.getDeclDesc(), AK);
576
577 if (!Ptr.isStatic() || !Ptr.isBlockPointer())
578 return true;
579 if (!Ptr.getDeclID())
580 return true;
581 return CheckConstant(S, OpPC, Desc: Ptr.getDeclDesc(), AK);
582}
583
584static bool CheckConstant(InterpState &S, CodePtr OpPC, PtrView Ptr,
585 AccessKinds AK = AK_Read) {
586 if (S.checkingConstantDestruction(VD: Ptr.getDeclDesc()->asVarDecl()))
587 return CheckConstant(S, OpPC, Desc: Ptr.getDeclDesc(), AK);
588
589 if (!Ptr.block()->isGlobal())
590 return true;
591 if (!Ptr.block()->getDeclID())
592 return true;
593 return CheckConstant(S, OpPC, Desc: Ptr.getDeclDesc(), AK);
594}
595
596bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
597 CheckSubobjectKind CSK) {
598 if (!Ptr.isZero())
599 return true;
600 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
601 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_null_subobject)
602 << CSK << S.Current->getRange(PC: OpPC);
603
604 return false;
605}
606
607bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
608 CheckSubobjectKind CSK) {
609 if (!Ptr.isElementPastEnd() && !Ptr.isZeroSizeArray())
610 return true;
611 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
612 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_past_end_subobject)
613 << CSK << S.Current->getRange(PC: OpPC);
614 return false;
615}
616
617bool CheckSubobject(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
618 CheckSubobjectKind CSK) {
619 if (!Ptr.isOnePastEnd())
620 return true;
621
622 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
623 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_past_end_subobject)
624 << CSK << S.Current->getRange(PC: OpPC);
625 return false;
626}
627
628static bool CheckConst(InterpState &S, CodePtr OpPC, PtrView Ptr) {
629 assert(Ptr.isLive() && "Pointer is not live");
630 if (!Ptr.isConst())
631 return true;
632
633 if (Ptr.isMutable() && !Ptr.isConstInMutable())
634 return true;
635
636 // The This pointer is writable in constructors and destructors,
637 // even if isConst() returns true.
638 for (PtrView V : llvm::reverse(C&: S.InitializingPtrs)) {
639 if (V.block() != Ptr.block())
640 continue;
641 if (!V.getFieldDesc()->IsConst) {
642 // If the pointer being initialized is not declared as const,
643 // Ptr is const because of a parent of V, but that is irrelevant
644 // since V is being initialized and NOT const.
645 // This is fine, so return true.
646 return true;
647 }
648
649 // We know that Ptr is const because of a parent field and we also
650 // know that V is explicitly marked const.
651 // But since V is in InitializingPtrs, the fact that it is const doesn't
652 // matter and it is writable.
653 // What we now need to check is whether there is a pointer between Ptr and V
654 // that is marked const but NOT in InitializingPtrs. If that is the case,
655 // Ptr is currently not writable.
656 bool FoundProblem = false;
657 for (PtrView P = Ptr; P != V; P = P.getBase()) {
658 if (P.getFieldDesc()->IsConst) {
659 FoundProblem = true;
660 break;
661 }
662 }
663
664 // We couldn't find any pointer that's explicitly marked const, so
665 // Ptr is writable right now.
666 if (!FoundProblem)
667 return true;
668 // We only need to find the right block once.
669 break;
670 }
671
672 if (!S.checkingPotentialConstantExpression()) {
673 QualType Ty = Ptr.getType();
674 if (!Ptr.getFieldDesc()->IsConst)
675 Ty.addConst();
676 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
677 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_modify_const_type) << Ty;
678 }
679 return false;
680}
681
682bool CheckConst(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
683 assert(Ptr.isLive() && "Pointer is not live");
684
685 if (!Ptr.isConst())
686 return true;
687
688 if (!Ptr.isBlockPointer())
689 return false;
690 return CheckConst(S, OpPC, Ptr: Ptr.view());
691}
692
693bool CheckMutable(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK) {
694 assert(Ptr.isLive() && "Pointer is not live");
695 if (!Ptr.isMutable())
696 return true;
697
698 if (S.checkingConstantDestruction()) {
699 // Never allowed when checking for constant destruction.
700 // Diagnose below.
701 } else if (S.getLangOpts().CPlusPlus14 &&
702 S.lifetimeStartedInEvaluation(B: Ptr.block())) {
703 // In C++14 onwards, it is permitted to read a mutable member whose
704 // lifetime began within the evaluation.
705 return true;
706 }
707
708 // Find the reason this pointer is mutable.
709 PtrView MutablePtr = Ptr;
710 while (!MutablePtr.isRoot() && MutablePtr.getBase().isMutable())
711 MutablePtr = MutablePtr.getBase();
712
713 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
714 const FieldDecl *Field = MutablePtr.getField();
715 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_access_mutable, ExtraNotes: 1) << AK << Field;
716 S.Note(Loc: Field->getLocation(), DiagId: diag::note_declared_at);
717 return false;
718}
719
720static bool CheckVolatile(InterpState &S, CodePtr OpPC, PtrView Ptr,
721 AccessKinds AK) {
722 assert(Ptr.isLive());
723
724 if (!Ptr.isVolatile())
725 return true;
726
727 if (!S.getLangOpts().CPlusPlus)
728 return Invalid(S, OpPC);
729
730 // Volatile object can be written-to and read if they are being constructed.
731 if (S.initializingBlock(B: Ptr.block()))
732 return true;
733
734 // The reason why Ptr is volatile might be further up the hierarchy.
735 // Find that pointer.
736 PtrView P = Ptr;
737 while (!P.isRoot()) {
738 if (P.getType().isVolatileQualified())
739 break;
740 P = P.getBase();
741 }
742
743 const NamedDecl *ND = nullptr;
744 int DiagKind;
745 SourceLocation Loc;
746 if (const auto *F = P.getField()) {
747 DiagKind = 2;
748 Loc = F->getLocation();
749 ND = F;
750 } else if (auto *VD = P.getFieldDesc()->asValueDecl()) {
751 DiagKind = 1;
752 Loc = VD->getLocation();
753 ND = VD;
754 } else {
755 DiagKind = 0;
756 if (const auto *E = P.getFieldDesc()->asExpr())
757 Loc = E->getExprLoc();
758 }
759
760 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
761 DiagId: diag::note_constexpr_access_volatile_obj, ExtraNotes: 1)
762 << AK << DiagKind << ND;
763 S.Note(Loc, DiagId: diag::note_constexpr_volatile_here) << DiagKind;
764 return false;
765}
766
767bool diagnoseUninitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
768 AccessKinds AK) {
769 assert(Ptr.isLive());
770 assert(!Ptr.isInitialized());
771 return diagnoseUninitialized(S, OpPC, Extern: Ptr.isExtern(), B: Ptr.block(),
772 LT: Ptr.getLifetime(), AK);
773}
774
775bool diagnoseUninitialized(InterpState &S, CodePtr OpPC, bool Extern,
776 const Block *B, Lifetime LT, AccessKinds AK) {
777 if (S.checkingPotentialConstantExpression()) {
778 // Extern and static member declarations might be initialized later.
779 if (Extern)
780 return false;
781
782 if (const VarDecl *VD = B->getDescriptor()->asVarDecl();
783 VD && VD->isStaticDataMember())
784 return false;
785 }
786
787 const Descriptor *Desc = B->getDescriptor();
788
789 if (const auto *VD = Desc->asVarDecl();
790 VD && (VD->isConstexpr() || VD->hasGlobalStorage())) {
791
792 if (VD == S.EvaluatingDecl &&
793 !(S.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType())) {
794 if (!S.getLangOpts().CPlusPlus14 &&
795 !VD->getType().isConstant(Ctx: S.getASTContext())) {
796 // Diagnose as non-const read.
797 diagnoseNonConstVariable(S, OpPC, VD);
798 } else {
799 // Diagnose as "read of object outside its lifetime".
800 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_uninit)
801 << AK << /*IsIndeterminate=*/false;
802 S.Note(Loc: VD->getFirstDecl()->getLocation(), DiagId: diag::note_declared_at);
803 }
804 return false;
805 }
806
807 if (VD->getAnyInitializer()) {
808 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
809 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD;
810 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
811 } else {
812 diagnoseMissingInitializer(S, OpPC, VD);
813 }
814 return false;
815 }
816
817 if (!S.checkingPotentialConstantExpression()) {
818 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_uninit)
819 << AK << /*uninitialized=*/(LT == Lifetime::Started)
820 << S.Current->getRange(PC: OpPC);
821 noteValueLocation(S, B);
822 }
823 return false;
824}
825
826static bool diagnoseUninitialized(InterpState &S, CodePtr OpPC, PtrView Ptr,
827 AccessKinds AK) {
828 assert(Ptr.isLive());
829 assert(!Ptr.isInitialized());
830 return diagnoseUninitialized(S, OpPC, Extern: Ptr.isExtern(), B: Ptr.block(),
831 LT: Ptr.getLifetime(), AK);
832}
833
834static bool CheckLifetime(InterpState &S, CodePtr OpPC, Lifetime LT,
835 const Block *B, AccessKinds AK) {
836 if (LT == Lifetime::Started)
837 return true;
838
839 if (!S.checkingPotentialConstantExpression()) {
840 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_uninit)
841 << AK << /*uninitialized=*/false << S.Current->getRange(PC: OpPC);
842 noteValueLocation(S, B);
843 }
844 return false;
845}
846static bool CheckLifetime(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
847 AccessKinds AK) {
848 if (!Ptr.isBlockPointer())
849 return true;
850 return CheckLifetime(S, OpPC, LT: Ptr.getLifetime(), B: Ptr.block(), AK);
851}
852
853static bool CheckWeak(InterpState &S, CodePtr OpPC, const Block *B) {
854 if (!B->isWeak())
855 return true;
856
857 const auto *VD = B->getDescriptor()->asVarDecl();
858 assert(VD);
859 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC), DiagId: diag::note_constexpr_var_init_weak)
860 << VD;
861 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
862
863 return false;
864}
865
866// The list of checks here is just the one from CheckLoad, but with the
867// ones removed that are impossible on primitive global values.
868// For example, since those can't be members of structs, they also can't
869// be mutable.
870bool CheckGlobalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
871 const auto &Desc = B->getBlockDesc<GlobalInlineDescriptor>();
872 if (!B->isAccessible()) {
873 if (!CheckExtern(S, OpPC, B))
874 return false;
875 if (!CheckWeak(S, OpPC, B))
876 return false;
877 return false;
878 }
879
880 if (!CheckConstant(S, OpPC, Desc: B->getDescriptor()))
881 return false;
882 if (Desc.InitState != GlobalInitState::Initialized)
883 return diagnoseUninitialized(S, OpPC, Extern: B->isExtern(), B);
884 if (!CheckTemporary(S, OpPC, B, AK: AK_Read))
885 return false;
886 if (B->getDescriptor()->IsVolatile) {
887 if (!S.getLangOpts().CPlusPlus)
888 return Invalid(S, OpPC);
889
890 const ValueDecl *D = B->getDescriptor()->asValueDecl();
891 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
892 DiagId: diag::note_constexpr_access_volatile_obj, ExtraNotes: 1)
893 << AK_Read << 1 << D;
894 S.Note(Loc: D->getLocation(), DiagId: diag::note_constexpr_volatile_here) << 1;
895 return false;
896 }
897 return true;
898}
899
900// Similarly, for local loads.
901bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
902 assert(!B->isExtern());
903 const auto &Desc = B->getBlockDesc<LocalInlineDescriptor>();
904 const Descriptor *BlockDesc = B->getDescriptor();
905 if (!Desc.IsInitialized)
906 return diagnoseUninitialized(S, OpPC, /*Extern=*/false, B,
907 LT: Desc.getLifetime());
908 if (!CheckLifetime(S, OpPC, LT: Desc.getLifetime(), B, AK: AK_Read))
909 return false;
910 if (BlockDesc->IsVolatile) {
911 if (!S.getLangOpts().CPlusPlus)
912 return Invalid(S, OpPC);
913
914 const ValueDecl *D = BlockDesc->asValueDecl();
915 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
916 DiagId: diag::note_constexpr_access_volatile_obj, ExtraNotes: 1)
917 << AK_Read << 1 << D;
918 S.Note(Loc: D->getLocation(), DiagId: diag::note_constexpr_volatile_here) << 1;
919 return false;
920 }
921
922 // A non-const local variable while we don't have a parent frame. This must be
923 // a local variable in a statement expression.
924 if (S.Current->isBottomFrame() && !BlockDesc->IsConst &&
925 !BlockDesc->IsTemporary && !S.checkingPotentialConstantExpression()) {
926 if (const ValueDecl *VD = BlockDesc->asValueDecl())
927 diagnoseNonConstVariable(S, OpPC, VD);
928 return false;
929 }
930 return true;
931}
932
933bool CheckLoad(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK) {
934 if (Ptr.isZero()) {
935 SourceInfo Loc = S.Current->getSource(PC: OpPC);
936
937 if (Ptr.isField())
938 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_null_subobject) << CSK_Field;
939 else
940 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_access_null) << AK;
941 return false;
942 }
943
944 if (!Ptr.block()->isAccessible()) {
945 if (!Ptr.isLive()) {
946 if (Ptr.block()->isDynamic()) {
947 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
948 DiagId: diag::note_constexpr_access_deleted_object)
949 << AK;
950 } else if (!S.checkingPotentialConstantExpression()) {
951 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_uninit)
952 << AK << /*uninitialized=*/false << S.Current->getRange(PC: OpPC);
953 noteValueLocation(S, B: Ptr.block());
954 }
955
956 return false;
957 }
958 if (!CheckExtern(S, OpPC, B: Ptr.block()))
959 return false;
960 if (!CheckWeak(S, OpPC, B: Ptr.block()))
961 return false;
962 return false;
963 }
964
965 if (!CheckConstant(S, OpPC, Ptr, AK))
966 return false;
967 if (!CheckRange(S, OpPC, Ptr, AK))
968 return false;
969 if (!CheckActive(S, OpPC, Ptr, AK))
970 return false;
971 if (!Ptr.isInitialized())
972 return diagnoseUninitialized(S, OpPC, Ptr, AK);
973
974 if (!CheckLifetime(S, OpPC, LT: Ptr.getLifetime(), B: Ptr.block(), AK))
975 return false;
976 if (!CheckTemporary(S, OpPC, B: Ptr.block(), AK))
977 return false;
978
979 if (!CheckMutable(S, OpPC, Ptr, AK))
980 return false;
981 if (!CheckVolatile(S, OpPC, Ptr, AK))
982 return false;
983
984 if (!Ptr.isArrayRoot()) {
985 // According to GCC info page:
986 //
987 // 6.28 Compound Literals
988 //
989 // As an optimization, G++ sometimes gives array compound literals
990 // longer lifetimes: when the array either appears outside a function or
991 // has a const-qualified type. If foo and its initializer had elements
992 // of type char *const rather than char *, or if foo were a global
993 // variable, the array would have static storage duration. But it is
994 // probably safest just to avoid the use of array compound literals in
995 // C++ code.
996 //
997 // Obey that rule by checking constness for converted array types.
998 const Descriptor *Desc = Ptr.getFieldDesc();
999 if (const auto *CLE =
1000 dyn_cast_if_present<CompoundLiteralExpr>(Val: Desc->asExpr())) {
1001 if (QualType CLETy = CLE->getType();
1002 CLETy->isArrayType() && !CLETy.isConstant(Ctx: S.getASTContext())) {
1003 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
1004 DiagId: diag::note_invalid_subexpr_in_const_expr)
1005 << S.Current->getRange(PC: OpPC);
1006 S.Note(Loc: CLE->getExprLoc(), DiagId: diag::note_declared_at);
1007 return false;
1008 }
1009 }
1010 }
1011 return true;
1012}
1013
1014bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1015 AccessKinds AK) {
1016 if (Ptr.isBlockPointer())
1017 return CheckLoad(S, OpPC, Ptr: Ptr.view(), AK);
1018
1019 if (Ptr.isZero()) {
1020 SourceInfo Loc = S.Current->getSource(PC: OpPC);
1021 if (Ptr.isField())
1022 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_null_subobject) << CSK_Field;
1023 else
1024 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_access_null) << AK;
1025 return false;
1026 }
1027
1028 // Block and string pointers are the only ones we can actually read from.
1029 if (!Ptr.isStringPointer())
1030 return diagnoseDummy(S, OpPC, Ptr, AK);
1031
1032 assert(Ptr.isStringPointer());
1033
1034 if (!CheckConstant(S, OpPC, Ptr, AK))
1035 return false;
1036 if (!CheckRange(S, OpPC, Ptr, AK))
1037 return false;
1038 if (!Ptr.isInitialized())
1039 return diagnoseUninitialized(S, OpPC, Ptr, AK);
1040 return true;
1041}
1042
1043/// This is not used by any of the opcodes directly. It's used by
1044/// EvalEmitter to do the final lvalue-to-rvalue conversion.
1045bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1046 assert(!Ptr.isZero());
1047 if (!Ptr.isReadablePointerType())
1048 return diagnoseDummy(S, OpPC, Ptr, AK: AK_Read);
1049
1050 if (Ptr.isBlockPointer() && !Ptr.block()->isAccessible()) {
1051 if (!CheckLive(S, OpPC, Ptr, AK: AK_Read))
1052 return false;
1053 if (!CheckExtern(S, OpPC, Ptr))
1054 return false;
1055 if (!CheckWeak(S, OpPC, B: Ptr.block()))
1056 return false;
1057 return false;
1058 }
1059
1060 if (Ptr.isPastEnd())
1061 return false;
1062
1063 if (!CheckConstant(S, OpPC, Ptr))
1064 return false;
1065
1066 if (!CheckActive(S, OpPC, Ptr, AK: AK_Read))
1067 return false;
1068 if (!Ptr.isInitialized())
1069 return diagnoseUninitialized(S, OpPC, Ptr, AK: AK_Read);
1070
1071 if (Ptr.isBlockPointer()) {
1072 if (!CheckLifetime(S, OpPC, LT: Ptr.getLifetime(), B: Ptr.block(), AK: AK_Read))
1073 return false;
1074 if (!CheckTemporary(S, OpPC, B: Ptr.block(), AK: AK_Read))
1075 return false;
1076 if (!CheckMutable(S, OpPC, Ptr: Ptr.view()))
1077 return false;
1078 }
1079 return true;
1080}
1081
1082bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1083 AccessKinds AK, bool WillBeActivated) {
1084 if (Ptr.isZero())
1085 return false;
1086
1087 if (Ptr.isOpaquePointer())
1088 return diagnoseDummy(S, OpPC, Ptr, AK);
1089
1090 if (!Ptr.isBlockPointer())
1091 return false;
1092
1093 PtrView P = Ptr.view();
1094 const Block *B = Ptr.block();
1095
1096 if (!B->isAccessible()) {
1097 if (!CheckLive(S, OpPC, Ptr, AK))
1098 return false;
1099 if (!CheckExtern(S, OpPC, Ptr))
1100 return false;
1101 return false;
1102 }
1103 if (!WillBeActivated && !CheckLifetime(S, OpPC, LT: P.getLifetime(), B, AK))
1104 return false;
1105 if (!CheckRange(S, OpPC, Ptr, AK))
1106 return false;
1107 if (!CheckActive(S, OpPC, Ptr: P, AK, WillActivate: WillBeActivated))
1108 return false;
1109 if (!CheckGlobal(S, OpPC, B))
1110 return false;
1111 if (!CheckConst(S, OpPC, Ptr: P))
1112 return false;
1113 if (!CheckVolatile(S, OpPC, Ptr: P, AK))
1114 return false;
1115 if (!CheckMutable(S, OpPC, Ptr: P, AK))
1116 return false;
1117 return true;
1118}
1119
1120static bool CheckInvoke(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1121 bool IsCtor, bool IsDtor) {
1122 if (!Ptr.isDummy() && !Ptr.isConstexprUnknown()) {
1123 if (!CheckLive(S, OpPC, Ptr, AK: AK_MemberCall))
1124 return false;
1125 if (!CheckRange(S, OpPC, Ptr, AK: AK_MemberCall))
1126 return false;
1127 if (!(IsCtor || IsDtor) && !CheckLifetime(S, OpPC, Ptr, AK: AK_MemberCall))
1128 return false;
1129 }
1130 return true;
1131}
1132
1133bool CheckInit(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1134 if (!CheckLive(S, OpPC, Ptr, AK: AK_Assign))
1135 return false;
1136 if (!CheckRange(S, OpPC, Ptr, AK: AK_Assign))
1137 return false;
1138 if (!Ptr.isBlockPointer())
1139 return false;
1140 return true;
1141}
1142
1143static bool diagnoseCallableDecl(InterpState &S, CodePtr OpPC,
1144 const FunctionDecl *DiagDecl) {
1145 if (!S.diagnosing())
1146 return false;
1147 // Bail out if the function declaration itself is invalid. We will
1148 // have produced a relevant diagnostic while parsing it, so just
1149 // note the problematic sub-expression.
1150 if (DiagDecl->isInvalidDecl())
1151 return Invalid(S, OpPC);
1152
1153 // Diagnose failed assertions specially.
1154 if (S.Current->getLocation(PC: OpPC).isMacroID() && DiagDecl->getIdentifier()) {
1155 // FIXME: Instead of checking for an implementation-defined function,
1156 // check and evaluate the assert() macro.
1157 StringRef Name = DiagDecl->getName();
1158 bool AssertFailed =
1159 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
1160 if (AssertFailed) {
1161 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
1162 DiagId: diag::note_constexpr_assert_failed);
1163 return false;
1164 }
1165 }
1166
1167 if (!S.getLangOpts().CPlusPlus11) {
1168 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
1169 DiagId: diag::note_invalid_subexpr_in_const_expr);
1170 return false;
1171 }
1172
1173 // If this function is not constexpr because it is an inherited
1174 // non-constexpr constructor, diagnose that directly.
1175 const auto *CD = dyn_cast<CXXConstructorDecl>(Val: DiagDecl);
1176 if (CD && CD->isInheritingConstructor()) {
1177 const auto *Inherited = CD->getInheritedConstructor().getConstructor();
1178 if (!Inherited->isConstexpr())
1179 DiagDecl = CD = Inherited;
1180 }
1181
1182 // Silently reject constructors of invalid classes. The invalid class
1183 // has been rejected elsewhere before.
1184 if (CD && CD->getParent()->isInvalidDecl())
1185 return false;
1186
1187 // FIXME: If DiagDecl is an implicitly-declared special member function
1188 // or an inheriting constructor, we should be much more explicit about why
1189 // it's not constexpr.
1190 if (CD && CD->isInheritingConstructor()) {
1191 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC), DiagId: diag::note_constexpr_invalid_inhctor,
1192 ExtraNotes: 1)
1193 << CD->getInheritedConstructor().getConstructor()->getParent();
1194 S.Note(Loc: DiagDecl->getLocation(), DiagId: diag::note_declared_at);
1195 } else {
1196 // Don't emit anything if the function isn't defined and we're checking
1197 // for a constant expression. It might be defined at the point we're
1198 // actually calling it.
1199 bool IsExtern = DiagDecl->getStorageClass() == SC_Extern;
1200 bool IsDefined = DiagDecl->isDefined();
1201 if (!IsDefined && !IsExtern && DiagDecl->isConstexpr() &&
1202 S.checkingPotentialConstantExpression())
1203 return false;
1204
1205 // If the declaration is defined, declared 'constexpr' _and_ has a body,
1206 // the below diagnostic doesn't add anything useful.
1207 if (DiagDecl->isDefined() && DiagDecl->isConstexpr() && DiagDecl->hasBody())
1208 return false;
1209
1210 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
1211 DiagId: diag::note_constexpr_invalid_function, ExtraNotes: 1)
1212 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
1213
1214 const FunctionDecl *Definition;
1215 bool HasBody = DiagDecl->hasBody(Definition);
1216 if (HasBody && Definition)
1217 S.Note(Loc: Definition->getLocation(), DiagId: diag::note_declared_at);
1218 else
1219 S.Note(Loc: DiagDecl->getLocation(), DiagId: diag::note_declared_at);
1220 }
1221
1222 return false;
1223}
1224
1225static bool CheckCallable(InterpState &S, CodePtr OpPC, const Function *F) {
1226 if (F->isVirtual() && !S.getLangOpts().CPlusPlus20) {
1227 const SourceLocation &Loc = S.Current->getLocation(PC: OpPC);
1228 S.CCEDiag(Loc, DiagId: diag::note_constexpr_virtual_call);
1229 return false;
1230 }
1231
1232 if (F->isValid() && F->hasBody() &&
1233 (F->isConstexpr() || (S.Current->MSVCConstexprAllowed &&
1234 F->getDecl()->hasAttr<MSConstexprAttr>())))
1235 return true;
1236
1237 const FunctionDecl *DiagDecl = F->getDecl();
1238 const FunctionDecl *Definition = nullptr;
1239 DiagDecl->hasBody(Definition);
1240
1241 if (!Definition && S.checkingPotentialConstantExpression() &&
1242 DiagDecl->isConstexpr()) {
1243 return false;
1244 }
1245
1246 return diagnoseCallableDecl(S, OpPC, DiagDecl);
1247}
1248
1249static bool CheckCallDepth(InterpState &S, CodePtr OpPC) {
1250 if ((S.FrameDepth + 1) > S.getLangOpts().ConstexprCallDepth) {
1251 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
1252 DiagId: diag::note_constexpr_depth_limit_exceeded)
1253 << S.getLangOpts().ConstexprCallDepth;
1254 return false;
1255 }
1256
1257 return true;
1258}
1259
1260bool CheckThis(InterpState &S, CodePtr OpPC) {
1261 if (S.Current->hasThisPointer())
1262 return true;
1263
1264 if (!S.diagnosing())
1265 return false;
1266
1267 const Expr *E = S.Current->getExpr(PC: OpPC);
1268 if (S.getLangOpts().CPlusPlus11) {
1269 bool IsImplicit = false;
1270 if (const auto *TE = dyn_cast<CXXThisExpr>(Val: E))
1271 IsImplicit = TE->isImplicit();
1272 S.FFDiag(E, DiagId: diag::note_constexpr_this) << IsImplicit;
1273 } else {
1274 S.FFDiag(E);
1275 }
1276
1277 return false;
1278}
1279
1280bool CheckFloatStatus(InterpState &S, CodePtr OpPC, APFloat::opStatus Status,
1281 FPOptions FPO) {
1282 // In a constant context, assume that any dynamic rounding mode or FP
1283 // exception state matches the default floating-point environment.
1284 if (S.inConstantContext())
1285 return true;
1286
1287 if ((Status & APFloat::opInexact) &&
1288 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
1289 // Inexact result means that it depends on rounding mode. If the requested
1290 // mode is dynamic, the evaluation cannot be made in compile time.
1291 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1292 S.FFDiag(SI: E, DiagId: diag::note_constexpr_dynamic_rounding);
1293 return false;
1294 }
1295
1296 if ((Status != APFloat::opOK) &&
1297 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
1298 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
1299 FPO.getAllowFEnvAccess())) {
1300 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1301 S.FFDiag(SI: E, DiagId: diag::note_constexpr_float_arithmetic_strict);
1302 return false;
1303 }
1304
1305 if ((Status & APFloat::opStatus::opInvalidOp) &&
1306 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
1307 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1308 // There is no usefully definable result.
1309 S.FFDiag(SI: E);
1310 return false;
1311 }
1312
1313 return true;
1314}
1315
1316bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result,
1317 APFloat::opStatus Status, FPOptions FPO) {
1318 // FIXME: The standard quote below is deleted by P3899R3.
1319 // [expr.pre]p4:
1320 // If during the evaluation of an expression, the result is not
1321 // mathematically defined [...], the behavior is undefined.
1322 // FIXME: C++ rules require us to not conform to IEEE 754 here.
1323 // FIXME: The NaN check should not be applied outside of "constant contexts"
1324 // because it prevents NaN propagation and the "invalid" status is the
1325 // responsibility of CheckFloatStatus.
1326 if (Result.isNan()) {
1327 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1328 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_float_arithmetic)
1329 << /*NaN=*/true << S.Current->getRange(PC: OpPC);
1330 return S.noteUndefinedBehavior();
1331 }
1332
1333 return CheckFloatStatus(S, OpPC, Status, FPO);
1334}
1335
1336bool CheckDynamicMemoryAllocation(InterpState &S, CodePtr OpPC) {
1337 if (S.getLangOpts().CPlusPlus20)
1338 return true;
1339
1340 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1341 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_new);
1342 return true;
1343}
1344
1345bool CheckNewDeleteForms(InterpState &S, CodePtr OpPC,
1346 DynamicAllocator::Form AllocForm,
1347 DynamicAllocator::Form DeleteForm, const Descriptor *D,
1348 const Expr *NewExpr) {
1349 if (AllocForm == DeleteForm)
1350 return true;
1351
1352 QualType TypeToDiagnose = D->getDataType(Ctx: S.getASTContext());
1353
1354 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1355 S.FFDiag(SI: E, DiagId: diag::note_constexpr_new_delete_mismatch)
1356 << static_cast<int>(DeleteForm) << static_cast<int>(AllocForm)
1357 << TypeToDiagnose;
1358 S.Note(Loc: NewExpr->getExprLoc(), DiagId: diag::note_constexpr_dynamic_alloc_here)
1359 << NewExpr->getSourceRange();
1360 return false;
1361}
1362
1363bool CheckDeleteSource(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1364 if (Ptr.isBlockPointer() && Ptr.block()->isDynamic())
1365 return true;
1366
1367 // Whatever this is, we didn't heap allocate it.
1368 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
1369 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_delete_not_heap_alloc)
1370 << Ptr.toDiagnosticString(Ctx: S.getASTContext());
1371 noteValueLocation(S, Ptr);
1372 return false;
1373}
1374
1375/// We aleady know the given DeclRefExpr is invalid for some reason,
1376/// now figure out why and print appropriate diagnostics.
1377bool CheckDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR) {
1378 if (!S.diagnosing())
1379 return false;
1380
1381 const ValueDecl *D = DR->getDecl();
1382 return diagnoseUnknownDecl(S, OpPC, D);
1383}
1384
1385bool InvalidDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR,
1386 bool InitializerFailed) {
1387 assert(DR);
1388
1389 if (InitializerFailed) {
1390 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
1391 const auto *VD = cast<VarDecl>(Val: DR->getDecl());
1392 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_var_init_non_constant, ExtraNotes: 1) << VD;
1393 S.Note(Loc: VD->getLocation(), DiagId: diag::note_declared_at);
1394 return false;
1395 }
1396
1397 return CheckDeclRef(S, OpPC, DR);
1398}
1399
1400bool diagnoseDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1401 AccessKinds AK) {
1402 if (!S.diagnosing())
1403 return false;
1404
1405 if (AK == AK_Read || AK == AK_Increment || AK == AK_Decrement) {
1406 const VarDecl *D = Ptr.getRootVarDecl();
1407 if (!D)
1408 return false;
1409 return diagnoseUnknownDecl(S, OpPC, D, AK);
1410 }
1411
1412 if (AK == AK_Destroy || S.getLangOpts().CPlusPlus14)
1413 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_modify_global);
1414 return false;
1415}
1416
1417bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1418 AccessKinds AK) {
1419 if (!Ptr.isDummy())
1420 return true;
1421 return diagnoseDummy(S, OpPC, Ptr, AK);
1422}
1423
1424static bool CheckNonNullArgs(InterpState &S, CodePtr OpPC, const Function *F,
1425 const CallExpr *CE, unsigned ArgSize) {
1426 auto Args = ArrayRef(CE->getArgs(), CE->getNumArgs());
1427 auto NonNullArgs = collectNonNullArgs(F: F->getDecl(), Args);
1428 unsigned Offset = 0;
1429 unsigned Index = 0;
1430 for (const Expr *Arg : Args) {
1431 if (NonNullArgs[Index] && Arg->getType()->isPointerType()) {
1432 const Pointer &ArgPtr = S.Stk.peek<Pointer>(Offset: ArgSize - Offset);
1433 if (ArgPtr.isZero()) {
1434 const SourceLocation &Loc = S.Current->getLocation(PC: OpPC);
1435 S.CCEDiag(Loc, DiagId: diag::note_non_null_attribute_failed);
1436 return false;
1437 }
1438 }
1439
1440 Offset += align(Size: primSize(Type: S.Ctx.classify(E: Arg).value_or(PT: PT_Ptr)));
1441 ++Index;
1442 }
1443 return true;
1444}
1445
1446static bool runRecordDestructor(InterpState &S, CodePtr OpPC,
1447 const Pointer &BasePtr,
1448 const Descriptor *Desc) {
1449 assert(Desc->isRecord());
1450 const Record *R = Desc->ElemRecord;
1451 assert(R);
1452
1453 if (!S.Current->isBottomFrame() && S.Current->hasThisPointer() &&
1454 S.Current->getFunction()->isDestructor() &&
1455 Pointer::pointToSameBlock(A: BasePtr, B: S.Current->getThis())) {
1456 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
1457 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_double_destroy);
1458 return false;
1459 }
1460
1461 // Destructor of this record.
1462 const CXXDestructorDecl *Dtor = R->getDestructor();
1463 assert(Dtor);
1464 assert(!Dtor->isTrivial());
1465 const Function *DtorFunc = S.getContext().getOrCreateFunction(FuncDecl: Dtor);
1466 if (!DtorFunc)
1467 return false;
1468
1469 S.Stk.push<Pointer>(Args: BasePtr);
1470 return Call(S, OpPC, Func: DtorFunc, VarArgSize: 0);
1471}
1472
1473static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B) {
1474 assert(B);
1475 const Descriptor *Desc = B->getDescriptor();
1476
1477 if (Desc->isPrimitive() || Desc->isPrimitiveArray())
1478 return true;
1479
1480 assert(Desc->isRecord() || Desc->isCompositeArray());
1481
1482 if (Desc->hasTrivialDtor())
1483 return true;
1484
1485 if (Desc->isCompositeArray()) {
1486 unsigned N = Desc->getNumElems();
1487 if (N == 0)
1488 return true;
1489 const Descriptor *ElemDesc = Desc->ElemDesc;
1490 assert(ElemDesc->isRecord());
1491
1492 Pointer RP(const_cast<Block *>(B));
1493 for (int I = static_cast<int>(N) - 1; I >= 0; --I) {
1494 if (!runRecordDestructor(S, OpPC, BasePtr: RP.atIndex(Idx: I).narrow(), Desc: ElemDesc))
1495 return false;
1496 }
1497 return true;
1498 }
1499
1500 assert(Desc->isRecord());
1501 return runRecordDestructor(S, OpPC, BasePtr: Pointer(const_cast<Block *>(B)), Desc);
1502}
1503
1504static bool hasVirtualDestructor(QualType T) {
1505 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1506 if (const CXXDestructorDecl *DD = RD->getDestructor())
1507 return DD->isVirtual();
1508 return false;
1509}
1510
1511bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm,
1512 bool IsGlobalDelete) {
1513 if (!CheckDynamicMemoryAllocation(S, OpPC))
1514 return false;
1515
1516 DynamicAllocator &Allocator = S.getAllocator();
1517
1518 const Expr *Source = nullptr;
1519 const Block *BlockToDelete = nullptr;
1520 {
1521 // Extra scope for this so the block doesn't have this pointer
1522 // pointing to it when we destroy it.
1523 Pointer Ptr = S.Stk.pop<Pointer>();
1524
1525 // Deleteing nullptr is always fine.
1526 if (Ptr.isZero())
1527 return true;
1528
1529 if (!Ptr.isBlockPointer())
1530 return CheckDeleteSource(S, OpPC, Ptr);
1531
1532 // Remove base casts.
1533 QualType InitialType = Ptr.getType();
1534 Ptr = Ptr.expand().stripBaseCasts();
1535
1536 Source = Ptr.getRootExpr();
1537 BlockToDelete = Ptr.block();
1538
1539 // Check that new[]/delete[] or new/delete were used, not a mixture.
1540 const Descriptor *BlockDesc = BlockToDelete->getDescriptor();
1541 if (std::optional<DynamicAllocator::Form> AllocForm =
1542 Allocator.getAllocationForm(Source)) {
1543 DynamicAllocator::Form DeleteForm =
1544 DeleteIsArrayForm ? DynamicAllocator::Form::Array
1545 : DynamicAllocator::Form::NonArray;
1546 if (!CheckNewDeleteForms(S, OpPC, AllocForm: *AllocForm, DeleteForm, D: BlockDesc,
1547 NewExpr: Source))
1548 return false;
1549 }
1550
1551 // For the non-array case, the types must match if the static type
1552 // does not have a virtual destructor.
1553 if (!DeleteIsArrayForm && Ptr.getType() != InitialType &&
1554 !hasVirtualDestructor(T: InitialType)) {
1555 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
1556 DiagId: diag::note_constexpr_delete_base_nonvirt_dtor)
1557 << InitialType << Ptr.getType();
1558 return false;
1559 }
1560
1561 if (!Ptr.isRoot() || (Ptr.isOnePastEnd() && !Ptr.isZeroSizeArray()) ||
1562 (Ptr.isArrayElement() && Ptr.getIndex() != 0)) {
1563 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
1564 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_delete_subobject)
1565 << Ptr.toDiagnosticString(Ctx: S.getASTContext()) << Ptr.isOnePastEnd();
1566 return false;
1567 }
1568
1569 if (!CheckDeleteSource(S, OpPC, Ptr))
1570 return false;
1571
1572 // For a class type with a virtual destructor, the selected operator delete
1573 // is the one looked up when building the destructor.
1574 if (!DeleteIsArrayForm && !IsGlobalDelete) {
1575 QualType AllocType = Ptr.getType();
1576 auto getVirtualOperatorDelete = [](QualType T) -> const FunctionDecl * {
1577 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1578 if (const CXXDestructorDecl *DD = RD->getDestructor())
1579 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
1580 return nullptr;
1581 };
1582
1583 if (const FunctionDecl *VirtualDelete =
1584 getVirtualOperatorDelete(AllocType);
1585 VirtualDelete &&
1586 !VirtualDelete
1587 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
1588 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
1589 DiagId: diag::note_constexpr_new_non_replaceable)
1590 << isa<CXXMethodDecl>(Val: VirtualDelete) << VirtualDelete;
1591 return false;
1592 }
1593 }
1594 }
1595 assert(Source);
1596 assert(BlockToDelete);
1597
1598 // Invoke destructors before deallocating the memory.
1599 if (!RunDestructors(S, OpPC, B: BlockToDelete))
1600 return false;
1601
1602 if (!Allocator.deallocate(Source, BlockToDelete)) {
1603 // Nothing has been deallocated, this must be a double-delete.
1604 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
1605 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_double_delete);
1606 return false;
1607 }
1608
1609 return true;
1610}
1611
1612void diagnoseEnumValue(InterpState &S, CodePtr OpPC, const EnumDecl *ED,
1613 const APSInt &Value) {
1614 llvm::APInt Min;
1615 llvm::APInt Max;
1616 ED->getValueRange(Max, Min);
1617 --Max;
1618
1619 if (ED->getNumNegativeBits() &&
1620 (Max.slt(RHS: Value.getSExtValue()) || Min.sgt(RHS: Value.getSExtValue()))) {
1621 const SourceLocation &Loc = S.Current->getLocation(PC: OpPC);
1622 S.CCEDiag(Loc, DiagId: diag::note_constexpr_unscoped_enum_out_of_range)
1623 << llvm::toString(I: Value, Radix: 10) << Min.getSExtValue() << Max.getSExtValue()
1624 << ED;
1625 } else if (!ED->getNumNegativeBits() && Max.ult(RHS: Value.getZExtValue())) {
1626 const SourceLocation &Loc = S.Current->getLocation(PC: OpPC);
1627 S.CCEDiag(Loc, DiagId: diag::note_constexpr_unscoped_enum_out_of_range)
1628 << llvm::toString(I: Value, Radix: 10) << Min.getZExtValue() << Max.getZExtValue()
1629 << ED;
1630 }
1631}
1632
1633bool CheckLiteralType(InterpState &S, CodePtr OpPC, const Type *T) {
1634 assert(T);
1635 assert(!S.getLangOpts().CPlusPlus23);
1636
1637 // C++1y: A constant initializer for an object o [...] may also invoke
1638 // constexpr constructors for o and its subobjects even if those objects
1639 // are of non-literal class types.
1640 //
1641 // C++11 missed this detail for aggregates, so classes like this:
1642 // struct foo_t { union { int i; volatile int j; } u; };
1643 // are not (obviously) initializable like so:
1644 // __attribute__((__require_constant_initialization__))
1645 // static const foo_t x = {{0}};
1646 // because "i" is a subobject with non-literal initialization (due to the
1647 // volatile member of the union). See:
1648 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1649 // Therefore, we use the C++1y behavior.
1650
1651 if (!S.Current->isBottomFrame() &&
1652 S.Current->getFunction()->isConstructor() &&
1653 S.Current->getThis().getDeclDesc()->asDecl() == S.EvaluatingDecl) {
1654 return true;
1655 }
1656
1657 const Expr *E = S.Current->getExpr(PC: OpPC);
1658 if (S.getLangOpts().CPlusPlus11)
1659 S.FFDiag(E, DiagId: diag::note_constexpr_nonliteral) << E->getType();
1660 else
1661 S.FFDiag(E, DiagId: diag::note_invalid_subexpr_in_const_expr);
1662 return false;
1663}
1664
1665static bool diagnoseTypeIdField(InterpState &S, CodePtr OpPC,
1666 const Pointer &Ptr, unsigned Offset) {
1667 assert(Ptr.isTypeidPointer());
1668 const Record *R = S.getContext().getRecord(
1669 D: Ptr.asTypeidPointer().TypeInfoType->getAsRecordDecl());
1670 if (!R)
1671 return false;
1672 const Record::Field *Field = R->findField(Offset);
1673 if (!Field)
1674 return false;
1675
1676 std::string TypeIdStr;
1677 llvm::raw_string_ostream SS(TypeIdStr);
1678 SS << "typeid(";
1679 QualType(Ptr.asTypeidPointer().TypePtr, 0)
1680 .print(OS&: SS, Policy: S.getASTContext().getPrintingPolicy());
1681 SS << ").";
1682 SS << Field->Decl->getNameAsString();
1683
1684 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
1685 DiagId: diag::note_constexpr_access_unreadable_object)
1686 << AK_Read << TypeIdStr;
1687 return false;
1688}
1689
1690static bool allowNullSubObj(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1691 return Ptr.isZero() && S.emitRelaxedDiag(Loc: S.Current->getSource(PC: OpPC).getLoc(),
1692 DiagId: diag::note_constexpr_null_subobject);
1693}
1694
1695static bool getField(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1696 uint32_t Off) {
1697 if (S.getLangOpts().CPlusPlus && S.inConstantContext() &&
1698 !allowNullSubObj(S, OpPC, Ptr) && !CheckNull(S, OpPC, Ptr, CSK: CSK_Field))
1699 return false;
1700
1701 if (!CheckRange(S, OpPC, Ptr, CSK: CSK_Field))
1702 return false;
1703 if (!CheckArray(S, OpPC, Ptr))
1704 return false;
1705 if (!CheckSubobject(S, OpPC, Ptr, CSK: CSK_Field))
1706 return false;
1707
1708 if (Ptr.isIntegralPointer()) {
1709 if (std::optional<IntPointer> IntPtr =
1710 Ptr.asIntPointer().atOffset(Ctx: S.Ctx, Offset: Off)) {
1711 S.Stk.push<Pointer>(Args: std::move(*IntPtr));
1712 return true;
1713 }
1714 return false;
1715 }
1716
1717 if (Ptr.isOpaquePointer()) {
1718 const OpaquePointer &OP = Ptr.asOpaquePointer();
1719 const RecordDecl *RD = OP.getFieldType()->getAsRecordDecl();
1720 if (!RD)
1721 return false;
1722 const Record *R = S.getContext().getRecord(D: RD);
1723 if (!R)
1724 return false;
1725
1726 const Record::Field *F = R->findField(Offset: Off);
1727 if (!F)
1728 return false;
1729
1730 PointerPathEntry *NewPath = S.extendPointerPath(
1731 NewLength: OP.PathLength + 1, OldPP: OP.Path, NewEntry: PointerPathEntry::field(FD: F->Decl));
1732
1733 S.Stk.push<Pointer>(Args: OP.withPath(Path: NewPath, PathLength: OP.PathLength + 1,
1734 FieldTy: F->Decl->getType().getTypePtr()),
1735 Args: Ptr.getByteOffset());
1736
1737 return true;
1738 }
1739
1740 if (!Ptr.isBlockPointer()) {
1741 // If we're trying to get the field of a TypeId pointer, try to produce a
1742 // proper diagnostic.
1743 if (Ptr.isTypeidPointer())
1744 return diagnoseTypeIdField(S, OpPC, Ptr, Offset: Off);
1745 return false;
1746 }
1747
1748 // We can't get the field of something that's not a record.
1749 if (!Ptr.getFieldDesc()->isRecord())
1750 return false;
1751
1752 if ((Ptr.getByteOffset() + Off) >= Ptr.block()->getSize())
1753 return false;
1754
1755 S.Stk.push<Pointer>(Args: Ptr.atField(Off));
1756 return true;
1757}
1758
1759bool GetPtrField(InterpState &S, CodePtr OpPC, uint32_t Off) {
1760 const auto &Ptr = S.Stk.peek<Pointer>();
1761 return getField(S, OpPC, Ptr, Off);
1762}
1763
1764bool GetPtrFieldPop(InterpState &S, CodePtr OpPC, uint32_t Off) {
1765 const auto &Ptr = S.Stk.pop<Pointer>();
1766 return getField(S, OpPC, Ptr, Off);
1767}
1768
1769static bool getBase(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1770 uint32_t Off, bool NullOK) {
1771 if (!NullOK && !CheckNull(S, OpPC, Ptr, CSK: CSK_Base))
1772 return false;
1773
1774 if (Ptr.isOpaquePointer()) {
1775 const OpaquePointer &OP = Ptr.asOpaquePointer();
1776 const RecordDecl *RD = OP.getFieldType()->getAsRecordDecl();
1777 if (!RD)
1778 return false;
1779 const Record *R = S.getContext().getRecord(D: RD);
1780 assert(R);
1781
1782 const Record::Base *B = R->findBase(Offset: Off);
1783 if (!B)
1784 return false;
1785
1786 PointerPathEntry *NewPath = S.extendPointerPath(
1787 NewLength: OP.PathLength + 1, OldPP: OP.Path,
1788 NewEntry: PointerPathEntry::base(RD: cast<CXXRecordDecl>(Val: B->Decl)));
1789 S.Stk.push<Pointer>(
1790 Args: OP.withPath(
1791 Path: NewPath, PathLength: OP.PathLength + 1,
1792 FieldTy: S.getASTContext().getCanonicalTagType(TD: B->Decl).getTypePtr()),
1793 Args: Ptr.getByteOffset());
1794 return true;
1795 }
1796
1797 if (!Ptr.isBlockPointer()) {
1798 if (!Ptr.isIntegralPointer())
1799 return false;
1800 S.Stk.push<Pointer>(Args: Ptr.asIntPointer().baseCast(Ctx: S.Ctx, BaseOffset: Off));
1801 return true;
1802 }
1803
1804 if (!CheckSubobject(S, OpPC, Ptr, CSK: CSK_Base))
1805 return false;
1806
1807 // In case this isn't something we can get the base of at all,
1808 // just return the pointer itself so it can be diagnosed later.
1809 if (!Ptr.getFieldDesc()->isRecord()) {
1810 S.Stk.push<Pointer>(Args: Ptr);
1811 return true;
1812 }
1813
1814 const Pointer &Result = Ptr.atField(Off);
1815 if (Result.isPastEnd() || !Result.isBaseClass())
1816 return false;
1817 S.Stk.push<Pointer>(Args: Result);
1818 return true;
1819}
1820
1821bool GetPtrBase(InterpState &S, CodePtr OpPC, uint32_t Off) {
1822 const auto &Ptr = S.Stk.peek<Pointer>();
1823 return getBase(S, OpPC, Ptr: Ptr.narrow(), Off, /*NullOK=*/true);
1824}
1825bool GetPtrBasePop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK) {
1826 const auto &Ptr = S.Stk.pop<Pointer>();
1827 return getBase(S, OpPC, Ptr: Ptr.narrow(), Off, NullOK);
1828}
1829
1830// Do ONE step of a BaseToDerived cast.
1831bool GetPtrDerivedPop(InterpState &S, CodePtr OpPC, bool NullOK,
1832 const Type *TargetType, const Type *FinalType) {
1833 const Pointer &Ptr = S.Stk.pop<Pointer>().narrow();
1834 if (!NullOK && !CheckNull(S, OpPC, Ptr, CSK: CSK_Derived))
1835 return false;
1836
1837 if (!Ptr.isBlockPointer()) {
1838 // FIXME: We don't have the necessary information in integral pointers.
1839 // The Descriptor only has a record, but that does of course not include
1840 // the potential derived classes of said record.
1841 S.Stk.push<Pointer>(Args: Ptr);
1842 return true;
1843 }
1844
1845 if (!Ptr.getFieldDesc()->isRecord()) {
1846 S.Stk.push<Pointer>(Args: Ptr);
1847 return true;
1848 }
1849
1850 if (!CheckSubobject(S, OpPC, Ptr, CSK: CSK_Derived))
1851 return false;
1852
1853 auto diagFailedCast = [&]() -> bool {
1854 QualType MostDerivedType = Ptr.getDeclDesc()->getType();
1855 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_invalid_downcast)
1856 << MostDerivedType << QualType(FinalType, 0);
1857 return false;
1858 };
1859
1860 // We're casting down one level, which isn't possible if the pointer is
1861 // already the root.
1862 if (Ptr.isRoot())
1863 return diagFailedCast();
1864
1865 auto unwrapPointerType = [](QualType T) -> const Type * {
1866 if (T->isPointerOrReferenceType())
1867 return T->getPointeeType().getTypePtr();
1868 return T.getTypePtr();
1869 };
1870
1871 PtrView BasePtr = Ptr.view().getBase();
1872 const Type *BaseTy = unwrapPointerType(BasePtr.getType());
1873 if (!ASTContext::hasSameType(T1: BaseTy, T2: TargetType))
1874 return diagFailedCast();
1875
1876 S.Stk.push<Pointer>(Args&: BasePtr);
1877 return true;
1878}
1879
1880static bool checkConstructor(InterpState &S, CodePtr OpPC, const Function *Func,
1881 const Pointer &ThisPtr) {
1882 assert(Func->isConstructor());
1883
1884 if (Func->getParentDecl()->isInvalidDecl())
1885 return false;
1886
1887 const Descriptor *D = ThisPtr.getFieldDesc();
1888 // FIXME: I think this case is not 100% correct. E.g. a pointer into a
1889 // subobject of a composite array.
1890 if (!D->ElemRecord)
1891 return true;
1892
1893 if (S.getLangOpts().CPlusPlus26)
1894 return true;
1895
1896 if (D->ElemRecord->getNumVirtualBases() == 0)
1897 return true;
1898
1899 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC), DiagId: diag::note_constexpr_virtual_base)
1900 << Func->getParentDecl();
1901 return false;
1902}
1903
1904static bool diagnoseOutOfLifetimeDestroy(InterpState &S, CodePtr OpPC,
1905 const Pointer &Ptr) {
1906 assert(Ptr.getLifetime() != Lifetime::Started);
1907 // Try to use the declaration for better diagnostics
1908 if (const Decl *D = Ptr.getDeclDesc()->asDecl()) {
1909 auto *ND = cast<NamedDecl>(Val: D);
1910 S.FFDiag(Loc: ND->getLocation(), DiagId: diag::note_constexpr_destroy_out_of_lifetime)
1911 << ND->getNameAsString();
1912 } else {
1913 S.FFDiag(Loc: Ptr.getDeclDesc()->getLocation(),
1914 DiagId: diag::note_constexpr_destroy_out_of_lifetime)
1915 << Ptr.toDiagnosticString(Ctx: S.getASTContext());
1916 }
1917 return false;
1918}
1919
1920bool checkDestructor(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1921 if (!CheckLive(S, OpPC, Ptr, AK: AK_Destroy))
1922 return false;
1923 if (!CheckTemporary(S, OpPC, Ptr, AK: AK_Destroy))
1924 return false;
1925 if (!CheckRange(S, OpPC, Ptr, AK: AK_Destroy))
1926 return false;
1927
1928 if (Ptr.getLifetime() == Lifetime::Destroyed)
1929 return diagnoseOutOfLifetimeDestroy(S, OpPC, Ptr);
1930 if (Ptr.getLifetime() == Lifetime::Ended)
1931 return CheckLifetime(S, OpPC, Ptr, AK: AK_Destroy);
1932
1933 // We _can_ call the destructor on the global variable we're checking constant
1934 // destruction for.
1935 if (S.checkingConstantDestruction(Ptr))
1936 return true;
1937
1938 // String pointers are immutable, so can't call a destructor on them.
1939 if (Ptr.isStringPointer()) {
1940 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
1941 DiagId: diag::note_constexpr_access_unreadable_object)
1942 << AK_Destroy << Ptr.toDiagnosticString(Ctx: S.getASTContext());
1943 return false;
1944 }
1945
1946 // Can't call a dtor on a global variable.
1947 if (Ptr.isOpaquePointer() || Ptr.block()->isGlobal()) {
1948 const SourceInfo &E = S.Current->getSource(PC: OpPC);
1949 S.FFDiag(SI: E, DiagId: diag::note_constexpr_modify_global);
1950 return false;
1951 }
1952 return CheckActive(S, OpPC, Ptr, AK: AK_Destroy);
1953}
1954
1955/// Opcode. Check if the function decl can be called at compile time.
1956bool CheckFunctionDecl(InterpState &S, CodePtr OpPC, const FunctionDecl *FD) {
1957 if (S.checkingPotentialConstantExpression() && !S.Current->isBottomFrame())
1958 return false;
1959
1960 const FunctionDecl *Definition = nullptr;
1961 bool HasBody = FD->hasBody(Definition);
1962
1963 if (Definition && HasBody &&
1964 (Definition->isConstexpr() || (S.Current->MSVCConstexprAllowed &&
1965 Definition->hasAttr<MSConstexprAttr>())))
1966 return true;
1967
1968 return diagnoseCallableDecl(S, OpPC, DiagDecl: FD);
1969}
1970
1971bool CheckBitCast(InterpState &S, CodePtr OpPC, const Type *TargetType,
1972 bool SrcIsVoidPtr) {
1973 const auto &Ptr = S.Stk.peek<Pointer>();
1974 if (Ptr.isZero())
1975 return true;
1976 if (!Ptr.isBlockPointer())
1977 return true;
1978
1979 if (TargetType->isIntegerType())
1980 return true;
1981
1982 if (SrcIsVoidPtr && S.getLangOpts().CPlusPlus) {
1983 bool HasValidResult = !Ptr.isZero();
1984
1985 if (HasValidResult) {
1986 if (S.getStdAllocatorCaller(Name: "allocate"))
1987 return true;
1988
1989 const auto *E = cast<CastExpr>(Val: S.Current->getExpr(PC: OpPC));
1990 if (S.getLangOpts().CPlusPlus26 &&
1991 S.getASTContext().hasSimilarType(T1: Ptr.getType(),
1992 T2: QualType(TargetType, 0)))
1993 return true;
1994
1995 S.CCEDiag(E, DiagId: diag::note_constexpr_invalid_void_star_cast)
1996 << E->getSubExpr()->getType() << S.getLangOpts().CPlusPlus26
1997 << Ptr.getType().getCanonicalType() << E->getType()->getPointeeType();
1998 } else if (!S.getLangOpts().CPlusPlus26) {
1999 const SourceInfo &E = S.Current->getSource(PC: OpPC);
2000 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_invalid_cast)
2001 << diag::ConstexprInvalidCastKind::CastFrom << "'void *'"
2002 << S.Current->getRange(PC: OpPC);
2003 }
2004 }
2005
2006 QualType PtrType = Ptr.getType();
2007 if (PtrType->isRecordType() &&
2008 PtrType->getAsRecordDecl() != TargetType->getAsRecordDecl()) {
2009 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_invalid_cast)
2010 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
2011 << S.getLangOpts().CPlusPlus << S.Current->getRange(PC: OpPC);
2012 }
2013 return true;
2014}
2015
2016bool PtrPtrCast(InterpState &S, CodePtr OpPC, bool SrcIsVoidPtr,
2017 const Type *TargetType) {
2018 const auto &Ptr = S.Stk.peek<Pointer>();
2019
2020 if (SrcIsVoidPtr && S.getLangOpts().CPlusPlus) {
2021 bool HasValidResult = !Ptr.isZero();
2022
2023 if (HasValidResult) {
2024 if (S.getStdAllocatorCaller(Name: "allocate"))
2025 return true;
2026
2027 if (S.getLangOpts().CPlusPlus26 &&
2028 S.getASTContext().hasSimilarType(T1: Ptr.getType(),
2029 T2: TargetType->getPointeeType()))
2030 return true;
2031
2032 const auto *E = cast<CastExpr>(Val: S.Current->getExpr(PC: OpPC));
2033 S.CCEDiag(E, DiagId: diag::note_constexpr_invalid_void_star_cast)
2034 << E->getSubExpr()->getType() << S.getLangOpts().CPlusPlus26
2035 << Ptr.getType().getCanonicalType() << E->getType()->getPointeeType();
2036 } else if (!S.getLangOpts().CPlusPlus26) {
2037 const SourceInfo &E = S.Current->getSource(PC: OpPC);
2038 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_invalid_cast)
2039 << diag::ConstexprInvalidCastKind::CastFrom << "'void *'"
2040 << S.Current->getRange(PC: OpPC);
2041 }
2042 } else {
2043 const SourceInfo &E = S.Current->getSource(PC: OpPC);
2044 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_invalid_cast)
2045 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
2046 << S.getLangOpts().CPlusPlus << S.Current->getRange(PC: OpPC);
2047 }
2048
2049 // Retain the casted type for opaque pointers.
2050 if (Ptr.isOpaquePointer()) {
2051 Pointer P = S.Stk.pop<Pointer>();
2052 const OpaquePointer &OP = P.asOpaquePointer();
2053
2054 if (OP.hasDeclBase() && !validType(T: TargetType->getPointeeType()))
2055 return Invalid(S, OpPC);
2056
2057 S.Stk.push<Pointer>(Args: OP.withFieldType(FieldTy: TargetType), Args: P.getByteOffset());
2058 }
2059
2060 return true;
2061}
2062
2063static void compileFunction(InterpState &S, const Function *Func,
2064 CodePtr OpPC) {
2065 const FunctionDecl *Fn = Func->getDecl();
2066
2067 // [C++26] [temp.inst] p5
2068 // [...] the function template specialization is implicitly instantiated
2069 // when the specialization is referenced in a context that requires a function
2070 // definition to exist or if the existence of the definition affects the
2071 // semantics of the program.
2072 if (FunctionDefinitionCanBeLazilyInstantiated(FD: Fn) && S.inConstantContext()) {
2073 SemaProxy *SProxy = S.getSemaProxy();
2074 if (!SProxy)
2075 return;
2076 SProxy->instantiateFunctionDefinition(PointOfInstantiation: S.Current->getLocation(PC: OpPC),
2077 Function: const_cast<FunctionDecl *>(Fn));
2078 }
2079
2080 const FunctionDecl *Definition;
2081 if (!Fn->hasBody(Definition))
2082 return;
2083 if (!Definition)
2084 return;
2085
2086 Compiler<ByteCodeEmitter>(S.getContext(), S.P)
2087 .compileFunc(FuncDecl: Definition, Func: const_cast<Function *>(Func));
2088}
2089
2090bool CallVar(InterpState &S, CodePtr OpPC, const Function *Func,
2091 uint32_t VarArgSize) {
2092 if (Func->hasThisPointer()) {
2093 size_t ArgSize = Func->getArgSize() + VarArgSize;
2094 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(Type: PT_Ptr) : 0);
2095 const Pointer &ThisPtr = S.Stk.peek<Pointer>(Offset: ThisOffset);
2096
2097 // If the current function is a lambda static invoker and
2098 // the function we're about to call is a lambda call operator,
2099 // skip the CheckInvoke, since the ThisPtr is a null pointer
2100 // anyway.
2101 if (!(S.Current->getFunction() &&
2102 S.Current->getFunction()->isLambdaStaticInvoker() &&
2103 Func->isLambdaCallOperator())) {
2104 if (!CheckInvoke(S, OpPC, Ptr: ThisPtr, IsCtor: Func->isConstructor(),
2105 IsDtor: Func->isDestructor()))
2106 return false;
2107 }
2108
2109 if (S.checkingPotentialConstantExpression())
2110 return false;
2111 }
2112
2113 if (!Func->isFullyCompiled())
2114 compileFunction(S, Func, OpPC);
2115
2116 if (!CheckCallable(S, OpPC, F: Func))
2117 return false;
2118
2119 if (!CheckCallDepth(S, OpPC))
2120 return false;
2121
2122 InterpFrame *NewFrame = S.allocFrame(F: Func, Args&: S.PC, Args&: VarArgSize);
2123 S.enterFrame(F: NewFrame);
2124
2125 InterpStateCCOverride CCOverride(S, Func->isImmediate());
2126 bool Success = Interpret(S);
2127 S.exitFrame();
2128 return Success;
2129}
2130
2131bool Call(InterpState &S, CodePtr OpPC, const Function *Func,
2132 uint32_t VarArgSize) {
2133
2134 // C doesn't have constexpr functions.
2135 if (!S.getLangOpts().CPlusPlus)
2136 return Invalid(S, OpPC);
2137
2138 assert(Func);
2139 auto cleanup = [&]() -> bool {
2140 cleanupAfterFunctionCall(S, Func);
2141 return false;
2142 };
2143
2144 bool InstancePtrTracked = false;
2145 if (Func->hasThisPointer()) {
2146 size_t ArgSize = Func->getArgSize() + VarArgSize;
2147 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(Type: PT_Ptr) : 0);
2148
2149 const Pointer &ThisPtr = S.Stk.peek<Pointer>(Offset: ThisOffset);
2150
2151 // C++23 [expr.const]p5.6
2152 // an invocation of a virtual function ([class.virtual]) for an object whose
2153 // dynamic type is constexpr-unknown;
2154 if (ThisPtr.isDummy() && Func->isVirtual())
2155 return false;
2156
2157 // If the current function is a lambda static invoker and
2158 // the function we're about to call is a lambda call operator,
2159 // skip the CheckInvoke, since the ThisPtr is a null pointer
2160 // anyway.
2161 if (S.Current->getFunction() &&
2162 S.Current->getFunction()->isLambdaStaticInvoker() &&
2163 Func->isLambdaCallOperator()) {
2164 assert(ThisPtr.isZero());
2165 } else {
2166 if (!CheckInvoke(S, OpPC, Ptr: ThisPtr, IsCtor: Func->isConstructor(),
2167 IsDtor: Func->isDestructor()))
2168 return cleanup();
2169
2170 if (Func->isCopyOrMoveOperator() || Func->isCopyOrMoveConstructor()) {
2171 const Pointer &RVOPtr =
2172 S.Stk.peek<Pointer>(Offset: ThisOffset - align(Size: sizeof(Pointer)));
2173 if (!CheckInvoke(S, OpPC, Ptr: RVOPtr, /*IsCtor=*/true, /*IsDtor=*/false))
2174 return cleanup();
2175 }
2176
2177 if (!Func->isConstructor() && !Func->isDestructor() &&
2178 !CheckActive(S, OpPC, Ptr: ThisPtr, AK: AK_MemberCall))
2179 return false;
2180 }
2181
2182 if (Func->isConstructor() && !checkConstructor(S, OpPC, Func, ThisPtr))
2183 return false;
2184 if (Func->isDestructor() && !checkDestructor(S, OpPC, Ptr: ThisPtr))
2185 return false;
2186
2187 InstancePtrTracked = (Func->isConstructor() || Func->isDestructor());
2188 if (InstancePtrTracked)
2189 S.InitializingPtrs.push_back(Elt: ThisPtr.view());
2190 }
2191
2192 if (!Func->isFullyCompiled())
2193 compileFunction(S, Func, OpPC);
2194
2195 if (!CheckCallable(S, OpPC, F: Func))
2196 return cleanup();
2197
2198 // Do not evaluate any function calls in checkingPotentialConstantExpression
2199 // mode. Constructors will be aborted later when their initializers are
2200 // evaluated.
2201 if (S.checkingPotentialConstantExpression() && !Func->isConstructor())
2202 return false;
2203
2204 if (!CheckCallDepth(S, OpPC))
2205 return cleanup();
2206
2207 InterpFrame *NewFrame = S.allocFrame(F: Func, Args&: S.PC, Args&: VarArgSize);
2208 S.enterFrame(F: NewFrame);
2209
2210 InterpStateCCOverride CCOverride(S, Func->isImmediate());
2211 bool Success = Interpret(S);
2212 // Remove initializing block again.
2213 if (InstancePtrTracked)
2214 S.InitializingPtrs.pop_back();
2215
2216 S.exitFrame();
2217 return Success;
2218}
2219
2220static bool getDynamicDecl(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
2221 const CXXRecordDecl *&DynamicDecl) {
2222
2223 auto diagUnknownDynamicType = [&](const Pointer &P) -> bool {
2224 APValue V = P.toAPValue(ASTCtx: S.getASTContext());
2225 QualType TT = S.getASTContext().getLValueReferenceType(T: P.getType());
2226 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
2227 DiagId: diag::note_constexpr_polymorphic_unknown_dynamic_type)
2228 << AK_MemberCall << V.getAsString(Ctx: S.getASTContext(), Ty: TT);
2229 return false;
2230 };
2231
2232 if (!Ptr.isBlockPointer())
2233 return diagUnknownDynamicType(Ptr);
2234
2235 PtrView TypePtr = Ptr.view();
2236 if (S.InitializingPtrs.empty()) {
2237 TypePtr = TypePtr.stripBaseCasts();
2238 } else {
2239 auto depth = [](PtrView V) -> unsigned {
2240 unsigned C = 1;
2241 while (!V.isRoot()) {
2242 ++C;
2243 V = V.getBase();
2244 }
2245 return C;
2246 };
2247 // Consider a 'normal' diamond hierarchy:
2248 // A A 3
2249 // | |
2250 // B C 2
2251 // \ /
2252 // \ /
2253 // D 1
2254 // When we use a pointer of D*, cast it to B's A* and
2255 // use it during the construction of C*, the expected
2256 // dynamic type is B.
2257 PtrView InitPtr = S.InitializingPtrs.back();
2258 assert(depth(TypePtr) >= depth(InitPtr));
2259 unsigned D = depth(TypePtr) - depth(InitPtr);
2260 for (unsigned I = 0; I != D; ++I)
2261 TypePtr = TypePtr.getBase();
2262 }
2263
2264 QualType DynamicType = TypePtr.getType();
2265 if (TypePtr.Pointee->isGlobal() || TypePtr.isConst()) {
2266 if (const VarDecl *VD = Pointer(TypePtr).getRootVarDecl();
2267 VD && !VD->isConstexpr())
2268 return diagUnknownDynamicType(Pointer(TypePtr));
2269 }
2270
2271 if (DynamicType->isPointerType() || DynamicType->isReferenceType()) {
2272 DynamicDecl = DynamicType->getPointeeCXXRecordDecl();
2273 } else if (DynamicType->isArrayType()) {
2274 const Type *ElemType = DynamicType->getPointeeOrArrayElementType();
2275 assert(ElemType);
2276 DynamicDecl = ElemType->getAsCXXRecordDecl();
2277 } else {
2278 DynamicDecl = DynamicType->getAsCXXRecordDecl();
2279 }
2280 return DynamicDecl != nullptr;
2281}
2282
2283namespace {
2284struct DynamicCastResult {
2285 UnsignedOrNone Offset = std::nullopt;
2286 bool Ambiguous = false;
2287
2288 bool valid() const { return !Ambiguous && Offset; }
2289
2290 void setOffset(unsigned O) {
2291 if (!Offset)
2292 Offset = O;
2293 else {
2294 Ambiguous = true;
2295 }
2296 }
2297
2298 void merge(DynamicCastResult C) {
2299 Ambiguous |= C.Ambiguous;
2300 if (C.Offset) {
2301 if (!Offset)
2302 Offset = C.Offset;
2303 else
2304 Ambiguous = true;
2305 }
2306 }
2307};
2308} // namespace
2309
2310// Walk UP the type hierarchy, starting at the decl of R to find Needle.
2311static DynamicCastResult findRecordBase(const ASTContext &Ctx, const Record *R,
2312 QualType Needle) {
2313 DynamicCastResult Res;
2314
2315 if (Ctx.hasSimilarType(T1: Needle, T2: Ctx.getCanonicalTagType(TD: R->getDecl())))
2316 Res.setOffset(0);
2317
2318 for (const Record::Base &B : R->bases()) {
2319 auto N = findRecordBase(Ctx, R: B.R, Needle);
2320 if (N.Offset)
2321 N.Offset = *N.Offset + B.Offset;
2322 Res.merge(C: N);
2323 }
2324
2325 return Res;
2326}
2327
2328bool DynamicCast(InterpState &S, CodePtr OpPC, const Type *DestTypePtr,
2329 bool IsReferenceCast) {
2330 const auto &Ptr = S.Stk.pop<Pointer>();
2331 QualType TargetType = QualType(DestTypePtr, 0);
2332
2333 if (Ptr.isConstexprUnknown() || Ptr.isOpaquePointer()) {
2334 QualType T = Ptr.getType();
2335 const Expr *E = S.Current->getExpr(PC: OpPC);
2336 APValue V = Ptr.toAPValue(ASTCtx: S.getASTContext());
2337 QualType TT = S.getASTContext().getLValueReferenceType(T);
2338 S.FFDiag(E, DiagId: diag::note_constexpr_polymorphic_unknown_dynamic_type)
2339 << AK_DynamicCast << V.getAsString(Ctx: S.getASTContext(), Ty: TT);
2340 return false;
2341 }
2342
2343 if (!Ptr.isBlockPointer() || !Ptr.getRecord())
2344 return false;
2345
2346 if (!Ptr.isInitialized())
2347 return diagnoseUninitialized(S, OpPC, Ptr, AK: AK_Read);
2348
2349 // Our given pointer, limited by the base that's currently being initialized,
2350 // if any.
2351 PtrView LimitedPtr;
2352 if (S.InitializingPtrs.empty() ||
2353 S.InitializingPtrs.back().block() != Ptr.block()) {
2354 LimitedPtr = Ptr.stripBaseCasts().view();
2355 } else {
2356 LimitedPtr = S.InitializingPtrs.back();
2357 assert(LimitedPtr.block() == Ptr.block());
2358 }
2359 assert(LimitedPtr.getRecord());
2360
2361 // C++ [expr.dynamic.cast]p7:
2362 // If T is "pointer to cv void", then the result is a pointer to the most
2363 // derived object
2364 if (TargetType->isVoidType()) {
2365 S.Stk.push<Pointer>(Args&: LimitedPtr);
2366 return true;
2367 }
2368
2369 assert(!TargetType.isNull());
2370 assert(!TargetType->isVoidType());
2371 assert(TargetType->isRecordType());
2372
2373 // Helper lambdas.
2374 auto typesMatch = [&](QualType A, QualType B) -> bool {
2375 return S.getASTContext().hasSimilarType(T1: A, T2: B);
2376 };
2377 auto getRecord = [](PtrView P) -> const CXXRecordDecl * {
2378 assert(P.getRecord());
2379 return cast<CXXRecordDecl>(Val: P.getRecord()->getDecl());
2380 };
2381
2382 auto baseIsPrivate = [&](PtrView P) -> bool {
2383 if (P.isRoot() || !P.isBaseClass())
2384 return false;
2385
2386 CXXBasePaths Paths;
2387 getRecord(P.getBase())->isDerivedFrom(Base: getRecord(P), Paths);
2388
2389 // Through virtual bases, there might be more than one "direct" base. They
2390 // can have different access specifiers. They must all be private to be
2391 // considered private.
2392 return llvm::all_of(Range&: Paths, P: [](const CXXBasePath &P) -> bool {
2393 return P.Access == AS_private;
2394 });
2395 };
2396
2397 enum {
2398 DiagPrivateBase = 0,
2399 DiagNoBase = 1,
2400 DiagAmbiguous = 2,
2401 DiagPrivateSibling = 3
2402 };
2403
2404 auto diag = [&](int DiagKind, QualType ResultType) -> bool {
2405 // Pointer casts return nullptr on failure.
2406 if (!IsReferenceCast) {
2407 S.Stk.push<Pointer>(Args: 0, Args&: DestTypePtr);
2408 return true;
2409 }
2410 QualType DynamicType = LimitedPtr.getType()->getCanonicalTypeUnqualified();
2411 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
2412 DiagId: diag::note_constexpr_dynamic_cast_to_reference_failed)
2413 << DiagKind << ResultType << DynamicType << TargetType;
2414 return false;
2415 };
2416
2417 // Check if Ptr's dynamic type is derived from our target type at all.
2418 // If it isn't, diagnose this as "operand does not have base class of type
2419 // [...]".
2420 {
2421 CXXBasePaths Paths;
2422 getRecord(LimitedPtr)
2423 ->isDerivedFrom(Base: TargetType->castAsCXXRecordDecl(), Paths);
2424 if (std::distance(first: Paths.begin(), last: Paths.end()) == 0 &&
2425 !typesMatch(LimitedPtr.getType(), TargetType)) {
2426 return diag(DiagNoBase, TargetType);
2427 }
2428 }
2429
2430 // Current base is already private.
2431 if (baseIsPrivate(Ptr.view()))
2432 return diag(DiagPrivateBase, Ptr.getType());
2433
2434 std::optional<PtrView> Result;
2435 // First, check simple downcasts without ambiguities.
2436 for (PtrView Iter = Ptr.view();;) {
2437 if (Iter.isRoot() || !Iter.isBaseClass())
2438 break;
2439
2440 if (typesMatch(TargetType, Iter.getType())) {
2441 Result = Iter;
2442 break;
2443 }
2444 // Moving DOWN the type hierarchy.
2445 Iter = Iter.getBase();
2446 }
2447
2448 // Simply walking down the type hierarchy has produced a valid result, use
2449 // that.
2450 if (Result) {
2451 if (baseIsPrivate(*Result))
2452 return diag(DiagPrivateBase, Result->getType());
2453 S.Stk.push<Pointer>(Args&: *Result);
2454 return true;
2455 }
2456
2457 // Otherwise, we need to do a deep hierarchy check.
2458 bool Ambiguous = false;
2459 for (PtrView Iter = LimitedPtr;;) {
2460 // If we can move up the hierarchy from this level and reach the target type
2461 // unambiguously, we're fine.
2462 auto R = findRecordBase(Ctx: S.getASTContext(), R: Iter.getRecord(), Needle: TargetType);
2463
2464 if (R.valid()) {
2465 Result = Iter.atField(Offset: *R.Offset);
2466 break;
2467 }
2468 if (R.Ambiguous) {
2469 Ambiguous = true;
2470 break;
2471 }
2472
2473 if (Iter.isRoot() || !Iter.isBaseClass())
2474 break;
2475 // This moves us DOWN the type hierarchy.
2476 Iter = Iter.getBase();
2477 }
2478
2479 if (Ambiguous)
2480 return diag(DiagAmbiguous, TargetType);
2481
2482 if (Result) {
2483 // Might still be invalid due to resulting in a private base though.
2484 if (baseIsPrivate(*Result))
2485 return diag(DiagPrivateSibling, TargetType);
2486 S.Stk.push<Pointer>(Args&: *Result);
2487 return true;
2488 }
2489
2490 // We couldn't find the requested base.
2491 return diag(DiagNoBase, TargetType);
2492}
2493
2494bool CallVirt(InterpState &S, CodePtr OpPC, const Function *Func,
2495 uint32_t VarArgSize) {
2496 // This happens in error cases.
2497 if (!Func->hasThisPointer()) {
2498 assert(!Func->isValid());
2499 return diagnoseCallableDecl(S, OpPC, DiagDecl: Func->getDecl());
2500 }
2501
2502 assert(Func->hasThisPointer());
2503 assert(Func->isVirtual());
2504 size_t ArgSize = Func->getArgSize() + VarArgSize;
2505 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(Type: PT_Ptr) : 0);
2506 Pointer &ThisPtr = S.Stk.peek<Pointer>(Offset: ThisOffset);
2507
2508 if (!ThisPtr.isBlockPointer() && !ThisPtr.isOpaquePointer())
2509 return false;
2510
2511 const FunctionDecl *Callee = Func->getDecl();
2512
2513 const CXXRecordDecl *DynamicDecl = nullptr;
2514 if (!getDynamicDecl(S, OpPC, Ptr: ThisPtr, DynamicDecl))
2515 return false;
2516 assert(DynamicDecl);
2517
2518 const auto *StaticDecl = Func->getParentDecl();
2519 const auto *InitialFunction = cast<CXXMethodDecl>(Val: Callee);
2520 const CXXMethodDecl *Overrider;
2521
2522 if (StaticDecl != DynamicDecl) {
2523 if (!DynamicDecl->isDerivedFrom(Base: StaticDecl))
2524 return false;
2525 Overrider = S.getContext().getOverridingFunction(DynamicDecl, StaticDecl,
2526 InitialFunction);
2527
2528 } else {
2529 Overrider = InitialFunction;
2530 }
2531
2532 // C++2a [class.abstract]p6:
2533 // the effect of making a virtual call to a pure virtual function [...] is
2534 // undefined
2535 if (Overrider->isPureVirtual()) {
2536 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_pure_virtual_call,
2537 ExtraNotes: 1)
2538 << Callee;
2539 S.Note(Loc: Callee->getLocation(), DiagId: diag::note_declared_at);
2540 return false;
2541 }
2542
2543 if (Overrider != InitialFunction) {
2544 // DR1872: An instantiated virtual constexpr function can't be called in a
2545 // constant expression (prior to C++20). We can still constant-fold such a
2546 // call.
2547 if (!S.getLangOpts().CPlusPlus20 && Overrider->isVirtual()) {
2548 const Expr *E = S.Current->getExpr(PC: OpPC);
2549 S.CCEDiag(E, DiagId: diag::note_constexpr_virtual_call) << E->getSourceRange();
2550 }
2551
2552 Func = S.getContext().getOrCreateFunction(FuncDecl: Overrider);
2553
2554 const CXXRecordDecl *ThisFieldDecl =
2555 ThisPtr.getFieldDesc()->getType()->castAsCXXRecordDecl();
2556 if (Func->getParentDecl()->isDerivedFrom(Base: ThisFieldDecl)) {
2557 // If the function we call is further DOWN the hierarchy than the
2558 // FieldDesc of our pointer, just go up the hierarchy of this field
2559 // the furthest we can go.
2560 ThisPtr = ThisPtr.stripBaseCasts();
2561 }
2562 }
2563
2564 if (!Call(S, OpPC, Func, VarArgSize))
2565 return false;
2566
2567 // Covariant return types. The return type of Overrider is a pointer
2568 // or reference to a class type.
2569 if (Overrider != InitialFunction &&
2570 Overrider->getReturnType()->isPointerOrReferenceType() &&
2571 InitialFunction->getReturnType()->isPointerOrReferenceType()) {
2572 QualType OverriderPointeeType =
2573 Overrider->getReturnType()->getPointeeType();
2574 QualType InitialPointeeType =
2575 InitialFunction->getReturnType()->getPointeeType();
2576
2577 // Nothing to do if the types already match.
2578 if (S.getASTContext().hasSimilarType(T1: InitialPointeeType,
2579 T2: OverriderPointeeType))
2580 return true;
2581
2582 // We've called Overrider above, but calling code expects us to return what
2583 // InitialFunction returned. According to the rules for covariant return
2584 // types, what InitialFunction returns needs to be a base class of what
2585 // Overrider returns. So, we need to do an upcast here.
2586 unsigned Offset = S.getContext().collectBaseOffset(
2587 BaseDecl: InitialPointeeType->getAsRecordDecl(),
2588 DerivedDecl: OverriderPointeeType->getAsRecordDecl());
2589 return GetPtrBasePop(S, OpPC, Off: Offset, /*IsNullOK=*/NullOK: true);
2590 }
2591
2592 return true;
2593}
2594
2595bool CallBI(InterpState &S, CodePtr OpPC, const CallExpr *CE,
2596 uint32_t BuiltinID) {
2597 // A little arbitrary, but the current interpreter allows evaluation
2598 // of builtin functions in this mode, with some exceptions.
2599 if (BuiltinID == Builtin::BI__builtin_operator_new &&
2600 S.checkingPotentialConstantExpression())
2601 return false;
2602
2603 return InterpretBuiltin(S, OpPC, Call: CE, BuiltinID);
2604}
2605
2606bool CallPtr(InterpState &S, CodePtr OpPC, uint32_t ArgSize,
2607 const CallExpr *CE) {
2608 const Pointer &Ptr = S.Stk.pop<Pointer>();
2609
2610 if (Ptr.isZero()) {
2611 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_null_callee)
2612 << const_cast<Expr *>(CE->getCallee()) << CE->getSourceRange();
2613 return false;
2614 }
2615
2616 if (!Ptr.isFunctionPointer())
2617 return Invalid(S, OpPC);
2618
2619 const Function *F = Ptr.asFunctionPointer().Func;
2620 assert(F);
2621 // Don't allow calling block pointers.
2622 if (!F->getDecl())
2623 return Invalid(S, OpPC);
2624
2625 // This happens when the call expression has been cast to
2626 // something else, but we don't support that.
2627 if (S.Ctx.classify(T: F->getDecl()->getReturnType()) !=
2628 S.Ctx.classify(T: CE->getCallReturnType(Ctx: S.getASTContext())))
2629 return false;
2630
2631 // Check argument nullability state.
2632 if (F->hasNonNullAttr()) {
2633 if (!CheckNonNullArgs(S, OpPC, F, CE, ArgSize))
2634 return false;
2635 }
2636
2637 // Can happen when casting function pointers around.
2638 QualType CalleeType = CE->getCallee()->getType();
2639 if (CalleeType->isPointerType() &&
2640 !S.getASTContext().hasSameFunctionTypeIgnoringExceptionSpec(
2641 T: F->getDecl()->getType(), U: CalleeType->getPointeeType())) {
2642 return false;
2643 }
2644
2645 // We nedd to compile (and check) early for function pointer calls
2646 // because the Call/CallVirt below might access the instance pointer
2647 // but the Function's information about them is wrong.
2648 if (!F->isFullyCompiled())
2649 compileFunction(S, Func: F, OpPC);
2650
2651 if (!CheckCallable(S, OpPC, F))
2652 return false;
2653
2654 assert(ArgSize >= F->getWrittenArgSize());
2655 uint32_t VarArgSize = ArgSize - F->getWrittenArgSize();
2656
2657 // We need to do this explicitly here since we don't have the necessary
2658 // information to do it automatically.
2659 if (F->hasExplicitThisPointer())
2660 VarArgSize -= align(Size: primSize(Type: PT_Ptr));
2661
2662 if (F->isVirtual())
2663 return CallVirt(S, OpPC, Func: F, VarArgSize);
2664
2665 return Call(S, OpPC, Func: F, VarArgSize);
2666}
2667
2668static void startLifetimeRecurse(PtrView Ptr) {
2669 if (const Record *R = Ptr.getRecord()) {
2670 Ptr.startLifetime();
2671
2672 for (const Record::Field &Fi : R->fields()) {
2673 PtrView FP = Ptr.atField(Offset: Fi.Offset);
2674 if (FP.getLifetime() != Lifetime::Started)
2675 startLifetimeRecurse(Ptr: FP);
2676 }
2677 return;
2678 }
2679
2680 if (const Descriptor *FieldDesc = Ptr.getFieldDesc();
2681 FieldDesc->isCompositeArray()) {
2682 for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I) {
2683 PtrView EP = Ptr.atIndex(Idx: I).narrow();
2684 if (EP.getLifetime() != Lifetime::Started)
2685 startLifetimeRecurse(Ptr: EP);
2686 }
2687 return;
2688 }
2689
2690 Ptr.startLifetime();
2691}
2692
2693bool StartThisLifetime(InterpState &S) {
2694 if (S.checkingPotentialConstantExpression())
2695 return true;
2696
2697 const auto &Ptr = S.Current->getThis();
2698 if (!Ptr.isBlockPointer())
2699 return false;
2700 startLifetimeRecurse(Ptr: Ptr.view());
2701 return true;
2702}
2703
2704bool StartThisLifetime1(InterpState &S) {
2705 if (S.checkingPotentialConstantExpression())
2706 return true;
2707
2708 const auto &Ptr = S.Current->getThis();
2709 if (!Ptr.isBlockPointer())
2710 return false;
2711 Ptr.startLifetime();
2712 return true;
2713}
2714
2715// FIXME: It might be better to the recursing as part of the generated code for
2716// a destructor?
2717static void setLifeStateRecurse(PtrView Ptr, Lifetime L) {
2718 if (const Record *R = Ptr.getRecord()) {
2719 Ptr.setLifeState(L);
2720 for (const Record::Field &Fi : R->fields())
2721 setLifeStateRecurse(Ptr: Ptr.atField(Offset: Fi.Offset), L);
2722 return;
2723 }
2724
2725 if (const Descriptor *FieldDesc = Ptr.getFieldDesc();
2726 FieldDesc->isCompositeArray()) {
2727 // No endLifetime() for primitive array roots.
2728 if (Ptr.getFieldDesc()->isPrimitiveArray())
2729 assert(Ptr.getLifetime() == Lifetime::Started);
2730 for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I)
2731 setLifeStateRecurse(Ptr: Ptr.atIndex(Idx: I).narrow(), L);
2732 return;
2733 }
2734
2735 Ptr.setLifeState(L);
2736}
2737
2738/// Ends the lifetime of the peek'd pointer.
2739bool EndLifetime(InterpState &S, CodePtr OpPC) {
2740 const auto &Ptr = S.Stk.peek<Pointer>();
2741 if (!CheckDummy(S, OpPC, Ptr, AK: AK_Destroy))
2742 return false;
2743
2744 setLifeStateRecurse(Ptr: Ptr.view().narrow(), L: Lifetime::Ended);
2745 return true;
2746}
2747
2748/// Ends the lifetime of the pop'd pointer.
2749bool PseudoDtor(InterpState &S, CodePtr OpPC) {
2750 const auto &Ptr = S.Stk.pop<Pointer>();
2751 if (!checkDestructor(S, OpPC, Ptr))
2752 return false;
2753 setLifeStateRecurse(Ptr: Ptr.view().narrow(), L: Lifetime::Ended);
2754 return true;
2755}
2756
2757bool MarkDestroyed(InterpState &S, CodePtr OpPC) {
2758 const auto &Ptr = S.Stk.peek<Pointer>();
2759 if (!CheckDummy(S, OpPC, Ptr, AK: AK_Destroy))
2760 return false;
2761
2762 setLifeStateRecurse(Ptr: Ptr.view().narrow(), L: Lifetime::Destroyed);
2763 return true;
2764}
2765
2766// Initializes all bases and virtual bases.
2767// Only starts the lifetime of fields, but doesn't initialize them.
2768static void initBasesRecurse(PtrView Ptr) {
2769 assert(Ptr.getRecord());
2770
2771 const Record *R = Ptr.getRecord();
2772 for (const Record::Base &B : R->bases()) {
2773 PtrView BasePtr = Ptr.atField(Offset: B.Offset);
2774 BasePtr.initialize();
2775 BasePtr.startLifetime();
2776 initBasesRecurse(Ptr: BasePtr);
2777 }
2778
2779 for (const Record::Field &F : R->fields()) {
2780 PtrView FieldPtr = Ptr.atField(Offset: F.Offset);
2781 FieldPtr.startLifetime();
2782 if (FieldPtr.getRecord())
2783 initBasesRecurse(Ptr: FieldPtr);
2784 }
2785
2786 for (const Record::Base &B : R->virtual_bases()) {
2787 PtrView BasePtr = Ptr.atField(Offset: B.Offset);
2788 BasePtr.initialize();
2789 BasePtr.startLifetime();
2790 initBasesRecurse(Ptr: BasePtr);
2791 }
2792}
2793
2794bool DefaultInit(InterpState &S, CodePtr OpPC, const CXXConstructorDecl *Ctor) {
2795 auto Ptr = S.Stk.peek<Pointer>();
2796
2797 if (!Ptr.isBlockPointer())
2798 return false;
2799 const Record *R = Ptr.getRecord();
2800 if (!R)
2801 return false;
2802
2803 if (Ctor->isInvalidDecl() || Ctor->getParent()->isInvalidDecl())
2804 return false;
2805
2806 if (!Ctor->isConstexpr()) {
2807 if (S.getLangOpts().CPlusPlus11) {
2808 // FIXME: If DiagDecl is an implicitly-declared special member function,
2809 // we should be much more explicit about why it's not constexpr.
2810 S.CCEDiag(SI: S.Current->getSource(PC: OpPC),
2811 DiagId: diag::note_constexpr_invalid_function, ExtraNotes: 1)
2812 << /*IsConstexpr*/ 0 << /*IsConstructor*/ 1 << Ctor;
2813 S.Note(Loc: Ctor->getLocation(), DiagId: diag::note_declared_at);
2814 } else {
2815 S.CCEDiag(SI: S.Current->getSource(PC: OpPC),
2816 DiagId: diag::note_invalid_subexpr_in_const_expr);
2817 }
2818 }
2819
2820 Ptr.startLifetime();
2821 Ptr.initialize();
2822
2823 startLifetimeRecurse(Ptr: Ptr.view());
2824 initBasesRecurse(Ptr: Ptr.view());
2825
2826 return true;
2827}
2828
2829bool CheckNewTypeMismatch(InterpState &S, CodePtr OpPC, const Expr *E,
2830 std::optional<uint64_t> ArraySize) {
2831 Pointer &Orig = S.Stk.peek<Pointer>();
2832 Pointer Ptr = Orig;
2833
2834 auto directBaseIsUnion = [](const Pointer &Ptr) -> bool {
2835 if (Ptr.isArrayElement())
2836 return false;
2837 const Record *R = Ptr.getBase().getRecord();
2838 return R && R->isUnion();
2839 };
2840
2841 if (Ptr.inUnion() && directBaseIsUnion(Ptr))
2842 Ptr.activate();
2843
2844 if (Ptr.isZero()) {
2845 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_null)
2846 << AK_Construct;
2847 return false;
2848 }
2849
2850 if (Ptr.isDummy())
2851 return diagnoseDummy(S, OpPC, Ptr, AK: AK_Construct);
2852 if (!Ptr.isBlockPointer())
2853 return false;
2854
2855 if (!CheckRange(S, OpPC, Ptr, AK: AK_Construct))
2856 return false;
2857
2858 startLifetimeRecurse(Ptr: Ptr.view());
2859
2860 // Similar to CheckStore(), but with the additional CheckTemporary() call and
2861 // the AccessKinds are different.
2862 if (!Ptr.block()->isAccessible()) {
2863 if (!CheckExtern(S, OpPC, Ptr))
2864 return false;
2865 if (!CheckLive(S, OpPC, Ptr, AK: AK_Construct))
2866 return false;
2867 return diagnoseDummy(S, OpPC, Ptr, AK: AK_Construct);
2868 }
2869 if (!CheckTemporary(S, OpPC, Ptr, AK: AK_Construct))
2870 return false;
2871
2872 // CheckLifetime for this and all base pointers.
2873 for (PtrView P = Ptr.view();;) {
2874 if (!CheckLifetime(S, OpPC, LT: P.getLifetime(), B: P.Pointee, AK: AK_Construct))
2875 return false;
2876
2877 if (P.isRoot())
2878 break;
2879 P = P.getBase();
2880 }
2881
2882 if (!CheckRange(S, OpPC, Ptr, AK: AK_Construct))
2883 return false;
2884 if (!CheckGlobal(S, OpPC, B: Ptr.block()))
2885 return false;
2886 if (!CheckConst(S, OpPC, Ptr: Ptr.view()))
2887 return false;
2888
2889 const auto *NewExpr = cast<CXXNewExpr>(Val: E);
2890 const ASTContext &ASTCtx = S.getASTContext();
2891 QualType StorageType = Ptr.getType();
2892 QualType AllocType;
2893 if (ArraySize) {
2894 AllocType = ASTCtx.getConstantArrayType(
2895 EltTy: NewExpr->getAllocatedType(),
2896 ArySize: APInt(64, static_cast<uint64_t>(*ArraySize), false), SizeExpr: nullptr,
2897 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
2898 } else {
2899 AllocType = NewExpr->getAllocatedType();
2900 }
2901
2902 if (AllocType->isArrayType() && Ptr.isArrayElement() &&
2903 Ptr.expand().getIndex() == 0) {
2904 // The destination of placement new is pointing to the first element
2905 // of an array. There's a special case in [expr.const]: "[...] if T is an
2906 // array type, to the first element of such an object [...]". Handle
2907 // that case here by using the base of the Pointer.
2908 QualType AllocElementType =
2909 ASTCtx.getAsArrayType(T: AllocType)->getElementType();
2910 if (ASTCtx.hasSimilarType(T1: AllocElementType, T2: StorageType)) {
2911 StorageType = Ptr.expand().getArray().getType();
2912 Orig = Orig.expand();
2913 }
2914 }
2915
2916 if (!ASTCtx.hasSimilarType(T1: AllocType, T2: StorageType)) {
2917 S.FFDiag(Loc: S.Current->getLocation(PC: OpPC),
2918 DiagId: diag::note_constexpr_placement_new_wrong_type)
2919 << StorageType << AllocType;
2920 return false;
2921 }
2922
2923 // Can't activate fields in a union, unless the direct base is the union.
2924 if (Ptr.inUnion() && !Ptr.isActive() && !directBaseIsUnion(Ptr))
2925 return CheckActive(S, OpPC, Ptr, AK: AK_Construct);
2926
2927 return true;
2928}
2929
2930bool InvalidNewDeleteExpr(InterpState &S, CodePtr OpPC, const Expr *E) {
2931 assert(E);
2932 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
2933
2934 if (const auto *NewExpr = dyn_cast<CXXNewExpr>(Val: E)) {
2935 const FunctionDecl *OperatorNew = NewExpr->getOperatorNew();
2936
2937 // The only new-placement list we support is (std::nothrow), and only for
2938 // the replaceable global allocation functions.
2939 bool IsNothrowForm = NewExpr->getNumPlacementArgs() == 1 &&
2940 NewExpr->getPlacementArg(I: 0)->getType()->isNothrowT();
2941 if (NewExpr->getNumPlacementArgs() > 0 && !IsNothrowForm) {
2942 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_new_placement)
2943 << /*Unsupported*/ 0 << E->getSourceRange();
2944 return false;
2945 }
2946
2947 assert(
2948 !OperatorNew->isUsableAsGlobalAllocationFunctionInConstantEvaluation());
2949 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_new_non_replaceable)
2950 << isa<CXXMethodDecl>(Val: OperatorNew) << OperatorNew;
2951 return false;
2952 }
2953
2954 const auto *DeleteExpr = cast<CXXDeleteExpr>(Val: E);
2955 const FunctionDecl *OperatorDelete = DeleteExpr->getOperatorDelete();
2956 assert(!OperatorDelete
2957 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation());
2958 S.FFDiag(SI: Loc, DiagId: diag::note_constexpr_new_non_replaceable)
2959 << isa<CXXMethodDecl>(Val: OperatorDelete) << OperatorDelete;
2960 return false;
2961}
2962
2963bool CheckPlacementNew(InterpState &S, CodePtr OpPC, const Expr *E) {
2964 // Placement new is allowed in C++26. Before that, it is only allowed in a
2965 // std:: function or if [[msvc::constexpr]] was used.
2966 if (S.getLangOpts().CPlusPlus26 || S.Current->isStdFunction() ||
2967 S.Current->MSVCConstexprAllowed)
2968 return true;
2969
2970 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_new_placement)
2971 << /*C++26 feature*/ 1 << E->getSourceRange();
2972 return false;
2973}
2974
2975bool handleFixedPointOverflow(InterpState &S, CodePtr OpPC,
2976 const FixedPoint &FP) {
2977 const Expr *E = S.Current->getExpr(PC: OpPC);
2978 if (S.checkingForUndefinedBehavior()) {
2979 S.getASTContext().getDiagnostics().Report(
2980 Loc: E->getExprLoc(), DiagID: diag::warn_fixedpoint_constant_overflow)
2981 << FP.toDiagnosticString(Ctx: S.getASTContext()) << E->getType();
2982 }
2983 S.CCEDiag(E, DiagId: diag::note_constexpr_overflow)
2984 << FP.toDiagnosticString(Ctx: S.getASTContext()) << E->getType();
2985 return S.noteUndefinedBehavior();
2986}
2987
2988bool InvalidShuffleVectorIndex(InterpState &S, CodePtr OpPC, uint32_t Index) {
2989 const SourceInfo &Loc = S.Current->getSource(PC: OpPC);
2990 S.FFDiag(SI: Loc,
2991 DiagId: diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
2992 << Index;
2993 return false;
2994}
2995
2996bool CheckPointerToIntegralCast(InterpState &S, CodePtr OpPC,
2997 const Pointer &Ptr, unsigned BitWidth) {
2998 SourceInfo E = S.Current->getSource(PC: OpPC);
2999
3000 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_invalid_cast_ptrtoint)
3001 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
3002 << S.getLangOpts().CPlusPlus << S.Current->getRange(PC: OpPC);
3003 if ((Ptr.isBlockPointer() && !Ptr.isZero()) || Ptr.isOpaquePointer())
3004 S.CCEDiag(SI: E, DiagId: diag::note_constexpr_has_lvalue) << S.Current->getRange(PC: OpPC);
3005 if (Ptr.isIntegralPointer())
3006 return true;
3007
3008 if (Ptr.isOpaquePointer()) {
3009 if (!CheckIntegralAddressCast(S, OpPC, BitWidth))
3010 return false;
3011 return Ptr.isRoot();
3012 }
3013
3014 if (!Ptr.isZero()) {
3015 // Only allow based lvalue casts if they are lossless.
3016 if (!CheckIntegralAddressCast(S, OpPC, BitWidth))
3017 return Invalid(S, OpPC);
3018 }
3019 return true;
3020}
3021
3022bool CheckIntegralAddressCast(InterpState &S, CodePtr OpPC, unsigned BitWidth) {
3023 return (S.getASTContext().getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default) ==
3024 BitWidth);
3025}
3026
3027bool CastPointerIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
3028 const Pointer &Ptr = S.Stk.pop<Pointer>();
3029
3030 if (!CheckPointerToIntegralCast(S, OpPC, Ptr, BitWidth))
3031 return false;
3032
3033 auto Result = S.allocAP<IntegralAP<false>>(BitWidth);
3034 Result.copy(V: APInt(BitWidth, Ptr.getIntegerRepresentation()));
3035
3036 S.Stk.push<IntegralAP<false>>(Args&: Result);
3037 return true;
3038}
3039
3040bool CastPointerIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
3041 const Pointer &Ptr = S.Stk.pop<Pointer>();
3042
3043 if (!CheckPointerToIntegralCast(S, OpPC, Ptr, BitWidth))
3044 return false;
3045
3046 auto Result = S.allocAP<IntegralAP<true>>(BitWidth);
3047 Result.copy(V: APInt(BitWidth, Ptr.getIntegerRepresentation()));
3048
3049 S.Stk.push<IntegralAP<true>>(Args&: Result);
3050 return true;
3051}
3052
3053bool CheckBitCast(InterpState &S, CodePtr OpPC, bool HasIndeterminateBits,
3054 bool TargetIsUCharOrByte) {
3055 // This is always fine.
3056 if (!HasIndeterminateBits)
3057 return true;
3058
3059 // Indeterminate bits can only be bitcast to unsigned char or std::byte.
3060 if (TargetIsUCharOrByte)
3061 return true;
3062
3063 const Expr *E = S.Current->getExpr(PC: OpPC);
3064 QualType ExprType = E->getType();
3065 S.FFDiag(E, DiagId: diag::note_constexpr_bit_cast_indet_dest)
3066 << ExprType << S.getLangOpts().CharIsSigned << E->getSourceRange();
3067 return false;
3068}
3069
3070bool handleReference(InterpState &S, CodePtr OpPC, Block *B) {
3071 if (B->isConstexprUnknown()) {
3072 S.Stk.push<Pointer>(Args&: B);
3073 return true;
3074 }
3075
3076 const auto &ID = B->getBlockDesc<LocalInlineDescriptor>();
3077 if (!ID.IsInitialized) {
3078 if (!S.checkingPotentialConstantExpression())
3079 S.FFDiag(SI: S.Current->getSource(PC: OpPC),
3080 DiagId: diag::note_constexpr_use_uninit_reference);
3081 return false;
3082 }
3083
3084 assert(B->getDescriptor()->getPrimType() == PT_Ptr);
3085 S.Stk.push<Pointer>(Args&: B->deref<Pointer>());
3086 return true;
3087}
3088
3089bool GetTypeid(InterpState &S, const Type *TypePtr, const Type *TypeInfoType) {
3090 S.Stk.push<Pointer>(Args&: TypePtr, Args&: TypeInfoType);
3091 return true;
3092}
3093
3094bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType) {
3095 const auto &P = S.Stk.pop<Pointer>();
3096
3097 if (!P.isBlockPointer() && !P.isOpaquePointer())
3098 return false;
3099
3100 if (P.isConstexprUnknown()) {
3101 QualType DynamicType = P.getType();
3102 const Expr *E = S.Current->getExpr(PC: OpPC);
3103 APValue V = P.toAPValue(ASTCtx: S.getASTContext());
3104 QualType TT = S.getASTContext().getLValueReferenceType(T: DynamicType);
3105 S.FFDiag(E, DiagId: diag::note_constexpr_polymorphic_unknown_dynamic_type)
3106 << AK_TypeId << V.getAsString(Ctx: S.getASTContext(), Ty: TT);
3107 return false;
3108 }
3109
3110 // Pick the most-derived type.
3111 CanQualType T;
3112 if (P.isBlockPointer())
3113 T = P.stripBaseCasts().getType()->getCanonicalTypeUnqualified();
3114 else
3115 T = P.getType()->getCanonicalTypeUnqualified();
3116
3117 // ... unless we're currently constructing this object.
3118 // FIXME: We have a similar check to this in more places.
3119 if (S.Current->getFunction()) {
3120 for (const InterpFrame *Frame = S.Current; Frame; Frame = Frame->Caller) {
3121 if (const Function *Func = Frame->getFunction();
3122 Func && (Func->isConstructor() || Func->isDestructor()) &&
3123 P.block() == Frame->getThis().block()) {
3124 T = S.getContext().getASTContext().getCanonicalTagType(
3125 TD: Func->getParentDecl());
3126 break;
3127 }
3128 }
3129 }
3130
3131 S.Stk.push<Pointer>(Args: T->getTypePtr(), Args&: TypeInfoType);
3132 return true;
3133}
3134
3135bool DiagTypeid(InterpState &S, CodePtr OpPC) {
3136 const auto *E = cast<CXXTypeidExpr>(Val: S.Current->getExpr(PC: OpPC));
3137 S.CCEDiag(E, DiagId: diag::note_constexpr_typeid_polymorphic)
3138 << E->getExprOperand()->getType()
3139 << E->getExprOperand()->getSourceRange();
3140 return false;
3141}
3142
3143bool arePotentiallyOverlappingStringLiterals(const Pointer &LHS,
3144 const Pointer &RHS) {
3145 assert(LHS.isStringPointer());
3146 assert(RHS.isStringPointer());
3147
3148 unsigned LHSOffset = LHS.isOnePastEnd() ? LHS.getNumElems() : LHS.getIndex();
3149 unsigned RHSOffset = RHS.isOnePastEnd() ? RHS.getNumElems() : RHS.getIndex();
3150 const auto *LHSLit = cast<StringLiteral>(Val: LHS.getRootExpr());
3151 const auto *RHSLit = cast<StringLiteral>(Val: RHS.getRootExpr());
3152
3153 StringRef LHSStr(LHSLit->getBytes());
3154 unsigned LHSLength = LHSStr.size();
3155 StringRef RHSStr(RHSLit->getBytes());
3156 unsigned RHSLength = RHSStr.size();
3157
3158 int32_t IndexDiff = RHSOffset - LHSOffset;
3159 if (IndexDiff < 0) {
3160 if (static_cast<int32_t>(LHSLength) < -IndexDiff)
3161 return false;
3162 LHSStr = LHSStr.drop_front(N: -IndexDiff);
3163 } else {
3164 if (static_cast<int32_t>(RHSLength) < IndexDiff)
3165 return false;
3166 RHSStr = RHSStr.drop_front(N: IndexDiff);
3167 }
3168
3169 unsigned ShorterCharWidth;
3170 StringRef Shorter;
3171 StringRef Longer;
3172 if (LHSLength < RHSLength) {
3173 ShorterCharWidth = LHSLit->getCharByteWidth();
3174 Shorter = LHSStr;
3175 Longer = RHSStr;
3176 } else {
3177 ShorterCharWidth = RHSLit->getCharByteWidth();
3178 Shorter = RHSStr;
3179 Longer = LHSStr;
3180 }
3181
3182 // The null terminator isn't included in the string data, so check for it
3183 // manually. If the longer string doesn't have a null terminator where the
3184 // shorter string ends, they aren't potentially overlapping.
3185 for (unsigned NullByte : llvm::seq(Size: ShorterCharWidth)) {
3186 if (Shorter.size() + NullByte >= Longer.size())
3187 break;
3188 if (Longer[Shorter.size() + NullByte])
3189 return false;
3190 }
3191 return Shorter == Longer.take_front(N: Shorter.size());
3192}
3193
3194static void copyPrimitiveMemory(InterpState &S, PtrView Ptr, PrimType T) {
3195 if (T == PT_IntAPS) {
3196 auto &Val = Ptr.deref<IntegralAP<true>>();
3197 if (!Val.singleWord()) {
3198 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3199 Val.take(NewMemory);
3200 }
3201 } else if (T == PT_IntAP) {
3202 auto &Val = Ptr.deref<IntegralAP<false>>();
3203 if (!Val.singleWord()) {
3204 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3205 Val.take(NewMemory);
3206 }
3207 } else if (T == PT_Float) {
3208 auto &Val = Ptr.deref<Floating>();
3209 if (!Val.singleWord()) {
3210 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3211 Val.take(NewMemory);
3212 }
3213 } else if (T == PT_MemberPtr) {
3214 auto &Val = Ptr.deref<MemberPointer>();
3215 unsigned PathLength = Val.getPathLength();
3216 auto *NewPath = new (S.P) const CXXRecordDecl *[PathLength];
3217 std::copy_n(first: Val.path(), n: PathLength, result: NewPath);
3218 Val.takePath(NewPath);
3219 } else if (T == PT_Ptr) {
3220 auto &Val = Ptr.deref<Pointer>();
3221 if (Val.isOpaquePointer() && Val.asOpaquePointer().PathLength != 0) {
3222 const OpaquePointer &OP = Val.asOpaquePointer();
3223 auto *NewPath = new (S.P) PointerPathEntry[OP.PathLength];
3224 std::memcpy(dest: NewPath, src: OP.Path, n: OP.PathLength * sizeof(PointerPathEntry));
3225 Val = Pointer(OP.withPath(Path: NewPath, PathLength: OP.PathLength,
3226 FieldTy: OP.getFieldType().getTypePtr(),
3227 PastEnd: OP.isOnePastEnd()),
3228 Val.getByteOffset());
3229 }
3230 }
3231}
3232
3233template <typename T>
3234static void copyPrimitiveMemory(InterpState &S, PtrView Ptr) {
3235 assert(needsAlloc<T>());
3236 if constexpr (std::is_same_v<T, MemberPointer>) {
3237 auto &Val = Ptr.deref<MemberPointer>();
3238 unsigned PathLength = Val.getPathLength();
3239 auto *NewPath = new (S.P) const CXXRecordDecl *[PathLength];
3240 std::copy_n(first: Val.path(), n: PathLength, result: NewPath);
3241 Val.takePath(NewPath);
3242 } else if constexpr (std::is_same_v<T, Pointer>) {
3243 auto &Val = Ptr.deref<Pointer>();
3244 if (Val.isOpaquePointer() && Val.asOpaquePointer().PathLength != 0) {
3245 const OpaquePointer &OP = Val.asOpaquePointer();
3246 auto *NewPath = new (S.P) PointerPathEntry[OP.PathLength];
3247 std::memcpy(dest: NewPath, src: OP.Path, n: OP.PathLength * sizeof(PointerPathEntry));
3248 Val = Pointer(OP.withPath(Path: NewPath, PathLength: OP.PathLength,
3249 FieldTy: OP.getFieldType().getTypePtr(),
3250 PastEnd: OP.isOnePastEnd()),
3251 Val.getByteOffset());
3252 }
3253 } else {
3254 auto &Val = Ptr.deref<T>();
3255 if (!Val.singleWord()) {
3256 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3257 Val.take(NewMemory);
3258 }
3259 }
3260}
3261
3262static void finishGlobalRecurse(InterpState &S, PtrView Ptr) {
3263 if (const Record *R = Ptr.getRecord()) {
3264 for (const Record::Field &Fi : R->fields()) {
3265 if (Fi.Desc->isPrimitive()) {
3266 TYPE_SWITCH_ALLOC(Fi.Desc->getPrimType(), {
3267 copyPrimitiveMemory<T>(S, Ptr.atField(Fi.Offset));
3268 });
3269 } else {
3270 finishGlobalRecurse(S, Ptr: Ptr.atField(Offset: Fi.Offset));
3271 }
3272 }
3273 return;
3274 }
3275
3276 if (const Descriptor *D = Ptr.getFieldDesc(); D && D->isArray()) {
3277 unsigned NumElems = D->getNumElems();
3278 if (NumElems == 0)
3279 return;
3280
3281 if (D->isPrimitiveArray()) {
3282 PrimType PT = D->getPrimType();
3283 if (!needsAlloc(T: PT))
3284 return;
3285 assert(NumElems >= 1);
3286 PtrView EP = Ptr.atIndex(Idx: 0);
3287 bool AllSingleWord = true;
3288 TYPE_SWITCH_ALLOC(PT, {
3289 if (!EP.deref<T>().singleWord()) {
3290 copyPrimitiveMemory<T>(S, EP);
3291 AllSingleWord = false;
3292 }
3293 });
3294 if (AllSingleWord)
3295 return;
3296 for (unsigned I = 1; I != D->getNumElems(); ++I) {
3297 PtrView EP = Ptr.atIndex(Idx: I);
3298 copyPrimitiveMemory(S, Ptr: EP, T: PT);
3299 }
3300 } else {
3301 assert(D->isCompositeArray());
3302 for (unsigned I = 0; I != D->getNumElems(); ++I) {
3303 PtrView EP = Ptr.atIndex(Idx: I).narrow();
3304 finishGlobalRecurse(S, Ptr: EP);
3305 }
3306 }
3307 }
3308}
3309
3310bool FinishInitGlobal(InterpState &S) {
3311 const Pointer &Ptr = S.Stk.pop<Pointer>();
3312 if (!Ptr.isBlockPointer())
3313 return true;
3314
3315 finishGlobalRecurse(S, Ptr: Ptr.view());
3316 Ptr.initialize();
3317 Ptr.activate();
3318
3319 return true;
3320}
3321
3322bool InvalidCast(InterpState &S, CodePtr OpPC, CastKind Kind, bool Fatal) {
3323 switch (Kind) {
3324 case CastKind::Reinterpret:
3325 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_invalid_cast)
3326 << diag::ConstexprInvalidCastKind::Reinterpret
3327 << S.Current->getRange(PC: OpPC);
3328 return !Fatal;
3329 case CastKind::ReinterpretPtrToInt:
3330 // Don't emit anything as we'll emit diag
3331 // for this in CheckPointerToIntegralCast
3332 assert(!Fatal);
3333 return true;
3334 case CastKind::ReinterpretLike:
3335 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_invalid_cast)
3336 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
3337 << S.getLangOpts().CPlusPlus << S.Current->getRange(PC: OpPC);
3338 return !Fatal;
3339 case CastKind::Volatile:
3340 if (!S.checkingPotentialConstantExpression()) {
3341 const auto *E = S.Current->getExpr(PC: OpPC);
3342 const auto *CE = dyn_cast<CastExpr>(Val: E);
3343 if (CE && S.getLangOpts().CPlusPlus)
3344 S.FFDiag(E, DiagId: diag::note_constexpr_access_volatile_type)
3345 << AK_Read << CE->getSubExpr()->getType();
3346 else
3347 S.FFDiag(E);
3348 }
3349
3350 return false;
3351 case CastKind::Dynamic:
3352 assert(!S.getLangOpts().CPlusPlus20);
3353 S.CCEDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_invalid_cast)
3354 << diag::ConstexprInvalidCastKind::Dynamic;
3355 return true;
3356 }
3357 llvm_unreachable("Unhandled CastKind");
3358 return false;
3359}
3360
3361// Destroy one scope: deallocate all local variables of the scope and diagnose
3362// out-of-lifetime destroys.
3363bool Destroy(InterpState &S, CodePtr OpPC, uint32_t I) {
3364 assert(S.Current->getFunction());
3365 for (auto &Local : S.Current->getFunction()->getScope(Idx: I).locals_reverse()) {
3366 Block *LocalBlock = S.Current->getLocalBlock(Offset: Local.Offset);
3367
3368 if (!LocalBlock->isInitialized())
3369 continue;
3370
3371 if (LocalBlock->getBlockDesc<LocalInlineDescriptor>().getLifetime() ==
3372 Lifetime::Ended) {
3373 const Pointer Ptr = S.Current->getLocalPointer(Offset: Local.Offset);
3374 return diagnoseOutOfLifetimeDestroy(S, OpPC, Ptr);
3375 }
3376
3377 S.deallocate(B: LocalBlock);
3378 }
3379
3380 return true;
3381}
3382
3383// Perform a cast towards the class of the Decl (either up or down the
3384// hierarchy).
3385static bool castBackMemberPointer(InterpState &S,
3386 const MemberPointer &MemberPtr,
3387 int32_t BaseOffset,
3388 const RecordDecl *BaseDecl) {
3389 if (!MemberPtr.getDecl()) {
3390 S.Stk.push<MemberPointer>(Args: MemberPtr);
3391 return true;
3392 }
3393
3394 const CXXRecordDecl *Expected;
3395 if (MemberPtr.getPathLength() >= 2)
3396 Expected = MemberPtr.getPathEntry(Index: MemberPtr.getPathLength() - 2);
3397 else
3398 Expected = MemberPtr.getRecordDecl();
3399
3400 assert(Expected);
3401 if (Expected->getCanonicalDecl() != BaseDecl->getCanonicalDecl()) {
3402 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
3403 // if B does not contain the original member and is not a base or
3404 // derived class of the class containing the original member, the result
3405 // of the cast is undefined.
3406 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
3407 // (D::*). We consider that to be a language defect.
3408 return false;
3409 }
3410
3411 unsigned OldPathLength = MemberPtr.getPathLength();
3412 unsigned NewPathLength = OldPathLength - 1;
3413 bool IsDerivedMember = NewPathLength != 0;
3414 auto *NewPath = S.allocMemberPointerPath(Length: NewPathLength);
3415 std::copy_n(first: MemberPtr.path(), n: NewPathLength, result: NewPath);
3416
3417 S.Stk.push<MemberPointer>(Args: MemberPtr.atInstanceBase(Offset: BaseOffset, PathLength: NewPathLength,
3418 Path: NewPath, NewIsDerived: IsDerivedMember));
3419 return true;
3420}
3421
3422static bool appendToMemberPointer(InterpState &S,
3423 const MemberPointer &MemberPtr,
3424 int32_t BaseOffset,
3425 const RecordDecl *BaseDecl,
3426 bool IsDerivedMember) {
3427 unsigned OldPathLength = MemberPtr.getPathLength();
3428 unsigned NewPathLength = OldPathLength + 1;
3429
3430 auto *NewPath = S.allocMemberPointerPath(Length: NewPathLength);
3431 std::copy_n(first: MemberPtr.path(), n: OldPathLength, result: NewPath);
3432 NewPath[OldPathLength] = cast<CXXRecordDecl>(Val: BaseDecl);
3433
3434 S.Stk.push<MemberPointer>(Args: MemberPtr.atInstanceBase(Offset: BaseOffset, PathLength: NewPathLength,
3435 Path: NewPath, NewIsDerived: IsDerivedMember));
3436 return true;
3437}
3438
3439/// DerivedToBaseMemberPointer
3440bool CastMemberPtrBasePop(InterpState &S, int32_t Off,
3441 const RecordDecl *BaseDecl) {
3442 const auto &Ptr = S.Stk.pop<MemberPointer>();
3443
3444 if (!Ptr.isDerivedMember() && Ptr.hasPath())
3445 return castBackMemberPointer(S, MemberPtr: Ptr, BaseOffset: Off, BaseDecl);
3446
3447 bool IsDerivedMember = Ptr.isDerivedMember() || !Ptr.hasPath();
3448 return appendToMemberPointer(S, MemberPtr: Ptr, BaseOffset: Off, BaseDecl, IsDerivedMember);
3449}
3450
3451/// BaseToDerivedMemberPointer
3452bool CastMemberPtrDerivedPop(InterpState &S, int32_t Off,
3453 const RecordDecl *BaseDecl) {
3454 const auto &Ptr = S.Stk.pop<MemberPointer>();
3455
3456 if (!Ptr.isDerivedMember()) {
3457 // Simply append.
3458 return appendToMemberPointer(S, MemberPtr: Ptr, BaseOffset: Off, BaseDecl,
3459 /*IsDerivedMember=*/false);
3460 }
3461
3462 return castBackMemberPointer(S, MemberPtr: Ptr, BaseOffset: Off, BaseDecl);
3463}
3464
3465bool GetMemberPtr(InterpState &S, const ValueDecl *D) {
3466 S.Stk.push<MemberPointer>(Args&: D);
3467 return true;
3468}
3469
3470bool GetMemberPtrBase(InterpState &S) {
3471 const auto &MP = S.Stk.pop<MemberPointer>();
3472
3473 if (!MP.isBaseCastPossible())
3474 return false;
3475
3476 S.Stk.push<Pointer>(Args: MP.getBase());
3477 return true;
3478}
3479
3480bool GetMemberPtrDecl(InterpState &S) {
3481 const auto &MP = S.Stk.pop<MemberPointer>();
3482
3483 const ValueDecl *D = MP.getDecl();
3484 const auto *FD = dyn_cast_if_present<FunctionDecl>(Val: D);
3485 if (!FD)
3486 return false;
3487
3488 const auto *Method = dyn_cast<CXXMethodDecl>(Val: FD);
3489 if (!Method)
3490 return false;
3491
3492 const Pointer &Base = MP.getBase();
3493 // The method must be accessible via the base of the MemberPointer.
3494 const CXXRecordDecl *MethodParent = Method->getParent();
3495 if (!Base.getRecord() || Base.getRecord()->getDecl() != MethodParent)
3496 return false;
3497
3498 const auto *Func = S.getContext().getOrCreateFunction(FuncDecl: FD);
3499 if (!Func)
3500 return false;
3501 S.Stk.push<Pointer>(Args&: Func);
3502 return true;
3503}
3504
3505/// Just append the given Entry to the MemberPointer's path.
3506/// This is used to re-inject APValues into the bytecode interpreter.
3507bool CopyMemberPtrPath(InterpState &S, const RecordDecl *Entry,
3508 bool IsDerived) {
3509 const auto &MemberPtr = S.Stk.pop<MemberPointer>();
3510
3511 unsigned OldPathLength = MemberPtr.getPathLength();
3512 unsigned NewPathLength = OldPathLength + 1;
3513
3514 auto *NewPath = S.allocMemberPointerPath(Length: NewPathLength);
3515 std::copy_n(first: MemberPtr.path(), n: OldPathLength, result: NewPath);
3516 NewPath[OldPathLength] = cast<CXXRecordDecl>(Val: Entry);
3517
3518 S.Stk.push<MemberPointer>(
3519 Args: MemberPtr.withPath(PathLength: NewPathLength, Path: NewPath, IsDerived));
3520 return true;
3521}
3522
3523template <bool Signed>
3524static bool floatAPCast(InterpState &S, CodePtr OpPC, const Floating &F,
3525 uint32_t BitWidth, uint32_t FPOI) {
3526 APSInt Result(BitWidth, /*IsUnsigned=*/!Signed);
3527 auto Status = F.convertToInteger(Result);
3528
3529 // Float-to-Integral overflow check.
3530 if ((Status & APFloat::opStatus::opInvalidOp) && F.isFinite() &&
3531 !handleOverflow(S, OpPC, SrcValue: F.getAPFloat()))
3532 return false;
3533
3534 FPOptions FPO = FPOptions::getFromOpaqueInt(Value: FPOI);
3535
3536 auto ResultAP = S.allocAP<IntegralAP<Signed>>(BitWidth);
3537 ResultAP.copy(Result);
3538
3539 S.Stk.push<IntegralAP<Signed>>(ResultAP);
3540
3541 return CheckFloatResult(S, OpPC, Result: F, Status, FPO);
3542}
3543
3544bool CastFloatingIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth,
3545 uint32_t FPOI) {
3546 Floating F = S.Stk.pop<Floating>();
3547 return floatAPCast<false>(S, OpPC, F, BitWidth, FPOI);
3548}
3549
3550bool CastFloatingIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth,
3551 uint32_t FPOI) {
3552 Floating F = S.Stk.pop<Floating>();
3553 return floatAPCast<true>(S, OpPC, F, BitWidth, FPOI);
3554}
3555
3556bool arrayElemPtrOpaque(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
3557 APSInt &&Index, bool AllowReplace) {
3558 const OpaquePointer &OP = Ptr.asOpaquePointer();
3559 QualType ArrTy = OP.getSurroundingArray();
3560
3561 if (isa<VariableArrayType>(Val: ArrTy) && OP.PathLength != 0)
3562 return false;
3563
3564 QualType ElemType;
3565 if (const ArrayType *AT = ArrTy->getAsArrayTypeUnsafe())
3566 ElemType = AT->getElementType();
3567 else
3568 ElemType = ArrTy;
3569
3570 if (ArrTy->isArrayType()) {
3571 unsigned IndexBits = std::max(a: Index.getBitWidth(), b: 32u) + 1;
3572 APSInt NewIndex =
3573 Index.extend(width: IndexBits) +
3574 APSInt(APInt(IndexBits, Ptr.getIndex()), Index.isUnsigned());
3575
3576 if (NewIndex > Ptr.getNumElems() || NewIndex.isNegative())
3577 diagnoseArrayIndex(S, OpPC, Index: NewIndex, NumElems: Ptr.getNumElems(),
3578 IsArray: OP.isArrayElement());
3579
3580 if (NewIndex.getActiveBits() > 64)
3581 return false;
3582
3583 unsigned NewPathLength;
3584 if (AllowReplace && OP.isArrayElement()) {
3585 // This is what happens after an array-to-pointer-decay. We don't enter
3586 // the array element but simply change the index in the array we're
3587 // already pointing into.
3588 NewPathLength = OP.PathLength;
3589 } else {
3590 NewPathLength = OP.PathLength + 1;
3591 }
3592
3593 PointerPathEntry NewEntry;
3594 if (Index.isNonNegative())
3595 NewEntry = PointerPathEntry::array(Index: Index.getZExtValue());
3596 else
3597 NewEntry = PointerPathEntry::negativeArray(Index: (-Index).getZExtValue());
3598
3599 PointerPathEntry *NewPath =
3600 S.extendPointerPath(NewLength: NewPathLength, OldPP: OP.Path, NewEntry);
3601 S.Stk.push<Pointer>(
3602 Args: OP.withPath(Path: NewPath, PathLength: NewPathLength, FieldTy: ElemType.getTypePtr()),
3603 Args: Ptr.getByteOffset());
3604
3605 } else {
3606 unsigned IndexBits = std::max(a: Index.getBitWidth(), b: 64u) + 1;
3607 size_t CurrentIndex = Ptr.getByteOffset();
3608 APSInt NewOffset =
3609 Index.extend(width: IndexBits) +
3610 APSInt(APInt(IndexBits, CurrentIndex), Index.isUnsigned());
3611 if (NewOffset > 1 || NewOffset.isNegative())
3612 diagnoseArrayIndex(S, OpPC, Index: NewOffset, NumElems: 0, IsArray: false);
3613
3614 if (NewOffset.getActiveBits() > 64)
3615 return false;
3616
3617 size_t NewByteOffset = CurrentIndex + Index.getZExtValue();
3618 bool PastEnd = NewByteOffset != 0;
3619 S.Stk.push<Pointer>(Args: OP.withFieldType(FieldTy: ElemType.getTypePtr(), PastEnd),
3620 Args&: NewByteOffset);
3621 }
3622 return true;
3623}
3624
3625std::optional<Pointer> addSubOffsetOpaque(InterpState &S, CodePtr OpPC,
3626 const Pointer &Ptr, APSInt &&Offset,
3627 ArithOp Op) {
3628 assert(Ptr.isOpaquePointer());
3629 if (Offset.isZero())
3630 return Ptr;
3631
3632 const OpaquePointer &OP = Ptr.asOpaquePointer();
3633 QualType ArrTy = OP.getSurroundingArray().getCanonicalType();
3634 QualType ElemTy = OP.getFieldType();
3635 unsigned NumElems = 1;
3636
3637 if (OP.isArrayElement()) {
3638 if (const ConstantArrayType *CAT =
3639 S.getASTContext().getAsConstantArrayType(T: ArrTy))
3640 NumElems = CAT->getZExtSize();
3641 } else {
3642 ArrTy = ElemTy;
3643 }
3644
3645 if (isa<IncompleteArrayType>(Val: ArrTy)) {
3646 const SourceInfo &E = S.Current->getSource(PC: OpPC);
3647 S.FFDiag(SI: E, DiagId: diag::note_constexpr_unsized_array_indexed);
3648 return std::nullopt;
3649 }
3650
3651 if (!validType(T: ElemTy) || !validType(T: ArrTy)) {
3652 Invalid(S, OpPC);
3653 return std::nullopt;
3654 }
3655
3656 APSInt NewIndex;
3657 if (Op == ArithOp::Add) {
3658 if (OP.isArrayElement()) {
3659 NewIndex = Ptr.getIndex() + (Offset.extend(width: Offset.getBitWidth() + 2));
3660 } else {
3661 NewIndex =
3662 (Ptr.getByteOffset()) + (Offset.extend(width: Offset.getBitWidth() + 2));
3663 }
3664 } else {
3665 if (OP.isArrayElement()) {
3666 NewIndex = Ptr.getIndex() - (Offset.extend(width: Offset.getBitWidth() + 2));
3667 } else {
3668 NewIndex =
3669 (Ptr.getByteOffset()) - (Offset.extend(width: Offset.getBitWidth() + 2));
3670 }
3671 }
3672
3673 if (NewIndex > NumElems || NewIndex < 0)
3674 diagnoseArrayIndex(S, OpPC, Index: NewIndex, NumElems, IsArray: OP.isArrayElement());
3675
3676 if (NewIndex.getActiveBits() > 64)
3677 return std::nullopt;
3678
3679 // If the pointer is an array element, advance that index.
3680 if (OP.isArrayElement()) {
3681 unsigned NewPathLength = OP.PathLength;
3682 PointerPathEntry *NewPath = S.allocPointerPath(Length: OP.PathLength, OldPP: OP.Path);
3683
3684 if (Op == ArithOp::Add)
3685 NewPath[NewPathLength - 1].Index += Offset.getZExtValue();
3686 else
3687 NewPath[NewPathLength - 1].Index -= Offset.getZExtValue();
3688 return OP.withPath(Path: NewPath, PathLength: NewPathLength, FieldTy: OP.FieldType.getPointer());
3689 }
3690
3691 return Pointer(OP.withPastEnd(PastEnd: true), NewIndex.getZExtValue());
3692}
3693
3694bool virtBaseHelper(InterpState &S, const CXXRecordDecl *Decl,
3695 const Pointer &Ptr) {
3696 if (Ptr.isOpaquePointer()) {
3697 const OpaquePointer &OP = Ptr.asOpaquePointer();
3698 if (!OP.getFieldType()->isRecordType()) {
3699 S.Stk.push<Pointer>(Args: Ptr);
3700 return true;
3701 }
3702
3703 PointerPathEntry *NewPath =
3704 S.extendPointerPath(NewLength: OP.PathLength + 1, OldPP: OP.Path,
3705 NewEntry: PointerPathEntry::base(RD: Decl, /*IsVirtual=*/Virtual: true));
3706
3707 S.Stk.push<Pointer>(
3708 Args: OP.withPath(Path: NewPath, PathLength: OP.PathLength + 1,
3709 FieldTy: S.getASTContext().getCanonicalTagType(TD: Decl).getTypePtr()),
3710 Args: Ptr.getByteOffset());
3711 return true;
3712 }
3713
3714 if (!Ptr.isBlockPointer())
3715 return false;
3716 if (!Ptr.getFieldDesc()->isRecord())
3717 return false;
3718 Pointer Base = Ptr.stripBaseCasts();
3719 const Record::Base *VirtBase = Base.getRecord()->findVirtualBase(RD: Decl);
3720 if (!VirtBase)
3721 return false;
3722 S.Stk.push<Pointer>(Args: Base.atField(Off: VirtBase->Offset));
3723 return true;
3724}
3725
3726bool Memcpy(InterpState &S, CodePtr OpPC) {
3727 const Pointer &Src = S.Stk.pop<Pointer>();
3728 Pointer &Dest = S.Stk.peek<Pointer>();
3729
3730 if (Src.isDummy() || !Src.isBlockPointer())
3731 return false;
3732 if (!Dest.isBlockPointer())
3733 return false;
3734
3735 if (!CheckLoad(S, OpPC, Ptr: Src))
3736 return false;
3737
3738 return DoMemcpy(S, OpPC, Src, Dest);
3739}
3740
3741bool TrivialCopy(InterpState &S, CodePtr OpPC, bool Activate,
3742 const Function *Func) {
3743 const Pointer &Src = S.Stk.pop<Pointer>();
3744 Pointer &Dest = S.Stk.peek<Pointer>();
3745
3746 if (Src.isDummy() || Src.isConstexprUnknown() || !Src.isBlockPointer())
3747 return false;
3748 if (!Dest.isBlockPointer() || Dest.isDummy() || Dest.isConstexprUnknown())
3749 return false;
3750
3751 if (!CheckStore(S, OpPC, Ptr: Dest, AK: AK_MemberCall,
3752 /*WillBeActivated=*/Activate))
3753 return false;
3754
3755 if (S.checkingPotentialConstantExpression())
3756 return false;
3757
3758 // NOTE: This is a fake function frame that doesn't do anything except show up
3759 // in the "in call to" diagnostics. Since the copies we replace with this
3760 // opcode are always defaulted/trivial, they don't add much there either
3761 // though. Once we default to the bytecode interpreter, we shoud consider just
3762 // removing it.
3763 auto Memory = std::make_unique<char[]>(num: InterpFrame::allocSize(F: Func));
3764 auto *NewFrame =
3765 new (Memory.get()) InterpFrame(S, Func, S.PC, /*VarArgSize=*/0);
3766 InterpFrame *FrameBefore = S.Current;
3767 S.Current = NewFrame;
3768
3769 if (!CheckLoad(S, OpPC, Ptr: Src, AK: AK_Read)) {
3770 S.Current = FrameBefore;
3771 return false;
3772 }
3773
3774 bool Result = DoMemcpy(S, OpPC, Src, Dest, Activate, /*Diagnose=*/true);
3775 S.Current = FrameBefore;
3776
3777 return Result;
3778}
3779
3780// FIXME: Would be nice to generate this instead of hardcoding it here.
3781[[maybe_unused]] static constexpr bool OpReturns(Opcode Op) {
3782 return Op == OP_RetVoid || Op == OP_RetValue || Op == OP_NoRet ||
3783 Op == OP_RetSint8 || Op == OP_RetUint8 || Op == OP_RetSint16 ||
3784 Op == OP_RetUint16 || Op == OP_RetSint32 || Op == OP_RetUint32 ||
3785 Op == OP_RetSint64 || Op == OP_RetUint64 || Op == OP_RetIntAP ||
3786 Op == OP_RetIntAPS || Op == OP_RetBool || Op == OP_RetFixedPoint ||
3787 Op == OP_RetPtr || Op == OP_RetMemberPtr || Op == OP_RetFloat ||
3788 Op == OP_RetReflect || Op == OP_EndSpeculation;
3789}
3790
3791#if USE_TAILCALLS
3792PRESERVE_NONE static bool InterpNext(InterpState &S);
3793#endif
3794
3795// The dispatcher functions read the opcode arguments from the
3796// bytecode and call the implementation function.
3797#define GET_INTERPFN_DISPATCHERS
3798#include "Opcodes.inc"
3799#undef GET_INTERPFN_DISPATCHERS
3800
3801using InterpFn = bool (*)(InterpState &) PRESERVE_NONE;
3802// Array of the dispatcher functions defined above.
3803const InterpFn InterpFunctions[] = {
3804#define GET_INTERPFN_LIST
3805#include "Opcodes.inc"
3806#undef GET_INTERPFN_LIST
3807};
3808
3809#if USE_TAILCALLS
3810// Read the next opcode and call the dispatcher function.
3811PRESERVE_NONE static bool InterpNext(InterpState &S) {
3812 auto Op = S.PC.read<Opcode>();
3813 auto Fn = InterpFunctions[Op];
3814 MUSTTAIL return Fn(S);
3815}
3816#endif
3817
3818bool Interpret(InterpState &S) {
3819 assert(S.Current->getFunction());
3820
3821 S.PC = S.Current->getFunction()->getCodeBegin();
3822
3823#if USE_TAILCALLS
3824 return InterpNext(S);
3825#else
3826 while (true) {
3827 auto Op = S.PC.read<Opcode>();
3828 auto Fn = InterpFunctions[Op];
3829
3830 if (!Fn(S))
3831 return false;
3832 if (OpReturns(Op))
3833 break;
3834 }
3835 return true;
3836#endif
3837}
3838
3839/// This is used to implement speculative execution via __builtin_constant_p
3840/// when we generate bytecode.
3841///
3842/// The setup here is that we use the same tailcall mechanism for speculative
3843/// evaluation that we use for the regular one.
3844/// Since each speculative execution ends with an EndSpeculation opcode,
3845/// that one does NOT call InterpNext() but simply returns true.
3846/// This way, we return back to this function when we see an EndSpeculation,
3847/// OR (of course), when we encounter an error and one of the opcodes
3848/// returns false.
3849PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
3850 PrimType PT) {
3851 // PC after reading the BCP opcode and both Offset/PT arguments.
3852 [[maybe_unused]] CodePtr PCBefore = S.PC;
3853 size_t StackSizeBefore = S.Stk.size();
3854
3855 // Speculation depth must be at least 1 here, since we must have
3856 // passed a StartSpeculation op before.
3857#ifndef NDEBUG
3858 [[maybe_unused]] unsigned DepthBefore = S.SpeculationDepth;
3859 assert(DepthBefore >= 1);
3860#endif
3861
3862 auto SpeculativeInterp = [&S]() -> bool {
3863 // Ignore diagnostics during speculative execution.
3864 PushIgnoreDiags(S);
3865 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
3866
3867#if USE_TAILCALLS
3868 auto Op = S.PC.read<Opcode>();
3869 auto Fn = InterpFunctions[Op];
3870 return Fn(S);
3871#else
3872 while (true) {
3873 auto Op = S.PC.read<Opcode>();
3874 auto Fn = InterpFunctions[Op];
3875
3876 if (!Fn(S))
3877 return false;
3878 if (OpReturns(Op))
3879 break;
3880 }
3881 return true;
3882#endif
3883 };
3884
3885 if (SpeculativeInterp()) {
3886 // Speculation must've ended naturally via a EndSpeculation opcode.
3887 assert(S.SpeculationDepth == DepthBefore - 1);
3888 if (PT == PT_Ptr) {
3889 const auto &Ptr = S.Stk.pop<Pointer>();
3890 assert(S.Stk.size() == StackSizeBefore);
3891 S.Stk.push<Integral<32, true>>(
3892 Args: Integral<32, true>::from(V: CheckBCPResult(S, Ptr)));
3893 } else {
3894 // Pop the result from the stack and return success.
3895 TYPE_SWITCH(PT, S.Stk.discard<T>(););
3896 assert(S.Stk.size() == StackSizeBefore);
3897 S.Stk.push<Integral<32, true>>(Args: Integral<32, true>::from(V: 1));
3898 }
3899 } else {
3900 // Jump to the end of the speculation, just after the actual EndSpeculation
3901 // op.
3902 S.PC = PCBefore + Offset - align(Size: sizeof(Opcode));
3903
3904 // End the speculation manually since we didn't call EndSpeculation
3905 // naturally.
3906 EndSpeculation(S);
3907
3908 if (!S.inConstantContext())
3909 return Invalid(S, OpPC);
3910
3911 S.Stk.clearTo(NewSize: StackSizeBefore);
3912 S.Stk.push<Integral<32, true>>(Args: Integral<32, true>::from(V: 0));
3913 }
3914
3915 // We have already evaluated this speculation's EndSpeculation opcode.
3916 assert(S.SpeculationDepth == DepthBefore - 1);
3917
3918 return true;
3919}
3920
3921} // namespace interp
3922} // namespace clang
3923