Generator.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. /*
  2. * Copyright (c) 2021-2024, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/TemporaryChange.h>
  8. #include <LibJS/AST.h>
  9. #include <LibJS/Bytecode/BasicBlock.h>
  10. #include <LibJS/Bytecode/Generator.h>
  11. #include <LibJS/Bytecode/Instruction.h>
  12. #include <LibJS/Bytecode/Op.h>
  13. #include <LibJS/Bytecode/Register.h>
  14. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  15. #include <LibJS/Runtime/VM.h>
  16. namespace JS::Bytecode {
  17. Generator::Generator(VM& vm, MustPropagateCompletion must_propagate_completion)
  18. : m_vm(vm)
  19. , m_string_table(make<StringTable>())
  20. , m_identifier_table(make<IdentifierTable>())
  21. , m_regex_table(make<RegexTable>())
  22. , m_constants(vm.heap())
  23. , m_accumulator(*this, Operand(Register::accumulator()))
  24. , m_must_propagate_completion(must_propagate_completion == MustPropagateCompletion::Yes)
  25. {
  26. }
  27. CodeGenerationErrorOr<void> Generator::emit_function_declaration_instantiation(ECMAScriptFunctionObject const& function)
  28. {
  29. if (function.m_has_parameter_expressions) {
  30. emit<Op::CreateLexicalEnvironment>();
  31. }
  32. for (auto const& parameter_name : function.m_parameter_names) {
  33. if (parameter_name.value == ECMAScriptFunctionObject::ParameterIsLocal::No) {
  34. auto id = intern_identifier(parameter_name.key);
  35. emit<Op::CreateVariable>(id, Op::EnvironmentMode::Lexical, false);
  36. if (function.m_has_duplicates) {
  37. emit<Op::InitializeLexicalBinding>(id, add_constant(js_undefined()));
  38. }
  39. }
  40. }
  41. if (function.m_arguments_object_needed) {
  42. if (function.m_strict || !function.has_simple_parameter_list()) {
  43. emit<Op::CreateArguments>(Op::CreateArguments::Kind::Unmapped, function.m_strict);
  44. } else {
  45. emit<Op::CreateArguments>(Op::CreateArguments::Kind::Mapped, function.m_strict);
  46. }
  47. }
  48. auto const& formal_parameters = function.formal_parameters();
  49. for (u32 param_index = 0; param_index < formal_parameters.size(); ++param_index) {
  50. auto const& parameter = formal_parameters[param_index];
  51. if (parameter.is_rest) {
  52. auto argument_reg = allocate_register();
  53. emit<Op::CreateRestParams>(argument_reg.operand(), param_index);
  54. emit<Op::SetArgument>(param_index, argument_reg.operand());
  55. } else if (parameter.default_value) {
  56. auto& if_undefined_block = make_block();
  57. auto& if_not_undefined_block = make_block();
  58. auto argument_reg = allocate_register();
  59. emit<Op::GetArgument>(argument_reg.operand(), param_index);
  60. emit<Op::JumpUndefined>(
  61. argument_reg.operand(),
  62. Label { if_undefined_block },
  63. Label { if_not_undefined_block });
  64. switch_to_basic_block(if_undefined_block);
  65. auto operand = TRY(parameter.default_value->generate_bytecode(*this));
  66. emit<Op::SetArgument>(param_index, *operand);
  67. emit<Op::Jump>(Label { if_not_undefined_block });
  68. switch_to_basic_block(if_not_undefined_block);
  69. }
  70. if (auto const* identifier = parameter.binding.get_pointer<NonnullRefPtr<Identifier const>>(); identifier) {
  71. if ((*identifier)->is_local()) {
  72. auto local_variable_index = (*identifier)->local_variable_index();
  73. emit<Op::GetArgument>(local(local_variable_index), param_index);
  74. set_local_initialized((*identifier)->local_variable_index());
  75. } else {
  76. auto id = intern_identifier((*identifier)->string());
  77. auto argument_reg = allocate_register();
  78. emit<Op::GetArgument>(argument_reg.operand(), param_index);
  79. if (function.m_has_duplicates) {
  80. emit<Op::SetLexicalBinding>(id, argument_reg.operand());
  81. } else {
  82. emit<Op::InitializeLexicalBinding>(id, argument_reg.operand());
  83. }
  84. }
  85. } else if (auto const* binding_pattern = parameter.binding.get_pointer<NonnullRefPtr<BindingPattern const>>(); binding_pattern) {
  86. auto input_operand = allocate_register();
  87. emit<Op::GetArgument>(input_operand.operand(), param_index);
  88. auto init_mode = function.m_has_duplicates ? Op::BindingInitializationMode::Set : Bytecode::Op::BindingInitializationMode::Initialize;
  89. TRY((*binding_pattern)->generate_bytecode(*this, init_mode, input_operand, false));
  90. }
  91. }
  92. ScopeNode const* scope_body = nullptr;
  93. if (is<ScopeNode>(*function.m_ecmascript_code))
  94. scope_body = static_cast<ScopeNode const*>(function.m_ecmascript_code.ptr());
  95. if (!function.m_has_parameter_expressions) {
  96. if (scope_body) {
  97. for (auto const& variable_to_initialize : function.m_var_names_to_initialize_binding) {
  98. auto const& id = variable_to_initialize.identifier;
  99. if (id.is_local()) {
  100. emit<Op::Mov>(local(id.local_variable_index()), add_constant(js_undefined()));
  101. } else {
  102. auto intern_id = intern_identifier(id.string());
  103. emit<Op::CreateVariable>(intern_id, Op::EnvironmentMode::Var, false);
  104. emit<Op::InitializeVariableBinding>(intern_id, add_constant(js_undefined()));
  105. }
  106. }
  107. }
  108. } else {
  109. emit<Op::CreateVariableEnvironment>(function.m_var_environment_bindings_count);
  110. if (scope_body) {
  111. for (auto const& variable_to_initialize : function.m_var_names_to_initialize_binding) {
  112. auto const& id = variable_to_initialize.identifier;
  113. auto initial_value = allocate_register();
  114. if (!variable_to_initialize.parameter_binding || variable_to_initialize.function_name) {
  115. emit<Op::Mov>(initial_value, add_constant(js_undefined()));
  116. } else {
  117. if (id.is_local()) {
  118. emit<Op::Mov>(initial_value, local(id.local_variable_index()));
  119. } else {
  120. emit<Op::GetBinding>(initial_value, intern_identifier(id.string()));
  121. }
  122. }
  123. if (id.is_local()) {
  124. emit<Op::Mov>(local(id.local_variable_index()), initial_value);
  125. } else {
  126. auto intern_id = intern_identifier(id.string());
  127. emit<Op::CreateVariable>(intern_id, Op::EnvironmentMode::Var, false);
  128. emit<Op::InitializeVariableBinding>(intern_id, initial_value);
  129. }
  130. }
  131. }
  132. }
  133. if (!function.m_strict && scope_body) {
  134. for (auto const& function_name : function.m_function_names_to_initialize_binding) {
  135. auto intern_id = intern_identifier(function_name);
  136. emit<Op::CreateVariable>(intern_id, Op::EnvironmentMode::Var, false);
  137. emit<Op::InitializeVariableBinding>(intern_id, add_constant(js_undefined()));
  138. }
  139. }
  140. if (!function.m_strict) {
  141. bool can_elide_declarative_environment = !function.m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_non_local_lexical_declarations());
  142. if (!can_elide_declarative_environment) {
  143. emit<Op::CreateLexicalEnvironment>(function.m_lex_environment_bindings_count);
  144. }
  145. }
  146. if (scope_body) {
  147. MUST(scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  148. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  149. if (id.is_local()) {
  150. return;
  151. }
  152. emit<Op::CreateVariable>(intern_identifier(id.string()),
  153. Op::EnvironmentMode::Lexical,
  154. declaration.is_constant_declaration(),
  155. false,
  156. declaration.is_constant_declaration());
  157. }));
  158. }));
  159. }
  160. for (auto const& declaration : function.m_functions_to_initialize) {
  161. auto function = allocate_register();
  162. emit<Op::NewFunction>(function, declaration, OptionalNone {});
  163. if (declaration.name_identifier()->is_local()) {
  164. emit<Op::Mov>(local(declaration.name_identifier()->local_variable_index()), function);
  165. } else {
  166. emit<Op::SetVariableBinding>(intern_identifier(declaration.name()), function);
  167. }
  168. }
  169. return {};
  170. }
  171. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::emit_function_body_bytecode(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind, GCPtr<ECMAScriptFunctionObject const> function, MustPropagateCompletion must_propagate_completion)
  172. {
  173. Generator generator(vm, must_propagate_completion);
  174. generator.switch_to_basic_block(generator.make_block());
  175. SourceLocationScope scope(generator, node);
  176. generator.m_enclosing_function_kind = enclosing_function_kind;
  177. if (generator.is_in_async_function() && !generator.is_in_generator_function()) {
  178. // Immediately yield with no value.
  179. auto& start_block = generator.make_block();
  180. generator.emit<Bytecode::Op::Yield>(Label { start_block }, generator.add_constant(js_undefined()));
  181. generator.switch_to_basic_block(start_block);
  182. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  183. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  184. }
  185. if (function)
  186. TRY(generator.emit_function_declaration_instantiation(*function));
  187. if (generator.is_in_generator_function()) {
  188. // Immediately yield with no value.
  189. auto& start_block = generator.make_block();
  190. generator.emit<Bytecode::Op::Yield>(Label { start_block }, generator.add_constant(js_undefined()));
  191. generator.switch_to_basic_block(start_block);
  192. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  193. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  194. }
  195. auto last_value = TRY(node.generate_bytecode(generator));
  196. if (!generator.current_block().is_terminated() && last_value.has_value()) {
  197. generator.emit<Bytecode::Op::End>(last_value.value());
  198. }
  199. if (generator.is_in_generator_or_async_function()) {
  200. // Terminate all unterminated blocks with yield return
  201. for (auto& block : generator.m_root_basic_blocks) {
  202. if (block->is_terminated())
  203. continue;
  204. generator.switch_to_basic_block(*block);
  205. generator.emit_return<Bytecode::Op::Yield>(generator.add_constant(js_undefined()));
  206. }
  207. }
  208. bool is_strict_mode = false;
  209. if (is<Program>(node))
  210. is_strict_mode = static_cast<Program const&>(node).is_strict_mode();
  211. else if (is<FunctionBody>(node))
  212. is_strict_mode = static_cast<FunctionBody const&>(node).in_strict_mode();
  213. else if (is<FunctionDeclaration>(node))
  214. is_strict_mode = static_cast<FunctionDeclaration const&>(node).is_strict_mode();
  215. size_t size_needed = 0;
  216. for (auto& block : generator.m_root_basic_blocks) {
  217. size_needed += block->size();
  218. }
  219. Vector<u8> bytecode;
  220. bytecode.ensure_capacity(size_needed);
  221. Vector<size_t> basic_block_start_offsets;
  222. basic_block_start_offsets.ensure_capacity(generator.m_root_basic_blocks.size());
  223. HashMap<BasicBlock const*, size_t> block_offsets;
  224. Vector<size_t> label_offsets;
  225. struct UnlinkedExceptionHandlers {
  226. size_t start_offset;
  227. size_t end_offset;
  228. BasicBlock const* handler;
  229. BasicBlock const* finalizer;
  230. };
  231. Vector<UnlinkedExceptionHandlers> unlinked_exception_handlers;
  232. HashMap<size_t, SourceRecord> source_map;
  233. for (auto& block : generator.m_root_basic_blocks) {
  234. if (!block->is_terminated()) {
  235. // NOTE: We must ensure that the "undefined" constant, which will be used by the not yet
  236. // emitted End instruction, is taken into account while shifting local operands by the
  237. // number of constants.
  238. (void)generator.add_constant(js_undefined());
  239. break;
  240. }
  241. }
  242. auto number_of_registers = generator.m_next_register;
  243. auto number_of_constants = generator.m_constants.size();
  244. for (auto& block : generator.m_root_basic_blocks) {
  245. basic_block_start_offsets.append(bytecode.size());
  246. if (block->handler() || block->finalizer()) {
  247. unlinked_exception_handlers.append({
  248. .start_offset = bytecode.size(),
  249. .end_offset = 0,
  250. .handler = block->handler(),
  251. .finalizer = block->finalizer(),
  252. });
  253. }
  254. block_offsets.set(block.ptr(), bytecode.size());
  255. for (auto& [offset, source_record] : block->source_map()) {
  256. source_map.set(bytecode.size() + offset, source_record);
  257. }
  258. Bytecode::InstructionStreamIterator it(block->instruction_stream());
  259. while (!it.at_end()) {
  260. auto& instruction = const_cast<Instruction&>(*it);
  261. instruction.visit_operands([number_of_registers, number_of_constants](Operand& operand) {
  262. switch (operand.type()) {
  263. case Operand::Type::Register:
  264. break;
  265. case Operand::Type::Local:
  266. operand.offset_index_by(number_of_registers + number_of_constants);
  267. break;
  268. case Operand::Type::Constant:
  269. operand.offset_index_by(number_of_registers);
  270. break;
  271. default:
  272. VERIFY_NOT_REACHED();
  273. }
  274. });
  275. // OPTIMIZATION: Don't emit jumps that just jump to the next block.
  276. if (instruction.type() == Instruction::Type::Jump) {
  277. auto& jump = static_cast<Bytecode::Op::Jump&>(instruction);
  278. if (jump.target().basic_block_index() == block->index() + 1) {
  279. if (basic_block_start_offsets.last() == bytecode.size()) {
  280. // This block is empty, just skip it.
  281. basic_block_start_offsets.take_last();
  282. }
  283. ++it;
  284. continue;
  285. }
  286. }
  287. // OPTIMIZATION: For `JumpIf` where one of the targets is the very next block,
  288. // we can emit a `JumpTrue` or `JumpFalse` (to the other block) instead.
  289. if (instruction.type() == Instruction::Type::JumpIf) {
  290. auto& jump = static_cast<Bytecode::Op::JumpIf&>(instruction);
  291. if (jump.true_target().basic_block_index() == block->index() + 1) {
  292. Op::JumpFalse jump_false(jump.condition(), Label { jump.false_target() });
  293. auto& label = jump_false.target();
  294. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&jump_false));
  295. label_offsets.append(label_offset);
  296. bytecode.append(reinterpret_cast<u8 const*>(&jump_false), jump_false.length());
  297. ++it;
  298. continue;
  299. }
  300. if (jump.false_target().basic_block_index() == block->index() + 1) {
  301. Op::JumpTrue jump_true(jump.condition(), Label { jump.true_target() });
  302. auto& label = jump_true.target();
  303. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&jump_true));
  304. label_offsets.append(label_offset);
  305. bytecode.append(reinterpret_cast<u8 const*>(&jump_true), jump_true.length());
  306. ++it;
  307. continue;
  308. }
  309. }
  310. instruction.visit_labels([&](Label& label) {
  311. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&instruction));
  312. label_offsets.append(label_offset);
  313. });
  314. bytecode.append(reinterpret_cast<u8 const*>(&instruction), instruction.length());
  315. ++it;
  316. }
  317. if (!block->is_terminated()) {
  318. Op::End end(generator.add_constant(js_undefined()));
  319. end.visit_operands([number_of_registers, number_of_constants](Operand& operand) {
  320. switch (operand.type()) {
  321. case Operand::Type::Register:
  322. break;
  323. case Operand::Type::Local:
  324. operand.offset_index_by(number_of_registers + number_of_constants);
  325. break;
  326. case Operand::Type::Constant:
  327. operand.offset_index_by(number_of_registers);
  328. break;
  329. default:
  330. VERIFY_NOT_REACHED();
  331. }
  332. });
  333. bytecode.append(reinterpret_cast<u8 const*>(&end), end.length());
  334. }
  335. if (block->handler() || block->finalizer()) {
  336. unlinked_exception_handlers.last().end_offset = bytecode.size();
  337. }
  338. }
  339. for (auto label_offset : label_offsets) {
  340. auto& label = *reinterpret_cast<Label*>(bytecode.data() + label_offset);
  341. auto* block = generator.m_root_basic_blocks[label.basic_block_index()].ptr();
  342. label.set_address(block_offsets.get(block).value());
  343. }
  344. auto executable = vm.heap().allocate_without_realm<Executable>(
  345. move(bytecode),
  346. move(generator.m_identifier_table),
  347. move(generator.m_string_table),
  348. move(generator.m_regex_table),
  349. move(generator.m_constants),
  350. node.source_code(),
  351. generator.m_next_property_lookup_cache,
  352. generator.m_next_global_variable_cache,
  353. generator.m_next_register,
  354. is_strict_mode);
  355. Vector<Executable::ExceptionHandlers> linked_exception_handlers;
  356. for (auto& unlinked_handler : unlinked_exception_handlers) {
  357. auto start_offset = unlinked_handler.start_offset;
  358. auto end_offset = unlinked_handler.end_offset;
  359. auto handler_offset = unlinked_handler.handler ? block_offsets.get(unlinked_handler.handler).value() : Optional<size_t> {};
  360. auto finalizer_offset = unlinked_handler.finalizer ? block_offsets.get(unlinked_handler.finalizer).value() : Optional<size_t> {};
  361. linked_exception_handlers.append({ start_offset, end_offset, handler_offset, finalizer_offset });
  362. }
  363. quick_sort(linked_exception_handlers, [](auto const& a, auto const& b) {
  364. return a.start_offset < b.start_offset;
  365. });
  366. executable->exception_handlers = move(linked_exception_handlers);
  367. executable->basic_block_start_offsets = move(basic_block_start_offsets);
  368. executable->source_map = move(source_map);
  369. generator.m_finished = true;
  370. return executable;
  371. }
  372. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate_from_ast_node(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind)
  373. {
  374. return emit_function_body_bytecode(vm, node, enclosing_function_kind, {});
  375. }
  376. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate_from_function(VM& vm, ECMAScriptFunctionObject const& function)
  377. {
  378. return emit_function_body_bytecode(vm, function.ecmascript_code(), function.kind(), &function, MustPropagateCompletion::No);
  379. }
  380. void Generator::grow(size_t additional_size)
  381. {
  382. VERIFY(m_current_basic_block);
  383. m_current_basic_block->grow(additional_size);
  384. }
  385. ScopedOperand Generator::allocate_register()
  386. {
  387. if (!m_free_registers.is_empty()) {
  388. return ScopedOperand { *this, Operand { m_free_registers.take_last() } };
  389. }
  390. VERIFY(m_next_register != NumericLimits<u32>::max());
  391. return ScopedOperand { *this, Operand { Register { m_next_register++ } } };
  392. }
  393. void Generator::free_register(Register reg)
  394. {
  395. m_free_registers.append(reg);
  396. }
  397. ScopedOperand Generator::local(u32 local_index)
  398. {
  399. return ScopedOperand { *this, Operand { Operand::Type::Local, static_cast<u32>(local_index) } };
  400. }
  401. Generator::SourceLocationScope::SourceLocationScope(Generator& generator, ASTNode const& node)
  402. : m_generator(generator)
  403. , m_previous_node(m_generator.m_current_ast_node)
  404. {
  405. m_generator.m_current_ast_node = &node;
  406. }
  407. Generator::SourceLocationScope::~SourceLocationScope()
  408. {
  409. m_generator.m_current_ast_node = m_previous_node;
  410. }
  411. Generator::UnwindContext::UnwindContext(Generator& generator, Optional<Label> finalizer)
  412. : m_generator(generator)
  413. , m_finalizer(finalizer)
  414. , m_previous_context(m_generator.m_current_unwind_context)
  415. {
  416. m_generator.m_current_unwind_context = this;
  417. }
  418. Generator::UnwindContext::~UnwindContext()
  419. {
  420. VERIFY(m_generator.m_current_unwind_context == this);
  421. m_generator.m_current_unwind_context = m_previous_context;
  422. }
  423. Label Generator::nearest_continuable_scope() const
  424. {
  425. return m_continuable_scopes.last().bytecode_target;
  426. }
  427. bool Generator::emit_block_declaration_instantiation(ScopeNode const& scope_node)
  428. {
  429. bool needs_block_declaration_instantiation = false;
  430. MUST(scope_node.for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  431. if (declaration.is_function_declaration()) {
  432. needs_block_declaration_instantiation = true;
  433. return;
  434. }
  435. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  436. if (!id.is_local())
  437. needs_block_declaration_instantiation = true;
  438. }));
  439. }));
  440. if (!needs_block_declaration_instantiation)
  441. return false;
  442. // FIXME: Generate the actual bytecode for block declaration instantiation
  443. // and get rid of the BlockDeclarationInstantiation instruction.
  444. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  445. emit<Bytecode::Op::BlockDeclarationInstantiation>(scope_node);
  446. return true;
  447. }
  448. void Generator::begin_variable_scope()
  449. {
  450. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  451. emit<Bytecode::Op::CreateLexicalEnvironment>();
  452. }
  453. void Generator::end_variable_scope()
  454. {
  455. end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  456. if (!m_current_basic_block->is_terminated()) {
  457. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  458. }
  459. }
  460. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  461. {
  462. m_continuable_scopes.append({ continue_target, language_label_set });
  463. start_boundary(BlockBoundaryType::Continue);
  464. }
  465. void Generator::end_continuable_scope()
  466. {
  467. m_continuable_scopes.take_last();
  468. end_boundary(BlockBoundaryType::Continue);
  469. }
  470. Label Generator::nearest_breakable_scope() const
  471. {
  472. return m_breakable_scopes.last().bytecode_target;
  473. }
  474. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  475. {
  476. m_breakable_scopes.append({ breakable_target, language_label_set });
  477. start_boundary(BlockBoundaryType::Break);
  478. }
  479. void Generator::end_breakable_scope()
  480. {
  481. m_breakable_scopes.take_last();
  482. end_boundary(BlockBoundaryType::Break);
  483. }
  484. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_super_reference(MemberExpression const& expression)
  485. {
  486. VERIFY(is<SuperExpression>(expression.object()));
  487. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  488. // 1. Let env be GetThisEnvironment().
  489. // 2. Let actualThis be ? env.GetThisBinding().
  490. auto actual_this = allocate_register();
  491. emit<Bytecode::Op::ResolveThisBinding>(actual_this);
  492. Optional<ScopedOperand> computed_property_value;
  493. if (expression.is_computed()) {
  494. // SuperProperty : super [ Expression ]
  495. // 3. Let propertyNameReference be ? Evaluation of Expression.
  496. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  497. computed_property_value = TRY(expression.property().generate_bytecode(*this)).value();
  498. }
  499. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  500. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  501. // 1. Let env be GetThisEnvironment().
  502. // 2. Assert: env.HasSuperBinding() is true.
  503. // 3. Let baseValue be ? env.GetSuperBase().
  504. auto base_value = allocate_register();
  505. emit<Bytecode::Op::ResolveSuperBase>(base_value);
  506. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  507. return ReferenceOperands {
  508. .base = base_value,
  509. .referenced_name = computed_property_value,
  510. .this_value = actual_this,
  511. };
  512. }
  513. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_load_from_reference(JS::ASTNode const& node, Optional<ScopedOperand> preferred_dst)
  514. {
  515. if (is<Identifier>(node)) {
  516. auto& identifier = static_cast<Identifier const&>(node);
  517. auto loaded_value = TRY(identifier.generate_bytecode(*this, preferred_dst)).value();
  518. return ReferenceOperands {
  519. .loaded_value = loaded_value,
  520. };
  521. }
  522. if (!is<MemberExpression>(node)) {
  523. return CodeGenerationError {
  524. &node,
  525. "Unimplemented/invalid node used as a reference"sv
  526. };
  527. }
  528. auto& expression = static_cast<MemberExpression const&>(node);
  529. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  530. if (is<SuperExpression>(expression.object())) {
  531. auto super_reference = TRY(emit_super_reference(expression));
  532. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  533. if (super_reference.referenced_name.has_value()) {
  534. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  535. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  536. emit<Bytecode::Op::GetByValueWithThis>(dst, *super_reference.base, *super_reference.referenced_name, *super_reference.this_value);
  537. } else {
  538. // 3. Let propertyKey be StringValue of IdentifierName.
  539. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  540. emit_get_by_id_with_this(dst, *super_reference.base, identifier_table_ref, *super_reference.this_value);
  541. }
  542. super_reference.loaded_value = dst;
  543. return super_reference;
  544. }
  545. auto base = TRY(expression.object().generate_bytecode(*this)).value();
  546. auto base_identifier = intern_identifier_for_expression(expression.object());
  547. if (expression.is_computed()) {
  548. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  549. auto saved_property = allocate_register();
  550. emit<Bytecode::Op::Mov>(saved_property, property);
  551. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  552. emit<Bytecode::Op::GetByValue>(dst, base, property, move(base_identifier));
  553. return ReferenceOperands {
  554. .base = base,
  555. .referenced_name = saved_property,
  556. .this_value = base,
  557. .loaded_value = dst,
  558. };
  559. }
  560. if (expression.property().is_identifier()) {
  561. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  562. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  563. emit_get_by_id(dst, base, identifier_table_ref, move(base_identifier));
  564. return ReferenceOperands {
  565. .base = base,
  566. .referenced_identifier = identifier_table_ref,
  567. .this_value = base,
  568. .loaded_value = dst,
  569. };
  570. }
  571. if (expression.property().is_private_identifier()) {
  572. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  573. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  574. emit<Bytecode::Op::GetPrivateById>(dst, base, identifier_table_ref);
  575. return ReferenceOperands {
  576. .base = base,
  577. .referenced_private_identifier = identifier_table_ref,
  578. .this_value = base,
  579. .loaded_value = dst,
  580. };
  581. }
  582. return CodeGenerationError {
  583. &expression,
  584. "Unimplemented non-computed member expression"sv
  585. };
  586. }
  587. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node, ScopedOperand value)
  588. {
  589. if (is<Identifier>(node)) {
  590. auto& identifier = static_cast<Identifier const&>(node);
  591. emit_set_variable(identifier, value);
  592. return {};
  593. }
  594. if (is<MemberExpression>(node)) {
  595. auto& expression = static_cast<MemberExpression const&>(node);
  596. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  597. if (is<SuperExpression>(expression.object())) {
  598. auto super_reference = TRY(emit_super_reference(expression));
  599. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  600. if (super_reference.referenced_name.has_value()) {
  601. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  602. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  603. emit<Bytecode::Op::PutByValueWithThis>(*super_reference.base, *super_reference.referenced_name, *super_reference.this_value, value);
  604. } else {
  605. // 3. Let propertyKey be StringValue of IdentifierName.
  606. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  607. emit<Bytecode::Op::PutByIdWithThis>(*super_reference.base, *super_reference.this_value, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  608. }
  609. } else {
  610. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  611. if (expression.is_computed()) {
  612. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  613. emit<Bytecode::Op::PutByValue>(object, property, value);
  614. } else if (expression.property().is_identifier()) {
  615. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  616. emit<Bytecode::Op::PutById>(object, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  617. } else if (expression.property().is_private_identifier()) {
  618. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  619. emit<Bytecode::Op::PutPrivateById>(object, identifier_table_ref, value);
  620. } else {
  621. return CodeGenerationError {
  622. &expression,
  623. "Unimplemented non-computed member expression"sv
  624. };
  625. }
  626. }
  627. return {};
  628. }
  629. return CodeGenerationError {
  630. &node,
  631. "Unimplemented/invalid node used a reference"sv
  632. };
  633. }
  634. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(ReferenceOperands const& reference, ScopedOperand value)
  635. {
  636. if (reference.referenced_private_identifier.has_value()) {
  637. emit<Bytecode::Op::PutPrivateById>(*reference.base, *reference.referenced_private_identifier, value);
  638. return {};
  639. }
  640. if (reference.referenced_identifier.has_value()) {
  641. if (reference.base == reference.this_value)
  642. emit<Bytecode::Op::PutById>(*reference.base, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  643. else
  644. emit<Bytecode::Op::PutByIdWithThis>(*reference.base, *reference.this_value, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  645. return {};
  646. }
  647. if (reference.base == reference.this_value)
  648. emit<Bytecode::Op::PutByValue>(*reference.base, *reference.referenced_name, value);
  649. else
  650. emit<Bytecode::Op::PutByValueWithThis>(*reference.base, *reference.referenced_name, *reference.this_value, value);
  651. return {};
  652. }
  653. CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_delete_reference(JS::ASTNode const& node)
  654. {
  655. if (is<Identifier>(node)) {
  656. auto& identifier = static_cast<Identifier const&>(node);
  657. if (identifier.is_local()) {
  658. return add_constant(Value(false));
  659. }
  660. auto dst = allocate_register();
  661. emit<Bytecode::Op::DeleteVariable>(dst, intern_identifier(identifier.string()));
  662. return dst;
  663. }
  664. if (is<MemberExpression>(node)) {
  665. auto& expression = static_cast<MemberExpression const&>(node);
  666. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  667. if (is<SuperExpression>(expression.object())) {
  668. auto super_reference = TRY(emit_super_reference(expression));
  669. auto dst = allocate_register();
  670. if (super_reference.referenced_name.has_value()) {
  671. emit<Bytecode::Op::DeleteByValueWithThis>(dst, *super_reference.base, *super_reference.this_value, *super_reference.referenced_name);
  672. } else {
  673. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  674. emit<Bytecode::Op::DeleteByIdWithThis>(dst, *super_reference.base, *super_reference.this_value, identifier_table_ref);
  675. }
  676. return Optional<ScopedOperand> {};
  677. }
  678. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  679. auto dst = allocate_register();
  680. if (expression.is_computed()) {
  681. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  682. emit<Bytecode::Op::DeleteByValue>(dst, object, property);
  683. } else if (expression.property().is_identifier()) {
  684. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  685. emit<Bytecode::Op::DeleteById>(dst, object, identifier_table_ref);
  686. } else {
  687. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  688. return CodeGenerationError {
  689. &expression,
  690. "Unimplemented non-computed member expression"sv
  691. };
  692. }
  693. return dst;
  694. }
  695. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  696. // For example: delete a(); delete ++c.b; etc.
  697. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  698. // 1. Let ref be the result of evaluating UnaryExpression.
  699. // 2. ReturnIfAbrupt(ref).
  700. (void)TRY(node.generate_bytecode(*this));
  701. // 3. If ref is not a Reference Record, return true.
  702. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  703. return add_constant(Value(true));
  704. }
  705. void Generator::emit_set_variable(JS::Identifier const& identifier, ScopedOperand value, Bytecode::Op::BindingInitializationMode initialization_mode, Bytecode::Op::EnvironmentMode environment_mode)
  706. {
  707. if (identifier.is_local()) {
  708. if (value.operand().is_local() && value.operand().index() == identifier.local_variable_index()) {
  709. // Moving a local to itself is a no-op.
  710. return;
  711. }
  712. emit<Bytecode::Op::Mov>(local(identifier.local_variable_index()), value);
  713. } else {
  714. auto identifier_index = intern_identifier(identifier.string());
  715. if (environment_mode == Bytecode::Op::EnvironmentMode::Lexical) {
  716. if (initialization_mode == Bytecode::Op::BindingInitializationMode::Initialize) {
  717. emit<Bytecode::Op::InitializeLexicalBinding>(identifier_index, value);
  718. } else if (initialization_mode == Bytecode::Op::BindingInitializationMode::Set) {
  719. emit<Bytecode::Op::SetLexicalBinding>(identifier_index, value);
  720. }
  721. } else if (environment_mode == Bytecode::Op::EnvironmentMode::Var) {
  722. if (initialization_mode == Bytecode::Op::BindingInitializationMode::Initialize) {
  723. emit<Bytecode::Op::InitializeVariableBinding>(identifier_index, value);
  724. } else if (initialization_mode == Bytecode::Op::BindingInitializationMode::Set) {
  725. emit<Bytecode::Op::SetVariableBinding>(identifier_index, value);
  726. }
  727. } else {
  728. VERIFY_NOT_REACHED();
  729. }
  730. }
  731. }
  732. static Optional<ByteString> expression_identifier(Expression const& expression)
  733. {
  734. if (expression.is_identifier()) {
  735. auto const& identifier = static_cast<Identifier const&>(expression);
  736. return identifier.string();
  737. }
  738. if (expression.is_numeric_literal()) {
  739. auto const& literal = static_cast<NumericLiteral const&>(expression);
  740. return literal.value().to_string_without_side_effects().to_byte_string();
  741. }
  742. if (expression.is_string_literal()) {
  743. auto const& literal = static_cast<StringLiteral const&>(expression);
  744. return ByteString::formatted("'{}'", literal.value());
  745. }
  746. if (expression.is_member_expression()) {
  747. auto const& member_expression = static_cast<MemberExpression const&>(expression);
  748. StringBuilder builder;
  749. if (auto identifer = expression_identifier(member_expression.object()); identifer.has_value())
  750. builder.append(*identifer);
  751. if (auto identifer = expression_identifier(member_expression.property()); identifer.has_value()) {
  752. if (member_expression.is_computed())
  753. builder.appendff("[{}]", *identifer);
  754. else
  755. builder.appendff(".{}", *identifer);
  756. }
  757. return builder.to_byte_string();
  758. }
  759. return {};
  760. }
  761. Optional<IdentifierTableIndex> Generator::intern_identifier_for_expression(Expression const& expression)
  762. {
  763. if (auto identifer = expression_identifier(expression); identifer.has_value())
  764. return intern_identifier(identifer.release_value());
  765. return {};
  766. }
  767. void Generator::generate_scoped_jump(JumpType type)
  768. {
  769. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  770. bool last_was_finally = false;
  771. for (size_t i = m_boundaries.size(); i > 0; --i) {
  772. auto boundary = m_boundaries[i - 1];
  773. using enum BlockBoundaryType;
  774. switch (boundary) {
  775. case Break:
  776. if (type == JumpType::Break) {
  777. emit<Op::Jump>(nearest_breakable_scope());
  778. return;
  779. }
  780. break;
  781. case Continue:
  782. if (type == JumpType::Continue) {
  783. emit<Op::Jump>(nearest_continuable_scope());
  784. return;
  785. }
  786. break;
  787. case Unwind:
  788. if (!last_was_finally) {
  789. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  790. emit<Bytecode::Op::LeaveUnwindContext>();
  791. m_current_unwind_context = m_current_unwind_context->previous();
  792. }
  793. last_was_finally = false;
  794. break;
  795. case LeaveLexicalEnvironment:
  796. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  797. break;
  798. case ReturnToFinally: {
  799. VERIFY(m_current_unwind_context->finalizer().has_value());
  800. m_current_unwind_context = m_current_unwind_context->previous();
  801. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  802. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  803. auto& block = make_block(block_name);
  804. emit<Op::ScheduleJump>(Label { block });
  805. switch_to_basic_block(block);
  806. last_was_finally = true;
  807. break;
  808. }
  809. case LeaveFinally:
  810. emit<Op::LeaveFinally>();
  811. break;
  812. }
  813. }
  814. VERIFY_NOT_REACHED();
  815. }
  816. void Generator::generate_labelled_jump(JumpType type, DeprecatedFlyString const& label)
  817. {
  818. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  819. size_t current_boundary = m_boundaries.size();
  820. bool last_was_finally = false;
  821. auto const& jumpable_scopes = type == JumpType::Continue ? m_continuable_scopes : m_breakable_scopes;
  822. for (auto const& jumpable_scope : jumpable_scopes.in_reverse()) {
  823. for (; current_boundary > 0; --current_boundary) {
  824. auto boundary = m_boundaries[current_boundary - 1];
  825. if (boundary == BlockBoundaryType::Unwind) {
  826. if (!last_was_finally) {
  827. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  828. emit<Bytecode::Op::LeaveUnwindContext>();
  829. m_current_unwind_context = m_current_unwind_context->previous();
  830. }
  831. last_was_finally = false;
  832. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  833. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  834. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  835. VERIFY(m_current_unwind_context->finalizer().has_value());
  836. m_current_unwind_context = m_current_unwind_context->previous();
  837. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  838. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  839. auto& block = make_block(block_name);
  840. emit<Op::ScheduleJump>(Label { block });
  841. switch_to_basic_block(block);
  842. last_was_finally = true;
  843. } else if ((type == JumpType::Continue && boundary == BlockBoundaryType::Continue) || (type == JumpType::Break && boundary == BlockBoundaryType::Break)) {
  844. // Make sure we don't process this boundary twice if the current jumpable scope doesn't contain the target label.
  845. --current_boundary;
  846. break;
  847. }
  848. }
  849. if (jumpable_scope.language_label_set.contains_slow(label)) {
  850. emit<Op::Jump>(jumpable_scope.bytecode_target);
  851. return;
  852. }
  853. }
  854. // We must have a jumpable scope available that contains the label, as this should be enforced by the parser.
  855. VERIFY_NOT_REACHED();
  856. }
  857. void Generator::generate_break()
  858. {
  859. generate_scoped_jump(JumpType::Break);
  860. }
  861. void Generator::generate_break(DeprecatedFlyString const& break_label)
  862. {
  863. generate_labelled_jump(JumpType::Break, break_label);
  864. }
  865. void Generator::generate_continue()
  866. {
  867. generate_scoped_jump(JumpType::Continue);
  868. }
  869. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  870. {
  871. generate_labelled_jump(JumpType::Continue, continue_label);
  872. }
  873. void Generator::push_home_object(ScopedOperand object)
  874. {
  875. m_home_objects.append(object);
  876. }
  877. void Generator::pop_home_object()
  878. {
  879. m_home_objects.take_last();
  880. }
  881. void Generator::emit_new_function(ScopedOperand dst, FunctionExpression const& function_node, Optional<IdentifierTableIndex> lhs_name)
  882. {
  883. if (m_home_objects.is_empty()) {
  884. emit<Op::NewFunction>(dst, function_node, lhs_name);
  885. } else {
  886. emit<Op::NewFunction>(dst, function_node, lhs_name, m_home_objects.last());
  887. }
  888. }
  889. CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_named_evaluation_if_anonymous_function(Expression const& expression, Optional<IdentifierTableIndex> lhs_name, Optional<ScopedOperand> preferred_dst)
  890. {
  891. if (is<FunctionExpression>(expression)) {
  892. auto const& function_expression = static_cast<FunctionExpression const&>(expression);
  893. if (!function_expression.has_name()) {
  894. return TRY(function_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  895. }
  896. }
  897. if (is<ClassExpression>(expression)) {
  898. auto const& class_expression = static_cast<ClassExpression const&>(expression);
  899. if (!class_expression.has_name()) {
  900. return TRY(class_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  901. }
  902. }
  903. return expression.generate_bytecode(*this, preferred_dst);
  904. }
  905. void Generator::emit_get_by_id(ScopedOperand dst, ScopedOperand base, IdentifierTableIndex property_identifier, Optional<IdentifierTableIndex> base_identifier)
  906. {
  907. emit<Op::GetById>(dst, base, property_identifier, move(base_identifier), m_next_property_lookup_cache++);
  908. }
  909. void Generator::emit_get_by_id_with_this(ScopedOperand dst, ScopedOperand base, IdentifierTableIndex id, ScopedOperand this_value)
  910. {
  911. emit<Op::GetByIdWithThis>(dst, base, id, this_value, m_next_property_lookup_cache++);
  912. }
  913. void Generator::emit_iterator_value(ScopedOperand dst, ScopedOperand result)
  914. {
  915. emit_get_by_id(dst, result, intern_identifier("value"sv));
  916. }
  917. void Generator::emit_iterator_complete(ScopedOperand dst, ScopedOperand result)
  918. {
  919. emit_get_by_id(dst, result, intern_identifier("done"sv));
  920. }
  921. bool Generator::is_local_initialized(u32 local_index) const
  922. {
  923. return m_initialized_locals.find(local_index) != m_initialized_locals.end();
  924. }
  925. void Generator::set_local_initialized(u32 local_index)
  926. {
  927. m_initialized_locals.set(local_index);
  928. }
  929. ScopedOperand Generator::get_this(Optional<ScopedOperand> preferred_dst)
  930. {
  931. if (m_current_basic_block->this_().has_value())
  932. return m_current_basic_block->this_().value();
  933. if (m_root_basic_blocks[0]->this_().has_value()) {
  934. m_current_basic_block->set_this(m_root_basic_blocks[0]->this_().value());
  935. return m_root_basic_blocks[0]->this_().value();
  936. }
  937. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  938. emit<Bytecode::Op::ResolveThisBinding>(dst);
  939. m_current_basic_block->set_this(dst);
  940. return dst;
  941. }
  942. ScopedOperand Generator::accumulator()
  943. {
  944. return m_accumulator;
  945. }
  946. bool Generator::fuse_compare_and_jump(ScopedOperand const& condition, Label true_target, Label false_target)
  947. {
  948. auto& last_instruction = *reinterpret_cast<Instruction const*>(m_current_basic_block->data() + m_current_basic_block->last_instruction_start_offset());
  949. #define HANDLE_COMPARISON_OP(op_TitleCase, op_snake_case, numeric_operator) \
  950. if (last_instruction.type() == Instruction::Type::op_TitleCase) { \
  951. auto& comparison = static_cast<Op::op_TitleCase const&>(last_instruction); \
  952. VERIFY(comparison.dst() == condition); \
  953. auto lhs = comparison.lhs(); \
  954. auto rhs = comparison.rhs(); \
  955. m_current_basic_block->rewind(); \
  956. emit<Op::Jump##op_TitleCase>(lhs, rhs, true_target, false_target); \
  957. return true; \
  958. }
  959. JS_ENUMERATE_COMPARISON_OPS(HANDLE_COMPARISON_OP);
  960. #undef HANDLE_COMPARISON_OP
  961. return false;
  962. }
  963. void Generator::emit_jump_if(ScopedOperand const& condition, Label true_target, Label false_target)
  964. {
  965. if (condition.operand().is_constant()) {
  966. auto value = m_constants[condition.operand().index()];
  967. if (value.is_boolean()) {
  968. if (value.as_bool()) {
  969. emit<Op::Jump>(true_target);
  970. } else {
  971. emit<Op::Jump>(false_target);
  972. }
  973. return;
  974. }
  975. }
  976. // NOTE: It's only safe to fuse compare-and-jump if the condition is a temporary with no other dependents.
  977. if (condition.operand().is_register()
  978. && condition.ref_count() == 1
  979. && m_current_basic_block->size() > 0) {
  980. if (fuse_compare_and_jump(condition, true_target, false_target))
  981. return;
  982. }
  983. emit<Op::JumpIf>(condition, true_target, false_target);
  984. }
  985. }