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