Generator.h 8.7 KB

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