Interpreter.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/TemporaryChange.h>
  8. #include <LibJS/Bytecode/BasicBlock.h>
  9. #include <LibJS/Bytecode/Instruction.h>
  10. #include <LibJS/Bytecode/Interpreter.h>
  11. #include <LibJS/Bytecode/Op.h>
  12. #include <LibJS/Interpreter.h>
  13. #include <LibJS/Runtime/GlobalEnvironment.h>
  14. #include <LibJS/Runtime/GlobalObject.h>
  15. #include <LibJS/Runtime/Realm.h>
  16. namespace JS::Bytecode {
  17. static Interpreter* s_current;
  18. bool g_dump_bytecode = false;
  19. Interpreter* Interpreter::current()
  20. {
  21. return s_current;
  22. }
  23. Interpreter::Interpreter(Realm& realm)
  24. : m_vm(realm.vm())
  25. , m_realm(realm)
  26. {
  27. VERIFY(!s_current);
  28. s_current = this;
  29. }
  30. Interpreter::~Interpreter()
  31. {
  32. VERIFY(s_current == this);
  33. s_current = nullptr;
  34. }
  35. Interpreter::ValueAndFrame Interpreter::run_and_return_frame(Executable const& executable, BasicBlock const* entry_point, RegisterWindow* in_frame)
  36. {
  37. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  38. TemporaryChange restore_executable { m_current_executable, &executable };
  39. VERIFY(m_saved_exception.is_null());
  40. bool pushed_execution_context = false;
  41. ExecutionContext execution_context(vm().heap());
  42. if (vm().execution_context_stack().is_empty() || !vm().running_execution_context().lexical_environment) {
  43. // The "normal" interpreter pushes an execution context without environment so in that case we also want to push one.
  44. execution_context.this_value = &m_realm.global_object();
  45. static FlyString global_execution_context_name = "(*BC* global execution context)";
  46. execution_context.function_name = global_execution_context_name;
  47. execution_context.lexical_environment = &m_realm.global_environment();
  48. execution_context.variable_environment = &m_realm.global_environment();
  49. execution_context.realm = &m_realm;
  50. execution_context.is_strict_mode = executable.is_strict_mode;
  51. vm().push_execution_context(execution_context);
  52. pushed_execution_context = true;
  53. }
  54. m_current_block = entry_point ?: &executable.basic_blocks.first();
  55. if (in_frame)
  56. m_register_windows.append(in_frame);
  57. else
  58. m_register_windows.append(make<RegisterWindow>(MarkedVector<Value>(vm().heap()), MarkedVector<Environment*>(vm().heap()), MarkedVector<Environment*>(vm().heap())));
  59. registers().resize(executable.number_of_registers);
  60. for (;;) {
  61. Bytecode::InstructionStreamIterator pc(m_current_block->instruction_stream());
  62. TemporaryChange temp_change { m_pc, &pc };
  63. bool will_jump = false;
  64. bool will_return = false;
  65. while (!pc.at_end()) {
  66. auto& instruction = *pc;
  67. auto ran_or_error = instruction.execute(*this);
  68. if (ran_or_error.is_error()) {
  69. auto exception_value = *ran_or_error.throw_completion().value();
  70. m_saved_exception = make_handle(exception_value);
  71. if (m_unwind_contexts.is_empty())
  72. break;
  73. auto& unwind_context = m_unwind_contexts.last();
  74. if (unwind_context.executable != m_current_executable)
  75. break;
  76. if (unwind_context.handler) {
  77. m_current_block = unwind_context.handler;
  78. unwind_context.handler = nullptr;
  79. // If there's no finalizer, there's nowhere for the handler block to unwind to, so the unwind context is no longer needed.
  80. if (!unwind_context.finalizer)
  81. m_unwind_contexts.take_last();
  82. accumulator() = exception_value;
  83. m_saved_exception = {};
  84. will_jump = true;
  85. break;
  86. }
  87. if (unwind_context.finalizer) {
  88. m_current_block = unwind_context.finalizer;
  89. m_unwind_contexts.take_last();
  90. will_jump = true;
  91. break;
  92. }
  93. // An unwind context with no handler or finalizer? We have nowhere to jump, and continuing on will make us crash on the next `Call` to a non-native function if there's an exception! So let's crash here instead.
  94. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  95. VERIFY_NOT_REACHED();
  96. }
  97. if (m_pending_jump.has_value()) {
  98. m_current_block = m_pending_jump.release_value();
  99. will_jump = true;
  100. break;
  101. }
  102. if (!m_return_value.is_empty()) {
  103. will_return = true;
  104. break;
  105. }
  106. ++pc;
  107. }
  108. if (will_return)
  109. break;
  110. if (pc.at_end() && !will_jump)
  111. break;
  112. if (!m_saved_exception.is_null())
  113. break;
  114. }
  115. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  116. if constexpr (JS_BYTECODE_DEBUG) {
  117. for (size_t i = 0; i < registers().size(); ++i) {
  118. String value_string;
  119. if (registers()[i].is_empty())
  120. value_string = "(empty)";
  121. else
  122. value_string = registers()[i].to_string_without_side_effects();
  123. dbgln("[{:3}] {}", i, value_string);
  124. }
  125. }
  126. auto frame = m_register_windows.take_last();
  127. auto return_value = m_return_value.value_or(js_undefined());
  128. m_return_value = {};
  129. // NOTE: The return value from a called function is put into $0 in the caller context.
  130. if (!m_register_windows.is_empty())
  131. window().registers[0] = return_value;
  132. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  133. // in which case this is a no-op.
  134. vm().run_queued_promise_jobs();
  135. if (pushed_execution_context) {
  136. VERIFY(&vm().running_execution_context() == &execution_context);
  137. vm().pop_execution_context();
  138. }
  139. vm().finish_execution_generation();
  140. if (!m_saved_exception.is_null()) {
  141. Value thrown_value = m_saved_exception.value();
  142. m_saved_exception = {};
  143. if (auto* register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  144. return { throw_completion(thrown_value), move(*register_window) };
  145. return { throw_completion(thrown_value), nullptr };
  146. }
  147. if (auto register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  148. return { return_value, move(*register_window) };
  149. return { return_value, nullptr };
  150. }
  151. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  152. {
  153. m_unwind_contexts.empend(m_current_executable, handler_target.has_value() ? &handler_target->block() : nullptr, finalizer_target.has_value() ? &finalizer_target->block() : nullptr);
  154. }
  155. void Interpreter::leave_unwind_context()
  156. {
  157. m_unwind_contexts.take_last();
  158. }
  159. ThrowCompletionOr<void> Interpreter::continue_pending_unwind(Label const& resume_label)
  160. {
  161. if (!m_saved_exception.is_null()) {
  162. auto result = throw_completion(m_saved_exception.value());
  163. m_saved_exception = {};
  164. return result;
  165. }
  166. jump(resume_label);
  167. return {};
  168. }
  169. VM::InterpreterExecutionScope Interpreter::ast_interpreter_scope()
  170. {
  171. if (!m_ast_interpreter)
  172. m_ast_interpreter = JS::Interpreter::create_with_existing_realm(m_realm);
  173. return { *m_ast_interpreter };
  174. }
  175. AK::Array<OwnPtr<PassManager>, static_cast<UnderlyingType<Interpreter::OptimizationLevel>>(Interpreter::OptimizationLevel::__Count)> Interpreter::s_optimization_pipelines {};
  176. Bytecode::PassManager& Interpreter::optimization_pipeline(Interpreter::OptimizationLevel level)
  177. {
  178. auto underlying_level = to_underlying(level);
  179. VERIFY(underlying_level <= to_underlying(Interpreter::OptimizationLevel::__Count));
  180. auto& entry = s_optimization_pipelines[underlying_level];
  181. if (entry)
  182. return *entry;
  183. auto pm = make<PassManager>();
  184. if (level == OptimizationLevel::None) {
  185. // No optimization.
  186. } else if (level == OptimizationLevel::Optimize) {
  187. pm->add<Passes::GenerateCFG>();
  188. pm->add<Passes::UnifySameBlocks>();
  189. pm->add<Passes::GenerateCFG>();
  190. pm->add<Passes::MergeBlocks>();
  191. pm->add<Passes::GenerateCFG>();
  192. pm->add<Passes::UnifySameBlocks>();
  193. pm->add<Passes::GenerateCFG>();
  194. pm->add<Passes::MergeBlocks>();
  195. pm->add<Passes::GenerateCFG>();
  196. pm->add<Passes::PlaceBlocks>();
  197. } else {
  198. VERIFY_NOT_REACHED();
  199. }
  200. auto& passes = *pm;
  201. entry = move(pm);
  202. return passes;
  203. }
  204. }