Generator.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * Copyright (c) 2021-2024, 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<NonnullGCPtr<Executable>> generate(VM&, ASTNode const&, ReadonlySpan<FunctionParameter> parameters, FunctionKind = FunctionKind::Normal);
  30. Register allocate_register();
  31. void set_local_initialized(u32 local_index);
  32. [[nodiscard]] bool is_local_initialized(u32 local_index) const;
  33. class SourceLocationScope {
  34. public:
  35. SourceLocationScope(Generator&, ASTNode const& node);
  36. ~SourceLocationScope();
  37. private:
  38. Generator& m_generator;
  39. ASTNode const* m_previous_node { nullptr };
  40. };
  41. class UnwindContext {
  42. public:
  43. UnwindContext(Generator&, Optional<Label> finalizer);
  44. UnwindContext const* previous() const { return m_previous_context; }
  45. void set_handler(Label handler) { m_handler = handler; }
  46. Optional<Label> handler() const { return m_handler; }
  47. Optional<Label> finalizer() const { return m_finalizer; }
  48. ~UnwindContext();
  49. private:
  50. Generator& m_generator;
  51. Optional<Label> m_finalizer;
  52. Optional<Label> m_handler {};
  53. UnwindContext const* m_previous_context { nullptr };
  54. };
  55. template<typename OpType, typename... Args>
  56. void emit(Args&&... args)
  57. {
  58. VERIFY(!is_current_block_terminated());
  59. size_t slot_offset = m_current_basic_block->size();
  60. grow(sizeof(OpType));
  61. void* slot = m_current_basic_block->data() + slot_offset;
  62. new (slot) OpType(forward<Args>(args)...);
  63. if constexpr (OpType::IsTerminator)
  64. m_current_basic_block->terminate({});
  65. auto* op = static_cast<OpType*>(slot);
  66. op->set_source_record({ m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  67. }
  68. template<typename OpType, typename... Args>
  69. void emit_with_extra_operand_slots(size_t extra_operand_slots, Args&&... args)
  70. {
  71. VERIFY(!is_current_block_terminated());
  72. size_t size_to_allocate = round_up_to_power_of_two(sizeof(OpType) + extra_operand_slots * sizeof(Operand), alignof(void*));
  73. size_t slot_offset = m_current_basic_block->size();
  74. grow(size_to_allocate);
  75. void* slot = m_current_basic_block->data() + slot_offset;
  76. new (slot) OpType(forward<Args>(args)...);
  77. if constexpr (OpType::IsTerminator)
  78. m_current_basic_block->terminate({});
  79. auto* op = static_cast<OpType*>(slot);
  80. op->set_source_record({ m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  81. }
  82. struct ReferenceOperands {
  83. Optional<Operand> base {}; // [[Base]]
  84. Optional<Operand> referenced_name {}; // [[ReferencedName]] as an operand
  85. Optional<IdentifierTableIndex> referenced_identifier {}; // [[ReferencedName]] as an identifier
  86. Optional<IdentifierTableIndex> referenced_private_identifier {}; // [[ReferencedName]] as a private identifier
  87. Optional<Operand> this_value {}; // [[ThisValue]]
  88. Optional<Operand> loaded_value {}; // Loaded value, if we've performed a load.
  89. };
  90. CodeGenerationErrorOr<ReferenceOperands> emit_load_from_reference(JS::ASTNode const&, Optional<Operand> preferred_dst = {});
  91. CodeGenerationErrorOr<void> emit_store_to_reference(JS::ASTNode const&, Operand value);
  92. CodeGenerationErrorOr<void> emit_store_to_reference(ReferenceOperands const&, Operand value);
  93. CodeGenerationErrorOr<Optional<Operand>> emit_delete_reference(JS::ASTNode const&);
  94. CodeGenerationErrorOr<ReferenceOperands> emit_super_reference(MemberExpression const&);
  95. void emit_set_variable(JS::Identifier const& identifier, Operand value, Bytecode::Op::SetVariable::InitializationMode initialization_mode = Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode mode = Bytecode::Op::EnvironmentMode::Lexical);
  96. void push_home_object(Operand);
  97. void pop_home_object();
  98. void emit_new_function(Operand dst, JS::FunctionExpression const&, Optional<IdentifierTableIndex> lhs_name);
  99. CodeGenerationErrorOr<Optional<Operand>> emit_named_evaluation_if_anonymous_function(Expression const&, Optional<IdentifierTableIndex> lhs_name, Optional<Operand> preferred_dst = {});
  100. void begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set);
  101. void end_continuable_scope();
  102. void begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set);
  103. void end_breakable_scope();
  104. [[nodiscard]] Label nearest_continuable_scope() const;
  105. [[nodiscard]] Label nearest_breakable_scope() const;
  106. void switch_to_basic_block(BasicBlock& block)
  107. {
  108. m_current_basic_block = &block;
  109. }
  110. [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; }
  111. BasicBlock& make_block(String name = {})
  112. {
  113. if (name.is_empty())
  114. name = MUST(String::number(m_next_block++));
  115. auto block = BasicBlock::create(name);
  116. if (auto const* context = m_current_unwind_context) {
  117. if (context->handler().has_value())
  118. block->set_handler(context->handler().value().block());
  119. if (m_current_unwind_context->finalizer().has_value())
  120. block->set_finalizer(context->finalizer().value().block());
  121. }
  122. m_root_basic_blocks.append(move(block));
  123. return *m_root_basic_blocks.last();
  124. }
  125. bool is_current_block_terminated() const
  126. {
  127. return m_current_basic_block->is_terminated();
  128. }
  129. StringTableIndex intern_string(ByteString string)
  130. {
  131. return m_string_table->insert(move(string));
  132. }
  133. RegexTableIndex intern_regex(ParsedRegex regex)
  134. {
  135. return m_regex_table->insert(move(regex));
  136. }
  137. IdentifierTableIndex intern_identifier(DeprecatedFlyString string)
  138. {
  139. return m_identifier_table->insert(move(string));
  140. }
  141. 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; }
  142. bool is_in_generator_function() const { return m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  143. bool is_in_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  144. bool is_in_async_generator_function() const { return m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  145. enum class BindingMode {
  146. Lexical,
  147. Var,
  148. Global,
  149. };
  150. struct LexicalScope {
  151. SurroundingScopeKind kind;
  152. };
  153. void block_declaration_instantiation(ScopeNode const&);
  154. void begin_variable_scope();
  155. void end_variable_scope();
  156. enum class BlockBoundaryType {
  157. Break,
  158. Continue,
  159. Unwind,
  160. ReturnToFinally,
  161. LeaveLexicalEnvironment,
  162. };
  163. template<typename OpType>
  164. void perform_needed_unwinds()
  165. requires(OpType::IsTerminator && !IsSame<OpType, Op::Jump>)
  166. {
  167. for (size_t i = m_boundaries.size(); i > 0; --i) {
  168. auto boundary = m_boundaries[i - 1];
  169. using enum BlockBoundaryType;
  170. switch (boundary) {
  171. case Unwind:
  172. if constexpr (IsSame<OpType, Bytecode::Op::Throw>)
  173. return;
  174. emit<Bytecode::Op::LeaveUnwindContext>();
  175. break;
  176. case LeaveLexicalEnvironment:
  177. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  178. break;
  179. case Break:
  180. case Continue:
  181. break;
  182. case ReturnToFinally:
  183. return;
  184. };
  185. }
  186. }
  187. void generate_break();
  188. void generate_break(DeprecatedFlyString const& break_label);
  189. void generate_continue();
  190. void generate_continue(DeprecatedFlyString const& continue_label);
  191. void start_boundary(BlockBoundaryType type) { m_boundaries.append(type); }
  192. void end_boundary(BlockBoundaryType type)
  193. {
  194. VERIFY(m_boundaries.last() == type);
  195. m_boundaries.take_last();
  196. }
  197. void emit_get_by_id(Operand dst, Operand base, IdentifierTableIndex);
  198. void emit_get_by_id_with_this(Operand dst, Operand base, IdentifierTableIndex, Operand this_value);
  199. void emit_iterator_value(Operand dst, Operand result);
  200. void emit_iterator_complete(Operand dst, Operand result);
  201. [[nodiscard]] size_t next_global_variable_cache() { return m_next_global_variable_cache++; }
  202. [[nodiscard]] size_t next_environment_variable_cache() { return m_next_environment_variable_cache++; }
  203. [[nodiscard]] size_t next_property_lookup_cache() { return m_next_property_lookup_cache++; }
  204. enum class DeduplicateConstant {
  205. Yes,
  206. No,
  207. };
  208. [[nodiscard]] Operand add_constant(Value value, DeduplicateConstant deduplicate_constant = DeduplicateConstant::Yes)
  209. {
  210. if (deduplicate_constant == DeduplicateConstant::Yes) {
  211. for (size_t i = 0; i < m_constants.size(); ++i) {
  212. if (m_constants[i] == value)
  213. return Operand(Operand::Type::Constant, i);
  214. }
  215. }
  216. m_constants.append(value);
  217. return Operand(Operand::Type::Constant, m_constants.size() - 1);
  218. }
  219. private:
  220. enum class JumpType {
  221. Continue,
  222. Break,
  223. };
  224. void generate_scoped_jump(JumpType);
  225. void generate_labelled_jump(JumpType, DeprecatedFlyString const& label);
  226. Generator();
  227. ~Generator() = default;
  228. void grow(size_t);
  229. struct LabelableScope {
  230. Label bytecode_target;
  231. Vector<DeprecatedFlyString> language_label_set;
  232. };
  233. BasicBlock* m_current_basic_block { nullptr };
  234. ASTNode const* m_current_ast_node { nullptr };
  235. UnwindContext const* m_current_unwind_context { nullptr };
  236. Vector<NonnullOwnPtr<BasicBlock>> m_root_basic_blocks;
  237. NonnullOwnPtr<StringTable> m_string_table;
  238. NonnullOwnPtr<IdentifierTable> m_identifier_table;
  239. NonnullOwnPtr<RegexTable> m_regex_table;
  240. Vector<Value> m_constants;
  241. u32 m_next_register { Register::reserved_register_count };
  242. u32 m_next_block { 1 };
  243. u32 m_next_property_lookup_cache { 0 };
  244. u32 m_next_global_variable_cache { 0 };
  245. u32 m_next_environment_variable_cache { 0 };
  246. FunctionKind m_enclosing_function_kind { FunctionKind::Normal };
  247. Vector<LabelableScope> m_continuable_scopes;
  248. Vector<LabelableScope> m_breakable_scopes;
  249. Vector<BlockBoundaryType> m_boundaries;
  250. Vector<Operand> m_home_objects;
  251. HashTable<u32> m_initialized_locals;
  252. };
  253. }