xref: /llvm-project/clang/lib/AST/ByteCode/Compiler.h (revision 6b62e04e3045e5d8f4361afc100a460622266f82)
1 //===--- Compiler.h - Code generator for expressions -----*- 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 // Defines the constexpr bytecode compiler.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_AST_INTERP_BYTECODEEXPRGEN_H
14 #define LLVM_CLANG_AST_INTERP_BYTECODEEXPRGEN_H
15 
16 #include "ByteCodeEmitter.h"
17 #include "EvalEmitter.h"
18 #include "Pointer.h"
19 #include "PrimType.h"
20 #include "Record.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 
26 namespace clang {
27 class QualType;
28 
29 namespace interp {
30 
31 template <class Emitter> class LocalScope;
32 template <class Emitter> class DestructorScope;
33 template <class Emitter> class VariableScope;
34 template <class Emitter> class DeclScope;
35 template <class Emitter> class InitLinkScope;
36 template <class Emitter> class InitStackScope;
37 template <class Emitter> class OptionScope;
38 template <class Emitter> class ArrayIndexScope;
39 template <class Emitter> class SourceLocScope;
40 template <class Emitter> class LoopScope;
41 template <class Emitter> class LabelScope;
42 template <class Emitter> class SwitchScope;
43 template <class Emitter> class StmtExprScope;
44 
45 template <class Emitter> class Compiler;
46 struct InitLink {
47 public:
48   enum {
49     K_This = 0,
50     K_Field = 1,
51     K_Temp = 2,
52     K_Decl = 3,
53     K_Elem = 5,
54   };
55 
56   static InitLink This() { return InitLink{K_This}; }
57   static InitLink Field(unsigned Offset) {
58     InitLink IL{K_Field};
59     IL.Offset = Offset;
60     return IL;
61   }
62   static InitLink Temp(unsigned Offset) {
63     InitLink IL{K_Temp};
64     IL.Offset = Offset;
65     return IL;
66   }
67   static InitLink Decl(const ValueDecl *D) {
68     InitLink IL{K_Decl};
69     IL.D = D;
70     return IL;
71   }
72   static InitLink Elem(unsigned Index) {
73     InitLink IL{K_Elem};
74     IL.Offset = Index;
75     return IL;
76   }
77 
78   InitLink(uint8_t Kind) : Kind(Kind) {}
79   template <class Emitter>
80   bool emit(Compiler<Emitter> *Ctx, const Expr *E) const;
81 
82   uint32_t Kind;
83   union {
84     unsigned Offset;
85     const ValueDecl *D;
86   };
87 };
88 
89 /// State encapsulating if a the variable creation has been successful,
90 /// unsuccessful, or no variable has been created at all.
91 struct VarCreationState {
92   std::optional<bool> S = std::nullopt;
93   VarCreationState() = default;
94   VarCreationState(bool b) : S(b) {}
95   static VarCreationState NotCreated() { return VarCreationState(); }
96 
97   operator bool() const { return S && *S; }
98   bool notCreated() const { return !S; }
99 };
100 
101 /// Compilation context for expressions.
102 template <class Emitter>
103 class Compiler : public ConstStmtVisitor<Compiler<Emitter>, bool>,
104                  public Emitter {
105 protected:
106   // Aliases for types defined in the emitter.
107   using LabelTy = typename Emitter::LabelTy;
108   using AddrTy = typename Emitter::AddrTy;
109   using OptLabelTy = std::optional<LabelTy>;
110   using CaseMap = llvm::DenseMap<const SwitchCase *, LabelTy>;
111 
112   /// Current compilation context.
113   Context &Ctx;
114   /// Program to link to.
115   Program &P;
116 
117 public:
118   /// Initializes the compiler and the backend emitter.
119   template <typename... Tys>
120   Compiler(Context &Ctx, Program &P, Tys &&...Args)
121       : Emitter(Ctx, P, Args...), Ctx(Ctx), P(P) {}
122 
123   // Expressions.
124   bool VisitCastExpr(const CastExpr *E);
125   bool VisitIntegerLiteral(const IntegerLiteral *E);
126   bool VisitFloatingLiteral(const FloatingLiteral *E);
127   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
128   bool VisitFixedPointLiteral(const FixedPointLiteral *E);
129   bool VisitParenExpr(const ParenExpr *E);
130   bool VisitBinaryOperator(const BinaryOperator *E);
131   bool VisitLogicalBinOp(const BinaryOperator *E);
132   bool VisitPointerArithBinOp(const BinaryOperator *E);
133   bool VisitComplexBinOp(const BinaryOperator *E);
134   bool VisitVectorBinOp(const BinaryOperator *E);
135   bool VisitFixedPointBinOp(const BinaryOperator *E);
136   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E);
137   bool VisitCallExpr(const CallExpr *E);
138   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID);
139   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E);
140   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E);
141   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
142   bool VisitGNUNullExpr(const GNUNullExpr *E);
143   bool VisitCXXThisExpr(const CXXThisExpr *E);
144   bool VisitUnaryOperator(const UnaryOperator *E);
145   bool VisitVectorUnaryOperator(const UnaryOperator *E);
146   bool VisitComplexUnaryOperator(const UnaryOperator *E);
147   bool VisitDeclRefExpr(const DeclRefExpr *E);
148   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E);
149   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E);
150   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
151   bool VisitInitListExpr(const InitListExpr *E);
152   bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
153   bool VisitConstantExpr(const ConstantExpr *E);
154   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
155   bool VisitMemberExpr(const MemberExpr *E);
156   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E);
157   bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
158   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E);
159   bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E);
160   bool VisitStringLiteral(const StringLiteral *E);
161   bool VisitObjCStringLiteral(const ObjCStringLiteral *E);
162   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
163   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E);
164   bool VisitCharacterLiteral(const CharacterLiteral *E);
165   bool VisitCompoundAssignOperator(const CompoundAssignOperator *E);
166   bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E);
167   bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E);
168   bool VisitExprWithCleanups(const ExprWithCleanups *E);
169   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
170   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E);
171   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
172   bool VisitTypeTraitExpr(const TypeTraitExpr *E);
173   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
174   bool VisitLambdaExpr(const LambdaExpr *E);
175   bool VisitPredefinedExpr(const PredefinedExpr *E);
176   bool VisitCXXThrowExpr(const CXXThrowExpr *E);
177   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E);
178   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
179   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
180   bool VisitSourceLocExpr(const SourceLocExpr *E);
181   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
182   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
183   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
184   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E);
185   bool VisitChooseExpr(const ChooseExpr *E);
186   bool VisitEmbedExpr(const EmbedExpr *E);
187   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E);
188   bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
189   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
190   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
191   bool VisitRequiresExpr(const RequiresExpr *E);
192   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
193   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E);
194   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E);
195   bool VisitPackIndexingExpr(const PackIndexingExpr *E);
196   bool VisitRecoveryExpr(const RecoveryExpr *E);
197   bool VisitAddrLabelExpr(const AddrLabelExpr *E);
198   bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
199   bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
200   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
201   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
202   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
203   bool VisitStmtExpr(const StmtExpr *E);
204   bool VisitCXXNewExpr(const CXXNewExpr *E);
205   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
206   bool VisitBlockExpr(const BlockExpr *E);
207 
208   // Statements.
209   bool visitCompoundStmt(const CompoundStmt *S);
210   bool visitDeclStmt(const DeclStmt *DS);
211   bool visitReturnStmt(const ReturnStmt *RS);
212   bool visitIfStmt(const IfStmt *IS);
213   bool visitWhileStmt(const WhileStmt *S);
214   bool visitDoStmt(const DoStmt *S);
215   bool visitForStmt(const ForStmt *S);
216   bool visitCXXForRangeStmt(const CXXForRangeStmt *S);
217   bool visitBreakStmt(const BreakStmt *S);
218   bool visitContinueStmt(const ContinueStmt *S);
219   bool visitSwitchStmt(const SwitchStmt *S);
220   bool visitCaseStmt(const CaseStmt *S);
221   bool visitDefaultStmt(const DefaultStmt *S);
222   bool visitAttributedStmt(const AttributedStmt *S);
223   bool visitCXXTryStmt(const CXXTryStmt *S);
224 
225 protected:
226   bool visitStmt(const Stmt *S);
227   bool visitExpr(const Expr *E, bool DestroyToplevelScope) override;
228   bool visitFunc(const FunctionDecl *F) override;
229 
230   bool visitDeclAndReturn(const VarDecl *VD, bool ConstantContext) override;
231 
232 protected:
233   /// Emits scope cleanup instructions.
234   void emitCleanup();
235 
236   /// Returns a record type from a record or pointer type.
237   const RecordType *getRecordTy(QualType Ty);
238 
239   /// Returns a record from a record or pointer type.
240   Record *getRecord(QualType Ty);
241   Record *getRecord(const RecordDecl *RD);
242 
243   /// Returns a function for the given FunctionDecl.
244   /// If the function does not exist yet, it is compiled.
245   const Function *getFunction(const FunctionDecl *FD);
246 
247   std::optional<PrimType> classify(const Expr *E) const {
248     return Ctx.classify(E);
249   }
250   std::optional<PrimType> classify(QualType Ty) const {
251     return Ctx.classify(Ty);
252   }
253 
254   /// Classifies a known primitive type.
255   PrimType classifyPrim(QualType Ty) const {
256     if (auto T = classify(Ty)) {
257       return *T;
258     }
259     llvm_unreachable("not a primitive type");
260   }
261   /// Classifies a known primitive expression.
262   PrimType classifyPrim(const Expr *E) const {
263     if (auto T = classify(E))
264       return *T;
265     llvm_unreachable("not a primitive type");
266   }
267 
268   /// Evaluates an expression and places the result on the stack. If the
269   /// expression is of composite type, a local variable will be created
270   /// and a pointer to said variable will be placed on the stack.
271   bool visit(const Expr *E);
272   /// Compiles an initializer. This is like visit() but it will never
273   /// create a variable and instead rely on a variable already having
274   /// been created. visitInitializer() then relies on a pointer to this
275   /// variable being on top of the stack.
276   bool visitInitializer(const Expr *E);
277   /// Evaluates an expression for side effects and discards the result.
278   bool discard(const Expr *E);
279   /// Just pass evaluation on to \p E. This leaves all the parsing flags
280   /// intact.
281   bool delegate(const Expr *E);
282   /// Creates and initializes a variable from the given decl.
283   VarCreationState visitVarDecl(const VarDecl *VD, bool Toplevel = false);
284   VarCreationState visitDecl(const VarDecl *VD);
285   /// Visit an APValue.
286   bool visitAPValue(const APValue &Val, PrimType ValType, const Expr *E);
287   bool visitAPValueInitializer(const APValue &Val, const Expr *E);
288   /// Visit the given decl as if we have a reference to it.
289   bool visitDeclRef(const ValueDecl *D, const Expr *E);
290 
291   /// Visits an expression and converts it to a boolean.
292   bool visitBool(const Expr *E);
293 
294   bool visitInitList(ArrayRef<const Expr *> Inits, const Expr *ArrayFiller,
295                      const Expr *E);
296   bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init);
297 
298   /// Creates a local primitive value.
299   unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsConst,
300                                   bool IsExtended = false);
301 
302   /// Allocates a space storing a local given its type.
303   std::optional<unsigned>
304   allocateLocal(DeclTy &&Decl, const ValueDecl *ExtendingDecl = nullptr);
305   unsigned allocateTemporary(const Expr *E);
306 
307 private:
308   friend class VariableScope<Emitter>;
309   friend class LocalScope<Emitter>;
310   friend class DestructorScope<Emitter>;
311   friend class DeclScope<Emitter>;
312   friend class InitLinkScope<Emitter>;
313   friend class InitStackScope<Emitter>;
314   friend class OptionScope<Emitter>;
315   friend class ArrayIndexScope<Emitter>;
316   friend class SourceLocScope<Emitter>;
317   friend struct InitLink;
318   friend class LoopScope<Emitter>;
319   friend class LabelScope<Emitter>;
320   friend class SwitchScope<Emitter>;
321   friend class StmtExprScope<Emitter>;
322 
323   /// Emits a zero initializer.
324   bool visitZeroInitializer(PrimType T, QualType QT, const Expr *E);
325   bool visitZeroRecordInitializer(const Record *R, const Expr *E);
326 
327   /// Emits an APSInt constant.
328   bool emitConst(const llvm::APSInt &Value, PrimType Ty, const Expr *E);
329   bool emitConst(const llvm::APSInt &Value, const Expr *E);
330   bool emitConst(const llvm::APInt &Value, const Expr *E) {
331     return emitConst(static_cast<llvm::APSInt>(Value), E);
332   }
333 
334   /// Emits an integer constant.
335   template <typename T> bool emitConst(T Value, PrimType Ty, const Expr *E);
336   template <typename T> bool emitConst(T Value, const Expr *E);
337 
338   llvm::RoundingMode getRoundingMode(const Expr *E) const {
339     FPOptions FPO = E->getFPFeaturesInEffect(Ctx.getLangOpts());
340 
341     if (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic)
342       return llvm::RoundingMode::NearestTiesToEven;
343 
344     return FPO.getRoundingMode();
345   }
346 
347   uint32_t getFPOptions(const Expr *E) const {
348     return E->getFPFeaturesInEffect(Ctx.getLangOpts()).getAsOpaqueInt();
349   }
350 
351   bool emitPrimCast(PrimType FromT, PrimType ToT, QualType ToQT, const Expr *E);
352   PrimType classifyComplexElementType(QualType T) const {
353     assert(T->isAnyComplexType());
354 
355     QualType ElemType = T->getAs<ComplexType>()->getElementType();
356 
357     return *this->classify(ElemType);
358   }
359 
360   PrimType classifyVectorElementType(QualType T) const {
361     assert(T->isVectorType());
362     return *this->classify(T->getAs<VectorType>()->getElementType());
363   }
364 
365   bool emitComplexReal(const Expr *SubExpr);
366   bool emitComplexBoolCast(const Expr *E);
367   bool emitComplexComparison(const Expr *LHS, const Expr *RHS,
368                              const BinaryOperator *E);
369   bool emitRecordDestruction(const Record *R, SourceInfo Loc);
370   bool emitDestruction(const Descriptor *Desc, SourceInfo Loc);
371   unsigned collectBaseOffset(const QualType BaseType,
372                              const QualType DerivedType);
373   bool emitLambdaStaticInvokerBody(const CXXMethodDecl *MD);
374   bool compileConstructor(const CXXConstructorDecl *Ctor);
375   bool compileDestructor(const CXXDestructorDecl *Dtor);
376 
377   bool checkLiteralType(const Expr *E);
378 
379 protected:
380   /// Variable to storage mapping.
381   llvm::DenseMap<const ValueDecl *, Scope::Local> Locals;
382 
383   /// OpaqueValueExpr to location mapping.
384   llvm::DenseMap<const OpaqueValueExpr *, unsigned> OpaqueExprs;
385 
386   /// Current scope.
387   VariableScope<Emitter> *VarScope = nullptr;
388 
389   /// Current argument index. Needed to emit ArrayInitIndexExpr.
390   std::optional<uint64_t> ArrayIndex;
391 
392   /// DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
393   const Expr *SourceLocDefaultExpr = nullptr;
394 
395   /// Flag indicating if return value is to be discarded.
396   bool DiscardResult = false;
397 
398   bool InStmtExpr = false;
399 
400   /// Flag inidicating if we're initializing an already created
401   /// variable. This is set in visitInitializer().
402   bool Initializing = false;
403   const ValueDecl *InitializingDecl = nullptr;
404 
405   llvm::SmallVector<InitLink> InitStack;
406   bool InitStackActive = false;
407 
408   /// Type of the expression returned by the function.
409   std::optional<PrimType> ReturnType;
410 
411   /// Switch case mapping.
412   CaseMap CaseLabels;
413 
414   /// Scope to cleanup until when we see a break statement.
415   VariableScope<Emitter> *BreakVarScope = nullptr;
416   /// Point to break to.
417   OptLabelTy BreakLabel;
418   /// Scope to cleanup until when we see a continue statement.
419   VariableScope<Emitter> *ContinueVarScope = nullptr;
420   /// Point to continue to.
421   OptLabelTy ContinueLabel;
422   /// Default case label.
423   OptLabelTy DefaultLabel;
424 };
425 
426 extern template class Compiler<ByteCodeEmitter>;
427 extern template class Compiler<EvalEmitter>;
428 
429 /// Scope chain managing the variable lifetimes.
430 template <class Emitter> class VariableScope {
431 public:
432   VariableScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
433       : Ctx(Ctx), Parent(Ctx->VarScope), ValDecl(VD) {
434     Ctx->VarScope = this;
435   }
436 
437   virtual ~VariableScope() { Ctx->VarScope = this->Parent; }
438 
439   void add(const Scope::Local &Local, bool IsExtended) {
440     if (IsExtended)
441       this->addExtended(Local);
442     else
443       this->addLocal(Local);
444   }
445 
446   virtual void addLocal(const Scope::Local &Local) {
447     if (this->Parent)
448       this->Parent->addLocal(Local);
449   }
450 
451   virtual void addExtended(const Scope::Local &Local) {
452     if (this->Parent)
453       this->Parent->addExtended(Local);
454   }
455 
456   void addExtended(const Scope::Local &Local, const ValueDecl *ExtendingDecl) {
457     // Walk up the chain of scopes until we find the one for ExtendingDecl.
458     // If there is no such scope, attach it to the parent one.
459     VariableScope *P = this;
460     while (P) {
461       if (P->ValDecl == ExtendingDecl) {
462         P->addLocal(Local);
463         return;
464       }
465       P = P->Parent;
466       if (!P)
467         break;
468     }
469 
470     // Use the parent scope.
471     if (this->Parent)
472       this->Parent->addLocal(Local);
473     else
474       this->addLocal(Local);
475   }
476 
477   virtual void emitDestruction() {}
478   virtual bool emitDestructors(const Expr *E = nullptr) { return true; }
479   virtual bool destroyLocals(const Expr *E = nullptr) { return true; }
480   VariableScope *getParent() const { return Parent; }
481 
482 protected:
483   /// Compiler instance.
484   Compiler<Emitter> *Ctx;
485   /// Link to the parent scope.
486   VariableScope *Parent;
487   const ValueDecl *ValDecl = nullptr;
488 };
489 
490 /// Generic scope for local variables.
491 template <class Emitter> class LocalScope : public VariableScope<Emitter> {
492 public:
493   LocalScope(Compiler<Emitter> *Ctx) : VariableScope<Emitter>(Ctx, nullptr) {}
494   LocalScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
495       : VariableScope<Emitter>(Ctx, VD) {}
496 
497   /// Emit a Destroy op for this scope.
498   ~LocalScope() override {
499     if (!Idx)
500       return;
501     this->Ctx->emitDestroy(*Idx, SourceInfo{});
502     removeStoredOpaqueValues();
503   }
504 
505   /// Overriden to support explicit destruction.
506   void emitDestruction() override {
507     if (!Idx)
508       return;
509 
510     this->emitDestructors();
511     this->Ctx->emitDestroy(*Idx, SourceInfo{});
512   }
513 
514   /// Explicit destruction of local variables.
515   bool destroyLocals(const Expr *E = nullptr) override {
516     if (!Idx)
517       return true;
518 
519     bool Success = this->emitDestructors(E);
520     this->Ctx->emitDestroy(*Idx, E);
521     this->Idx = std::nullopt;
522     return Success;
523   }
524 
525   void addLocal(const Scope::Local &Local) override {
526     if (!Idx) {
527       Idx = this->Ctx->Descriptors.size();
528       this->Ctx->Descriptors.emplace_back();
529       this->Ctx->emitInitScope(*Idx, {});
530     }
531 
532     this->Ctx->Descriptors[*Idx].emplace_back(Local);
533   }
534 
535   bool emitDestructors(const Expr *E = nullptr) override {
536     if (!Idx)
537       return true;
538     // Emit destructor calls for local variables of record
539     // type with a destructor.
540     for (Scope::Local &Local : llvm::reverse(this->Ctx->Descriptors[*Idx])) {
541       if (!Local.Desc->isPrimitive() && !Local.Desc->isPrimitiveArray()) {
542         if (!this->Ctx->emitGetPtrLocal(Local.Offset, E))
543           return false;
544 
545         if (!this->Ctx->emitDestruction(Local.Desc, Local.Desc->getLoc()))
546           return false;
547 
548         if (!this->Ctx->emitPopPtr(E))
549           return false;
550         removeIfStoredOpaqueValue(Local);
551       }
552     }
553     return true;
554   }
555 
556   void removeStoredOpaqueValues() {
557     if (!Idx)
558       return;
559 
560     for (const Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
561       removeIfStoredOpaqueValue(Local);
562     }
563   }
564 
565   void removeIfStoredOpaqueValue(const Scope::Local &Local) {
566     if (const auto *OVE =
567             llvm::dyn_cast_if_present<OpaqueValueExpr>(Local.Desc->asExpr())) {
568       if (auto It = this->Ctx->OpaqueExprs.find(OVE);
569           It != this->Ctx->OpaqueExprs.end())
570         this->Ctx->OpaqueExprs.erase(It);
571     };
572   }
573 
574   /// Index of the scope in the chain.
575   std::optional<unsigned> Idx;
576 };
577 
578 /// Scope for storage declared in a compound statement.
579 template <class Emitter> class BlockScope final : public LocalScope<Emitter> {
580 public:
581   BlockScope(Compiler<Emitter> *Ctx) : LocalScope<Emitter>(Ctx) {}
582 
583   void addExtended(const Scope::Local &Local) override {
584     // If we to this point, just add the variable as a normal local
585     // variable. It will be destroyed at the end of the block just
586     // like all others.
587     this->addLocal(Local);
588   }
589 };
590 
591 template <class Emitter> class ArrayIndexScope final {
592 public:
593   ArrayIndexScope(Compiler<Emitter> *Ctx, uint64_t Index) : Ctx(Ctx) {
594     OldArrayIndex = Ctx->ArrayIndex;
595     Ctx->ArrayIndex = Index;
596   }
597 
598   ~ArrayIndexScope() { Ctx->ArrayIndex = OldArrayIndex; }
599 
600 private:
601   Compiler<Emitter> *Ctx;
602   std::optional<uint64_t> OldArrayIndex;
603 };
604 
605 template <class Emitter> class SourceLocScope final {
606 public:
607   SourceLocScope(Compiler<Emitter> *Ctx, const Expr *DefaultExpr) : Ctx(Ctx) {
608     assert(DefaultExpr);
609     // We only switch if the current SourceLocDefaultExpr is null.
610     if (!Ctx->SourceLocDefaultExpr) {
611       Enabled = true;
612       Ctx->SourceLocDefaultExpr = DefaultExpr;
613     }
614   }
615 
616   ~SourceLocScope() {
617     if (Enabled)
618       Ctx->SourceLocDefaultExpr = nullptr;
619   }
620 
621 private:
622   Compiler<Emitter> *Ctx;
623   bool Enabled = false;
624 };
625 
626 template <class Emitter> class InitLinkScope final {
627 public:
628   InitLinkScope(Compiler<Emitter> *Ctx, InitLink &&Link) : Ctx(Ctx) {
629     Ctx->InitStack.push_back(std::move(Link));
630   }
631 
632   ~InitLinkScope() { this->Ctx->InitStack.pop_back(); }
633 
634 private:
635   Compiler<Emitter> *Ctx;
636 };
637 
638 template <class Emitter> class InitStackScope final {
639 public:
640   InitStackScope(Compiler<Emitter> *Ctx, bool Active)
641       : Ctx(Ctx), OldValue(Ctx->InitStackActive) {
642     Ctx->InitStackActive = Active;
643   }
644 
645   ~InitStackScope() { this->Ctx->InitStackActive = OldValue; }
646 
647 private:
648   Compiler<Emitter> *Ctx;
649   bool OldValue;
650 };
651 
652 } // namespace interp
653 } // namespace clang
654 
655 #endif
656