clang 23.0.0git
Interp.cpp
Go to the documentation of this file.
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"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
26#include "llvm/ADT/StringExtras.h"
27
28using namespace clang;
29using namespace clang::interp;
30
31#if __has_cpp_attribute(clang::musttail)
32#define MUSTTAIL [[clang::musttail]]
33#elif __has_cpp_attribute(msvc::musttail)
34#define MUSTTAIL [[msvc::musttail]]
35#elif __has_attribute(musttail)
36#define MUSTTAIL __attribute__((musttail))
37#endif
38
39// On MSVC, musttail does not guarantee tail calls in debug mode.
40// We disable it on MSVC generally since it doesn't seem to be able
41// to handle the way we use tailcalls.
42// PPC can't tail-call external calls, which is a problem for InterpNext.
43#if defined(_MSC_VER) || defined(__powerpc__) || !defined(MUSTTAIL) || \
44 defined(__i386__) || defined(__sparc__)
45#undef MUSTTAIL
46#define MUSTTAIL
47#define USE_TAILCALLS 0
48#else
49#define USE_TAILCALLS 1
50#endif
51
53 llvm::report_fatal_error("Interpreter cannot return values");
54}
55
56//===----------------------------------------------------------------------===//
57// Jmp, Jt, Jf
58//===----------------------------------------------------------------------===//
59
60static bool Jmp(InterpState &S, CodePtr &PC, int32_t Offset) {
61 PC += Offset;
62 return S.noteStep(PC);
63}
64
65static bool Jt(InterpState &S, CodePtr &PC, int32_t Offset) {
66 if (S.Stk.pop<bool>()) {
67 PC += Offset;
68 }
69 return S.noteStep(PC);
70}
71
72static bool Jf(InterpState &S, CodePtr &PC, int32_t Offset) {
73 if (!S.Stk.pop<bool>()) {
74 PC += Offset;
75 }
76 return S.noteStep(PC);
77}
78
80 const ValueDecl *VD) {
81 const SourceInfo &E = S.Current->getSource(OpPC);
82 S.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) << VD;
83 S.Note(VD->getLocation(), diag::note_declared_at) << VD->getSourceRange();
84}
85
86static void noteValueLocation(InterpState &S, const Block *B) {
87 const Descriptor *Desc = B->getDescriptor();
88
89 if (B->isDynamic())
90 S.Note(Desc->getLocation(), diag::note_constexpr_dynamic_alloc_here);
91 else if (B->isTemporary())
92 S.Note(Desc->getLocation(), diag::note_constexpr_temporary_here);
93 else
94 S.Note(Desc->getLocation(), diag::note_declared_at);
95}
96
98 const ValueDecl *VD);
100 const ValueDecl *D) {
101 // This function tries pretty hard to produce a good diagnostic. Just skip
102 // that if nobody will see it anyway.
103 if (!S.diagnosing())
104 return false;
105
106 if (isa<ParmVarDecl>(D)) {
107 if (D->getType()->isReferenceType()) {
108 if (S.inConstantContext() && S.getLangOpts().CPlusPlus &&
109 !S.getLangOpts().CPlusPlus11) {
110 diagnoseNonConstVariable(S, OpPC, D);
111 return false;
112 }
113 }
114
115 const SourceInfo &Loc = S.Current->getSource(OpPC);
116 if (S.getLangOpts().CPlusPlus23 && D->getType()->isReferenceType()) {
117 S.FFDiag(Loc, diag::note_constexpr_access_unknown_variable, 1)
118 << AK_Read << D;
119 S.Note(D->getLocation(), diag::note_declared_at) << D->getSourceRange();
120 } else if (S.getLangOpts().CPlusPlus11) {
121 S.FFDiag(Loc, diag::note_constexpr_function_param_value_unknown, 1) << D;
122 S.Note(D->getLocation(), diag::note_declared_at) << D->getSourceRange();
123 } else {
124 S.FFDiag(Loc);
125 }
126 return false;
127 }
128
129 if (!D->getType().isConstQualified()) {
130 diagnoseNonConstVariable(S, OpPC, D);
131 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
132 if (!VD->getAnyInitializer()) {
133 diagnoseMissingInitializer(S, OpPC, VD);
134 } else {
135 const SourceInfo &Loc = S.Current->getSource(OpPC);
136 S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
137 S.Note(VD->getLocation(), diag::note_declared_at);
138 }
139 }
140
141 return false;
142}
143
145 const ValueDecl *VD) {
146 if (!S.diagnosing())
147 return;
148
149 const SourceInfo &Loc = S.Current->getSource(OpPC);
150 if (!S.getLangOpts().CPlusPlus) {
151 S.FFDiag(Loc);
152 return;
153 }
154
155 if (const auto *VarD = dyn_cast<VarDecl>(VD);
156 VarD && VarD->getType().isConstQualified() &&
157 !VarD->getAnyInitializer()) {
158 diagnoseMissingInitializer(S, OpPC, VD);
159 return;
160 }
161
162 // Rather random, but this is to match the diagnostic output of the current
163 // interpreter.
164 if (isa<ObjCIvarDecl>(VD))
165 return;
166
168 S.FFDiag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
169 S.Note(VD->getLocation(), diag::note_declared_at);
170 return;
171 }
172
173 S.FFDiag(Loc,
174 S.getLangOpts().CPlusPlus11 ? diag::note_constexpr_ltor_non_constexpr
175 : diag::note_constexpr_ltor_non_integral,
176 1)
177 << VD << VD->getType();
178 S.Note(VD->getLocation(), diag::note_declared_at);
179}
180
181static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Block *B,
182 AccessKinds AK) {
183 if (B->getDeclID()) {
184 if (!(B->isStatic() && B->isTemporary()))
185 return true;
186
187 const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(
188 B->getDescriptor()->asExpr());
189 if (!MTE)
190 return true;
191
192 // FIXME(perf): Since we do this check on every Load from a static
193 // temporary, it might make sense to cache the value of the
194 // isUsableInConstantExpressions call.
195 if (B->getEvalID() != S.EvalID &&
196 !MTE->isUsableInConstantExpressions(S.getASTContext())) {
197 const SourceInfo &E = S.Current->getSource(OpPC);
198 S.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
199 noteValueLocation(S, B);
200 return false;
201 }
202 }
203 return true;
204}
205
206static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
207 if (auto ID = Ptr.getDeclID()) {
208 if (!Ptr.isStatic())
209 return true;
210
211 if (S.P.getCurrentDecl() == ID)
212 return true;
213
214 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_modify_global);
215 return false;
216 }
217 return true;
218}
219
220namespace clang {
221namespace interp {
222PRESERVE_NONE static bool BCP(InterpState &S, CodePtr &RealPC, int32_t Offset,
223 PrimType PT);
224
225static void popArg(InterpState &S, const Expr *Arg) {
227 TYPE_SWITCH(Ty, S.Stk.discard<T>());
228}
229
231 const Function *Func) {
232 assert(S.Current);
233 assert(Func);
234
235 if (S.Current->Caller && Func->isVariadic()) {
236 // CallExpr we're look for is at the return PC of the current function, i.e.
237 // in the caller.
238 // This code path should be executed very rarely.
239 unsigned NumVarArgs;
240 const Expr *const *Args = nullptr;
241 unsigned NumArgs = 0;
242 const Expr *CallSite = S.Current->Caller->getExpr(S.Current->getRetPC());
243 if (const auto *CE = dyn_cast<CallExpr>(CallSite)) {
244 Args = CE->getArgs();
245 NumArgs = CE->getNumArgs();
246 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite)) {
247 Args = CE->getArgs();
248 NumArgs = CE->getNumArgs();
249 } else
250 assert(false && "Can't get arguments from that expression type");
251
252 assert(NumArgs >= Func->getNumWrittenParams());
253 NumVarArgs = NumArgs - (Func->getNumWrittenParams() +
254 isa<CXXOperatorCallExpr>(CallSite));
255 for (unsigned I = 0; I != NumVarArgs; ++I) {
256 const Expr *A = Args[NumArgs - 1 - I];
257 popArg(S, A);
258 }
259 }
260
261 // And in any case, remove the fixed parameters (the non-variadic ones)
262 // at the end.
263 for (const Function::ParamDescriptor &PDesc : Func->args_reverse())
264 TYPE_SWITCH(PDesc.T, S.Stk.discard<T>());
265
266 if (Func->hasThisPointer() && !Func->isThisPointerExplicit())
267 S.Stk.discard<Pointer>();
268 if (Func->hasRVO())
269 S.Stk.discard<Pointer>();
270}
271
272bool isConstexprUnknown(const Block *B) {
273 if (B->isDummy())
274 return isa_and_nonnull<ParmVarDecl>(B->getDescriptor()->asValueDecl());
276}
277
279 if (!P.isBlockPointer() || P.isZero())
280 return false;
281 return isConstexprUnknown(P.block());
282}
283
284bool CheckBCPResult(InterpState &S, const Pointer &Ptr) {
285 if (Ptr.isDummy())
286 return false;
287 if (Ptr.isZero())
288 return true;
289 if (Ptr.isFunctionPointer())
290 return false;
291 if (Ptr.isIntegralPointer())
292 return true;
293 if (Ptr.isTypeidPointer())
294 return true;
295
296 if (Ptr.getType()->isAnyComplexType())
297 return true;
298
299 if (const Expr *Base = Ptr.getDeclDesc()->asExpr())
300 return isa<StringLiteral>(Base) && Ptr.getIndex() == 0;
301 return false;
302}
303
304bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
305 AccessKinds AK, bool WillActivate) {
306 if (Ptr.isActive())
307 return true;
308
309 assert(Ptr.inUnion());
310
311 // Find the outermost union.
312 Pointer U = Ptr.getBase();
313 Pointer C = Ptr;
314 while (!U.isRoot() && !U.isActive()) {
315 // A little arbitrary, but this is what the current interpreter does.
316 // See the AnonymousUnion test in test/AST/ByteCode/unions.cpp.
317 // GCC's output is more similar to what we would get without
318 // this condition.
319 if (U.getRecord() && U.getRecord()->isAnonymousUnion())
320 break;
321
322 C = U;
323 U = U.getBase();
324 }
325 assert(C.isField());
326 assert(C.getBase() == U);
327
328 // Consider:
329 // union U {
330 // struct {
331 // int x;
332 // int y;
333 // } a;
334 // }
335 //
336 // When activating x, we will also activate a. If we now try to read
337 // from y, we will get to CheckActive, because y is not active. In that
338 // case, our U will be a (not a union). We return here and let later code
339 // handle this.
340 if (!U.getFieldDesc()->isUnion())
341 return true;
342
343 // When we will activate Ptr, check that none of the unions in its path have a
344 // non-trivial default constructor.
345 if (WillActivate) {
346 bool Fails = false;
347 Pointer It = Ptr;
348 while (!It.isRoot() && !It.isActive()) {
349 if (const Record *R = It.getRecord(); R && R->isUnion()) {
350 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl());
351 CXXRD && !CXXRD->hasTrivialDefaultConstructor()) {
352 Fails = true;
353 break;
354 }
355 }
356 It = It.getBase();
357 }
358 if (!Fails)
359 return true;
360 }
361
362 // Get the inactive field descriptor.
363 assert(!C.isActive());
364 const FieldDecl *InactiveField = C.getField();
365 assert(InactiveField);
366
367 // Find the active field of the union.
368 const Record *R = U.getRecord();
369 assert(R && R->isUnion() && "Not a union");
370
371 const FieldDecl *ActiveField = nullptr;
372 for (const Record::Field &F : R->fields()) {
373 const Pointer &Field = U.atField(F.Offset);
374 if (Field.isActive()) {
375 ActiveField = Field.getField();
376 break;
377 }
378 }
379
380 const SourceInfo &Loc = S.Current->getSource(OpPC);
381 S.FFDiag(Loc, diag::note_constexpr_access_inactive_union_member)
382 << AK << InactiveField << !ActiveField << ActiveField;
383 return false;
384}
385
386bool CheckExtern(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
387 if (!Ptr.isExtern())
388 return true;
389
390 if (!Ptr.isPastEnd() &&
391 (Ptr.isInitialized() ||
392 (Ptr.getDeclDesc()->asVarDecl() == S.EvaluatingDecl)))
393 return true;
394
395 if (S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus &&
396 Ptr.isConst())
397 return false;
398
399 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
400 diagnoseNonConstVariable(S, OpPC, VD);
401 return false;
402}
403
404bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
405 if (!Ptr.isUnknownSizeArray())
406 return true;
407 const SourceInfo &E = S.Current->getSource(OpPC);
408 S.FFDiag(E, diag::note_constexpr_unsized_array_indexed);
409 return false;
410}
411
412bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
413 AccessKinds AK) {
414 if (Ptr.isZero()) {
415 const auto &Src = S.Current->getSource(OpPC);
416
417 if (Ptr.isField())
418 S.FFDiag(Src, diag::note_constexpr_null_subobject) << CSK_Field;
419 else
420 S.FFDiag(Src, diag::note_constexpr_access_null) << AK;
421
422 return false;
423 }
424
425 if (!Ptr.isLive()) {
426 const auto &Src = S.Current->getSource(OpPC);
427
428 if (Ptr.isDynamic()) {
429 S.FFDiag(Src, diag::note_constexpr_access_deleted_object) << AK;
430 } else if (!S.checkingPotentialConstantExpression()) {
431 S.FFDiag(Src, diag::note_constexpr_access_uninit)
432 << AK << /*uninitialized=*/false << S.Current->getRange(OpPC);
433 noteValueLocation(S, Ptr.block());
434 }
435
436 return false;
437 }
438
439 return true;
440}
441
442bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc) {
443 assert(Desc);
444
445 const auto *D = Desc->asVarDecl();
446 if (!D || D == S.EvaluatingDecl || D->isConstexpr())
447 return true;
448
449 // If we're evaluating the initializer for a constexpr variable in C23, we may
450 // only read other contexpr variables. Abort here since this one isn't
451 // constexpr.
452 if (const auto *VD = dyn_cast_if_present<VarDecl>(S.EvaluatingDecl);
453 VD && VD->isConstexpr() && S.getLangOpts().C23)
454 return Invalid(S, OpPC);
455
456 QualType T = D->getType();
457 bool IsConstant = T.isConstant(S.getASTContext());
458 if (T->isIntegralOrEnumerationType()) {
459 if (!IsConstant) {
460 diagnoseNonConstVariable(S, OpPC, D);
461 return false;
462 }
463 return true;
464 }
465
466 if (IsConstant) {
467 if (S.getLangOpts().CPlusPlus) {
468 S.CCEDiag(S.Current->getLocation(OpPC),
469 S.getLangOpts().CPlusPlus11
470 ? diag::note_constexpr_ltor_non_constexpr
471 : diag::note_constexpr_ltor_non_integral,
472 1)
473 << D << T;
474 S.Note(D->getLocation(), diag::note_declared_at);
475 } else {
476 S.CCEDiag(S.Current->getLocation(OpPC));
477 }
478 return true;
479 }
480
481 if (T->isPointerOrReferenceType()) {
482 if (!T->getPointeeType().isConstant(S.getASTContext()) ||
483 !S.getLangOpts().CPlusPlus11) {
484 diagnoseNonConstVariable(S, OpPC, D);
485 return false;
486 }
487 return true;
488 }
489
490 diagnoseNonConstVariable(S, OpPC, D);
491 return false;
492}
493
494static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
495 if (!Ptr.isStatic() || !Ptr.isBlockPointer())
496 return true;
497 if (!Ptr.getDeclID())
498 return true;
499 return CheckConstant(S, OpPC, Ptr.getDeclDesc());
500}
501
502bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
503 CheckSubobjectKind CSK) {
504 if (!Ptr.isZero())
505 return true;
506 const SourceInfo &Loc = S.Current->getSource(OpPC);
507 S.FFDiag(Loc, diag::note_constexpr_null_subobject)
508 << CSK << S.Current->getRange(OpPC);
509
510 return false;
511}
512
513bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
514 AccessKinds AK) {
515 if (!Ptr.isOnePastEnd() && !Ptr.isZeroSizeArray())
516 return true;
517 if (S.getLangOpts().CPlusPlus) {
518 const SourceInfo &Loc = S.Current->getSource(OpPC);
519 S.FFDiag(Loc, diag::note_constexpr_access_past_end)
520 << AK << S.Current->getRange(OpPC);
521 }
522 return false;
523}
524
525bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
526 CheckSubobjectKind CSK) {
527 if (!Ptr.isElementPastEnd() && !Ptr.isZeroSizeArray())
528 return true;
529 const SourceInfo &Loc = S.Current->getSource(OpPC);
530 S.FFDiag(Loc, diag::note_constexpr_past_end_subobject)
531 << CSK << S.Current->getRange(OpPC);
532 return false;
533}
534
535bool CheckSubobject(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
536 CheckSubobjectKind CSK) {
537 if (!Ptr.isOnePastEnd())
538 return true;
539
540 const SourceInfo &Loc = S.Current->getSource(OpPC);
541 S.FFDiag(Loc, diag::note_constexpr_past_end_subobject)
542 << CSK << S.Current->getRange(OpPC);
543 return false;
544}
545
546bool CheckDowncast(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
547 uint32_t Offset) {
548 uint32_t MinOffset = Ptr.getDeclDesc()->getMetadataSize();
549 uint32_t PtrOffset = Ptr.getByteOffset();
550
551 // We subtract Offset from PtrOffset. The result must be at least
552 // MinOffset.
553 if (Offset < PtrOffset && (PtrOffset - Offset) >= MinOffset)
554 return true;
555
556 const auto *E = cast<CastExpr>(S.Current->getExpr(OpPC));
557 QualType TargetQT = E->getType()->getPointeeType();
558 QualType MostDerivedQT = Ptr.getDeclPtr().getType();
559
560 S.CCEDiag(E, diag::note_constexpr_invalid_downcast)
561 << MostDerivedQT << TargetQT;
562
563 return false;
564}
565
566bool CheckConst(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
567 assert(Ptr.isLive() && "Pointer is not live");
568 if (!Ptr.isConst())
569 return true;
570
571 if (Ptr.isMutable() && !Ptr.isConstInMutable())
572 return true;
573
574 if (!Ptr.isBlockPointer())
575 return false;
576
577 // The This pointer is writable in constructors and destructors,
578 // even if isConst() returns true.
579 if (llvm::is_contained(S.InitializingBlocks, Ptr.block()))
580 return true;
581
583 const QualType Ty = Ptr.getType();
584 const SourceInfo &Loc = S.Current->getSource(OpPC);
585 S.FFDiag(Loc, diag::note_constexpr_modify_const_type) << Ty;
586 }
587 return false;
588}
589
590bool CheckMutable(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
591 assert(Ptr.isLive() && "Pointer is not live");
592 if (!Ptr.isMutable())
593 return true;
594
595 // In C++14 onwards, it is permitted to read a mutable member whose
596 // lifetime began within the evaluation.
597 if (S.getLangOpts().CPlusPlus14 && Ptr.block()->getEvalID() == S.EvalID)
598 return true;
599
600 const SourceInfo &Loc = S.Current->getSource(OpPC);
601 const FieldDecl *Field = Ptr.getField();
602 S.FFDiag(Loc, diag::note_constexpr_access_mutable, 1) << AK_Read << Field;
603 S.Note(Field->getLocation(), diag::note_declared_at);
604 return false;
605}
606
607static bool CheckVolatile(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
608 AccessKinds AK) {
609 assert(Ptr.isLive());
610
611 if (!Ptr.isVolatile())
612 return true;
613
614 if (!S.getLangOpts().CPlusPlus)
615 return Invalid(S, OpPC);
616
617 // Volatile object can be written-to and read if they are being constructed.
618 if (llvm::is_contained(S.InitializingBlocks, Ptr.block()))
619 return true;
620
621 // The reason why Ptr is volatile might be further up the hierarchy.
622 // Find that pointer.
623 Pointer P = Ptr;
624 while (!P.isRoot()) {
626 break;
627 P = P.getBase();
628 }
629
630 const NamedDecl *ND = nullptr;
631 int DiagKind;
632 SourceLocation Loc;
633 if (const auto *F = P.getField()) {
634 DiagKind = 2;
635 Loc = F->getLocation();
636 ND = F;
637 } else if (auto *VD = P.getFieldDesc()->asValueDecl()) {
638 DiagKind = 1;
639 Loc = VD->getLocation();
640 ND = VD;
641 } else {
642 DiagKind = 0;
643 if (const auto *E = P.getFieldDesc()->asExpr())
644 Loc = E->getExprLoc();
645 }
646
647 S.FFDiag(S.Current->getLocation(OpPC),
648 diag::note_constexpr_access_volatile_obj, 1)
649 << AK << DiagKind << ND;
650 S.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
651 return false;
652}
653
655 AccessKinds AK) {
656 assert(Ptr.isLive());
657 assert(!Ptr.isInitialized());
658 return DiagnoseUninitialized(S, OpPC, Ptr.isExtern(), Ptr.block(), AK);
659}
660
661bool DiagnoseUninitialized(InterpState &S, CodePtr OpPC, bool Extern,
662 const Block *B, AccessKinds AK) {
663 if (Extern && S.checkingPotentialConstantExpression())
664 return false;
665
666 const Descriptor *Desc = B->getDescriptor();
667
668 if (const auto *VD = Desc->asVarDecl();
669 VD && (VD->isConstexpr() || VD->hasGlobalStorage())) {
670
671 if (VD == S.EvaluatingDecl &&
672 !(S.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType())) {
673 if (!S.getLangOpts().CPlusPlus14 &&
674 !VD->getType().isConstant(S.getASTContext())) {
675 // Diagnose as non-const read.
676 diagnoseNonConstVariable(S, OpPC, VD);
677 } else {
678 const SourceInfo &Loc = S.Current->getSource(OpPC);
679 // Diagnose as "read of object outside its lifetime".
680 S.FFDiag(Loc, diag::note_constexpr_access_uninit)
681 << AK << /*IsIndeterminate=*/false;
682 S.Note(VD->getLocation(), diag::note_declared_at);
683 }
684 return false;
685 }
686
687 if (VD->getAnyInitializer()) {
688 const SourceInfo &Loc = S.Current->getSource(OpPC);
689 S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
690 S.Note(VD->getLocation(), diag::note_declared_at);
691 } else {
692 diagnoseMissingInitializer(S, OpPC, VD);
693 }
694 return false;
695 }
696
698 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
699 << AK << /*uninitialized=*/true << S.Current->getRange(OpPC);
700 noteValueLocation(S, B);
701 }
702 return false;
703}
704
706 const Block *B, AccessKinds AK) {
707 if (LT == Lifetime::Started)
708 return true;
709
711 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
712 << AK << /*uninitialized=*/false << S.Current->getRange(OpPC);
713 noteValueLocation(S, B);
714 }
715 return false;
716}
717static bool CheckLifetime(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
718 AccessKinds AK) {
719 return CheckLifetime(S, OpPC, Ptr.getLifetime(), Ptr.block(), AK);
720}
721
722static bool CheckWeak(InterpState &S, CodePtr OpPC, const Block *B) {
723 if (!B->isWeak())
724 return true;
725
726 const auto *VD = B->getDescriptor()->asVarDecl();
727 assert(VD);
728 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_var_init_weak)
729 << VD;
730 S.Note(VD->getLocation(), diag::note_declared_at);
731
732 return false;
733}
734
735// The list of checks here is just the one from CheckLoad, but with the
736// ones removed that are impossible on primitive global values.
737// For example, since those can't be members of structs, they also can't
738// be mutable.
739bool CheckGlobalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
740 const auto &Desc = B->getBlockDesc<GlobalInlineDescriptor>();
741 if (!B->isAccessible()) {
742 if (!CheckExtern(S, OpPC, Pointer(const_cast<Block *>(B))))
743 return false;
744 if (!CheckDummy(S, OpPC, B, AK_Read))
745 return false;
746 return CheckWeak(S, OpPC, B);
747 }
748
749 if (!CheckConstant(S, OpPC, B->getDescriptor()))
750 return false;
751 if (Desc.InitState != GlobalInitState::Initialized)
752 return DiagnoseUninitialized(S, OpPC, B->isExtern(), B, AK_Read);
753 if (!CheckTemporary(S, OpPC, B, AK_Read))
754 return false;
755 if (B->getDescriptor()->IsVolatile) {
756 if (!S.getLangOpts().CPlusPlus)
757 return Invalid(S, OpPC);
758
759 const ValueDecl *D = B->getDescriptor()->asValueDecl();
760 S.FFDiag(S.Current->getLocation(OpPC),
761 diag::note_constexpr_access_volatile_obj, 1)
762 << AK_Read << 1 << D;
763 S.Note(D->getLocation(), diag::note_constexpr_volatile_here) << 1;
764 return false;
765 }
766 return true;
767}
768
769// Similarly, for local loads.
770bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
771 assert(!B->isExtern());
772 const auto &Desc = *reinterpret_cast<const InlineDescriptor *>(B->rawData());
773 if (!CheckLifetime(S, OpPC, Desc.LifeState, B, AK_Read))
774 return false;
775 if (!Desc.IsInitialized)
776 return DiagnoseUninitialized(S, OpPC, /*Extern=*/false, B, AK_Read);
777 if (B->getDescriptor()->IsVolatile) {
778 if (!S.getLangOpts().CPlusPlus)
779 return Invalid(S, OpPC);
780
781 const ValueDecl *D = B->getDescriptor()->asValueDecl();
782 S.FFDiag(S.Current->getLocation(OpPC),
783 diag::note_constexpr_access_volatile_obj, 1)
784 << AK_Read << 1 << D;
785 S.Note(D->getLocation(), diag::note_constexpr_volatile_here) << 1;
786 return false;
787 }
788 return true;
789}
790
791bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
792 AccessKinds AK) {
793 if (Ptr.isZero()) {
794 const auto &Src = S.Current->getSource(OpPC);
795
796 if (Ptr.isField())
797 S.FFDiag(Src, diag::note_constexpr_null_subobject) << CSK_Field;
798 else
799 S.FFDiag(Src, diag::note_constexpr_access_null) << AK;
800 return false;
801 }
802 // Block pointers are the only ones we can actually read from.
803 if (!Ptr.isBlockPointer())
804 return false;
805
806 if (!Ptr.block()->isAccessible()) {
807 if (!CheckLive(S, OpPC, Ptr, AK))
808 return false;
809 if (!CheckExtern(S, OpPC, Ptr))
810 return false;
811 if (!CheckDummy(S, OpPC, Ptr.block(), AK))
812 return false;
813 return CheckWeak(S, OpPC, Ptr.block());
814 }
815
816 if (!CheckConstant(S, OpPC, Ptr))
817 return false;
818 if (!CheckRange(S, OpPC, Ptr, AK))
819 return false;
820 if (!CheckActive(S, OpPC, Ptr, AK))
821 return false;
822 if (!Ptr.isInitialized())
823 return DiagnoseUninitialized(S, OpPC, Ptr, AK);
824 if (!CheckLifetime(S, OpPC, Ptr, AK))
825 return false;
826 if (!CheckTemporary(S, OpPC, Ptr.block(), AK))
827 return false;
828
829 if (!CheckMutable(S, OpPC, Ptr))
830 return false;
831 if (!CheckVolatile(S, OpPC, Ptr, AK))
832 return false;
833 if (isConstexprUnknown(Ptr))
834 return false;
835
836 if (!Ptr.isArrayRoot()) {
837 // According to GCC info page:
838 //
839 // 6.28 Compound Literals
840 //
841 // As an optimization, G++ sometimes gives array compound literals
842 // longer lifetimes: when the array either appears outside a function or
843 // has a const-qualified type. If foo and its initializer had elements
844 // of type char *const rather than char *, or if foo were a global
845 // variable, the array would have static storage duration. But it is
846 // probably safest just to avoid the use of array compound literals in
847 // C++ code.
848 //
849 // Obey that rule by checking constness for converted array types.
850 const Descriptor *Desc = Ptr.getFieldDesc();
851 if (const auto *CLE =
852 dyn_cast_if_present<CompoundLiteralExpr>(Desc->asExpr())) {
853 if (QualType CLETy = CLE->getType();
854 CLETy->isArrayType() && !CLETy.isConstant(S.getASTContext())) {
855 S.FFDiag(S.Current->getLocation(OpPC),
856 diag::note_invalid_subexpr_in_const_expr)
857 << S.Current->getRange(OpPC);
858 S.Note(CLE->getExprLoc(), diag::note_declared_at);
859 return false;
860 }
861 }
862 }
863 return true;
864}
865
866/// This is not used by any of the opcodes directly. It's used by
867/// EvalEmitter to do the final lvalue-to-rvalue conversion.
868bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
869 assert(!Ptr.isZero());
870 if (!Ptr.isBlockPointer())
871 return false;
872
873 if (!Ptr.block()->isAccessible()) {
874 if (!CheckLive(S, OpPC, Ptr, AK_Read))
875 return false;
876 if (!CheckExtern(S, OpPC, Ptr))
877 return false;
878 if (!CheckDummy(S, OpPC, Ptr.block(), AK_Read))
879 return false;
880 return CheckWeak(S, OpPC, Ptr.block());
881 }
882
883 if (!CheckConstant(S, OpPC, Ptr))
884 return false;
885
886 if (!CheckActive(S, OpPC, Ptr, AK_Read))
887 return false;
888 if (!CheckLifetime(S, OpPC, Ptr, AK_Read))
889 return false;
890 if (!Ptr.isInitialized())
891 return DiagnoseUninitialized(S, OpPC, Ptr, AK_Read);
892 if (!CheckTemporary(S, OpPC, Ptr.block(), AK_Read))
893 return false;
894 if (!CheckMutable(S, OpPC, Ptr))
895 return false;
896 if (Ptr.isConstexprUnknown())
897 return false;
898 return true;
899}
900
901bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
902 bool WillBeActivated) {
903 if (!Ptr.isBlockPointer() || Ptr.isZero())
904 return false;
905
906 if (!Ptr.block()->isAccessible()) {
907 if (!CheckLive(S, OpPC, Ptr, AK_Assign))
908 return false;
909 if (!CheckExtern(S, OpPC, Ptr))
910 return false;
911 return CheckDummy(S, OpPC, Ptr.block(), AK_Assign);
912 }
913 if (!WillBeActivated && !CheckLifetime(S, OpPC, Ptr, AK_Assign))
914 return false;
915 if (!CheckRange(S, OpPC, Ptr, AK_Assign))
916 return false;
917 if (!CheckActive(S, OpPC, Ptr, AK_Assign, WillBeActivated))
918 return false;
919 if (!CheckGlobal(S, OpPC, Ptr))
920 return false;
921 if (!CheckConst(S, OpPC, Ptr))
922 return false;
923 if (!CheckVolatile(S, OpPC, Ptr, AK_Assign))
924 return false;
925 if (isConstexprUnknown(Ptr))
926 return false;
927 return true;
928}
929
930static bool CheckInvoke(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
931 bool IsCtorDtor = false) {
932 if (!Ptr.isDummy() && !isConstexprUnknown(Ptr)) {
933 if (!CheckLive(S, OpPC, Ptr, AK_MemberCall))
934 return false;
935 if (!CheckRange(S, OpPC, Ptr, AK_MemberCall))
936 return false;
937 if (!IsCtorDtor && !CheckLifetime(S, OpPC, Ptr, AK_MemberCall))
938 return false;
939 if (!CheckMutable(S, OpPC, Ptr))
940 return false;
941 }
942 return true;
943}
944
945bool CheckInit(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
946 if (!CheckLive(S, OpPC, Ptr, AK_Assign))
947 return false;
948 if (!CheckRange(S, OpPC, Ptr, AK_Assign))
949 return false;
950 return true;
951}
952
954 const FunctionDecl *DiagDecl) {
955 // Bail out if the function declaration itself is invalid. We will
956 // have produced a relevant diagnostic while parsing it, so just
957 // note the problematic sub-expression.
958 if (DiagDecl->isInvalidDecl())
959 return Invalid(S, OpPC);
960
961 // Diagnose failed assertions specially.
962 if (S.Current->getLocation(OpPC).isMacroID() && DiagDecl->getIdentifier()) {
963 // FIXME: Instead of checking for an implementation-defined function,
964 // check and evaluate the assert() macro.
965 StringRef Name = DiagDecl->getName();
966 bool AssertFailed =
967 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
968 if (AssertFailed) {
969 S.FFDiag(S.Current->getLocation(OpPC),
970 diag::note_constexpr_assert_failed);
971 return false;
972 }
973 }
974
975 if (!S.getLangOpts().CPlusPlus11) {
976 S.FFDiag(S.Current->getLocation(OpPC),
977 diag::note_invalid_subexpr_in_const_expr);
978 return false;
979 }
980
981 // Invalid decls have been diagnosed before.
982 if (DiagDecl->isInvalidDecl())
983 return false;
984
985 // If this function is not constexpr because it is an inherited
986 // non-constexpr constructor, diagnose that directly.
987 const auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
988 if (CD && CD->isInheritingConstructor()) {
989 const auto *Inherited = CD->getInheritedConstructor().getConstructor();
990 if (!Inherited->isConstexpr())
991 DiagDecl = CD = Inherited;
992 }
993
994 // Silently reject constructors of invalid classes. The invalid class
995 // has been rejected elsewhere before.
996 if (CD && CD->getParent()->isInvalidDecl())
997 return false;
998
999 // FIXME: If DiagDecl is an implicitly-declared special member function
1000 // or an inheriting constructor, we should be much more explicit about why
1001 // it's not constexpr.
1002 if (CD && CD->isInheritingConstructor()) {
1003 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_invalid_inhctor,
1004 1)
1005 << CD->getInheritedConstructor().getConstructor()->getParent();
1006 S.Note(DiagDecl->getLocation(), diag::note_declared_at);
1007 } else {
1008 // Don't emit anything if the function isn't defined and we're checking
1009 // for a constant expression. It might be defined at the point we're
1010 // actually calling it.
1011 bool IsExtern = DiagDecl->getStorageClass() == SC_Extern;
1012 bool IsDefined = DiagDecl->isDefined();
1013 if (!IsDefined && !IsExtern && DiagDecl->isConstexpr() &&
1015 return false;
1016
1017 // If the declaration is defined, declared 'constexpr' _and_ has a body,
1018 // the below diagnostic doesn't add anything useful.
1019 if (DiagDecl->isDefined() && DiagDecl->isConstexpr() && DiagDecl->hasBody())
1020 return false;
1021
1022 S.FFDiag(S.Current->getLocation(OpPC),
1023 diag::note_constexpr_invalid_function, 1)
1024 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
1025
1026 if (DiagDecl->getDefinition())
1027 S.Note(DiagDecl->getDefinition()->getLocation(), diag::note_declared_at);
1028 else
1029 S.Note(DiagDecl->getLocation(), diag::note_declared_at);
1030 }
1031
1032 return false;
1033}
1034
1035static bool CheckCallable(InterpState &S, CodePtr OpPC, const Function *F) {
1036 if (F->isVirtual() && !S.getLangOpts().CPlusPlus20) {
1037 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1038 S.CCEDiag(Loc, diag::note_constexpr_virtual_call);
1039 return false;
1040 }
1041
1042 if (F->isValid() && F->hasBody() &&
1044 F->getDecl()->hasAttr<MSConstexprAttr>())))
1045 return true;
1046
1047 const FunctionDecl *DiagDecl = F->getDecl();
1048 const FunctionDecl *Definition = nullptr;
1049 DiagDecl->getBody(Definition);
1050
1052 DiagDecl->isConstexpr()) {
1053 return false;
1054 }
1055
1056 // Implicitly constexpr.
1057 if (F->isLambdaStaticInvoker())
1058 return true;
1059
1060 return diagnoseCallableDecl(S, OpPC, DiagDecl);
1061}
1062
1063static bool CheckCallDepth(InterpState &S, CodePtr OpPC) {
1064 if ((S.Current->getDepth() + 1) > S.getLangOpts().ConstexprCallDepth) {
1065 S.FFDiag(S.Current->getSource(OpPC),
1066 diag::note_constexpr_depth_limit_exceeded)
1067 << S.getLangOpts().ConstexprCallDepth;
1068 return false;
1069 }
1070
1071 return true;
1072}
1073
1075 if (S.Current->hasThisPointer())
1076 return true;
1077
1078 const Expr *E = S.Current->getExpr(OpPC);
1079 if (S.getLangOpts().CPlusPlus11) {
1080 bool IsImplicit = false;
1081 if (const auto *TE = dyn_cast<CXXThisExpr>(E))
1082 IsImplicit = TE->isImplicit();
1083 S.FFDiag(E, diag::note_constexpr_this) << IsImplicit;
1084 } else {
1085 S.FFDiag(E);
1086 }
1087
1088 return false;
1089}
1090
1092 APFloat::opStatus Status, FPOptions FPO) {
1093 // [expr.pre]p4:
1094 // If during the evaluation of an expression, the result is not
1095 // mathematically defined [...], the behavior is undefined.
1096 // FIXME: C++ rules require us to not conform to IEEE 754 here.
1097 if (Result.isNan()) {
1098 const SourceInfo &E = S.Current->getSource(OpPC);
1099 S.CCEDiag(E, diag::note_constexpr_float_arithmetic)
1100 << /*NaN=*/true << S.Current->getRange(OpPC);
1101 return S.noteUndefinedBehavior();
1102 }
1103
1104 // In a constant context, assume that any dynamic rounding mode or FP
1105 // exception state matches the default floating-point environment.
1106 if (S.inConstantContext())
1107 return true;
1108
1109 if ((Status & APFloat::opInexact) &&
1110 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
1111 // Inexact result means that it depends on rounding mode. If the requested
1112 // mode is dynamic, the evaluation cannot be made in compile time.
1113 const SourceInfo &E = S.Current->getSource(OpPC);
1114 S.FFDiag(E, diag::note_constexpr_dynamic_rounding);
1115 return false;
1116 }
1117
1118 if ((Status != APFloat::opOK) &&
1119 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
1121 FPO.getAllowFEnvAccess())) {
1122 const SourceInfo &E = S.Current->getSource(OpPC);
1123 S.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
1124 return false;
1125 }
1126
1127 if ((Status & APFloat::opStatus::opInvalidOp) &&
1129 const SourceInfo &E = S.Current->getSource(OpPC);
1130 // There is no usefully definable result.
1131 S.FFDiag(E);
1132 return false;
1133 }
1134
1135 return true;
1136}
1137
1139 if (S.getLangOpts().CPlusPlus20)
1140 return true;
1141
1142 const SourceInfo &E = S.Current->getSource(OpPC);
1143 S.CCEDiag(E, diag::note_constexpr_new);
1144 return true;
1145}
1146
1148 DynamicAllocator::Form AllocForm,
1149 DynamicAllocator::Form DeleteForm, const Descriptor *D,
1150 const Expr *NewExpr) {
1151 if (AllocForm == DeleteForm)
1152 return true;
1153
1154 QualType TypeToDiagnose = D->getDataType(S.getASTContext());
1155
1156 const SourceInfo &E = S.Current->getSource(OpPC);
1157 S.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
1158 << static_cast<int>(DeleteForm) << static_cast<int>(AllocForm)
1159 << TypeToDiagnose;
1160 S.Note(NewExpr->getExprLoc(), diag::note_constexpr_dynamic_alloc_here)
1161 << NewExpr->getSourceRange();
1162 return false;
1163}
1164
1165bool CheckDeleteSource(InterpState &S, CodePtr OpPC, const Expr *Source,
1166 const Pointer &Ptr) {
1167 // Regular new type(...) call.
1168 if (isa_and_nonnull<CXXNewExpr>(Source))
1169 return true;
1170 // operator new.
1171 if (const auto *CE = dyn_cast_if_present<CallExpr>(Source);
1172 CE && CE->getBuiltinCallee() == Builtin::BI__builtin_operator_new)
1173 return true;
1174 // std::allocator.allocate() call
1175 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(Source);
1176 MCE && MCE->getMethodDecl()->getIdentifier()->isStr("allocate"))
1177 return true;
1178
1179 // Whatever this is, we didn't heap allocate it.
1180 const SourceInfo &Loc = S.Current->getSource(OpPC);
1181 S.FFDiag(Loc, diag::note_constexpr_delete_not_heap_alloc)
1183 noteValueLocation(S, Ptr.block());
1184 return false;
1185}
1186
1187/// We aleady know the given DeclRefExpr is invalid for some reason,
1188/// now figure out why and print appropriate diagnostics.
1189bool CheckDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR) {
1190 const ValueDecl *D = DR->getDecl();
1191 return diagnoseUnknownDecl(S, OpPC, D);
1192}
1193
1195 bool InitializerFailed) {
1196 assert(DR);
1197
1198 if (InitializerFailed) {
1199 const SourceInfo &Loc = S.Current->getSource(OpPC);
1200 const auto *VD = cast<VarDecl>(DR->getDecl());
1201 S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
1202 S.Note(VD->getLocation(), diag::note_declared_at);
1203 return false;
1204 }
1205
1206 return CheckDeclRef(S, OpPC, DR);
1207}
1208
1209bool CheckDummy(InterpState &S, CodePtr OpPC, const Block *B, AccessKinds AK) {
1210 if (!B->isDummy())
1211 return true;
1212
1213 const ValueDecl *D = B->getDescriptor()->asValueDecl();
1214 if (!D)
1215 return false;
1216
1217 if (AK == AK_Read || AK == AK_Increment || AK == AK_Decrement)
1218 return diagnoseUnknownDecl(S, OpPC, D);
1219
1220 if (AK == AK_Destroy || S.getLangOpts().CPlusPlus14) {
1221 const SourceInfo &E = S.Current->getSource(OpPC);
1222 S.FFDiag(E, diag::note_constexpr_modify_global);
1223 }
1224 return false;
1225}
1226
1227static bool CheckNonNullArgs(InterpState &S, CodePtr OpPC, const Function *F,
1228 const CallExpr *CE, unsigned ArgSize) {
1229 auto Args = ArrayRef(CE->getArgs(), CE->getNumArgs());
1230 auto NonNullArgs = collectNonNullArgs(F->getDecl(), Args);
1231 unsigned Offset = 0;
1232 unsigned Index = 0;
1233 for (const Expr *Arg : Args) {
1234 if (NonNullArgs[Index] && Arg->getType()->isPointerType()) {
1235 const Pointer &ArgPtr = S.Stk.peek<Pointer>(ArgSize - Offset);
1236 if (ArgPtr.isZero()) {
1237 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1238 S.CCEDiag(Loc, diag::note_non_null_attribute_failed);
1239 return false;
1240 }
1241 }
1242
1243 Offset += align(primSize(S.Ctx.classify(Arg).value_or(PT_Ptr)));
1244 ++Index;
1245 }
1246 return true;
1247}
1248
1250 const Pointer &BasePtr,
1251 const Descriptor *Desc) {
1252 assert(Desc->isRecord());
1253 const Record *R = Desc->ElemRecord;
1254 assert(R);
1255
1256 if (!S.Current->isBottomFrame() && S.Current->hasThisPointer() &&
1258 Pointer::pointToSameBlock(BasePtr, S.Current->getThis())) {
1259 const SourceInfo &Loc = S.Current->getSource(OpPC);
1260 S.FFDiag(Loc, diag::note_constexpr_double_destroy);
1261 return false;
1262 }
1263
1264 // Destructor of this record.
1265 const CXXDestructorDecl *Dtor = R->getDestructor();
1266 assert(Dtor);
1267 assert(!Dtor->isTrivial());
1268 const Function *DtorFunc = S.getContext().getOrCreateFunction(Dtor);
1269 if (!DtorFunc)
1270 return false;
1271
1272 S.Stk.push<Pointer>(BasePtr);
1273 return Call(S, OpPC, DtorFunc, 0);
1274}
1275
1276static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B) {
1277 assert(B);
1278 const Descriptor *Desc = B->getDescriptor();
1279
1280 if (Desc->isPrimitive() || Desc->isPrimitiveArray())
1281 return true;
1282
1283 assert(Desc->isRecord() || Desc->isCompositeArray());
1284
1285 if (Desc->hasTrivialDtor())
1286 return true;
1287
1288 if (Desc->isCompositeArray()) {
1289 unsigned N = Desc->getNumElems();
1290 if (N == 0)
1291 return true;
1292 const Descriptor *ElemDesc = Desc->ElemDesc;
1293 assert(ElemDesc->isRecord());
1294
1295 Pointer RP(const_cast<Block *>(B));
1296 for (int I = static_cast<int>(N) - 1; I >= 0; --I) {
1297 if (!runRecordDestructor(S, OpPC, RP.atIndex(I).narrow(), ElemDesc))
1298 return false;
1299 }
1300 return true;
1301 }
1302
1303 assert(Desc->isRecord());
1304 return runRecordDestructor(S, OpPC, Pointer(const_cast<Block *>(B)), Desc);
1305}
1306
1308 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1309 if (const CXXDestructorDecl *DD = RD->getDestructor())
1310 return DD->isVirtual();
1311 return false;
1312}
1313
1314bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm,
1315 bool IsGlobalDelete) {
1316 if (!CheckDynamicMemoryAllocation(S, OpPC))
1317 return false;
1318
1319 DynamicAllocator &Allocator = S.getAllocator();
1320
1321 const Expr *Source = nullptr;
1322 const Block *BlockToDelete = nullptr;
1323 {
1324 // Extra scope for this so the block doesn't have this pointer
1325 // pointing to it when we destroy it.
1326 Pointer Ptr = S.Stk.pop<Pointer>();
1327
1328 // Deleteing nullptr is always fine.
1329 if (Ptr.isZero())
1330 return true;
1331
1332 // Remove base casts.
1333 QualType InitialType = Ptr.getType();
1334 Ptr = Ptr.expand().stripBaseCasts();
1335
1336 Source = Ptr.getDeclDesc()->asExpr();
1337 BlockToDelete = Ptr.block();
1338
1339 // Check that new[]/delete[] or new/delete were used, not a mixture.
1340 const Descriptor *BlockDesc = BlockToDelete->getDescriptor();
1341 if (std::optional<DynamicAllocator::Form> AllocForm =
1342 Allocator.getAllocationForm(Source)) {
1343 DynamicAllocator::Form DeleteForm =
1344 DeleteIsArrayForm ? DynamicAllocator::Form::Array
1346 if (!CheckNewDeleteForms(S, OpPC, *AllocForm, DeleteForm, BlockDesc,
1347 Source))
1348 return false;
1349 }
1350
1351 // For the non-array case, the types must match if the static type
1352 // does not have a virtual destructor.
1353 if (!DeleteIsArrayForm && Ptr.getType() != InitialType &&
1354 !hasVirtualDestructor(InitialType)) {
1355 S.FFDiag(S.Current->getSource(OpPC),
1356 diag::note_constexpr_delete_base_nonvirt_dtor)
1357 << InitialType << Ptr.getType();
1358 return false;
1359 }
1360
1361 if (!Ptr.isRoot() || (Ptr.isOnePastEnd() && !Ptr.isZeroSizeArray()) ||
1362 (Ptr.isArrayElement() && Ptr.getIndex() != 0)) {
1363 const SourceInfo &Loc = S.Current->getSource(OpPC);
1364 S.FFDiag(Loc, diag::note_constexpr_delete_subobject)
1365 << Ptr.toDiagnosticString(S.getASTContext()) << Ptr.isOnePastEnd();
1366 return false;
1367 }
1368
1369 if (!CheckDeleteSource(S, OpPC, Source, Ptr))
1370 return false;
1371
1372 // For a class type with a virtual destructor, the selected operator delete
1373 // is the one looked up when building the destructor.
1374 if (!DeleteIsArrayForm && !IsGlobalDelete) {
1375 QualType AllocType = Ptr.getType();
1376 auto getVirtualOperatorDelete = [](QualType T) -> const FunctionDecl * {
1377 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1378 if (const CXXDestructorDecl *DD = RD->getDestructor())
1379 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
1380 return nullptr;
1381 };
1382
1383 if (const FunctionDecl *VirtualDelete =
1384 getVirtualOperatorDelete(AllocType);
1385 VirtualDelete &&
1386 !VirtualDelete
1388 S.FFDiag(S.Current->getSource(OpPC),
1389 diag::note_constexpr_new_non_replaceable)
1390 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
1391 return false;
1392 }
1393 }
1394 }
1395 assert(Source);
1396 assert(BlockToDelete);
1397
1398 // Invoke destructors before deallocating the memory.
1399 if (!RunDestructors(S, OpPC, BlockToDelete))
1400 return false;
1401
1402 if (!Allocator.deallocate(Source, BlockToDelete, S)) {
1403 // Nothing has been deallocated, this must be a double-delete.
1404 const SourceInfo &Loc = S.Current->getSource(OpPC);
1405 S.FFDiag(Loc, diag::note_constexpr_double_delete);
1406 return false;
1407 }
1408
1409 return true;
1410}
1411
1413 const APSInt &Value) {
1414 llvm::APInt Min;
1415 llvm::APInt Max;
1416 ED->getValueRange(Max, Min);
1417 --Max;
1418
1419 if (ED->getNumNegativeBits() &&
1420 (Max.slt(Value.getSExtValue()) || Min.sgt(Value.getSExtValue()))) {
1421 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1422 S.CCEDiag(Loc, diag::note_constexpr_unscoped_enum_out_of_range)
1423 << llvm::toString(Value, 10) << Min.getSExtValue() << Max.getSExtValue()
1424 << ED;
1425 } else if (!ED->getNumNegativeBits() && Max.ult(Value.getZExtValue())) {
1426 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1427 S.CCEDiag(Loc, diag::note_constexpr_unscoped_enum_out_of_range)
1428 << llvm::toString(Value, 10) << Min.getZExtValue() << Max.getZExtValue()
1429 << ED;
1430 }
1431}
1432
1433bool CheckLiteralType(InterpState &S, CodePtr OpPC, const Type *T) {
1434 assert(T);
1435 assert(!S.getLangOpts().CPlusPlus23);
1436
1437 // C++1y: A constant initializer for an object o [...] may also invoke
1438 // constexpr constructors for o and its subobjects even if those objects
1439 // are of non-literal class types.
1440 //
1441 // C++11 missed this detail for aggregates, so classes like this:
1442 // struct foo_t { union { int i; volatile int j; } u; };
1443 // are not (obviously) initializable like so:
1444 // __attribute__((__require_constant_initialization__))
1445 // static const foo_t x = {{0}};
1446 // because "i" is a subobject with non-literal initialization (due to the
1447 // volatile member of the union). See:
1448 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1449 // Therefore, we use the C++1y behavior.
1450
1451 if (!S.Current->isBottomFrame() &&
1454 return true;
1455 }
1456
1457 const Expr *E = S.Current->getExpr(OpPC);
1458 if (S.getLangOpts().CPlusPlus11)
1459 S.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
1460 else
1461 S.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1462 return false;
1463}
1464
1465static bool getField(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1466 uint32_t Off) {
1467 if (S.getLangOpts().CPlusPlus && S.inConstantContext() &&
1468 !CheckNull(S, OpPC, Ptr, CSK_Field))
1469 return false;
1470
1471 if (!CheckRange(S, OpPC, Ptr, CSK_Field))
1472 return false;
1473 if (!CheckArray(S, OpPC, Ptr))
1474 return false;
1475 if (!CheckSubobject(S, OpPC, Ptr, CSK_Field))
1476 return false;
1477
1478 if (Ptr.isIntegralPointer()) {
1479 if (std::optional<IntPointer> IntPtr =
1480 Ptr.asIntPointer().atOffset(S.getASTContext(), Off)) {
1481 S.Stk.push<Pointer>(std::move(*IntPtr));
1482 return true;
1483 }
1484 return false;
1485 }
1486
1487 if (!Ptr.isBlockPointer()) {
1488 // FIXME: The only time we (seem to) get here is when trying to access a
1489 // field of a typeid pointer. In that case, we're supposed to diagnose e.g.
1490 // `typeid(int).name`, but we currently diagnose `&typeid(int)`.
1491 S.FFDiag(S.Current->getSource(OpPC),
1492 diag::note_constexpr_access_unreadable_object)
1494 return false;
1495 }
1496
1497 // We can't get the field of something that's not a record.
1498 if (!Ptr.getFieldDesc()->isRecord())
1499 return false;
1500
1501 if ((Ptr.getByteOffset() + Off) >= Ptr.block()->getSize())
1502 return false;
1503
1504 S.Stk.push<Pointer>(Ptr.atField(Off));
1505 return true;
1506}
1507
1508bool GetPtrField(InterpState &S, CodePtr OpPC, uint32_t Off) {
1509 const auto &Ptr = S.Stk.peek<Pointer>();
1510 return getField(S, OpPC, Ptr, Off);
1511}
1512
1513bool GetPtrFieldPop(InterpState &S, CodePtr OpPC, uint32_t Off) {
1514 const auto &Ptr = S.Stk.pop<Pointer>();
1515 return getField(S, OpPC, Ptr, Off);
1516}
1517
1518static bool getBase(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1519 uint32_t Off, bool NullOK) {
1520 if (!NullOK && !CheckNull(S, OpPC, Ptr, CSK_Base))
1521 return false;
1522
1523 if (!Ptr.isBlockPointer()) {
1524 if (!Ptr.isIntegralPointer())
1525 return false;
1526 S.Stk.push<Pointer>(Ptr.asIntPointer().baseCast(S.getASTContext(), Off));
1527 return true;
1528 }
1529
1530 if (!CheckSubobject(S, OpPC, Ptr, CSK_Base))
1531 return false;
1532
1533 // In case this isn't something we can get the base of at all,
1534 // just return the pointer itself so it can be diagnosed later.
1535 if (!Ptr.getFieldDesc()->isRecord()) {
1536 S.Stk.push<Pointer>(Ptr);
1537 return true;
1538 }
1539
1540 const Pointer &Result = Ptr.atField(Off);
1541 if (Result.isPastEnd() || !Result.isBaseClass())
1542 return false;
1543 S.Stk.push<Pointer>(Result);
1544 return true;
1545}
1546
1547bool GetPtrBase(InterpState &S, CodePtr OpPC, uint32_t Off) {
1548 const auto &Ptr = S.Stk.peek<Pointer>();
1549 return getBase(S, OpPC, Ptr.narrow(), Off, /*NullOK=*/true);
1550}
1551bool GetPtrBasePop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK) {
1552 const auto &Ptr = S.Stk.pop<Pointer>();
1553 return getBase(S, OpPC, Ptr.narrow(), Off, NullOK);
1554}
1555
1556bool GetPtrDerivedPop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK,
1557 const Type *TargetType) {
1558 const Pointer &Ptr = S.Stk.pop<Pointer>().narrow();
1559 if (!NullOK && !CheckNull(S, OpPC, Ptr, CSK_Derived))
1560 return false;
1561
1562 if (!Ptr.isBlockPointer()) {
1563 // FIXME: We don't have the necessary information in integral pointers.
1564 // The Descriptor only has a record, but that does of course not include
1565 // the potential derived classes of said record.
1566 S.Stk.push<Pointer>(Ptr);
1567 return true;
1568 }
1569
1570 if (!CheckSubobject(S, OpPC, Ptr, CSK_Derived))
1571 return false;
1572 if (!CheckDowncast(S, OpPC, Ptr, Off))
1573 return false;
1574
1575 if (!Ptr.getFieldDesc()->isRecord()) {
1576 S.Stk.push<Pointer>(Ptr);
1577 return true;
1578 }
1579
1580 const Record *TargetRecord = Ptr.atFieldSub(Off).getRecord();
1581 assert(TargetRecord);
1582
1583 if (TargetRecord->getDecl()->getCanonicalDecl() !=
1584 TargetType->getAsCXXRecordDecl()->getCanonicalDecl()) {
1585 QualType MostDerivedType = Ptr.getDeclDesc()->getType();
1586 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_downcast)
1587 << MostDerivedType << QualType(TargetType, 0);
1588 return false;
1589 }
1590
1591 S.Stk.push<Pointer>(Ptr.atFieldSub(Off));
1592 return true;
1593}
1594
1595static bool checkConstructor(InterpState &S, CodePtr OpPC, const Function *Func,
1596 const Pointer &ThisPtr) {
1597 assert(Func->isConstructor());
1598
1599 if (Func->getParentDecl()->isInvalidDecl())
1600 return false;
1601
1602 const Descriptor *D = ThisPtr.getFieldDesc();
1603 // FIXME: I think this case is not 100% correct. E.g. a pointer into a
1604 // subobject of a composite array.
1605 if (!D->ElemRecord)
1606 return true;
1607
1608 if (D->ElemRecord->getNumVirtualBases() == 0)
1609 return true;
1610
1611 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_virtual_base)
1612 << Func->getParentDecl();
1613 return false;
1614}
1615
1617 const Pointer &Ptr) {
1618 assert(Ptr.getLifetime() != Lifetime::Started);
1619 // Try to use the declaration for better diagnostics
1620 if (const Decl *D = Ptr.getDeclDesc()->asDecl()) {
1621 auto *ND = cast<NamedDecl>(D);
1622 S.FFDiag(ND->getLocation(), diag::note_constexpr_destroy_out_of_lifetime)
1623 << ND->getNameAsString();
1624 } else {
1625 S.FFDiag(Ptr.getDeclDesc()->getLocation(),
1626 diag::note_constexpr_destroy_out_of_lifetime)
1628 }
1629 return false;
1630}
1631
1632bool CheckDestructor(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1633 if (!CheckLive(S, OpPC, Ptr, AK_Destroy))
1634 return false;
1635 if (!CheckTemporary(S, OpPC, Ptr.block(), AK_Destroy))
1636 return false;
1637 if (!CheckRange(S, OpPC, Ptr, AK_Destroy))
1638 return false;
1639
1640 if (Ptr.getLifetime() == Lifetime::Destroyed)
1641 return diagnoseOutOfLifetimeDestroy(S, OpPC, Ptr);
1642 if (Ptr.getLifetime() == Lifetime::Ended)
1643 return CheckLifetime(S, OpPC, Ptr, AK_Destroy);
1644
1645 // Can't call a dtor on a global variable.
1646 if (Ptr.block()->isStatic()) {
1647 const SourceInfo &E = S.Current->getSource(OpPC);
1648 S.FFDiag(E, diag::note_constexpr_modify_global);
1649 return false;
1650 }
1651 return CheckActive(S, OpPC, Ptr, AK_Destroy);
1652}
1653
1654/// Opcode. Check if the function decl can be called at compile time.
1657 return false;
1658
1659 const FunctionDecl *Definition = nullptr;
1660 const Stmt *Body = FD->getBody(Definition);
1661
1662 if (Definition && Body &&
1663 (Definition->isConstexpr() || (S.Current->MSVCConstexprAllowed &&
1664 Definition->hasAttr<MSConstexprAttr>())))
1665 return true;
1666
1667 return diagnoseCallableDecl(S, OpPC, FD);
1668}
1669
1670bool CheckBitCast(InterpState &S, CodePtr OpPC, const Type *TargetType,
1671 bool SrcIsVoidPtr) {
1672 const auto &Ptr = S.Stk.peek<Pointer>();
1673 if (Ptr.isZero())
1674 return true;
1675 if (!Ptr.isBlockPointer())
1676 return true;
1677
1678 if (TargetType->isIntegerType())
1679 return true;
1680
1681 if (SrcIsVoidPtr && S.getLangOpts().CPlusPlus) {
1682 bool HasValidResult = !Ptr.isZero();
1683
1684 if (HasValidResult) {
1685 if (S.getStdAllocatorCaller("allocate"))
1686 return true;
1687
1688 const auto *E = cast<CastExpr>(S.Current->getExpr(OpPC));
1689 if (S.getLangOpts().CPlusPlus26 &&
1690 S.getASTContext().hasSimilarType(Ptr.getType(),
1691 QualType(TargetType, 0)))
1692 return true;
1693
1694 S.CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
1695 << E->getSubExpr()->getType() << S.getLangOpts().CPlusPlus26
1696 << Ptr.getType().getCanonicalType() << E->getType()->getPointeeType();
1697 } else if (!S.getLangOpts().CPlusPlus26) {
1698 const SourceInfo &E = S.Current->getSource(OpPC);
1699 S.CCEDiag(E, diag::note_constexpr_invalid_cast)
1700 << diag::ConstexprInvalidCastKind::CastFrom << "'void *'"
1701 << S.Current->getRange(OpPC);
1702 }
1703 }
1704
1705 QualType PtrType = Ptr.getType();
1706 if (PtrType->isRecordType() &&
1707 PtrType->getAsRecordDecl() != TargetType->getAsRecordDecl()) {
1708 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_cast)
1709 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
1710 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
1711 return false;
1712 }
1713 return true;
1714}
1715
1716static void compileFunction(InterpState &S, const Function *Func) {
1717 const FunctionDecl *Definition = Func->getDecl()->getDefinition();
1718 if (!Definition)
1719 return;
1720
1722 .compileFunc(Definition, const_cast<Function *>(Func));
1723}
1724
1726 uint32_t VarArgSize) {
1727 if (Func->hasThisPointer()) {
1728 size_t ArgSize = Func->getArgSize() + VarArgSize;
1729 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(PT_Ptr) : 0);
1730 const Pointer &ThisPtr = S.Stk.peek<Pointer>(ThisOffset);
1731
1732 // If the current function is a lambda static invoker and
1733 // the function we're about to call is a lambda call operator,
1734 // skip the CheckInvoke, since the ThisPtr is a null pointer
1735 // anyway.
1736 if (!(S.Current->getFunction() &&
1738 Func->isLambdaCallOperator())) {
1739 if (!CheckInvoke(S, OpPC, ThisPtr))
1740 return false;
1741 }
1742
1744 return false;
1745 }
1746
1747 if (!Func->isFullyCompiled())
1749
1750 if (!CheckCallable(S, OpPC, Func))
1751 return false;
1752
1753 if (!CheckCallDepth(S, OpPC))
1754 return false;
1755
1756 auto Memory = new char[InterpFrame::allocSize(Func)];
1757 auto NewFrame = new (Memory) InterpFrame(S, Func, OpPC, VarArgSize);
1758 InterpFrame *FrameBefore = S.Current;
1759 S.Current = NewFrame;
1760
1761 // Note that we cannot assert(CallResult.hasValue()) here since
1762 // Ret() above only sets the APValue if the curent frame doesn't
1763 // have a caller set.
1764 if (Interpret(S)) {
1765 assert(S.Current == FrameBefore);
1766 return true;
1767 }
1768
1769 InterpFrame::free(NewFrame);
1770 // Interpreting the function failed somehow. Reset to
1771 // previous state.
1772 S.Current = FrameBefore;
1773 return false;
1774}
1775bool Call(InterpState &S, CodePtr OpPC, const Function *Func,
1776 uint32_t VarArgSize) {
1777
1778 // C doesn't have constexpr functions.
1779 if (!S.getLangOpts().CPlusPlus)
1780 return Invalid(S, OpPC);
1781
1782 assert(Func);
1783 auto cleanup = [&]() -> bool {
1785 return false;
1786 };
1787
1788 if (Func->hasThisPointer()) {
1789 size_t ArgSize = Func->getArgSize() + VarArgSize;
1790 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(PT_Ptr) : 0);
1791
1792 const Pointer &ThisPtr = S.Stk.peek<Pointer>(ThisOffset);
1793
1794 // C++23 [expr.const]p5.6
1795 // an invocation of a virtual function ([class.virtual]) for an object whose
1796 // dynamic type is constexpr-unknown;
1797 if (ThisPtr.isDummy() && Func->isVirtual())
1798 return false;
1799
1800 // If the current function is a lambda static invoker and
1801 // the function we're about to call is a lambda call operator,
1802 // skip the CheckInvoke, since the ThisPtr is a null pointer
1803 // anyway.
1804 if (S.Current->getFunction() &&
1806 Func->isLambdaCallOperator()) {
1807 assert(ThisPtr.isZero());
1808 } else {
1809 if (!CheckInvoke(S, OpPC, ThisPtr,
1810 Func->isConstructor() || Func->isDestructor()))
1811 return cleanup();
1812
1813 if (Func->isCopyOrMoveOperator() || Func->isCopyOrMoveConstructor()) {
1814 const Pointer &RVOPtr =
1815 S.Stk.peek<Pointer>(ThisOffset - align(sizeof(Pointer)));
1816 if (!CheckInvoke(S, OpPC, RVOPtr, /*IsCtorDtor=*/true))
1817 return cleanup();
1818 }
1819
1820 if (!Func->isConstructor() && !Func->isDestructor() &&
1821 !CheckActive(S, OpPC, ThisPtr, AK_MemberCall))
1822 return false;
1823 }
1824
1825 if (Func->isConstructor() && !checkConstructor(S, OpPC, Func, ThisPtr))
1826 return false;
1827 if (Func->isDestructor() && !CheckDestructor(S, OpPC, ThisPtr))
1828 return false;
1829
1830 if (Func->isConstructor() || Func->isDestructor())
1831 S.InitializingBlocks.push_back(ThisPtr.block());
1832 }
1833
1834 if (!Func->isFullyCompiled())
1836
1837 if (!CheckCallable(S, OpPC, Func))
1838 return cleanup();
1839
1840 // Do not evaluate any function calls in checkingPotentialConstantExpression
1841 // mode. Constructors will be aborted later when their initializers are
1842 // evaluated.
1843 if (S.checkingPotentialConstantExpression() && !Func->isConstructor())
1844 return false;
1845
1846 if (!CheckCallDepth(S, OpPC))
1847 return cleanup();
1848
1849 auto Memory = new char[InterpFrame::allocSize(Func)];
1850 auto NewFrame = new (Memory) InterpFrame(S, Func, OpPC, VarArgSize);
1851 InterpFrame *FrameBefore = S.Current;
1852 S.Current = NewFrame;
1853
1854 InterpStateCCOverride CCOverride(S, Func->isImmediate());
1855 // Note that we cannot assert(CallResult.hasValue()) here since
1856 // Ret() above only sets the APValue if the curent frame doesn't
1857 // have a caller set.
1858 bool Success = Interpret(S);
1859 // Remove initializing block again.
1860 if (Func->isConstructor() || Func->isDestructor())
1861 S.InitializingBlocks.pop_back();
1862
1863 if (!Success) {
1864 InterpFrame::free(NewFrame);
1865 // Interpreting the function failed somehow. Reset to
1866 // previous state.
1867 S.Current = FrameBefore;
1868 return false;
1869 }
1870
1871 assert(S.Current == FrameBefore);
1872 return true;
1873}
1874
1875static bool getDynamicDecl(InterpState &S, CodePtr OpPC, Pointer TypePtr,
1876 const CXXRecordDecl *&DynamicDecl) {
1877 TypePtr = TypePtr.stripBaseCasts();
1878
1879 QualType DynamicType = TypePtr.getType();
1880 if (TypePtr.isStatic() || TypePtr.isConst()) {
1881 if (const VarDecl *VD = TypePtr.getDeclDesc()->asVarDecl();
1882 VD && !VD->isConstexpr()) {
1883 const Expr *E = S.Current->getExpr(OpPC);
1884 APValue V = TypePtr.toAPValue(S.getASTContext());
1886 S.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
1887 << AccessKinds::AK_MemberCall << V.getAsString(S.getASTContext(), TT);
1888 return false;
1889 }
1890 }
1891
1892 if (DynamicType->isPointerType() || DynamicType->isReferenceType()) {
1893 DynamicDecl = DynamicType->getPointeeCXXRecordDecl();
1894 } else if (DynamicType->isArrayType()) {
1895 const Type *ElemType = DynamicType->getPointeeOrArrayElementType();
1896 assert(ElemType);
1897 DynamicDecl = ElemType->getAsCXXRecordDecl();
1898 } else {
1899 DynamicDecl = DynamicType->getAsCXXRecordDecl();
1900 }
1901 return DynamicDecl != nullptr;
1902}
1903
1905 uint32_t VarArgSize) {
1906 assert(Func->hasThisPointer());
1907 assert(Func->isVirtual());
1908 size_t ArgSize = Func->getArgSize() + VarArgSize;
1909 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(PT_Ptr) : 0);
1910 Pointer &ThisPtr = S.Stk.peek<Pointer>(ThisOffset);
1911 const FunctionDecl *Callee = Func->getDecl();
1912
1913 const CXXRecordDecl *DynamicDecl = nullptr;
1914 if (!getDynamicDecl(S, OpPC, ThisPtr, DynamicDecl))
1915 return false;
1916 assert(DynamicDecl);
1917
1918 const auto *StaticDecl = cast<CXXRecordDecl>(Func->getParentDecl());
1919 const auto *InitialFunction = cast<CXXMethodDecl>(Callee);
1920 const CXXMethodDecl *Overrider;
1921
1922 if (StaticDecl != DynamicDecl &&
1923 !llvm::is_contained(S.InitializingBlocks, ThisPtr.block())) {
1924 if (!DynamicDecl->isDerivedFrom(StaticDecl))
1925 return false;
1926 Overrider = S.getContext().getOverridingFunction(DynamicDecl, StaticDecl,
1927 InitialFunction);
1928
1929 } else {
1930 Overrider = InitialFunction;
1931 }
1932
1933 // C++2a [class.abstract]p6:
1934 // the effect of making a virtual call to a pure virtual function [...] is
1935 // undefined
1936 if (Overrider->isPureVirtual()) {
1937 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_pure_virtual_call,
1938 1)
1939 << Callee;
1940 S.Note(Callee->getLocation(), diag::note_declared_at);
1941 return false;
1942 }
1943
1944 if (Overrider != InitialFunction) {
1945 // DR1872: An instantiated virtual constexpr function can't be called in a
1946 // constant expression (prior to C++20). We can still constant-fold such a
1947 // call.
1948 if (!S.getLangOpts().CPlusPlus20 && Overrider->isVirtual()) {
1949 const Expr *E = S.Current->getExpr(OpPC);
1950 S.CCEDiag(E, diag::note_constexpr_virtual_call) << E->getSourceRange();
1951 }
1952
1953 Func = S.getContext().getOrCreateFunction(Overrider);
1954
1955 const CXXRecordDecl *ThisFieldDecl =
1956 ThisPtr.getFieldDesc()->getType()->getAsCXXRecordDecl();
1957 if (Func->getParentDecl()->isDerivedFrom(ThisFieldDecl)) {
1958 // If the function we call is further DOWN the hierarchy than the
1959 // FieldDesc of our pointer, just go up the hierarchy of this field
1960 // the furthest we can go.
1961 ThisPtr = ThisPtr.stripBaseCasts();
1962 }
1963 }
1964
1965 if (!Call(S, OpPC, Func, VarArgSize))
1966 return false;
1967
1968 // Covariant return types. The return type of Overrider is a pointer
1969 // or reference to a class type.
1970 if (Overrider != InitialFunction &&
1971 Overrider->getReturnType()->isPointerOrReferenceType() &&
1972 InitialFunction->getReturnType()->isPointerOrReferenceType()) {
1973 QualType OverriderPointeeType =
1974 Overrider->getReturnType()->getPointeeType();
1975 QualType InitialPointeeType =
1976 InitialFunction->getReturnType()->getPointeeType();
1977 // We've called Overrider above, but calling code expects us to return what
1978 // InitialFunction returned. According to the rules for covariant return
1979 // types, what InitialFunction returns needs to be a base class of what
1980 // Overrider returns. So, we need to do an upcast here.
1981 unsigned Offset = S.getContext().collectBaseOffset(
1982 InitialPointeeType->getAsRecordDecl(),
1983 OverriderPointeeType->getAsRecordDecl());
1984 return GetPtrBasePop(S, OpPC, Offset, /*IsNullOK=*/true);
1985 }
1986
1987 return true;
1988}
1989
1990bool CallBI(InterpState &S, CodePtr OpPC, const CallExpr *CE,
1991 uint32_t BuiltinID) {
1992 // A little arbitrary, but the current interpreter allows evaluation
1993 // of builtin functions in this mode, with some exceptions.
1994 if (BuiltinID == Builtin::BI__builtin_operator_new &&
1996 return false;
1997
1998 return InterpretBuiltin(S, OpPC, CE, BuiltinID);
1999}
2000
2001bool CallPtr(InterpState &S, CodePtr OpPC, uint32_t ArgSize,
2002 const CallExpr *CE) {
2003 const Pointer &Ptr = S.Stk.pop<Pointer>();
2004
2005 if (Ptr.isZero()) {
2006 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_null_callee)
2007 << const_cast<Expr *>(CE->getCallee()) << CE->getSourceRange();
2008 return false;
2009 }
2010
2011 if (!Ptr.isFunctionPointer())
2012 return Invalid(S, OpPC);
2013
2014 const Function *F = Ptr.asFunctionPointer().Func;
2015 assert(F);
2016 // Don't allow calling block pointers.
2017 if (!F->getDecl())
2018 return Invalid(S, OpPC);
2019
2020 // This happens when the call expression has been cast to
2021 // something else, but we don't support that.
2022 if (S.Ctx.classify(F->getDecl()->getReturnType()) !=
2024 return false;
2025
2026 // Check argument nullability state.
2027 if (F->hasNonNullAttr()) {
2028 if (!CheckNonNullArgs(S, OpPC, F, CE, ArgSize))
2029 return false;
2030 }
2031
2032 // Can happen when casting function pointers around.
2033 QualType CalleeType = CE->getCallee()->getType();
2034 if (CalleeType->isPointerType() &&
2036 F->getDecl()->getType(), CalleeType->getPointeeType())) {
2037 return false;
2038 }
2039
2040 // We nedd to compile (and check) early for function pointer calls
2041 // because the Call/CallVirt below might access the instance pointer
2042 // but the Function's information about them is wrong.
2043 if (!F->isFullyCompiled())
2044 compileFunction(S, F);
2045
2046 if (!CheckCallable(S, OpPC, F))
2047 return false;
2048
2049 assert(ArgSize >= F->getWrittenArgSize());
2050 uint32_t VarArgSize = ArgSize - F->getWrittenArgSize();
2051
2052 // We need to do this explicitly here since we don't have the necessary
2053 // information to do it automatically.
2054 if (F->isThisPointerExplicit())
2055 VarArgSize -= align(primSize(PT_Ptr));
2056
2057 if (F->isVirtual())
2058 return CallVirt(S, OpPC, F, VarArgSize);
2059
2060 return Call(S, OpPC, F, VarArgSize);
2061}
2062
2063static void startLifetimeRecurse(const Pointer &Ptr) {
2064 if (const Record *R = Ptr.getRecord()) {
2065 Ptr.startLifetime();
2066
2067 for (const Record::Field &Fi : R->fields()) {
2068 Pointer FP = Ptr.atField(Fi.Offset);
2069 if (FP.getLifetime() != Lifetime::Started)
2071 }
2072 return;
2073 }
2074
2075 if (const Descriptor *FieldDesc = Ptr.getFieldDesc();
2076 FieldDesc->isCompositeArray()) {
2077 for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I) {
2078 Pointer EP = Ptr.atIndex(I).narrow();
2079 if (EP.getLifetime() != Lifetime::Started)
2081 }
2082 return;
2083 }
2084
2085 Ptr.startLifetime();
2086}
2087
2090 return true;
2091
2092 const auto &Ptr = S.Current->getThis();
2093 if (!Ptr.isBlockPointer())
2094 return false;
2096 return true;
2097}
2098
2101 return true;
2102
2103 const auto &Ptr = S.Current->getThis();
2104 if (!Ptr.isBlockPointer())
2105 return false;
2106 Ptr.startLifetime();
2107 return true;
2108}
2109
2110// FIXME: It might be better to the recursing as part of the generated code for
2111// a destructor?
2112static void setLifeStateRecurse(const Pointer &Ptr, Lifetime L) {
2113 if (const Record *R = Ptr.getRecord()) {
2114 Ptr.setLifeState(L);
2115 for (const Record::Field &Fi : R->fields())
2116 setLifeStateRecurse(Ptr.atField(Fi.Offset), L);
2117 return;
2118 }
2119
2120 if (const Descriptor *FieldDesc = Ptr.getFieldDesc();
2121 FieldDesc->isCompositeArray()) {
2122 // No endLifetime() for primitive array roots.
2123 if (Ptr.getFieldDesc()->isPrimitiveArray())
2124 assert(Ptr.getLifetime() == Lifetime::Started);
2125 for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I)
2126 setLifeStateRecurse(Ptr.atIndex(I).narrow(), L);
2127 return;
2128 }
2129
2130 Ptr.setLifeState(L);
2131}
2132
2133/// Ends the lifetime of the peek'd pointer.
2135 const auto &Ptr = S.Stk.peek<Pointer>();
2136 if (Ptr.isBlockPointer() && !CheckDummy(S, OpPC, Ptr.block(), AK_Destroy))
2137 return false;
2138
2139 setLifeStateRecurse(Ptr.narrow(), Lifetime::Ended);
2140 return true;
2141}
2142
2143/// Ends the lifetime of the pop'd pointer.
2145 const auto &Ptr = S.Stk.pop<Pointer>();
2146 if (Ptr.isBlockPointer() && !CheckDummy(S, OpPC, Ptr.block(), AK_Destroy))
2147 return false;
2148
2149 setLifeStateRecurse(Ptr.narrow(), Lifetime::Ended);
2150 return true;
2151}
2152
2154 const auto &Ptr = S.Stk.peek<Pointer>();
2155 if (Ptr.isBlockPointer() && !CheckDummy(S, OpPC, Ptr.block(), AK_Destroy))
2156 return false;
2157
2159 return true;
2160}
2161
2163 std::optional<uint64_t> ArraySize) {
2164 const Pointer &Ptr = S.Stk.peek<Pointer>();
2165
2166 auto directBaseIsUnion = [](const Pointer &Ptr) -> bool {
2167 if (Ptr.isArrayElement())
2168 return false;
2169 const Record *R = Ptr.getBase().getRecord();
2170 return R && R->isUnion();
2171 };
2172
2173 if (Ptr.inUnion() && directBaseIsUnion(Ptr))
2174 Ptr.activate();
2175
2176 if (Ptr.isZero()) {
2177 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
2178 << AK_Construct;
2179 return false;
2180 }
2181
2182 if (!Ptr.isBlockPointer())
2183 return false;
2184
2185 if (!CheckRange(S, OpPC, Ptr, AK_Construct))
2186 return false;
2187
2189
2190 // Similar to CheckStore(), but with the additional CheckTemporary() call and
2191 // the AccessKinds are different.
2192 if (!Ptr.block()->isAccessible()) {
2193 if (!CheckExtern(S, OpPC, Ptr))
2194 return false;
2195 if (!CheckLive(S, OpPC, Ptr, AK_Construct))
2196 return false;
2197 return CheckDummy(S, OpPC, Ptr.block(), AK_Construct);
2198 }
2199 if (!CheckTemporary(S, OpPC, Ptr.block(), AK_Construct))
2200 return false;
2201
2202 // CheckLifetime for this and all base pointers.
2203 for (Pointer P = Ptr;;) {
2204 if (!CheckLifetime(S, OpPC, P, AK_Construct))
2205 return false;
2206
2207 if (P.isRoot())
2208 break;
2209 P = P.getBase();
2210 }
2211
2212 if (!CheckRange(S, OpPC, Ptr, AK_Construct))
2213 return false;
2214 if (!CheckGlobal(S, OpPC, Ptr))
2215 return false;
2216 if (!CheckConst(S, OpPC, Ptr))
2217 return false;
2218 if (!S.inConstantContext() && isConstexprUnknown(Ptr))
2219 return false;
2220
2221 if (!InvalidNewDeleteExpr(S, OpPC, E))
2222 return false;
2223
2224 const auto *NewExpr = cast<CXXNewExpr>(E);
2225 QualType StorageType = Ptr.getFieldDesc()->getDataType(S.getASTContext());
2226 const ASTContext &ASTCtx = S.getASTContext();
2227 QualType AllocType;
2228 if (ArraySize) {
2229 AllocType = ASTCtx.getConstantArrayType(
2230 NewExpr->getAllocatedType(),
2231 APInt(64, static_cast<uint64_t>(*ArraySize), false), nullptr,
2233 } else {
2234 AllocType = NewExpr->getAllocatedType();
2235 }
2236
2237 unsigned StorageSize = 1;
2238 unsigned AllocSize = 1;
2239 if (const auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
2240 AllocSize = CAT->getZExtSize();
2241 if (const auto *CAT = dyn_cast<ConstantArrayType>(StorageType))
2242 StorageSize = CAT->getZExtSize();
2243
2244 if (AllocSize > StorageSize ||
2245 !ASTCtx.hasSimilarType(ASTCtx.getBaseElementType(AllocType),
2246 ASTCtx.getBaseElementType(StorageType))) {
2247 S.FFDiag(S.Current->getLocation(OpPC),
2248 diag::note_constexpr_placement_new_wrong_type)
2249 << StorageType << AllocType;
2250 return false;
2251 }
2252
2253 // Can't activate fields in a union, unless the direct base is the union.
2254 if (Ptr.inUnion() && !Ptr.isActive() && !directBaseIsUnion(Ptr))
2255 return CheckActive(S, OpPC, Ptr, AK_Construct);
2256
2257 return true;
2258}
2259
2261 assert(E);
2262
2263 if (const auto *NewExpr = dyn_cast<CXXNewExpr>(E)) {
2264 const FunctionDecl *OperatorNew = NewExpr->getOperatorNew();
2265
2266 if (NewExpr->getNumPlacementArgs() > 0) {
2267 // This is allowed pre-C++26, but only an std function or if
2268 // [[msvc::constexpr]] was used.
2269 if (S.getLangOpts().CPlusPlus26 || S.Current->isStdFunction() ||
2271 return true;
2272
2273 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_new_placement)
2274 << /*C++26 feature*/ 1 << E->getSourceRange();
2275 } else if (
2276 !OperatorNew
2277 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
2278 S.FFDiag(S.Current->getSource(OpPC),
2279 diag::note_constexpr_new_non_replaceable)
2280 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
2281 return false;
2282 } else if (!S.getLangOpts().CPlusPlus26 &&
2283 NewExpr->getNumPlacementArgs() == 1 &&
2284 !OperatorNew->isReservedGlobalPlacementOperator()) {
2285 if (!S.getLangOpts().CPlusPlus26) {
2286 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_new_placement)
2287 << /*Unsupported*/ 0 << E->getSourceRange();
2288 return false;
2289 }
2290 return true;
2291 }
2292 } else {
2293 const auto *DeleteExpr = cast<CXXDeleteExpr>(E);
2294 const FunctionDecl *OperatorDelete = DeleteExpr->getOperatorDelete();
2295 if (!OperatorDelete
2296 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
2297 S.FFDiag(S.Current->getSource(OpPC),
2298 diag::note_constexpr_new_non_replaceable)
2299 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
2300 return false;
2301 }
2302 }
2303
2304 return false;
2305}
2306
2308 const FixedPoint &FP) {
2309 const Expr *E = S.Current->getExpr(OpPC);
2312 E->getExprLoc(), diag::warn_fixedpoint_constant_overflow)
2313 << FP.toDiagnosticString(S.getASTContext()) << E->getType();
2314 }
2315 S.CCEDiag(E, diag::note_constexpr_overflow)
2316 << FP.toDiagnosticString(S.getASTContext()) << E->getType();
2317 return S.noteUndefinedBehavior();
2318}
2319
2320bool InvalidShuffleVectorIndex(InterpState &S, CodePtr OpPC, uint32_t Index) {
2321 const SourceInfo &Loc = S.Current->getSource(OpPC);
2322 S.FFDiag(Loc,
2323 diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
2324 << Index;
2325 return false;
2326}
2327
2329 const Pointer &Ptr, unsigned BitWidth) {
2330 SourceInfo E = S.Current->getSource(OpPC);
2331 S.CCEDiag(E, diag::note_constexpr_invalid_cast)
2332 << 2 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
2333
2334 if (Ptr.isIntegralPointer())
2335 return true;
2336
2337 if (Ptr.isDummy()) {
2338 if (!CheckIntegralAddressCast(S, OpPC, BitWidth))
2339 return false;
2340 return Ptr.getIndex() == 0;
2341 }
2342
2343 if (!Ptr.isZero()) {
2344 // Only allow based lvalue casts if they are lossless.
2345 if (!CheckIntegralAddressCast(S, OpPC, BitWidth))
2346 return Invalid(S, OpPC);
2347 }
2348 return true;
2349}
2350
2351bool CheckIntegralAddressCast(InterpState &S, CodePtr OpPC, unsigned BitWidth) {
2353 BitWidth);
2354}
2355
2356bool CastPointerIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
2357 const Pointer &Ptr = S.Stk.pop<Pointer>();
2358
2359 if (!CheckPointerToIntegralCast(S, OpPC, Ptr, BitWidth))
2360 return false;
2361
2362 auto Result = S.allocAP<IntegralAP<false>>(BitWidth);
2363 Result.copy(APInt(BitWidth, Ptr.getIntegerRepresentation()));
2364
2366 return true;
2367}
2368
2369bool CastPointerIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
2370 const Pointer &Ptr = S.Stk.pop<Pointer>();
2371
2372 if (!CheckPointerToIntegralCast(S, OpPC, Ptr, BitWidth))
2373 return false;
2374
2375 auto Result = S.allocAP<IntegralAP<true>>(BitWidth);
2376 Result.copy(APInt(BitWidth, Ptr.getIntegerRepresentation()));
2377
2379 return true;
2380}
2381
2382bool CheckBitCast(InterpState &S, CodePtr OpPC, bool HasIndeterminateBits,
2383 bool TargetIsUCharOrByte) {
2384 // This is always fine.
2385 if (!HasIndeterminateBits)
2386 return true;
2387
2388 // Indeterminate bits can only be bitcast to unsigned char or std::byte.
2389 if (TargetIsUCharOrByte)
2390 return true;
2391
2392 const Expr *E = S.Current->getExpr(OpPC);
2393 QualType ExprType = E->getType();
2394 S.FFDiag(E, diag::note_constexpr_bit_cast_indet_dest)
2395 << ExprType << S.getLangOpts().CharIsSigned << E->getSourceRange();
2396 return false;
2397}
2398
2400 if (isConstexprUnknown(B)) {
2401 S.Stk.push<Pointer>(B);
2402 return true;
2403 }
2404
2405 const auto &ID = B->getBlockDesc<const InlineDescriptor>();
2406 if (!ID.IsInitialized) {
2408 S.FFDiag(S.Current->getSource(OpPC),
2409 diag::note_constexpr_use_uninit_reference);
2410 return false;
2411 }
2412
2413 assert(B->getDescriptor()->getPrimType() == PT_Ptr);
2414 S.Stk.push<Pointer>(B->deref<Pointer>());
2415 return true;
2416}
2417
2418bool GetTypeid(InterpState &S, CodePtr OpPC, const Type *TypePtr,
2419 const Type *TypeInfoType) {
2420 S.Stk.push<Pointer>(TypePtr, TypeInfoType);
2421 return true;
2422}
2423
2424bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType) {
2425 const auto &P = S.Stk.pop<Pointer>();
2426
2427 if (!P.isBlockPointer())
2428 return false;
2429
2430 // Pick the most-derived type.
2431 CanQualType T = P.getDeclPtr().getType()->getCanonicalTypeUnqualified();
2432 // ... unless we're currently constructing this object.
2433 // FIXME: We have a similar check to this in more places.
2434 if (S.Current->getFunction()) {
2435 for (const InterpFrame *Frame = S.Current; Frame; Frame = Frame->Caller) {
2436 if (const Function *Func = Frame->getFunction();
2437 Func && (Func->isConstructor() || Func->isDestructor()) &&
2438 P.block() == Frame->getThis().block()) {
2440 Func->getParentDecl());
2441 break;
2442 }
2443 }
2444 }
2445
2446 S.Stk.push<Pointer>(T->getTypePtr(), TypeInfoType);
2447 return true;
2448}
2449
2451 const auto *E = cast<CXXTypeidExpr>(S.Current->getExpr(OpPC));
2452 S.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
2453 << E->getExprOperand()->getType()
2454 << E->getExprOperand()->getSourceRange();
2455 return false;
2456}
2457
2459 const Pointer &RHS) {
2460 if (!LHS.pointsToStringLiteral() || !RHS.pointsToStringLiteral())
2461 return false;
2462
2463 unsigned LHSOffset = LHS.isOnePastEnd() ? LHS.getNumElems() : LHS.getIndex();
2464 unsigned RHSOffset = RHS.isOnePastEnd() ? RHS.getNumElems() : RHS.getIndex();
2465 const auto *LHSLit = cast<StringLiteral>(LHS.getDeclDesc()->asExpr());
2466 const auto *RHSLit = cast<StringLiteral>(RHS.getDeclDesc()->asExpr());
2467
2468 StringRef LHSStr(LHSLit->getBytes());
2469 unsigned LHSLength = LHSStr.size();
2470 StringRef RHSStr(RHSLit->getBytes());
2471 unsigned RHSLength = RHSStr.size();
2472
2473 int32_t IndexDiff = RHSOffset - LHSOffset;
2474 if (IndexDiff < 0) {
2475 if (static_cast<int32_t>(LHSLength) < -IndexDiff)
2476 return false;
2477 LHSStr = LHSStr.drop_front(-IndexDiff);
2478 } else {
2479 if (static_cast<int32_t>(RHSLength) < IndexDiff)
2480 return false;
2481 RHSStr = RHSStr.drop_front(IndexDiff);
2482 }
2483
2484 unsigned ShorterCharWidth;
2485 StringRef Shorter;
2486 StringRef Longer;
2487 if (LHSLength < RHSLength) {
2488 ShorterCharWidth = LHS.getFieldDesc()->getElemDataSize();
2489 Shorter = LHSStr;
2490 Longer = RHSStr;
2491 } else {
2492 ShorterCharWidth = RHS.getFieldDesc()->getElemDataSize();
2493 Shorter = RHSStr;
2494 Longer = LHSStr;
2495 }
2496
2497 // The null terminator isn't included in the string data, so check for it
2498 // manually. If the longer string doesn't have a null terminator where the
2499 // shorter string ends, they aren't potentially overlapping.
2500 for (unsigned NullByte : llvm::seq(ShorterCharWidth)) {
2501 if (Shorter.size() + NullByte >= Longer.size())
2502 break;
2503 if (Longer[Shorter.size() + NullByte])
2504 return false;
2505 }
2506 return Shorter == Longer.take_front(Shorter.size());
2507}
2508
2509static void copyPrimitiveMemory(InterpState &S, const Pointer &Ptr,
2510 PrimType T) {
2511 if (T == PT_IntAPS) {
2512 auto &Val = Ptr.deref<IntegralAP<true>>();
2513 if (!Val.singleWord()) {
2514 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
2515 Val.take(NewMemory);
2516 }
2517 } else if (T == PT_IntAP) {
2518 auto &Val = Ptr.deref<IntegralAP<false>>();
2519 if (!Val.singleWord()) {
2520 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
2521 Val.take(NewMemory);
2522 }
2523 } else if (T == PT_Float) {
2524 auto &Val = Ptr.deref<Floating>();
2525 if (!Val.singleWord()) {
2526 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
2527 Val.take(NewMemory);
2528 }
2529 } else if (T == PT_MemberPtr) {
2530 auto &Val = Ptr.deref<MemberPointer>();
2531 unsigned PathLength = Val.getPathLength();
2532 auto *NewPath = new (S.P) const CXXRecordDecl *[PathLength];
2533 std::copy_n(Val.path(), PathLength, NewPath);
2534 Val.takePath(NewPath);
2535 }
2536}
2537
2538template <typename T>
2539static void copyPrimitiveMemory(InterpState &S, const Pointer &Ptr) {
2540 assert(needsAlloc<T>());
2541 if constexpr (std::is_same_v<T, MemberPointer>) {
2542 auto &Val = Ptr.deref<MemberPointer>();
2543 unsigned PathLength = Val.getPathLength();
2544 auto *NewPath = new (S.P) const CXXRecordDecl *[PathLength];
2545 std::copy_n(Val.path(), PathLength, NewPath);
2546 Val.takePath(NewPath);
2547 } else {
2548 auto &Val = Ptr.deref<T>();
2549 if (!Val.singleWord()) {
2550 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
2551 Val.take(NewMemory);
2552 }
2553 }
2554}
2555
2556static void finishGlobalRecurse(InterpState &S, const Pointer &Ptr) {
2557 if (const Record *R = Ptr.getRecord()) {
2558 for (const Record::Field &Fi : R->fields()) {
2559 if (Fi.Desc->isPrimitive()) {
2560 TYPE_SWITCH_ALLOC(Fi.Desc->getPrimType(), {
2561 copyPrimitiveMemory<T>(S, Ptr.atField(Fi.Offset));
2562 });
2563 } else {
2564 finishGlobalRecurse(S, Ptr.atField(Fi.Offset));
2565 }
2566 }
2567 return;
2568 }
2569
2570 if (const Descriptor *D = Ptr.getFieldDesc(); D && D->isArray()) {
2571 unsigned NumElems = D->getNumElems();
2572 if (NumElems == 0)
2573 return;
2574
2575 if (D->isPrimitiveArray()) {
2576 PrimType PT = D->getPrimType();
2577 if (!needsAlloc(PT))
2578 return;
2579 assert(NumElems >= 1);
2580 const Pointer EP = Ptr.atIndex(0);
2581 bool AllSingleWord = true;
2582 TYPE_SWITCH_ALLOC(PT, {
2583 if (!EP.deref<T>().singleWord()) {
2585 AllSingleWord = false;
2586 }
2587 });
2588 if (AllSingleWord)
2589 return;
2590 for (unsigned I = 1; I != D->getNumElems(); ++I) {
2591 const Pointer EP = Ptr.atIndex(I);
2592 copyPrimitiveMemory(S, EP, PT);
2593 }
2594 } else {
2595 assert(D->isCompositeArray());
2596 for (unsigned I = 0; I != D->getNumElems(); ++I) {
2597 const Pointer EP = Ptr.atIndex(I).narrow();
2598 finishGlobalRecurse(S, EP);
2599 }
2600 }
2601 }
2602}
2603
2605 const Pointer &Ptr = S.Stk.pop<Pointer>();
2606
2607 finishGlobalRecurse(S, Ptr);
2608 if (Ptr.canBeInitialized()) {
2609 Ptr.initialize();
2610 Ptr.activate();
2611 }
2612
2613 return true;
2614}
2615
2616bool InvalidCast(InterpState &S, CodePtr OpPC, CastKind Kind, bool Fatal) {
2617 const SourceLocation &Loc = S.Current->getLocation(OpPC);
2618
2619 switch (Kind) {
2621 S.CCEDiag(Loc, diag::note_constexpr_invalid_cast)
2622 << diag::ConstexprInvalidCastKind::Reinterpret
2623 << S.Current->getRange(OpPC);
2624 return !Fatal;
2626 S.CCEDiag(Loc, diag::note_constexpr_invalid_cast)
2627 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
2628 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
2629 return !Fatal;
2630 case CastKind::Volatile:
2632 const auto *E = cast<CastExpr>(S.Current->getExpr(OpPC));
2633 if (S.getLangOpts().CPlusPlus)
2634 S.FFDiag(E, diag::note_constexpr_access_volatile_type)
2635 << AK_Read << E->getSubExpr()->getType();
2636 else
2637 S.FFDiag(E);
2638 }
2639
2640 return false;
2641 case CastKind::Dynamic:
2642 assert(!S.getLangOpts().CPlusPlus20);
2643 S.CCEDiag(Loc, diag::note_constexpr_invalid_cast)
2644 << diag::ConstexprInvalidCastKind::Dynamic;
2645 return true;
2646 }
2647 llvm_unreachable("Unhandled CastKind");
2648 return false;
2649}
2650
2651bool Destroy(InterpState &S, CodePtr OpPC, uint32_t I) {
2652 assert(S.Current->getFunction());
2653 // FIXME: We iterate the scope once here and then again in the destroy() call
2654 // below.
2655 for (auto &Local : S.Current->getFunction()->getScope(I).locals_reverse()) {
2656 if (!S.Current->getLocalBlock(Local.Offset)->isInitialized())
2657 continue;
2658 const Pointer &Ptr = S.Current->getLocalPointer(Local.Offset);
2659 if (Ptr.getLifetime() == Lifetime::Ended)
2660 return diagnoseOutOfLifetimeDestroy(S, OpPC, Ptr);
2661 }
2662
2663 S.Current->destroy(I);
2664 return true;
2665}
2666
2667// Perform a cast towards the class of the Decl (either up or down the
2668// hierarchy).
2670 const MemberPointer &MemberPtr,
2671 int32_t BaseOffset,
2672 const RecordDecl *BaseDecl) {
2673 const CXXRecordDecl *Expected;
2674 if (MemberPtr.getPathLength() >= 2)
2675 Expected = MemberPtr.getPathEntry(MemberPtr.getPathLength() - 2);
2676 else
2677 Expected = MemberPtr.getRecordDecl();
2678
2679 assert(Expected);
2680 if (Expected->getCanonicalDecl() != BaseDecl->getCanonicalDecl()) {
2681 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
2682 // if B does not contain the original member and is not a base or
2683 // derived class of the class containing the original member, the result
2684 // of the cast is undefined.
2685 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
2686 // (D::*). We consider that to be a language defect.
2687 return false;
2688 }
2689
2690 unsigned OldPathLength = MemberPtr.getPathLength();
2691 unsigned NewPathLength = OldPathLength - 1;
2692 bool IsDerivedMember = NewPathLength != 0;
2693 auto NewPath = S.allocMemberPointerPath(NewPathLength);
2694 std::copy_n(MemberPtr.path(), NewPathLength, NewPath);
2695
2696 S.Stk.push<MemberPointer>(MemberPtr.atInstanceBase(BaseOffset, NewPathLength,
2697 NewPath, IsDerivedMember));
2698 return true;
2699}
2700
2702 const MemberPointer &MemberPtr,
2703 int32_t BaseOffset,
2704 const RecordDecl *BaseDecl,
2705 bool IsDerivedMember) {
2706 unsigned OldPathLength = MemberPtr.getPathLength();
2707 unsigned NewPathLength = OldPathLength + 1;
2708
2709 auto NewPath = S.allocMemberPointerPath(NewPathLength);
2710 std::copy_n(MemberPtr.path(), OldPathLength, NewPath);
2711 NewPath[OldPathLength] = cast<CXXRecordDecl>(BaseDecl);
2712
2713 S.Stk.push<MemberPointer>(MemberPtr.atInstanceBase(BaseOffset, NewPathLength,
2714 NewPath, IsDerivedMember));
2715 return true;
2716}
2717
2718/// DerivedToBaseMemberPointer
2719bool CastMemberPtrBasePop(InterpState &S, CodePtr OpPC, int32_t Off,
2720 const RecordDecl *BaseDecl) {
2721 const auto &Ptr = S.Stk.pop<MemberPointer>();
2722
2723 if (!Ptr.isDerivedMember() && Ptr.hasPath())
2724 return castBackMemberPointer(S, Ptr, Off, BaseDecl);
2725
2726 bool IsDerivedMember = Ptr.isDerivedMember() || !Ptr.hasPath();
2727 return appendToMemberPointer(S, Ptr, Off, BaseDecl, IsDerivedMember);
2728}
2729
2730/// BaseToDerivedMemberPointer
2732 const RecordDecl *BaseDecl) {
2733 const auto &Ptr = S.Stk.pop<MemberPointer>();
2734
2735 if (!Ptr.isDerivedMember()) {
2736 // Simply append.
2737 return appendToMemberPointer(S, Ptr, Off, BaseDecl,
2738 /*IsDerivedMember=*/false);
2739 }
2740
2741 return castBackMemberPointer(S, Ptr, Off, BaseDecl);
2742}
2743
2744bool GetMemberPtr(InterpState &S, CodePtr OpPC, const ValueDecl *D) {
2745 S.Stk.push<MemberPointer>(D);
2746 return true;
2747}
2748
2750 const auto &MP = S.Stk.pop<MemberPointer>();
2751
2752 if (!MP.isBaseCastPossible())
2753 return false;
2754
2755 S.Stk.push<Pointer>(MP.getBase());
2756 return true;
2757}
2758
2760 const auto &MP = S.Stk.pop<MemberPointer>();
2761
2762 const ValueDecl *D = MP.getDecl();
2763 const auto *FD = dyn_cast_if_present<FunctionDecl>(D);
2764 if (!FD)
2765 return false;
2766
2767 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
2768 if (!Method)
2769 return false;
2770
2771 const Pointer &Base = MP.getBase();
2772 // The method must be accessible via the base of the MemberPointer.
2773 const CXXRecordDecl *MethodParent = Method->getParent();
2774 if (!Base.getRecord() || Base.getRecord()->getDecl() != MethodParent)
2775 return false;
2776
2777 const auto *Func = S.getContext().getOrCreateFunction(FD);
2778 if (!Func)
2779 return false;
2780 S.Stk.push<Pointer>(Func);
2781 return true;
2782}
2783
2784/// Just append the given Entry to the MemberPointer's path.
2785/// This is used to re-inject APValues into the bytecode interpreter.
2787 bool IsDerived) {
2788 const auto &MemberPtr = S.Stk.pop<MemberPointer>();
2789
2790 unsigned OldPathLength = MemberPtr.getPathLength();
2791 unsigned NewPathLength = OldPathLength + 1;
2792
2793 auto NewPath = S.allocMemberPointerPath(NewPathLength);
2794 std::copy_n(MemberPtr.path(), OldPathLength, NewPath);
2795 NewPath[OldPathLength] = cast<CXXRecordDecl>(Entry);
2796
2798 MemberPtr.withPath(NewPathLength, NewPath, IsDerived));
2799 return true;
2800}
2801
2802// FIXME: Would be nice to generate this instead of hardcoding it here.
2803constexpr bool OpReturns(Opcode Op) {
2804 return Op == OP_RetVoid || Op == OP_RetValue || Op == OP_NoRet ||
2805 Op == OP_RetSint8 || Op == OP_RetUint8 || Op == OP_RetSint16 ||
2806 Op == OP_RetUint16 || Op == OP_RetSint32 || Op == OP_RetUint32 ||
2807 Op == OP_RetSint64 || Op == OP_RetUint64 || Op == OP_RetIntAP ||
2808 Op == OP_RetIntAPS || Op == OP_RetBool || Op == OP_RetFixedPoint ||
2809 Op == OP_RetPtr || Op == OP_RetMemberPtr || Op == OP_RetFloat ||
2810 Op == OP_EndSpeculation;
2811}
2812
2813#if USE_TAILCALLS
2814PRESERVE_NONE static bool InterpNext(InterpState &S, CodePtr &PC);
2815#endif
2816
2817// The dispatcher functions read the opcode arguments from the
2818// bytecode and call the implementation function.
2819#define GET_INTERPFN_DISPATCHERS
2820#include "Opcodes.inc"
2821#undef GET_INTERPFN_DISPATCHERS
2822
2824// Array of the dispatcher functions defined above.
2826#define GET_INTERPFN_LIST
2827#include "Opcodes.inc"
2828#undef GET_INTERPFN_LIST
2829};
2830
2831#if USE_TAILCALLS
2832// Read the next opcode and call the dispatcher function.
2833PRESERVE_NONE static bool InterpNext(InterpState &S, CodePtr &PC) {
2834 auto Op = PC.read<Opcode>();
2835 auto Fn = InterpFunctions[Op];
2836 MUSTTAIL return Fn(S, PC);
2837}
2838#endif
2839
2841 // The current stack frame when we started Interpret().
2842 // This is being used by the ops to determine wheter
2843 // to return from this function and thus terminate
2844 // interpretation.
2845 assert(!S.Current->isRoot());
2846 CodePtr PC = S.Current->getPC();
2847
2848#if USE_TAILCALLS
2849 return InterpNext(S, PC);
2850#else
2851 while (true) {
2852 auto Op = PC.read<Opcode>();
2853 auto Fn = InterpFunctions[Op];
2854
2855 if (!Fn(S, PC))
2856 return false;
2857 if (OpReturns(Op))
2858 break;
2859 }
2860 return true;
2861#endif
2862}
2863
2864/// This is used to implement speculative execution via __builtin_constant_p
2865/// when we generate bytecode.
2866///
2867/// The setup here is that we use the same tailcall mechanism for speculative
2868/// evaluation that we use for the regular one.
2869/// Since each speculative execution ends with an EndSpeculation opcode,
2870/// that one does NOT call InterpNext() but simply returns true.
2871/// This way, we return back to this function when we see an EndSpeculation,
2872/// OR (of course), when we encounter an error and one of the opcodes
2873/// returns false.
2874PRESERVE_NONE static bool BCP(InterpState &S, CodePtr &RealPC, int32_t Offset,
2875 PrimType PT) {
2876 [[maybe_unused]] CodePtr PCBefore = RealPC;
2877 size_t StackSizeBefore = S.Stk.size();
2878
2879 // Speculation depth must be at least 1 here, since we must have
2880 // passed a StartSpeculation op before.
2881#ifndef NDEBUG
2882 [[maybe_unused]] unsigned DepthBefore = S.SpeculationDepth;
2883 assert(DepthBefore >= 1);
2884#endif
2885
2886 CodePtr PC = RealPC;
2887 auto SpeculativeInterp = [&S, &PC]() -> bool {
2888 // Ignore diagnostics during speculative execution.
2889 PushIgnoreDiags(S, PC);
2890 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S, PC); });
2891
2892#if USE_TAILCALLS
2893 auto Op = PC.read<Opcode>();
2894 auto Fn = InterpFunctions[Op];
2895 return Fn(S, PC);
2896#else
2897 while (true) {
2898 auto Op = PC.read<Opcode>();
2899 auto Fn = InterpFunctions[Op];
2900
2901 if (!Fn(S, PC))
2902 return false;
2903 if (OpReturns(Op))
2904 break;
2905 }
2906 return true;
2907#endif
2908 };
2909
2910 if (SpeculativeInterp()) {
2911 // Speculation must've ended naturally via a EndSpeculation opcode.
2912 assert(S.SpeculationDepth == DepthBefore - 1);
2913 if (PT == PT_Ptr) {
2914 const auto &Ptr = S.Stk.pop<Pointer>();
2915 assert(S.Stk.size() == StackSizeBefore);
2918 } else {
2919 // Pop the result from the stack and return success.
2920 TYPE_SWITCH(PT, S.Stk.discard<T>(););
2921 assert(S.Stk.size() == StackSizeBefore);
2923 }
2924 } else {
2925 // End the speculation manually since we didn't call EndSpeculation
2926 // naturally.
2927 EndSpeculation(S, RealPC);
2928
2929 if (!S.inConstantContext())
2930 return Invalid(S, RealPC);
2931
2932 S.Stk.clearTo(StackSizeBefore);
2934 }
2935
2936 // RealPC should not have been modified.
2937 assert(*RealPC == *PCBefore);
2938
2939 // We have already evaluated this speculation's EndSpeculation opcode.
2940 assert(S.SpeculationDepth == DepthBefore - 1);
2941
2942 // Jump to end label. This is a little tricker than just RealPC += Offset
2943 // because our usual jump instructions don't have any arguments, to the offset
2944 // we get is a little too much and we need to subtract the size of the
2945 // bool and PrimType arguments again.
2946 int32_t ParamSize = align(sizeof(PrimType));
2947 assert(Offset >= ParamSize);
2948 RealPC += Offset - ParamSize;
2949
2950 return true;
2951}
2952
2953} // namespace interp
2954} // namespace clang
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the clang::Expr interface and subclasses for C++ expressions.
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
static bool Jmp(InterpState &S, CodePtr &PC, int32_t Offset)
Definition Interp.cpp:60
static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Block *B, AccessKinds AK)
Definition Interp.cpp:181
static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:206
static PRESERVE_NONE bool RetValue(InterpState &S, CodePtr &Ptr)
Definition Interp.cpp:52
static bool Jt(InterpState &S, CodePtr &PC, int32_t Offset)
Definition Interp.cpp:65
static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC, const ValueDecl *VD)
Definition Interp.cpp:144
#define MUSTTAIL
Definition Interp.cpp:46
static void noteValueLocation(InterpState &S, const Block *B)
Definition Interp.cpp:86
static bool diagnoseUnknownDecl(InterpState &S, CodePtr OpPC, const ValueDecl *D)
Definition Interp.cpp:99
static bool Jf(InterpState &S, CodePtr &PC, int32_t Offset)
Definition Interp.cpp:72
static void diagnoseMissingInitializer(InterpState &S, CodePtr OpPC, const ValueDecl *VD)
Definition Interp.cpp:79
#define PRESERVE_NONE
Definition Interp.h:49
static StringRef getIdentifier(const Token &Tok)
#define TYPE_SWITCH_ALLOC(Expr, B)
Definition PrimType.h:297
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:223
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:227
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:924
CanQualType getCanonicalTagType(const TagDecl *TD) const
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
bool isVirtual() const
Definition DeclCXX.h:2187
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3140
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1603
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
ValueDecl * getDecl()
Definition Expr.h:1341
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
bool hasAttr() const
Definition DeclBase.h:585
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Represents an enum.
Definition Decl.h:4029
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition Decl.h:4239
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition Decl.cpp:5184
This represents one expression.
Definition Expr.h:112
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
LangOptions::FPExceptionModeKind getExceptionMode() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3178
Represents a function declaration or definition.
Definition Decl.h:2018
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3274
QualType getReturnType() const
Definition Decl.h:2863
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:2906
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2488
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2371
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3421
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2300
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3194
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3241
@ FPE_Ignore
Assume that floating-point exceptions are masked.
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8520
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8509
Represents a struct/union/class.
Definition Decl.h:4343
Encodes a location in the source.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:4894
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:490
The base class of the type hierarchy.
Definition TypeBase.h:1871
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8772
bool isPointerType() const
Definition TypeBase.h:8673
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9083
bool isReferenceType() const
Definition TypeBase.h:8697
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9161
bool isAnyComplexType() const
Definition TypeBase.h:8808
bool isPointerOrReferenceType() const
Definition TypeBase.h:8677
bool isRecordType() const
Definition TypeBase.h:8800
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1582
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
unsigned getSize() const
Returns the size of the block.
Definition InterpBlock.h:87
const T & deref() const
bool isExtern() const
Checks if the block is extern.
Definition InterpBlock.h:77
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition InterpBlock.h:73
bool isStatic() const
Checks if the block has static storage duration.
Definition InterpBlock.h:79
bool isTemporary() const
Checks if the block is temporary.
Definition InterpBlock.h:81
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition InterpBlock.h:92
bool isDynamic() const
Definition InterpBlock.h:83
UnsignedOrNone getDeclID() const
Returns the declaration ID.
Definition InterpBlock.h:89
bool isDummy() const
Definition InterpBlock.h:84
unsigned getEvalID() const
The Evaluation ID this block was created in.
Definition InterpBlock.h:94
bool isWeak() const
Definition InterpBlock.h:82
bool isAccessible() const
Pointer into the code segment.
Definition Source.h:30
std::enable_if_t<!std::is_pointer< T >::value, T > read()
Reads data and advances the pointer.
Definition Source.h:57
Compilation context for expressions.
Definition Compiler.h:112
unsigned collectBaseOffset(const RecordDecl *BaseDecl, const RecordDecl *DerivedDecl) const
Definition Context.cpp:688
const Function * getOrCreateFunction(const FunctionDecl *FuncDecl)
Definition Context.cpp:556
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:98
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:408
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition Context.cpp:520
Manages dynamic memory allocations done during bytecode interpretation.
bool deallocate(const Expr *Source, const Block *BlockToDelete, InterpState &S)
Deallocate the given source+block combination.
std::optional< Form > getAllocationForm(const Expr *Source) const
Checks whether the allocation done at the given source is an array allocation.
Wrapper around fixed point types.
Definition FixedPoint.h:23
std::string toDiagnosticString(const ASTContext &Ctx) const
Definition FixedPoint.h:81
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
Base class for stack frames, shared between VM and walker.
Definition Frame.h:25
Bytecode function.
Definition Function.h:99
Scope & getScope(unsigned Idx)
Returns a specific scope.
Definition Function.h:174
bool isDestructor() const
Checks if the function is a destructor.
Definition Function.h:197
bool isVirtual() const
Checks if the function is virtual.
Definition Function.h:184
bool hasNonNullAttr() const
Definition Function.h:158
bool isFullyCompiled() const
Checks if the function is fully done compiling.
Definition Function.h:224
bool isConstructor() const
Checks if the function is a constructor.
Definition Function.h:189
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition Function.h:134
bool hasBody() const
Checks if the function already has a body attached.
Definition Function.h:229
bool isConstexpr() const
Definition Function.h:186
bool isThisPointerExplicit() const
Definition Function.h:250
unsigned getWrittenArgSize() const
Definition Function.h:246
bool isLambdaStaticInvoker() const
Returns whether this function is a lambda static invoker, which we generate custom byte code for.
Definition Function.h:205
bool isValid() const
Checks if the function is valid to call.
Definition Function.h:181
If an IntegralAP is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition IntegralAP.h:36
Wrapper around numeric types.
Definition Integral.h:69
static std::enable_if_t<!std::is_same_v< ValT, IntegralKind >, Integral > from(ValT V, unsigned NumBits=0)
Definition Integral.h:320
Frame storing local variables.
Definition InterpFrame.h:27
static void free(InterpFrame *F)
Definition InterpFrame.h:62
const Expr * getExpr(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Definition InterpFrame.h:30
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
CodePtr getRetPC() const
Returns the return address of the frame.
Block * getLocalBlock(unsigned Offset) const
CodePtr getPC() const
Returns the PC of the frame's code start.
SourceLocation getLocation(CodePtr PC) const
const Pointer & getThis() const
Returns the 'this' pointer.
const Function * getFunction() const
Returns the current function.
Definition InterpFrame.h:93
SourceRange getRange(CodePtr PC) const
bool isRoot() const
Checks if the frame is a root frame - return should quit the interpreter.
Pointer getLocalPointer(unsigned Offset) const
Returns a pointer to a local variables.
unsigned getDepth() const
void destroy(unsigned Idx)
Invokes the destructors for a scope.
static size_t allocSize(const Function *F)
Returns the number of bytes needed to allocate an InterpFrame for the given function.
Definition InterpFrame.h:51
void clearTo(size_t NewSize)
T pop()
Returns the value from the top of the stack and removes it.
Definition InterpStack.h:39
void push(Tys &&...Args)
Constructs a value in place on the top of the stack.
Definition InterpStack.h:33
size_t size() const
Returns the size of the stack in bytes.
Definition InterpStack.h:77
void discard()
Discards the top value from the stack.
Definition InterpStack.h:50
T & peek() const
Returns a reference to the value on the top of the stack.
Definition InterpStack.h:62
Interpreter context.
Definition InterpState.h:36
Context & getContext() const
Definition InterpState.h:74
DynamicAllocator & getAllocator()
Definition InterpState.h:78
Context & Ctx
Interpreter Context.
bool noteStep(CodePtr OpPC)
Note that a step has been executed.
const unsigned EvalID
ID identifying this evaluation.
llvm::SmallVector< const Block * > InitializingBlocks
List of blocks we're currently running either constructors or destructors for.
InterpStack & Stk
Temporary stack.
const VarDecl * EvaluatingDecl
Declaration we're initializing/evaluting, if any.
InterpFrame * Current
The current frame.
const CXXRecordDecl ** allocMemberPointerPath(unsigned Length)
T allocAP(unsigned BitWidth)
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
Program & P
Reference to the module containing all bytecode.
unsigned getPathLength() const
Return the length of the cast path.
PrimType value_or(PrimType PT) const
Definition PrimType.h:88
A pointer to a memory block, live or dead.
Definition Pointer.h:97
Pointer narrow() const
Restricts the scope of an array element pointer.
Definition Pointer.h:194
UnsignedOrNone getDeclID() const
Returns the declaration ID.
Definition Pointer.h:591
Pointer stripBaseCasts() const
Strip base casts from this Pointer.
Definition Pointer.h:797
bool isVolatile() const
Checks if an object or a subfield is volatile.
Definition Pointer.h:584
bool isInitialized() const
Checks if an object was initialized.
Definition Pointer.cpp:443
bool isStatic() const
Checks if the storage is static.
Definition Pointer.h:505
bool isDynamic() const
Checks if the storage has been dynamically allocated.
Definition Pointer.h:520
bool inUnion() const
Definition Pointer.h:413
bool isZeroSizeArray() const
Checks if the pointer is pointing to a zero-size array.
Definition Pointer.h:669
Pointer atIndex(uint64_t Idx) const
Offsets a pointer inside an array.
Definition Pointer.h:162
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition Pointer.h:562
Pointer atFieldSub(unsigned Off) const
Subtract the given offset from the current Base and Offset of the pointer.
Definition Pointer.h:187
bool isExtern() const
Checks if the storage is extern.
Definition Pointer.h:499
int64_t getIndex() const
Returns the index into an array.
Definition Pointer.h:627
bool isActive() const
Checks if the object is active.
Definition Pointer.h:551
void startLifetime() const
Start the lifetime of this pointer.
Definition Pointer.cpp:507
bool isConst() const
Checks if an object or a subfield is mutable.
Definition Pointer.h:572
Pointer atField(unsigned Off) const
Creates a pointer to a field.
Definition Pointer.h:179
T & deref() const
Dereferences the pointer, if it's live.
Definition Pointer.h:687
bool isMutable() const
Checks if the field is mutable.
Definition Pointer.h:531
bool isConstInMutable() const
Definition Pointer.h:577
unsigned getNumElems() const
Returns the number of elements.
Definition Pointer.h:611
bool isUnknownSizeArray() const
Checks if the structure is an array of unknown size.
Definition Pointer.h:426
void activate() const
Activats a field.
Definition Pointer.cpp:624
bool isIntegralPointer() const
Definition Pointer.h:480
QualType getType() const
Returns the type of the innermost field.
Definition Pointer.h:346
bool isArrayElement() const
Checks if the pointer points to an array.
Definition Pointer.h:432
bool pointsToStringLiteral() const
Definition Pointer.cpp:728
bool isArrayRoot() const
Whether this array refers to an array, but not to the first element.
Definition Pointer.h:405
bool isLive() const
Checks if the pointer is live.
Definition Pointer.h:278
Pointer getBase() const
Returns a pointer to the object of which this pointer is a field.
Definition Pointer.h:317
uint64_t getByteOffset() const
Returns the byte offset from the start.
Definition Pointer.h:600
void setLifeState(Lifetime L) const
Definition Pointer.cpp:511
bool isTypeidPointer() const
Definition Pointer.h:482
std::string toDiagnosticString(const ASTContext &Ctx) const
Converts the pointer to a string usable in diagnostics.
Definition Pointer.cpp:433
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:264
bool isConstexprUnknown() const
Definition Pointer.h:719
const IntPointer & asIntPointer() const
Definition Pointer.h:466
bool isRoot() const
Pointer points directly to a block.
Definition Pointer.h:448
const Descriptor * getDeclDesc() const
Accessor for information about the declaration site.
Definition Pointer.h:292
static bool pointToSameBlock(const Pointer &A, const Pointer &B)
Checks if both given pointers point to the same block.
Definition Pointer.cpp:706
APValue toAPValue(const ASTContext &ASTCtx) const
Converts the pointer to an APValue.
Definition Pointer.cpp:173
bool isOnePastEnd() const
Checks if the index is one past end.
Definition Pointer.h:644
uint64_t getIntegerRepresentation() const
Definition Pointer.h:149
bool isPastEnd() const
Checks if the pointer points past the end of the object.
Definition Pointer.h:658
const FieldDecl * getField() const
Returns the field information.
Definition Pointer.h:492
Pointer expand() const
Expands a pointer to the containing array, undoing narrowing.
Definition Pointer.h:229
bool isElementPastEnd() const
Checks if the pointer is an out-of-bounds element pointer.
Definition Pointer.h:666
bool isBlockPointer() const
Definition Pointer.h:479
const FunctionPointer & asFunctionPointer() const
Definition Pointer.h:470
const Block * block() const
Definition Pointer.h:617
bool isFunctionPointer() const
Definition Pointer.h:481
Pointer getDeclPtr() const
Definition Pointer.h:366
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition Pointer.h:336
bool canBeInitialized() const
If this pointer has an InlineDescriptor we can use to initialize.
Definition Pointer.h:455
Lifetime getLifetime() const
Definition Pointer.h:761
void initialize() const
Initializes a field.
Definition Pointer.cpp:535
bool isField() const
Checks if the item is a field in an object.
Definition Pointer.h:284
const Record * getRecord() const
Returns the record descriptor of a class.
Definition Pointer.h:485
UnsignedOrNone getCurrentDecl() const
Returns the current declaration ID.
Definition Program.h:161
Structure/Class descriptor.
Definition Record.h:25
const RecordDecl * getDecl() const
Returns the underlying declaration.
Definition Record.h:65
unsigned getNumVirtualBases() const
Definition Record.h:121
llvm::iterator_range< LocalVectorTy::const_reverse_iterator > locals_reverse() const
Definition Function.h:57
Describes the statement/declaration an opcode was generated from.
Definition Source.h:74
bool checkingForUndefinedBehavior() const
Are we checking an expression for overflow?
Definition State.h:124
OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId)
Add a note to a prior diagnostic.
Definition State.cpp:63
OptionalDiagnostic FFDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation could not be folded (FF => FoldFailure)
Definition State.cpp:21
ASTContext & getASTContext() const
Definition State.h:93
bool noteUndefinedBehavior() const
Note that we hit something that was technically undefined behavior, but that we can evaluate past it ...
Definition State.h:113
OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation does not produce a C++11 core constant expression.
Definition State.cpp:42
const LangOptions & getLangOpts() const
Definition State.h:94
bool checkingPotentialConstantExpression() const
Are we checking whether the expression is a potential constant expression?
Definition State.h:120
Defines the clang::TargetInfo interface.
bool arePotentiallyOverlappingStringLiterals(const Pointer &LHS, const Pointer &RHS)
Definition Interp.cpp:2458
bool GetPtrFieldPop(InterpState &S, CodePtr OpPC, uint32_t Off)
Definition Interp.cpp:1513
static bool CheckCallDepth(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:1063
const InterpFn InterpFunctions[]
Definition Interp.cpp:2825
static bool diagnoseCallableDecl(InterpState &S, CodePtr OpPC, const FunctionDecl *DiagDecl)
Definition Interp.cpp:953
constexpr bool OpReturns(Opcode Op)
Definition Interp.cpp:2803
static bool getDynamicDecl(InterpState &S, CodePtr OpPC, Pointer TypePtr, const CXXRecordDecl *&DynamicDecl)
Definition Interp.cpp:1875
static void startLifetimeRecurse(const Pointer &Ptr)
Definition Interp.cpp:2063
bool CastPointerIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth)
Definition Interp.cpp:2369
static bool CheckVolatile(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Definition Interp.cpp:607
bool CastPointerIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth)
Definition Interp.cpp:2356
bool CheckInit(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if a value can be initialized.
Definition Interp.cpp:945
bool GetMemberPtrBase(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2749
bool CheckFunctionDecl(InterpState &S, CodePtr OpPC, const FunctionDecl *FD)
Opcode. Check if the function decl can be called at compile time.
Definition Interp.cpp:1655
static bool appendToMemberPointer(InterpState &S, const MemberPointer &MemberPtr, int32_t BaseOffset, const RecordDecl *BaseDecl, bool IsDerivedMember)
Definition Interp.cpp:2701
bool EndLifetimePop(InterpState &S, CodePtr OpPC)
Ends the lifetime of the pop'd pointer.
Definition Interp.cpp:2144
static bool CheckCallable(InterpState &S, CodePtr OpPC, const Function *F)
Definition Interp.cpp:1035
static bool runRecordDestructor(InterpState &S, CodePtr OpPC, const Pointer &BasePtr, const Descriptor *Desc)
Definition Interp.cpp:1249
bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType)
Definition Interp.cpp:2424
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1449
bool CheckDowncast(InterpState &S, CodePtr OpPC, const Pointer &Ptr, uint32_t Offset)
Checks if the dowcast using the given offset is possible with the given pointer.
Definition Interp.cpp:546
bool CheckNewDeleteForms(InterpState &S, CodePtr OpPC, DynamicAllocator::Form AllocForm, DynamicAllocator::Form DeleteForm, const Descriptor *D, const Expr *NewExpr)
Diagnose mismatched new[]/delete or new/delete[] pairs.
Definition Interp.cpp:1147
bool CheckGlobalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Checks a direct load of a primitive value from a global or local variable.
Definition Interp.cpp:739
bool CheckDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR)
We aleady know the given DeclRefExpr is invalid for some reason, now figure out why and print appropr...
Definition Interp.cpp:1189
bool EndLifetime(InterpState &S, CodePtr OpPC)
Ends the lifetime of the peek'd pointer.
Definition Interp.cpp:2134
bool GetTypeid(InterpState &S, CodePtr OpPC, const Type *TypePtr, const Type *TypeInfoType)
Typeid support.
Definition Interp.cpp:2418
static PRESERVE_NONE bool BCP(InterpState &S, CodePtr &RealPC, int32_t Offset, PrimType PT)
This is used to implement speculative execution via __builtin_constant_p when we generate bytecode.
Definition Interp.cpp:2874
static bool CheckWeak(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:722
bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Checks if the Descriptor is of a constexpr or const global variable.
Definition Interp.cpp:442
bool CheckPointerToIntegralCast(InterpState &S, CodePtr OpPC, const Pointer &Ptr, unsigned BitWidth)
Definition Interp.cpp:2328
static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:1276
bool GetPtrField(InterpState &S, CodePtr OpPC, uint32_t Off)
1) Peeks a Pointer 2) Pushes Pointer.atField(Off) on the stack
Definition Interp.cpp:1508
bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK, bool WillActivate)
Definition Interp.cpp:304
static bool CheckNonNullArgs(InterpState &S, CodePtr OpPC, const Function *F, const CallExpr *CE, unsigned ArgSize)
Definition Interp.cpp:1227
bool StartThisLifetime1(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2099
PRESERVE_NONE bool EndSpeculation(InterpState &S, CodePtr &OpPC)
Definition Interp.h:3570
bool CheckMutable(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if a pointer points to a mutable field.
Definition Interp.cpp:590
static void finishGlobalRecurse(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:2556
bool CheckSubobject(InterpState &S, CodePtr OpPC, const Pointer &Ptr, CheckSubobjectKind CSK)
Checks if Ptr is a one-past-the-end pointer.
Definition Interp.cpp:535
bool handleFixedPointOverflow(InterpState &S, CodePtr OpPC, const FixedPoint &FP)
Definition Interp.cpp:2307
bool handleReference(InterpState &S, CodePtr OpPC, Block *B)
Definition Interp.cpp:2399
bool CheckBitCast(InterpState &S, CodePtr OpPC, const Type *TargetType, bool SrcIsVoidPtr)
Definition Interp.cpp:1670
static bool getField(InterpState &S, CodePtr OpPC, const Pointer &Ptr, uint32_t Off)
Definition Interp.cpp:1465
static bool hasVirtualDestructor(QualType T)
Definition Interp.cpp:1307
bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a value can be loaded from a block.
Definition Interp.cpp:791
static bool getBase(InterpState &S, CodePtr OpPC, const Pointer &Ptr, uint32_t Off, bool NullOK)
Definition Interp.cpp:1518
bool RVOPtr(InterpState &S, CodePtr OpPC)
Definition Interp.h:3093
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:201
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:284
bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a pointer is in range.
Definition Interp.cpp:513
bool CheckDynamicMemoryAllocation(InterpState &S, CodePtr OpPC)
Checks if dynamic memory allocation is available in the current language mode.
Definition Interp.cpp:1138
bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a pointer is live and accessible.
Definition Interp.cpp:412
bool GetPtrDerivedPop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK, const Type *TargetType)
Definition Interp.cpp:1556
bool DiagTypeid(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2450
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:868
bool CopyMemberPtrPath(InterpState &S, CodePtr OpPC, const RecordDecl *Entry, bool IsDerived)
Just append the given Entry to the MemberPointer's path.
Definition Interp.cpp:2786
static void popArg(InterpState &S, const Expr *Arg)
Definition Interp.cpp:225
static bool checkConstructor(InterpState &S, CodePtr OpPC, const Function *Func, const Pointer &ThisPtr)
Definition Interp.cpp:1595
llvm::APInt APInt
Definition FixedPoint.h:19
bool PushIgnoreDiags(InterpState &S, CodePtr OpPC)
Definition Interp.h:3539
void diagnoseEnumValue(InterpState &S, CodePtr OpPC, const EnumDecl *ED, const APSInt &Value)
Definition Interp.cpp:1412
bool CastMemberPtrDerivedPop(InterpState &S, CodePtr OpPC, int32_t Off, const RecordDecl *BaseDecl)
BaseToDerivedMemberPointer.
Definition Interp.cpp:2731
bool PopIgnoreDiags(InterpState &S, CodePtr OpPC)
Definition Interp.h:3550
bool isConstexprUnknown(const Block *B)
Definition Interp.cpp:272
bool InvalidDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR, bool InitializerFailed)
Definition Interp.cpp:1194
bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr, CheckSubobjectKind CSK)
Checks if a pointer is null.
Definition Interp.cpp:502
bool CheckDeleteSource(InterpState &S, CodePtr OpPC, const Expr *Source, const Pointer &Ptr)
Check the source of the pointer passed to delete/delete[] has actually been heap allocated by us.
Definition Interp.cpp:1165
bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result, APFloat::opStatus Status, FPOptions FPO)
Checks if the result of a floating-point operation is valid in the current context.
Definition Interp.cpp:1091
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call, uint32_t BuiltinID)
Interpret a builtin function.
bool CallVar(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition Interp.cpp:1725
constexpr bool needsAlloc()
Definition PrimType.h:131
bool InvalidShuffleVectorIndex(InterpState &S, CodePtr OpPC, uint32_t Index)
Definition Interp.cpp:2320
bool CheckDummy(InterpState &S, CodePtr OpPC, const Block *B, AccessKinds AK)
Checks if a pointer is a dummy pointer.
Definition Interp.cpp:1209
static bool diagnoseOutOfLifetimeDestroy(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:1616
bool CheckNewTypeMismatch(InterpState &S, CodePtr OpPC, const Expr *E, std::optional< uint64_t > ArraySize)
Check if the initializer and storage types of a placement-new expression match.
Definition Interp.cpp:2162
bool GetMemberPtr(InterpState &S, CodePtr OpPC, const ValueDecl *D)
Definition Interp.cpp:2744
bool CheckLiteralType(InterpState &S, CodePtr OpPC, const Type *T)
Definition Interp.cpp:1433
bool StartThisLifetime(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2088
bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if the array is offsetable.
Definition Interp.cpp:404
bool GetPtrBase(InterpState &S, CodePtr OpPC, uint32_t Off)
Definition Interp.cpp:1547
bool GetMemberPtrDecl(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2759
static void compileFunction(InterpState &S, const Function *Func)
Definition Interp.cpp:1716
bool CheckThis(InterpState &S, CodePtr OpPC)
Checks the 'this' pointer.
Definition Interp.cpp:1074
bool FinishInitGlobal(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2604
void cleanupAfterFunctionCall(InterpState &S, CodePtr OpPC, const Function *Func)
Definition Interp.cpp:230
bool CheckIntegralAddressCast(InterpState &S, CodePtr OpPC, unsigned BitWidth)
Definition Interp.cpp:2351
static void copyPrimitiveMemory(InterpState &S, const Pointer &Ptr, PrimType T)
Definition Interp.cpp:2509
bool CastMemberPtrBasePop(InterpState &S, CodePtr OpPC, int32_t Off, const RecordDecl *BaseDecl)
DerivedToBaseMemberPointer.
Definition Interp.cpp:2719
bool Destroy(InterpState &S, CodePtr OpPC, uint32_t I)
Definition Interp.cpp:2651
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:24
bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm, bool IsGlobalDelete)
Definition Interp.cpp:1314
bool InvalidNewDeleteExpr(InterpState &S, CodePtr OpPC, const Expr *E)
Definition Interp.cpp:2260
bool CallBI(InterpState &S, CodePtr OpPC, const CallExpr *CE, uint32_t BuiltinID)
Definition Interp.cpp:1990
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:770
bool CheckExtern(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if the variable has externally defined storage.
Definition Interp.cpp:386
static bool CheckLifetime(InterpState &S, CodePtr OpPC, Lifetime LT, const Block *B, AccessKinds AK)
Definition Interp.cpp:705
bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr, bool WillBeActivated)
Checks if a value can be stored in a block.
Definition Interp.cpp:901
bool GetPtrBasePop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK)
Definition Interp.cpp:1551
bool DiagnoseUninitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Definition Interp.cpp:654
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
static bool castBackMemberPointer(InterpState &S, const MemberPointer &MemberPtr, int32_t BaseOffset, const RecordDecl *BaseDecl)
Definition Interp.cpp:2669
bool CallPtr(InterpState &S, CodePtr OpPC, uint32_t ArgSize, const CallExpr *CE)
Definition Interp.cpp:2001
static void setLifeStateRecurse(const Pointer &Ptr, Lifetime L)
Definition Interp.cpp:2112
bool MarkDestroyed(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2153
bool CallVirt(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition Interp.cpp:1904
bool CheckConst(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if a pointer points to const storage.
Definition Interp.cpp:566
bool Interpret(InterpState &S)
Interpreter entry point.
Definition Interp.cpp:2840
bool(*)(InterpState &, CodePtr &PC) PRESERVE_NONE InterpFn
Definition Interp.cpp:2823
llvm::APSInt APSInt
Definition FixedPoint.h:20
bool InvalidCast(InterpState &S, CodePtr OpPC, CastKind Kind, bool Fatal)
Definition Interp.cpp:2616
bool CheckDestructor(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:1632
static bool CheckInvoke(InterpState &S, CodePtr OpPC, const Pointer &Ptr, bool IsCtorDtor=false)
Definition Interp.cpp:930
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Success
Annotation was successful.
Definition Parser.h:65
@ SC_Extern
Definition Specifiers.h:252
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:44
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Field
Definition State.h:47
@ Result
The result type of a method or function.
Definition TypeBase.h:905
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:28
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_MemberCall
Definition State.h:34
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
U cast(CodeGen::Address addr)
Definition Address.h:327
Describes a memory block created by an allocation site.
Definition Descriptor.h:123
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:260
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:274
bool hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:267
const ValueDecl * asValueDecl() const
Definition Descriptor.h:216
QualType getType() const
const Decl * asDecl() const
Definition Descriptor.h:212
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:156
unsigned getMetadataSize() const
Returns the size of the metadata.
Definition Descriptor.h:257
SourceLocation getLocation() const
QualType getDataType(const ASTContext &Ctx) const
unsigned getElemDataSize() const
Returns the element data size, i.e.
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:265
const VarDecl * asVarDecl() const
Definition Descriptor.h:220
PrimType getPrimType() const
Definition Descriptor.h:242
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:279
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:154
const Expr * asExpr() const
Definition Descriptor.h:213
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:277
const Function * Func
Definition Pointer.h:57
Descriptor used for global variables.
Definition Descriptor.h:50
Inline descriptor embedded in structures and arrays.
Definition Descriptor.h:68
std::optional< IntPointer > atOffset(const ASTContext &ASTCtx, unsigned Offset) const
Definition Pointer.cpp:985