Generator.cpp 47 KB

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