Generator.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/OwnPtr.h>
  8. #include <AK/SinglyLinkedList.h>
  9. #include <LibJS/AST.h>
  10. #include <LibJS/Bytecode/BasicBlock.h>
  11. #include <LibJS/Bytecode/CodeGenerationError.h>
  12. #include <LibJS/Bytecode/Executable.h>
  13. #include <LibJS/Bytecode/IdentifierTable.h>
  14. #include <LibJS/Bytecode/Label.h>
  15. #include <LibJS/Bytecode/Op.h>
  16. #include <LibJS/Bytecode/Register.h>
  17. #include <LibJS/Bytecode/StringTable.h>
  18. #include <LibJS/Forward.h>
  19. #include <LibJS/Runtime/FunctionKind.h>
  20. #include <LibRegex/Regex.h>
  21. namespace JS::Bytecode {
  22. class Generator {
  23. public:
  24. enum class SurroundingScopeKind {
  25. Global,
  26. Function,
  27. Block,
  28. };
  29. static CodeGenerationErrorOr<NonnullRefPtr<Executable>> generate(ASTNode const&, FunctionKind = FunctionKind::Normal);
  30. Register allocate_register();
  31. class SourceLocationScope {
  32. public:
  33. SourceLocationScope(Generator&, ASTNode const& node);
  34. ~SourceLocationScope();
  35. private:
  36. Generator& m_generator;
  37. ASTNode const* m_previous_node { nullptr };
  38. };
  39. class UnwindContext {
  40. public:
  41. UnwindContext(Generator&, Optional<Label> finalizer);
  42. UnwindContext const* previous() const { return m_previous_context; }
  43. void set_handler(Label handler) { m_handler = handler; }
  44. Optional<Label> handler() const { return m_handler; }
  45. Optional<Label> finalizer() const { return m_finalizer; }
  46. ~UnwindContext();
  47. private:
  48. Generator& m_generator;
  49. Optional<Label> m_finalizer;
  50. Optional<Label> m_handler {};
  51. UnwindContext const* m_previous_context { nullptr };
  52. };
  53. template<typename OpType, typename... Args>
  54. void emit(Args&&... args)
  55. {
  56. VERIFY(!is_current_block_terminated());
  57. size_t slot_offset = m_current_basic_block->size();
  58. grow(sizeof(OpType));
  59. void* slot = m_current_basic_block->data() + slot_offset;
  60. new (slot) OpType(forward<Args>(args)...);
  61. if constexpr (OpType::IsTerminator)
  62. m_current_basic_block->terminate({});
  63. auto* op = static_cast<OpType*>(slot);
  64. op->set_source_record({ m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  65. }
  66. template<typename OpType, typename... Args>
  67. void emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args)
  68. {
  69. VERIFY(!is_current_block_terminated());
  70. size_t size_to_allocate = round_up_to_power_of_two(sizeof(OpType) + extra_register_slots * sizeof(Register), alignof(void*));
  71. size_t slot_offset = m_current_basic_block->size();
  72. grow(size_to_allocate);
  73. void* slot = m_current_basic_block->data() + slot_offset;
  74. new (slot) OpType(forward<Args>(args)...);
  75. if constexpr (OpType::IsTerminator)
  76. m_current_basic_block->terminate({});
  77. auto* op = static_cast<OpType*>(slot);
  78. op->set_source_record({ m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  79. }
  80. struct ReferenceRegisters {
  81. Register base; // [[Base]]
  82. Optional<Register> referenced_name; // [[ReferencedName]]
  83. Register this_value; // [[ThisValue]]
  84. };
  85. enum class CollectRegisters {
  86. Yes,
  87. No
  88. };
  89. CodeGenerationErrorOr<Optional<ReferenceRegisters>> emit_load_from_reference(JS::ASTNode const&, CollectRegisters);
  90. CodeGenerationErrorOr<void> emit_store_to_reference(JS::ASTNode const&);
  91. CodeGenerationErrorOr<void> emit_store_to_reference(ReferenceRegisters const&);
  92. CodeGenerationErrorOr<void> emit_delete_reference(JS::ASTNode const&);
  93. CodeGenerationErrorOr<ReferenceRegisters> emit_super_reference(MemberExpression const&);
  94. void emit_set_variable(JS::Identifier const& identifier, Bytecode::Op::SetVariable::InitializationMode initialization_mode = Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode mode = Bytecode::Op::EnvironmentMode::Lexical);
  95. void push_home_object(Register);
  96. void pop_home_object();
  97. void emit_new_function(JS::FunctionExpression const&, Optional<IdentifierTableIndex> lhs_name);
  98. CodeGenerationErrorOr<void> emit_named_evaluation_if_anonymous_function(Expression const&, Optional<IdentifierTableIndex> lhs_name);
  99. void begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set);
  100. void end_continuable_scope();
  101. void begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set);
  102. void end_breakable_scope();
  103. [[nodiscard]] Label nearest_continuable_scope() const;
  104. [[nodiscard]] Label nearest_breakable_scope() const;
  105. void switch_to_basic_block(BasicBlock& block)
  106. {
  107. m_current_basic_block = &block;
  108. }
  109. [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; }
  110. BasicBlock& make_block(String name = {})
  111. {
  112. if (name.is_empty())
  113. name = MUST(String::number(m_next_block++));
  114. auto block = BasicBlock::create(name);
  115. if (auto const* context = m_current_unwind_context) {
  116. if (context->handler().has_value())
  117. block->set_handler(context->handler().value().block());
  118. if (m_current_unwind_context->finalizer().has_value())
  119. block->set_finalizer(context->finalizer().value().block());
  120. }
  121. m_root_basic_blocks.append(move(block));
  122. return *m_root_basic_blocks.last();
  123. }
  124. bool is_current_block_terminated() const
  125. {
  126. return m_current_basic_block->is_terminated();
  127. }
  128. StringTableIndex intern_string(DeprecatedString string)
  129. {
  130. return m_string_table->insert(move(string));
  131. }
  132. RegexTableIndex intern_regex(ParsedRegex regex)
  133. {
  134. return m_regex_table->insert(move(regex));
  135. }
  136. IdentifierTableIndex intern_identifier(DeprecatedFlyString string)
  137. {
  138. return m_identifier_table->insert(move(string));
  139. }
  140. bool is_in_generator_or_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  141. bool is_in_generator_function() const { return m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  142. bool is_in_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  143. bool is_in_async_generator_function() const { return m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  144. enum class BindingMode {
  145. Lexical,
  146. Var,
  147. Global,
  148. };
  149. struct LexicalScope {
  150. SurroundingScopeKind kind;
  151. };
  152. void block_declaration_instantiation(ScopeNode const&);
  153. void begin_variable_scope();
  154. void end_variable_scope();
  155. enum class BlockBoundaryType {
  156. Break,
  157. Continue,
  158. Unwind,
  159. ReturnToFinally,
  160. LeaveLexicalEnvironment,
  161. };
  162. template<typename OpType>
  163. void perform_needed_unwinds()
  164. requires(OpType::IsTerminator && !IsSame<OpType, Op::Jump>)
  165. {
  166. for (size_t i = m_boundaries.size(); i > 0; --i) {
  167. auto boundary = m_boundaries[i - 1];
  168. using enum BlockBoundaryType;
  169. switch (boundary) {
  170. case Unwind:
  171. if constexpr (IsSame<OpType, Bytecode::Op::Throw>)
  172. return;
  173. emit<Bytecode::Op::LeaveUnwindContext>();
  174. break;
  175. case LeaveLexicalEnvironment:
  176. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  177. break;
  178. case Break:
  179. case Continue:
  180. break;
  181. case ReturnToFinally:
  182. return;
  183. };
  184. }
  185. }
  186. void generate_break();
  187. void generate_break(DeprecatedFlyString const& break_label);
  188. void generate_continue();
  189. void generate_continue(DeprecatedFlyString const& continue_label);
  190. void start_boundary(BlockBoundaryType type) { m_boundaries.append(type); }
  191. void end_boundary(BlockBoundaryType type)
  192. {
  193. VERIFY(m_boundaries.last() == type);
  194. m_boundaries.take_last();
  195. }
  196. void emit_get_by_id(IdentifierTableIndex);
  197. void emit_get_by_id_with_this(IdentifierTableIndex, Register);
  198. [[nodiscard]] size_t next_global_variable_cache() { return m_next_global_variable_cache++; }
  199. [[nodiscard]] size_t next_environment_variable_cache() { return m_next_environment_variable_cache++; }
  200. [[nodiscard]] size_t next_property_lookup_cache() { return m_next_property_lookup_cache++; }
  201. private:
  202. enum class JumpType {
  203. Continue,
  204. Break,
  205. };
  206. void generate_scoped_jump(JumpType);
  207. void generate_labelled_jump(JumpType, DeprecatedFlyString const& label);
  208. Generator();
  209. ~Generator() = default;
  210. void grow(size_t);
  211. struct LabelableScope {
  212. Label bytecode_target;
  213. Vector<DeprecatedFlyString> language_label_set;
  214. };
  215. BasicBlock* m_current_basic_block { nullptr };
  216. ASTNode const* m_current_ast_node { nullptr };
  217. UnwindContext const* m_current_unwind_context { nullptr };
  218. Vector<NonnullOwnPtr<BasicBlock>> m_root_basic_blocks;
  219. NonnullOwnPtr<StringTable> m_string_table;
  220. NonnullOwnPtr<IdentifierTable> m_identifier_table;
  221. NonnullOwnPtr<RegexTable> m_regex_table;
  222. u32 m_next_register { Register::reserved_register_count };
  223. u32 m_next_block { 1 };
  224. u32 m_next_property_lookup_cache { 0 };
  225. u32 m_next_global_variable_cache { 0 };
  226. u32 m_next_environment_variable_cache { 0 };
  227. FunctionKind m_enclosing_function_kind { FunctionKind::Normal };
  228. Vector<LabelableScope> m_continuable_scopes;
  229. Vector<LabelableScope> m_breakable_scopes;
  230. Vector<BlockBoundaryType> m_boundaries;
  231. Vector<Register> m_home_objects;
  232. };
  233. }