Generator.h 8.5 KB

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