Interpreter.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. TemporaryChange restore_saved_jump { m_scheduled_jump, static_cast<BasicBlock const*>(nullptr) };
  40. TemporaryChange restore_saved_exception { m_saved_exception, {} };
  41. bool pushed_execution_context = false;
  42. ExecutionContext execution_context(vm().heap());
  43. if (vm().execution_context_stack().is_empty() || !vm().running_execution_context().lexical_environment) {
  44. // The "normal" interpreter pushes an execution context without environment so in that case we also want to push one.
  45. execution_context.this_value = &m_realm.global_object();
  46. static DeprecatedFlyString global_execution_context_name = "(*BC* global execution context)";
  47. execution_context.function_name = global_execution_context_name;
  48. execution_context.lexical_environment = &m_realm.global_environment();
  49. execution_context.variable_environment = &m_realm.global_environment();
  50. execution_context.realm = &m_realm;
  51. execution_context.is_strict_mode = executable.is_strict_mode;
  52. vm().push_execution_context(execution_context);
  53. pushed_execution_context = true;
  54. }
  55. TemporaryChange restore_current_block { m_current_block, entry_point ?: executable.basic_blocks.first() };
  56. if (in_frame)
  57. m_register_windows.append(in_frame);
  58. else
  59. m_register_windows.append(make<RegisterWindow>(MarkedVector<Value>(vm().heap()), MarkedVector<Environment*>(vm().heap()), MarkedVector<Environment*>(vm().heap()), Vector<UnwindInfo> {}));
  60. registers().resize(executable.number_of_registers);
  61. for (;;) {
  62. Bytecode::InstructionStreamIterator pc(m_current_block->instruction_stream());
  63. TemporaryChange temp_change { m_pc, &pc };
  64. // FIXME: This is getting kinda spaghetti-y
  65. bool will_jump = false;
  66. bool will_return = false;
  67. bool will_yield = false;
  68. while (!pc.at_end()) {
  69. auto& instruction = *pc;
  70. auto ran_or_error = instruction.execute(*this);
  71. if (ran_or_error.is_error()) {
  72. auto exception_value = *ran_or_error.throw_completion().value();
  73. m_saved_exception = make_handle(exception_value);
  74. if (unwind_contexts().is_empty())
  75. break;
  76. auto& unwind_context = unwind_contexts().last();
  77. if (unwind_context.executable != m_current_executable)
  78. break;
  79. if (unwind_context.handler) {
  80. m_current_block = unwind_context.handler;
  81. unwind_context.handler = nullptr;
  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. will_jump = true;
  90. break;
  91. }
  92. // 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.
  93. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  94. VERIFY_NOT_REACHED();
  95. }
  96. if (m_pending_jump.has_value()) {
  97. m_current_block = m_pending_jump.release_value();
  98. will_jump = true;
  99. break;
  100. }
  101. if (!m_return_value.is_empty()) {
  102. will_return = true;
  103. // Note: A `yield` statement will not go through a finally statement,
  104. // hence we need to set a flag to not do so,
  105. // but we generate a Yield Operation in the case of returns in
  106. // generators as well, so we need to check if it will actually
  107. // continue or is a `return` in disguise
  108. will_yield = instruction.type() == Instruction::Type::Yield && static_cast<Op::Yield const&>(instruction).continuation().has_value();
  109. break;
  110. }
  111. ++pc;
  112. }
  113. if (will_jump)
  114. continue;
  115. if (!unwind_contexts().is_empty() && !will_yield) {
  116. auto& unwind_context = unwind_contexts().last();
  117. if (unwind_context.executable == m_current_executable && unwind_context.finalizer) {
  118. m_saved_return_value = make_handle(m_return_value);
  119. m_return_value = {};
  120. m_current_block = unwind_context.finalizer;
  121. // the unwind_context will be pop'ed when entering the finally block
  122. continue;
  123. }
  124. }
  125. if (pc.at_end())
  126. break;
  127. if (!m_saved_exception.is_null())
  128. break;
  129. if (will_return)
  130. break;
  131. }
  132. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  133. if constexpr (JS_BYTECODE_DEBUG) {
  134. for (size_t i = 0; i < registers().size(); ++i) {
  135. String value_string;
  136. if (registers()[i].is_empty())
  137. value_string = MUST("(empty)"_string);
  138. else
  139. value_string = MUST(registers()[i].to_string_without_side_effects());
  140. dbgln("[{:3}] {}", i, value_string);
  141. }
  142. }
  143. auto frame = m_register_windows.take_last();
  144. Value return_value = js_undefined();
  145. if (!m_return_value.is_empty()) {
  146. return_value = m_return_value;
  147. m_return_value = {};
  148. } else if (!m_saved_return_value.is_null() && m_saved_exception.is_null()) {
  149. return_value = m_saved_return_value.value();
  150. m_saved_return_value = {};
  151. }
  152. // NOTE: The return value from a called function is put into $0 in the caller context.
  153. if (!m_register_windows.is_empty())
  154. window().registers[0] = return_value;
  155. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  156. // in which case this is a no-op.
  157. vm().run_queued_promise_jobs();
  158. if (pushed_execution_context) {
  159. VERIFY(&vm().running_execution_context() == &execution_context);
  160. vm().pop_execution_context();
  161. }
  162. vm().finish_execution_generation();
  163. if (!m_saved_exception.is_null()) {
  164. Value thrown_value = m_saved_exception.value();
  165. m_saved_exception = {};
  166. m_saved_return_value = {};
  167. if (auto* register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  168. return { throw_completion(thrown_value), move(*register_window) };
  169. return { throw_completion(thrown_value), nullptr };
  170. }
  171. if (auto* register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  172. return { return_value, move(*register_window) };
  173. return { return_value, nullptr };
  174. }
  175. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  176. {
  177. unwind_contexts().empend(m_current_executable, handler_target.has_value() ? &handler_target->block() : nullptr, finalizer_target.has_value() ? &finalizer_target->block() : nullptr);
  178. }
  179. void Interpreter::leave_unwind_context()
  180. {
  181. unwind_contexts().take_last();
  182. }
  183. ThrowCompletionOr<void> Interpreter::continue_pending_unwind(Label const& resume_label)
  184. {
  185. if (!m_saved_exception.is_null()) {
  186. auto result = throw_completion(m_saved_exception.value());
  187. m_saved_exception = {};
  188. return result;
  189. }
  190. if (!m_saved_return_value.is_null()) {
  191. do_return(m_saved_return_value.value());
  192. m_saved_return_value = {};
  193. return {};
  194. }
  195. if (m_scheduled_jump) {
  196. // FIXME: If we `break` or `continue` in the finally, we need to clear
  197. // this field
  198. jump(Label { *m_scheduled_jump });
  199. m_scheduled_jump = nullptr;
  200. } else {
  201. jump(resume_label);
  202. }
  203. return {};
  204. }
  205. VM::InterpreterExecutionScope Interpreter::ast_interpreter_scope()
  206. {
  207. if (!m_ast_interpreter)
  208. m_ast_interpreter = JS::Interpreter::create_with_existing_realm(m_realm);
  209. return { *m_ast_interpreter };
  210. }
  211. AK::Array<OwnPtr<PassManager>, static_cast<UnderlyingType<Interpreter::OptimizationLevel>>(Interpreter::OptimizationLevel::__Count)> Interpreter::s_optimization_pipelines {};
  212. Bytecode::PassManager& Interpreter::optimization_pipeline(Interpreter::OptimizationLevel level)
  213. {
  214. auto underlying_level = to_underlying(level);
  215. VERIFY(underlying_level <= to_underlying(Interpreter::OptimizationLevel::__Count));
  216. auto& entry = s_optimization_pipelines[underlying_level];
  217. if (entry)
  218. return *entry;
  219. auto pm = make<PassManager>();
  220. if (level == OptimizationLevel::None) {
  221. // No optimization.
  222. } else if (level == OptimizationLevel::Optimize) {
  223. pm->add<Passes::GenerateCFG>();
  224. pm->add<Passes::UnifySameBlocks>();
  225. pm->add<Passes::GenerateCFG>();
  226. pm->add<Passes::MergeBlocks>();
  227. pm->add<Passes::GenerateCFG>();
  228. pm->add<Passes::UnifySameBlocks>();
  229. pm->add<Passes::GenerateCFG>();
  230. pm->add<Passes::MergeBlocks>();
  231. pm->add<Passes::GenerateCFG>();
  232. pm->add<Passes::PlaceBlocks>();
  233. pm->add<Passes::EliminateLoads>();
  234. } else {
  235. VERIFY_NOT_REACHED();
  236. }
  237. auto& passes = *pm;
  238. entry = move(pm);
  239. return passes;
  240. }
  241. }