Generator.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. #include <LibRegex/Regex.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({}, static_cast<Instruction const*>(slot));
  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({}, static_cast<Instruction const*>(slot));
  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. struct ReferenceRegisters {
  74. Register base; // [[Base]]
  75. Optional<Bytecode::Register> referenced_name; // [[ReferencedName]]
  76. Register this_value; // [[ThisValue]]
  77. };
  78. CodeGenerationErrorOr<ReferenceRegisters> emit_super_reference(MemberExpression const&);
  79. 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);
  80. void push_home_object(Register);
  81. void pop_home_object();
  82. void emit_new_function(JS::FunctionExpression const&, Optional<IdentifierTableIndex> lhs_name);
  83. CodeGenerationErrorOr<void> emit_named_evaluation_if_anonymous_function(Expression const&, Optional<IdentifierTableIndex> lhs_name);
  84. void begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set);
  85. void end_continuable_scope();
  86. void begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set);
  87. void end_breakable_scope();
  88. [[nodiscard]] Label nearest_continuable_scope() const;
  89. [[nodiscard]] Label nearest_breakable_scope() const;
  90. void switch_to_basic_block(BasicBlock& block)
  91. {
  92. m_current_basic_block = &block;
  93. }
  94. [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; }
  95. BasicBlock& make_block(DeprecatedString name = {})
  96. {
  97. if (name.is_empty())
  98. name = DeprecatedString::number(m_next_block++);
  99. m_root_basic_blocks.append(BasicBlock::create(name));
  100. return *m_root_basic_blocks.last();
  101. }
  102. bool is_current_block_terminated() const
  103. {
  104. return m_current_basic_block->is_terminated();
  105. }
  106. StringTableIndex intern_string(DeprecatedString string)
  107. {
  108. return m_string_table->insert(move(string));
  109. }
  110. RegexTableIndex intern_regex(ParsedRegex regex)
  111. {
  112. return m_regex_table->insert(move(regex));
  113. }
  114. IdentifierTableIndex intern_identifier(DeprecatedFlyString string)
  115. {
  116. return m_identifier_table->insert(move(string));
  117. }
  118. 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; }
  119. bool is_in_generator_function() const { return m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  120. bool is_in_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  121. bool is_in_async_generator_function() const { return m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  122. enum class BindingMode {
  123. Lexical,
  124. Var,
  125. Global,
  126. };
  127. struct LexicalScope {
  128. SurroundingScopeKind kind;
  129. };
  130. void block_declaration_instantiation(ScopeNode const&);
  131. void begin_variable_scope();
  132. void end_variable_scope();
  133. enum class BlockBoundaryType {
  134. Break,
  135. Continue,
  136. Unwind,
  137. ReturnToFinally,
  138. LeaveLexicalEnvironment,
  139. };
  140. template<typename OpType>
  141. void perform_needed_unwinds()
  142. requires(OpType::IsTerminator && !IsSame<OpType, Op::Jump>)
  143. {
  144. for (size_t i = m_boundaries.size(); i > 0; --i) {
  145. auto boundary = m_boundaries[i - 1];
  146. using enum BlockBoundaryType;
  147. switch (boundary) {
  148. case Unwind:
  149. if constexpr (IsSame<OpType, Bytecode::Op::Throw>)
  150. return;
  151. emit<Bytecode::Op::LeaveUnwindContext>();
  152. break;
  153. case LeaveLexicalEnvironment:
  154. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  155. break;
  156. case Break:
  157. case Continue:
  158. break;
  159. case ReturnToFinally:
  160. return;
  161. };
  162. }
  163. }
  164. void generate_break();
  165. void generate_break(DeprecatedFlyString const& break_label);
  166. void generate_continue();
  167. void generate_continue(DeprecatedFlyString const& continue_label);
  168. void start_boundary(BlockBoundaryType type) { m_boundaries.append(type); }
  169. void end_boundary(BlockBoundaryType type)
  170. {
  171. VERIFY(m_boundaries.last() == type);
  172. m_boundaries.take_last();
  173. }
  174. void emit_get_by_id(IdentifierTableIndex);
  175. void emit_get_by_id_with_this(IdentifierTableIndex, Register);
  176. [[nodiscard]] size_t next_global_variable_cache() { return m_next_global_variable_cache++; }
  177. private:
  178. Generator();
  179. ~Generator() = default;
  180. void grow(size_t);
  181. void* next_slot();
  182. struct LabelableScope {
  183. Label bytecode_target;
  184. Vector<DeprecatedFlyString> language_label_set;
  185. };
  186. BasicBlock* m_current_basic_block { nullptr };
  187. Vector<NonnullOwnPtr<BasicBlock>> m_root_basic_blocks;
  188. NonnullOwnPtr<StringTable> m_string_table;
  189. NonnullOwnPtr<IdentifierTable> m_identifier_table;
  190. NonnullOwnPtr<RegexTable> m_regex_table;
  191. u32 m_next_register { 2 };
  192. u32 m_next_block { 1 };
  193. u32 m_next_property_lookup_cache { 0 };
  194. u32 m_next_global_variable_cache { 0 };
  195. FunctionKind m_enclosing_function_kind { FunctionKind::Normal };
  196. Vector<LabelableScope> m_continuable_scopes;
  197. Vector<LabelableScope> m_breakable_scopes;
  198. Vector<BlockBoundaryType> m_boundaries;
  199. Vector<Register> m_home_objects;
  200. };
  201. }