Generator.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/AST.h>
  7. #include <LibJS/Bytecode/BasicBlock.h>
  8. #include <LibJS/Bytecode/Generator.h>
  9. #include <LibJS/Bytecode/Instruction.h>
  10. #include <LibJS/Bytecode/Op.h>
  11. #include <LibJS/Bytecode/Register.h>
  12. #include <LibJS/Forward.h>
  13. namespace JS::Bytecode {
  14. Generator::Generator()
  15. : m_string_table(make<StringTable>())
  16. {
  17. }
  18. Generator::~Generator()
  19. {
  20. }
  21. Executable Generator::generate(ASTNode const& node, bool is_in_generator_function)
  22. {
  23. Generator generator;
  24. generator.switch_to_basic_block(generator.make_block());
  25. if (is_in_generator_function) {
  26. generator.enter_generator_context();
  27. // Immediately yield with no value.
  28. auto& start_block = generator.make_block();
  29. generator.emit<Bytecode::Op::Yield>(Label { start_block });
  30. generator.switch_to_basic_block(start_block);
  31. }
  32. node.generate_bytecode(generator);
  33. if (is_in_generator_function) {
  34. // Terminate all unterminated blocks with yield return
  35. for (auto& block : generator.m_root_basic_blocks) {
  36. if (block.is_terminated())
  37. continue;
  38. generator.switch_to_basic_block(block);
  39. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  40. generator.emit<Bytecode::Op::Yield>(nullptr);
  41. }
  42. }
  43. return { move(generator.m_root_basic_blocks), move(generator.m_string_table), generator.m_next_register };
  44. }
  45. void Generator::grow(size_t additional_size)
  46. {
  47. VERIFY(m_current_basic_block);
  48. m_current_basic_block->grow(additional_size);
  49. }
  50. void* Generator::next_slot()
  51. {
  52. VERIFY(m_current_basic_block);
  53. return m_current_basic_block->next_slot();
  54. }
  55. Register Generator::allocate_register()
  56. {
  57. VERIFY(m_next_register != NumericLimits<u32>::max());
  58. return Register { m_next_register++ };
  59. }
  60. Label Generator::nearest_continuable_scope() const
  61. {
  62. return m_continuable_scopes.last();
  63. }
  64. void Generator::begin_continuable_scope(Label continue_target)
  65. {
  66. m_continuable_scopes.append(continue_target);
  67. }
  68. void Generator::end_continuable_scope()
  69. {
  70. m_continuable_scopes.take_last();
  71. }
  72. Label Generator::nearest_breakable_scope() const
  73. {
  74. return m_breakable_scopes.last();
  75. }
  76. void Generator::begin_breakable_scope(Label breakable_target)
  77. {
  78. m_breakable_scopes.append(breakable_target);
  79. }
  80. void Generator::end_breakable_scope()
  81. {
  82. m_breakable_scopes.take_last();
  83. }
  84. }