Generator.h 8.2 KB

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