Generator.cpp 48 KB

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