Generator.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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/NonnullOwnPtrVector.h>
  8. #include <AK/OwnPtr.h>
  9. #include <AK/SinglyLinkedList.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. namespace JS::Bytecode {
  21. class Generator {
  22. public:
  23. enum class SurroundingScopeKind {
  24. Global,
  25. Function,
  26. Block,
  27. };
  28. static CodeGenerationErrorOr<NonnullOwnPtr<Executable>> generate(ASTNode const&, FunctionKind = FunctionKind::Normal);
  29. Register allocate_register();
  30. void ensure_enough_space(size_t size)
  31. {
  32. // Make sure there's always enough space for a single jump at the end.
  33. if (!m_current_basic_block->can_grow(size + sizeof(Op::Jump))) {
  34. auto& new_block = make_block();
  35. emit<Op::Jump>().set_targets(
  36. Label { new_block },
  37. {});
  38. switch_to_basic_block(new_block);
  39. }
  40. }
  41. template<typename OpType, typename... Args>
  42. OpType& emit(Args&&... args)
  43. {
  44. VERIFY(!is_current_block_terminated());
  45. // If the block doesn't have enough space, switch to another block
  46. if constexpr (!OpType::IsTerminator)
  47. ensure_enough_space(sizeof(OpType));
  48. void* slot = next_slot();
  49. grow(sizeof(OpType));
  50. new (slot) OpType(forward<Args>(args)...);
  51. if constexpr (OpType::IsTerminator)
  52. m_current_basic_block->terminate({});
  53. return *static_cast<OpType*>(slot);
  54. }
  55. template<typename OpType, typename... Args>
  56. OpType& emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args)
  57. {
  58. VERIFY(!is_current_block_terminated());
  59. size_t size_to_allocate = round_up_to_power_of_two(sizeof(OpType) + extra_register_slots * sizeof(Register), alignof(void*));
  60. // If the block doesn't have enough space, switch to another block
  61. if constexpr (!OpType::IsTerminator)
  62. ensure_enough_space(size_to_allocate);
  63. void* slot = next_slot();
  64. grow(size_to_allocate);
  65. new (slot) OpType(forward<Args>(args)...);
  66. if constexpr (OpType::IsTerminator)
  67. m_current_basic_block->terminate({});
  68. return *static_cast<OpType*>(slot);
  69. }
  70. CodeGenerationErrorOr<void> emit_load_from_reference(JS::ASTNode const&);
  71. CodeGenerationErrorOr<void> emit_store_to_reference(JS::ASTNode const&);
  72. CodeGenerationErrorOr<void> emit_delete_reference(JS::ASTNode const&);
  73. void begin_continuable_scope(Label continue_target, Vector<FlyString> const& language_label_set);
  74. void end_continuable_scope();
  75. void begin_breakable_scope(Label breakable_target, Vector<FlyString> const& language_label_set);
  76. void end_breakable_scope();
  77. [[nodiscard]] Label nearest_continuable_scope() const;
  78. [[nodiscard]] Label nearest_breakable_scope() const;
  79. void switch_to_basic_block(BasicBlock& block)
  80. {
  81. m_current_basic_block = &block;
  82. }
  83. [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; }
  84. BasicBlock& make_block(String name = {})
  85. {
  86. if (name.is_empty())
  87. name = String::number(m_next_block++);
  88. m_root_basic_blocks.append(BasicBlock::create(name));
  89. return m_root_basic_blocks.last();
  90. }
  91. bool is_current_block_terminated() const
  92. {
  93. return m_current_basic_block->is_terminated();
  94. }
  95. StringTableIndex intern_string(String string)
  96. {
  97. return m_string_table->insert(move(string));
  98. }
  99. IdentifierTableIndex intern_identifier(FlyString string)
  100. {
  101. return m_identifier_table->insert(move(string));
  102. }
  103. bool is_in_generator_or_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::Generator; }
  104. bool is_in_generator_function() const { return m_enclosing_function_kind == FunctionKind::Generator; }
  105. bool is_in_async_function() const { return m_enclosing_function_kind == FunctionKind::Async; }
  106. enum class BindingMode {
  107. Lexical,
  108. Var,
  109. Global,
  110. };
  111. struct LexicalScope {
  112. SurroundingScopeKind kind;
  113. BindingMode mode;
  114. HashTable<IdentifierTableIndex> known_bindings;
  115. };
  116. void register_binding(IdentifierTableIndex identifier, BindingMode mode = BindingMode::Lexical)
  117. {
  118. m_variable_scopes.last_matching([&](auto& x) { return x.mode == BindingMode::Global || x.mode == mode; })->known_bindings.set(identifier);
  119. }
  120. bool has_binding(IdentifierTableIndex identifier, Optional<BindingMode> const& specific_binding_mode = {}) const
  121. {
  122. for (auto index = m_variable_scopes.size(); index > 0; --index) {
  123. auto& scope = m_variable_scopes[index - 1];
  124. if (scope.mode != BindingMode::Global && specific_binding_mode.value_or(scope.mode) != scope.mode)
  125. continue;
  126. if (scope.known_bindings.contains(identifier))
  127. return true;
  128. }
  129. return false;
  130. }
  131. bool has_binding_in_current_scope(IdentifierTableIndex identifier) const
  132. {
  133. if (m_variable_scopes.is_empty())
  134. return false;
  135. return m_variable_scopes.last().known_bindings.contains(identifier);
  136. }
  137. void begin_variable_scope(BindingMode mode = BindingMode::Lexical, SurroundingScopeKind kind = SurroundingScopeKind::Block);
  138. void end_variable_scope();
  139. enum class BlockBoundaryType {
  140. Break,
  141. Continue,
  142. Unwind,
  143. LeaveLexicalEnvironment,
  144. LeaveVariableEnvironment,
  145. };
  146. template<typename OpType>
  147. void perform_needed_unwinds(bool is_break_node = false) requires(OpType::IsTerminator)
  148. {
  149. Optional<BlockBoundaryType> boundary_to_stop_at;
  150. if constexpr (IsSame<OpType, Bytecode::Op::Return> || IsSame<OpType, Bytecode::Op::Yield>)
  151. VERIFY(!is_break_node);
  152. else if constexpr (IsSame<OpType, Bytecode::Op::Throw>)
  153. boundary_to_stop_at = BlockBoundaryType::Unwind;
  154. else
  155. boundary_to_stop_at = is_break_node ? BlockBoundaryType::Break : BlockBoundaryType::Continue;
  156. for (size_t i = m_boundaries.size(); i > 0; --i) {
  157. auto boundary = m_boundaries[i - 1];
  158. if (boundary_to_stop_at.has_value() && boundary == *boundary_to_stop_at)
  159. break;
  160. if (boundary == BlockBoundaryType::Unwind)
  161. emit<Bytecode::Op::LeaveUnwindContext>();
  162. else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment)
  163. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  164. else if (boundary == BlockBoundaryType::LeaveVariableEnvironment)
  165. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  166. }
  167. }
  168. Label perform_needed_unwinds_for_labelled_break_and_return_target_block(FlyString const& break_label);
  169. Label perform_needed_unwinds_for_labelled_continue_and_return_target_block(FlyString const& continue_label);
  170. void start_boundary(BlockBoundaryType type) { m_boundaries.append(type); }
  171. void end_boundary(BlockBoundaryType type)
  172. {
  173. VERIFY(m_boundaries.last() == type);
  174. m_boundaries.take_last();
  175. }
  176. private:
  177. Generator();
  178. ~Generator() = default;
  179. void grow(size_t);
  180. void* next_slot();
  181. struct LabelableScope {
  182. Label bytecode_target;
  183. Vector<FlyString> language_label_set;
  184. };
  185. BasicBlock* m_current_basic_block { nullptr };
  186. NonnullOwnPtrVector<BasicBlock> m_root_basic_blocks;
  187. NonnullOwnPtr<StringTable> m_string_table;
  188. NonnullOwnPtr<IdentifierTable> m_identifier_table;
  189. u32 m_next_register { 2 };
  190. u32 m_next_block { 1 };
  191. FunctionKind m_enclosing_function_kind { FunctionKind::Normal };
  192. Vector<LabelableScope> m_continuable_scopes;
  193. Vector<LabelableScope> m_breakable_scopes;
  194. Vector<LexicalScope> m_variable_scopes;
  195. Vector<BlockBoundaryType> m_boundaries;
  196. };
  197. }