Generator.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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, Vector<DeprecatedFlyString> local_variable_names)
  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. Optional<ScopedOperand> undefined_constant;
  240. for (auto& block : generator.m_root_basic_blocks) {
  241. if (!block->is_terminated()) {
  242. // NOTE: We must ensure that the "undefined" constant, which will be used by the not yet
  243. // emitted End instruction, is taken into account while shifting local operands by the
  244. // number of constants.
  245. undefined_constant = generator.add_constant(js_undefined());
  246. break;
  247. }
  248. }
  249. auto number_of_registers = generator.m_next_register;
  250. auto number_of_constants = generator.m_constants.size();
  251. // Pass: Rewrite the bytecode to use the correct register and constant indices.
  252. for (auto& block : generator.m_root_basic_blocks) {
  253. Bytecode::InstructionStreamIterator it(block->instruction_stream());
  254. while (!it.at_end()) {
  255. auto& instruction = const_cast<Instruction&>(*it);
  256. instruction.visit_operands([number_of_registers, number_of_constants](Operand& operand) {
  257. switch (operand.type()) {
  258. case Operand::Type::Register:
  259. break;
  260. case Operand::Type::Local:
  261. operand.offset_index_by(number_of_registers + number_of_constants);
  262. break;
  263. case Operand::Type::Constant:
  264. operand.offset_index_by(number_of_registers);
  265. break;
  266. default:
  267. VERIFY_NOT_REACHED();
  268. }
  269. });
  270. ++it;
  271. }
  272. }
  273. // Also rewrite the `undefined` constant if we have one for inserting End.
  274. if (undefined_constant.has_value())
  275. undefined_constant.value().operand().offset_index_by(number_of_registers);
  276. for (auto& block : generator.m_root_basic_blocks) {
  277. basic_block_start_offsets.append(bytecode.size());
  278. if (block->handler() || block->finalizer()) {
  279. unlinked_exception_handlers.append({
  280. .start_offset = bytecode.size(),
  281. .end_offset = 0,
  282. .handler = block->handler(),
  283. .finalizer = block->finalizer(),
  284. });
  285. }
  286. block_offsets.set(block.ptr(), bytecode.size());
  287. for (auto& [offset, source_record] : block->source_map()) {
  288. source_map.set(bytecode.size() + offset, source_record);
  289. }
  290. Bytecode::InstructionStreamIterator it(block->instruction_stream());
  291. while (!it.at_end()) {
  292. auto& instruction = const_cast<Instruction&>(*it);
  293. if (instruction.type() == Instruction::Type::Jump) {
  294. auto& jump = static_cast<Bytecode::Op::Jump&>(instruction);
  295. // OPTIMIZATION: Don't emit jumps that just jump to the next block.
  296. if (jump.target().basic_block_index() == block->index() + 1) {
  297. if (basic_block_start_offsets.last() == bytecode.size()) {
  298. // This block is empty, just skip it.
  299. basic_block_start_offsets.take_last();
  300. }
  301. ++it;
  302. continue;
  303. }
  304. // OPTIMIZATION: For jumps to a return-or-end-only block, we can emit a `Return` or `End` directly instead.
  305. auto& target_block = *generator.m_root_basic_blocks[jump.target().basic_block_index()];
  306. if (target_block.is_terminated()) {
  307. auto target_instruction_iterator = InstructionStreamIterator { target_block.instruction_stream() };
  308. auto& target_instruction = *target_instruction_iterator;
  309. if (target_instruction.type() == Instruction::Type::Return) {
  310. auto& return_instruction = static_cast<Bytecode::Op::Return const&>(target_instruction);
  311. Op::Return return_op(return_instruction.value());
  312. bytecode.append(reinterpret_cast<u8 const*>(&return_op), return_op.length());
  313. ++it;
  314. continue;
  315. }
  316. if (target_instruction.type() == Instruction::Type::End) {
  317. auto& return_instruction = static_cast<Bytecode::Op::End const&>(target_instruction);
  318. Op::End end_op(return_instruction.value());
  319. bytecode.append(reinterpret_cast<u8 const*>(&end_op), end_op.length());
  320. ++it;
  321. continue;
  322. }
  323. }
  324. }
  325. // OPTIMIZATION: For `JumpIf` where one of the targets is the very next block,
  326. // we can emit a `JumpTrue` or `JumpFalse` (to the other block) instead.
  327. if (instruction.type() == Instruction::Type::JumpIf) {
  328. auto& jump = static_cast<Bytecode::Op::JumpIf&>(instruction);
  329. if (jump.true_target().basic_block_index() == block->index() + 1) {
  330. Op::JumpFalse jump_false(jump.condition(), Label { jump.false_target() });
  331. auto& label = jump_false.target();
  332. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&jump_false));
  333. label_offsets.append(label_offset);
  334. bytecode.append(reinterpret_cast<u8 const*>(&jump_false), jump_false.length());
  335. ++it;
  336. continue;
  337. }
  338. if (jump.false_target().basic_block_index() == block->index() + 1) {
  339. Op::JumpTrue jump_true(jump.condition(), Label { jump.true_target() });
  340. auto& label = jump_true.target();
  341. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&jump_true));
  342. label_offsets.append(label_offset);
  343. bytecode.append(reinterpret_cast<u8 const*>(&jump_true), jump_true.length());
  344. ++it;
  345. continue;
  346. }
  347. }
  348. instruction.visit_labels([&](Label& label) {
  349. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&instruction));
  350. label_offsets.append(label_offset);
  351. });
  352. bytecode.append(reinterpret_cast<u8 const*>(&instruction), instruction.length());
  353. ++it;
  354. }
  355. if (!block->is_terminated()) {
  356. Op::End end(*undefined_constant);
  357. bytecode.append(reinterpret_cast<u8 const*>(&end), end.length());
  358. }
  359. if (block->handler() || block->finalizer()) {
  360. unlinked_exception_handlers.last().end_offset = bytecode.size();
  361. }
  362. }
  363. for (auto label_offset : label_offsets) {
  364. auto& label = *reinterpret_cast<Label*>(bytecode.data() + label_offset);
  365. auto* block = generator.m_root_basic_blocks[label.basic_block_index()].ptr();
  366. label.set_address(block_offsets.get(block).value());
  367. }
  368. auto executable = vm.heap().allocate_without_realm<Executable>(
  369. move(bytecode),
  370. move(generator.m_identifier_table),
  371. move(generator.m_string_table),
  372. move(generator.m_regex_table),
  373. move(generator.m_constants),
  374. node.source_code(),
  375. generator.m_next_property_lookup_cache,
  376. generator.m_next_global_variable_cache,
  377. generator.m_next_register,
  378. is_strict_mode);
  379. Vector<Executable::ExceptionHandlers> linked_exception_handlers;
  380. for (auto& unlinked_handler : unlinked_exception_handlers) {
  381. auto start_offset = unlinked_handler.start_offset;
  382. auto end_offset = unlinked_handler.end_offset;
  383. auto handler_offset = unlinked_handler.handler ? block_offsets.get(unlinked_handler.handler).value() : Optional<size_t> {};
  384. auto finalizer_offset = unlinked_handler.finalizer ? block_offsets.get(unlinked_handler.finalizer).value() : Optional<size_t> {};
  385. linked_exception_handlers.append({ start_offset, end_offset, handler_offset, finalizer_offset });
  386. }
  387. quick_sort(linked_exception_handlers, [](auto const& a, auto const& b) {
  388. return a.start_offset < b.start_offset;
  389. });
  390. executable->exception_handlers = move(linked_exception_handlers);
  391. executable->basic_block_start_offsets = move(basic_block_start_offsets);
  392. executable->source_map = move(source_map);
  393. executable->local_variable_names = move(local_variable_names);
  394. executable->local_index_base = number_of_registers + number_of_constants;
  395. generator.m_finished = true;
  396. return executable;
  397. }
  398. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate_from_ast_node(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind)
  399. {
  400. Vector<DeprecatedFlyString> local_variable_names;
  401. if (is<ScopeNode>(node))
  402. local_variable_names = static_cast<ScopeNode const&>(node).local_variables_names();
  403. return compile(vm, node, enclosing_function_kind, {}, MustPropagateCompletion::Yes, move(local_variable_names));
  404. }
  405. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate_from_function(VM& vm, ECMAScriptFunctionObject const& function)
  406. {
  407. return compile(vm, function.ecmascript_code(), function.kind(), &function, MustPropagateCompletion::No, function.local_variables_names());
  408. }
  409. void Generator::grow(size_t additional_size)
  410. {
  411. VERIFY(m_current_basic_block);
  412. m_current_basic_block->grow(additional_size);
  413. }
  414. ScopedOperand Generator::allocate_register()
  415. {
  416. if (!m_free_registers.is_empty()) {
  417. return ScopedOperand { *this, Operand { m_free_registers.take_last() } };
  418. }
  419. VERIFY(m_next_register != NumericLimits<u32>::max());
  420. return ScopedOperand { *this, Operand { Register { m_next_register++ } } };
  421. }
  422. void Generator::free_register(Register reg)
  423. {
  424. m_free_registers.append(reg);
  425. }
  426. ScopedOperand Generator::local(u32 local_index)
  427. {
  428. return ScopedOperand { *this, Operand { Operand::Type::Local, static_cast<u32>(local_index) } };
  429. }
  430. Generator::SourceLocationScope::SourceLocationScope(Generator& generator, ASTNode const& node)
  431. : m_generator(generator)
  432. , m_previous_node(m_generator.m_current_ast_node)
  433. {
  434. m_generator.m_current_ast_node = &node;
  435. }
  436. Generator::SourceLocationScope::~SourceLocationScope()
  437. {
  438. m_generator.m_current_ast_node = m_previous_node;
  439. }
  440. Generator::UnwindContext::UnwindContext(Generator& generator, Optional<Label> finalizer)
  441. : m_generator(generator)
  442. , m_finalizer(finalizer)
  443. , m_previous_context(m_generator.m_current_unwind_context)
  444. {
  445. m_generator.m_current_unwind_context = this;
  446. }
  447. Generator::UnwindContext::~UnwindContext()
  448. {
  449. VERIFY(m_generator.m_current_unwind_context == this);
  450. m_generator.m_current_unwind_context = m_previous_context;
  451. }
  452. Label Generator::nearest_continuable_scope() const
  453. {
  454. return m_continuable_scopes.last().bytecode_target;
  455. }
  456. bool Generator::emit_block_declaration_instantiation(ScopeNode const& scope_node)
  457. {
  458. bool needs_block_declaration_instantiation = false;
  459. MUST(scope_node.for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  460. if (declaration.is_function_declaration()) {
  461. needs_block_declaration_instantiation = true;
  462. return;
  463. }
  464. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  465. if (!id.is_local())
  466. needs_block_declaration_instantiation = true;
  467. }));
  468. }));
  469. if (!needs_block_declaration_instantiation)
  470. return false;
  471. // FIXME: Generate the actual bytecode for block declaration instantiation
  472. // and get rid of the BlockDeclarationInstantiation instruction.
  473. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  474. emit<Bytecode::Op::BlockDeclarationInstantiation>(scope_node);
  475. return true;
  476. }
  477. void Generator::begin_variable_scope()
  478. {
  479. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  480. emit<Bytecode::Op::CreateLexicalEnvironment>();
  481. }
  482. void Generator::end_variable_scope()
  483. {
  484. end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  485. if (!m_current_basic_block->is_terminated()) {
  486. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  487. }
  488. }
  489. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  490. {
  491. m_continuable_scopes.append({ continue_target, language_label_set });
  492. start_boundary(BlockBoundaryType::Continue);
  493. }
  494. void Generator::end_continuable_scope()
  495. {
  496. m_continuable_scopes.take_last();
  497. end_boundary(BlockBoundaryType::Continue);
  498. }
  499. Label Generator::nearest_breakable_scope() const
  500. {
  501. return m_breakable_scopes.last().bytecode_target;
  502. }
  503. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  504. {
  505. m_breakable_scopes.append({ breakable_target, language_label_set });
  506. start_boundary(BlockBoundaryType::Break);
  507. }
  508. void Generator::end_breakable_scope()
  509. {
  510. m_breakable_scopes.take_last();
  511. end_boundary(BlockBoundaryType::Break);
  512. }
  513. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_super_reference(MemberExpression const& expression)
  514. {
  515. VERIFY(is<SuperExpression>(expression.object()));
  516. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  517. // 1. Let env be GetThisEnvironment().
  518. // 2. Let actualThis be ? env.GetThisBinding().
  519. auto actual_this = get_this();
  520. Optional<ScopedOperand> computed_property_value;
  521. if (expression.is_computed()) {
  522. // SuperProperty : super [ Expression ]
  523. // 3. Let propertyNameReference be ? Evaluation of Expression.
  524. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  525. computed_property_value = TRY(expression.property().generate_bytecode(*this)).value();
  526. }
  527. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  528. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  529. // 1. Let env be GetThisEnvironment().
  530. // 2. Assert: env.HasSuperBinding() is true.
  531. // 3. Let baseValue be ? env.GetSuperBase().
  532. auto base_value = allocate_register();
  533. emit<Bytecode::Op::ResolveSuperBase>(base_value);
  534. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  535. return ReferenceOperands {
  536. .base = base_value,
  537. .referenced_name = computed_property_value,
  538. .this_value = actual_this,
  539. };
  540. }
  541. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_load_from_reference(JS::ASTNode const& node, Optional<ScopedOperand> preferred_dst)
  542. {
  543. if (is<Identifier>(node)) {
  544. auto& identifier = static_cast<Identifier const&>(node);
  545. auto loaded_value = TRY(identifier.generate_bytecode(*this, preferred_dst)).value();
  546. return ReferenceOperands {
  547. .loaded_value = loaded_value,
  548. };
  549. }
  550. if (!is<MemberExpression>(node)) {
  551. return CodeGenerationError {
  552. &node,
  553. "Unimplemented/invalid node used as a reference"sv
  554. };
  555. }
  556. auto& expression = static_cast<MemberExpression const&>(node);
  557. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  558. if (is<SuperExpression>(expression.object())) {
  559. auto super_reference = TRY(emit_super_reference(expression));
  560. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  561. if (super_reference.referenced_name.has_value()) {
  562. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  563. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  564. emit<Bytecode::Op::GetByValueWithThis>(dst, *super_reference.base, *super_reference.referenced_name, *super_reference.this_value);
  565. } else {
  566. // 3. Let propertyKey be StringValue of IdentifierName.
  567. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  568. emit_get_by_id_with_this(dst, *super_reference.base, identifier_table_ref, *super_reference.this_value);
  569. }
  570. super_reference.loaded_value = dst;
  571. return super_reference;
  572. }
  573. auto base = TRY(expression.object().generate_bytecode(*this)).value();
  574. auto base_identifier = intern_identifier_for_expression(expression.object());
  575. if (expression.is_computed()) {
  576. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  577. auto saved_property = allocate_register();
  578. emit<Bytecode::Op::Mov>(saved_property, property);
  579. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  580. emit<Bytecode::Op::GetByValue>(dst, base, property, move(base_identifier));
  581. return ReferenceOperands {
  582. .base = base,
  583. .referenced_name = saved_property,
  584. .this_value = base,
  585. .loaded_value = dst,
  586. };
  587. }
  588. if (expression.property().is_identifier()) {
  589. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  590. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  591. emit_get_by_id(dst, base, identifier_table_ref, move(base_identifier));
  592. return ReferenceOperands {
  593. .base = base,
  594. .referenced_identifier = identifier_table_ref,
  595. .this_value = base,
  596. .loaded_value = dst,
  597. };
  598. }
  599. if (expression.property().is_private_identifier()) {
  600. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  601. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  602. emit<Bytecode::Op::GetPrivateById>(dst, base, identifier_table_ref);
  603. return ReferenceOperands {
  604. .base = base,
  605. .referenced_private_identifier = identifier_table_ref,
  606. .this_value = base,
  607. .loaded_value = dst,
  608. };
  609. }
  610. return CodeGenerationError {
  611. &expression,
  612. "Unimplemented non-computed member expression"sv
  613. };
  614. }
  615. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node, ScopedOperand value)
  616. {
  617. if (is<Identifier>(node)) {
  618. auto& identifier = static_cast<Identifier const&>(node);
  619. emit_set_variable(identifier, value);
  620. return {};
  621. }
  622. if (is<MemberExpression>(node)) {
  623. auto& expression = static_cast<MemberExpression const&>(node);
  624. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  625. if (is<SuperExpression>(expression.object())) {
  626. auto super_reference = TRY(emit_super_reference(expression));
  627. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  628. if (super_reference.referenced_name.has_value()) {
  629. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  630. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  631. emit<Bytecode::Op::PutByValueWithThis>(*super_reference.base, *super_reference.referenced_name, *super_reference.this_value, value);
  632. } else {
  633. // 3. Let propertyKey be StringValue of IdentifierName.
  634. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  635. emit<Bytecode::Op::PutByIdWithThis>(*super_reference.base, *super_reference.this_value, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  636. }
  637. } else {
  638. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  639. if (expression.is_computed()) {
  640. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  641. emit<Bytecode::Op::PutByValue>(object, property, value);
  642. } else if (expression.property().is_identifier()) {
  643. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  644. emit<Bytecode::Op::PutById>(object, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  645. } else if (expression.property().is_private_identifier()) {
  646. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  647. emit<Bytecode::Op::PutPrivateById>(object, identifier_table_ref, value);
  648. } else {
  649. return CodeGenerationError {
  650. &expression,
  651. "Unimplemented non-computed member expression"sv
  652. };
  653. }
  654. }
  655. return {};
  656. }
  657. return CodeGenerationError {
  658. &node,
  659. "Unimplemented/invalid node used a reference"sv
  660. };
  661. }
  662. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(ReferenceOperands const& reference, ScopedOperand value)
  663. {
  664. if (reference.referenced_private_identifier.has_value()) {
  665. emit<Bytecode::Op::PutPrivateById>(*reference.base, *reference.referenced_private_identifier, value);
  666. return {};
  667. }
  668. if (reference.referenced_identifier.has_value()) {
  669. if (reference.base == reference.this_value)
  670. emit<Bytecode::Op::PutById>(*reference.base, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  671. else
  672. emit<Bytecode::Op::PutByIdWithThis>(*reference.base, *reference.this_value, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  673. return {};
  674. }
  675. if (reference.base == reference.this_value)
  676. emit<Bytecode::Op::PutByValue>(*reference.base, *reference.referenced_name, value);
  677. else
  678. emit<Bytecode::Op::PutByValueWithThis>(*reference.base, *reference.referenced_name, *reference.this_value, value);
  679. return {};
  680. }
  681. CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_delete_reference(JS::ASTNode const& node)
  682. {
  683. if (is<Identifier>(node)) {
  684. auto& identifier = static_cast<Identifier const&>(node);
  685. if (identifier.is_local()) {
  686. return add_constant(Value(false));
  687. }
  688. auto dst = allocate_register();
  689. emit<Bytecode::Op::DeleteVariable>(dst, intern_identifier(identifier.string()));
  690. return dst;
  691. }
  692. if (is<MemberExpression>(node)) {
  693. auto& expression = static_cast<MemberExpression const&>(node);
  694. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  695. if (is<SuperExpression>(expression.object())) {
  696. auto super_reference = TRY(emit_super_reference(expression));
  697. auto dst = allocate_register();
  698. if (super_reference.referenced_name.has_value()) {
  699. emit<Bytecode::Op::DeleteByValueWithThis>(dst, *super_reference.base, *super_reference.this_value, *super_reference.referenced_name);
  700. } else {
  701. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  702. emit<Bytecode::Op::DeleteByIdWithThis>(dst, *super_reference.base, *super_reference.this_value, identifier_table_ref);
  703. }
  704. return Optional<ScopedOperand> {};
  705. }
  706. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  707. auto dst = allocate_register();
  708. if (expression.is_computed()) {
  709. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  710. emit<Bytecode::Op::DeleteByValue>(dst, object, property);
  711. } else if (expression.property().is_identifier()) {
  712. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  713. emit<Bytecode::Op::DeleteById>(dst, object, identifier_table_ref);
  714. } else {
  715. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  716. return CodeGenerationError {
  717. &expression,
  718. "Unimplemented non-computed member expression"sv
  719. };
  720. }
  721. return dst;
  722. }
  723. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  724. // For example: delete a(); delete ++c.b; etc.
  725. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  726. // 1. Let ref be the result of evaluating UnaryExpression.
  727. // 2. ReturnIfAbrupt(ref).
  728. (void)TRY(node.generate_bytecode(*this));
  729. // 3. If ref is not a Reference Record, return true.
  730. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  731. return add_constant(Value(true));
  732. }
  733. void Generator::emit_set_variable(JS::Identifier const& identifier, ScopedOperand value, Bytecode::Op::BindingInitializationMode initialization_mode, Bytecode::Op::EnvironmentMode environment_mode)
  734. {
  735. if (identifier.is_local()) {
  736. if (value.operand().is_local() && value.operand().index() == identifier.local_variable_index()) {
  737. // Moving a local to itself is a no-op.
  738. return;
  739. }
  740. emit<Bytecode::Op::Mov>(local(identifier.local_variable_index()), value);
  741. } else {
  742. auto identifier_index = intern_identifier(identifier.string());
  743. if (environment_mode == Bytecode::Op::EnvironmentMode::Lexical) {
  744. if (initialization_mode == Bytecode::Op::BindingInitializationMode::Initialize) {
  745. emit<Bytecode::Op::InitializeLexicalBinding>(identifier_index, value);
  746. } else if (initialization_mode == Bytecode::Op::BindingInitializationMode::Set) {
  747. emit<Bytecode::Op::SetLexicalBinding>(identifier_index, value);
  748. }
  749. } else if (environment_mode == Bytecode::Op::EnvironmentMode::Var) {
  750. if (initialization_mode == Bytecode::Op::BindingInitializationMode::Initialize) {
  751. emit<Bytecode::Op::InitializeVariableBinding>(identifier_index, value);
  752. } else if (initialization_mode == Bytecode::Op::BindingInitializationMode::Set) {
  753. emit<Bytecode::Op::SetVariableBinding>(identifier_index, value);
  754. }
  755. } else {
  756. VERIFY_NOT_REACHED();
  757. }
  758. }
  759. }
  760. static Optional<ByteString> expression_identifier(Expression const& expression)
  761. {
  762. if (expression.is_identifier()) {
  763. auto const& identifier = static_cast<Identifier const&>(expression);
  764. return identifier.string();
  765. }
  766. if (expression.is_numeric_literal()) {
  767. auto const& literal = static_cast<NumericLiteral const&>(expression);
  768. return literal.value().to_string_without_side_effects().to_byte_string();
  769. }
  770. if (expression.is_string_literal()) {
  771. auto const& literal = static_cast<StringLiteral const&>(expression);
  772. return ByteString::formatted("'{}'", literal.value());
  773. }
  774. if (expression.is_member_expression()) {
  775. auto const& member_expression = static_cast<MemberExpression const&>(expression);
  776. StringBuilder builder;
  777. if (auto identifer = expression_identifier(member_expression.object()); identifer.has_value())
  778. builder.append(*identifer);
  779. if (auto identifer = expression_identifier(member_expression.property()); identifer.has_value()) {
  780. if (member_expression.is_computed())
  781. builder.appendff("[{}]", *identifer);
  782. else
  783. builder.appendff(".{}", *identifer);
  784. }
  785. return builder.to_byte_string();
  786. }
  787. return {};
  788. }
  789. Optional<IdentifierTableIndex> Generator::intern_identifier_for_expression(Expression const& expression)
  790. {
  791. if (auto identifer = expression_identifier(expression); identifer.has_value())
  792. return intern_identifier(identifer.release_value());
  793. return {};
  794. }
  795. void Generator::generate_scoped_jump(JumpType type)
  796. {
  797. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  798. bool last_was_finally = false;
  799. for (size_t i = m_boundaries.size(); i > 0; --i) {
  800. auto boundary = m_boundaries[i - 1];
  801. using enum BlockBoundaryType;
  802. switch (boundary) {
  803. case Break:
  804. if (type == JumpType::Break) {
  805. emit<Op::Jump>(nearest_breakable_scope());
  806. return;
  807. }
  808. break;
  809. case Continue:
  810. if (type == JumpType::Continue) {
  811. emit<Op::Jump>(nearest_continuable_scope());
  812. return;
  813. }
  814. break;
  815. case Unwind:
  816. if (!last_was_finally) {
  817. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  818. emit<Bytecode::Op::LeaveUnwindContext>();
  819. m_current_unwind_context = m_current_unwind_context->previous();
  820. }
  821. last_was_finally = false;
  822. break;
  823. case LeaveLexicalEnvironment:
  824. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  825. break;
  826. case ReturnToFinally: {
  827. VERIFY(m_current_unwind_context->finalizer().has_value());
  828. m_current_unwind_context = m_current_unwind_context->previous();
  829. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  830. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  831. auto& block = make_block(block_name);
  832. emit<Op::ScheduleJump>(Label { block });
  833. switch_to_basic_block(block);
  834. last_was_finally = true;
  835. break;
  836. }
  837. case LeaveFinally:
  838. emit<Op::LeaveFinally>();
  839. break;
  840. }
  841. }
  842. VERIFY_NOT_REACHED();
  843. }
  844. void Generator::generate_labelled_jump(JumpType type, DeprecatedFlyString const& label)
  845. {
  846. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  847. size_t current_boundary = m_boundaries.size();
  848. bool last_was_finally = false;
  849. auto const& jumpable_scopes = type == JumpType::Continue ? m_continuable_scopes : m_breakable_scopes;
  850. for (auto const& jumpable_scope : jumpable_scopes.in_reverse()) {
  851. for (; current_boundary > 0; --current_boundary) {
  852. auto boundary = m_boundaries[current_boundary - 1];
  853. if (boundary == BlockBoundaryType::Unwind) {
  854. if (!last_was_finally) {
  855. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  856. emit<Bytecode::Op::LeaveUnwindContext>();
  857. m_current_unwind_context = m_current_unwind_context->previous();
  858. }
  859. last_was_finally = false;
  860. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  861. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  862. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  863. VERIFY(m_current_unwind_context->finalizer().has_value());
  864. m_current_unwind_context = m_current_unwind_context->previous();
  865. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  866. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  867. auto& block = make_block(block_name);
  868. emit<Op::ScheduleJump>(Label { block });
  869. switch_to_basic_block(block);
  870. last_was_finally = true;
  871. } else if ((type == JumpType::Continue && boundary == BlockBoundaryType::Continue) || (type == JumpType::Break && boundary == BlockBoundaryType::Break)) {
  872. // Make sure we don't process this boundary twice if the current jumpable scope doesn't contain the target label.
  873. --current_boundary;
  874. break;
  875. }
  876. }
  877. if (jumpable_scope.language_label_set.contains_slow(label)) {
  878. emit<Op::Jump>(jumpable_scope.bytecode_target);
  879. return;
  880. }
  881. }
  882. // We must have a jumpable scope available that contains the label, as this should be enforced by the parser.
  883. VERIFY_NOT_REACHED();
  884. }
  885. void Generator::generate_break()
  886. {
  887. generate_scoped_jump(JumpType::Break);
  888. }
  889. void Generator::generate_break(DeprecatedFlyString const& break_label)
  890. {
  891. generate_labelled_jump(JumpType::Break, break_label);
  892. }
  893. void Generator::generate_continue()
  894. {
  895. generate_scoped_jump(JumpType::Continue);
  896. }
  897. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  898. {
  899. generate_labelled_jump(JumpType::Continue, continue_label);
  900. }
  901. void Generator::push_home_object(ScopedOperand object)
  902. {
  903. m_home_objects.append(object);
  904. }
  905. void Generator::pop_home_object()
  906. {
  907. m_home_objects.take_last();
  908. }
  909. void Generator::emit_new_function(ScopedOperand dst, FunctionExpression const& function_node, Optional<IdentifierTableIndex> lhs_name)
  910. {
  911. if (m_home_objects.is_empty()) {
  912. emit<Op::NewFunction>(dst, function_node, lhs_name);
  913. } else {
  914. emit<Op::NewFunction>(dst, function_node, lhs_name, m_home_objects.last());
  915. }
  916. }
  917. CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_named_evaluation_if_anonymous_function(Expression const& expression, Optional<IdentifierTableIndex> lhs_name, Optional<ScopedOperand> preferred_dst)
  918. {
  919. if (is<FunctionExpression>(expression)) {
  920. auto const& function_expression = static_cast<FunctionExpression const&>(expression);
  921. if (!function_expression.has_name()) {
  922. return TRY(function_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  923. }
  924. }
  925. if (is<ClassExpression>(expression)) {
  926. auto const& class_expression = static_cast<ClassExpression const&>(expression);
  927. if (!class_expression.has_name()) {
  928. return TRY(class_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  929. }
  930. }
  931. return expression.generate_bytecode(*this, preferred_dst);
  932. }
  933. void Generator::emit_get_by_id(ScopedOperand dst, ScopedOperand base, IdentifierTableIndex property_identifier, Optional<IdentifierTableIndex> base_identifier)
  934. {
  935. if (m_identifier_table->get(property_identifier) == "length"sv) {
  936. emit<Op::GetLength>(dst, base, move(base_identifier), m_next_property_lookup_cache++);
  937. return;
  938. }
  939. emit<Op::GetById>(dst, base, property_identifier, move(base_identifier), m_next_property_lookup_cache++);
  940. }
  941. void Generator::emit_get_by_id_with_this(ScopedOperand dst, ScopedOperand base, IdentifierTableIndex id, ScopedOperand this_value)
  942. {
  943. if (m_identifier_table->get(id) == "length"sv) {
  944. emit<Op::GetLengthWithThis>(dst, base, this_value, m_next_property_lookup_cache++);
  945. return;
  946. }
  947. emit<Op::GetByIdWithThis>(dst, base, id, this_value, m_next_property_lookup_cache++);
  948. }
  949. void Generator::emit_iterator_value(ScopedOperand dst, ScopedOperand result)
  950. {
  951. emit_get_by_id(dst, result, intern_identifier("value"sv));
  952. }
  953. void Generator::emit_iterator_complete(ScopedOperand dst, ScopedOperand result)
  954. {
  955. emit_get_by_id(dst, result, intern_identifier("done"sv));
  956. }
  957. bool Generator::is_local_initialized(u32 local_index) const
  958. {
  959. return m_initialized_locals.find(local_index) != m_initialized_locals.end();
  960. }
  961. void Generator::set_local_initialized(u32 local_index)
  962. {
  963. m_initialized_locals.set(local_index);
  964. }
  965. ScopedOperand Generator::get_this(Optional<ScopedOperand> preferred_dst)
  966. {
  967. if (m_current_basic_block->has_resolved_this())
  968. return this_value();
  969. if (m_root_basic_blocks[0]->has_resolved_this()) {
  970. m_current_basic_block->set_has_resolved_this();
  971. return this_value();
  972. }
  973. // OPTIMIZATION: If we're compiling a function that doesn't allocate a FunctionEnvironment,
  974. // it will always have the same `this` value as the outer function,
  975. // and so the `this` value is already in the `this` register!
  976. if (m_function && !m_function->allocates_function_environment())
  977. return this_value();
  978. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  979. emit<Bytecode::Op::ResolveThisBinding>();
  980. m_current_basic_block->set_has_resolved_this();
  981. return this_value();
  982. }
  983. ScopedOperand Generator::accumulator()
  984. {
  985. return m_accumulator;
  986. }
  987. ScopedOperand Generator::this_value()
  988. {
  989. return m_this_value;
  990. }
  991. bool Generator::fuse_compare_and_jump(ScopedOperand const& condition, Label true_target, Label false_target)
  992. {
  993. auto& last_instruction = *reinterpret_cast<Instruction const*>(m_current_basic_block->data() + m_current_basic_block->last_instruction_start_offset());
  994. #define HANDLE_COMPARISON_OP(op_TitleCase, op_snake_case, numeric_operator) \
  995. if (last_instruction.type() == Instruction::Type::op_TitleCase) { \
  996. auto& comparison = static_cast<Op::op_TitleCase const&>(last_instruction); \
  997. VERIFY(comparison.dst() == condition); \
  998. auto lhs = comparison.lhs(); \
  999. auto rhs = comparison.rhs(); \
  1000. m_current_basic_block->rewind(); \
  1001. emit<Op::Jump##op_TitleCase>(lhs, rhs, true_target, false_target); \
  1002. return true; \
  1003. }
  1004. JS_ENUMERATE_COMPARISON_OPS(HANDLE_COMPARISON_OP);
  1005. #undef HANDLE_COMPARISON_OP
  1006. return false;
  1007. }
  1008. void Generator::emit_jump_if(ScopedOperand const& condition, Label true_target, Label false_target)
  1009. {
  1010. if (condition.operand().is_constant()) {
  1011. auto value = m_constants[condition.operand().index()];
  1012. if (value.is_boolean()) {
  1013. if (value.as_bool()) {
  1014. emit<Op::Jump>(true_target);
  1015. } else {
  1016. emit<Op::Jump>(false_target);
  1017. }
  1018. return;
  1019. }
  1020. }
  1021. // NOTE: It's only safe to fuse compare-and-jump if the condition is a temporary with no other dependents.
  1022. if (condition.operand().is_register()
  1023. && condition.ref_count() == 1
  1024. && m_current_basic_block->size() > 0) {
  1025. if (fuse_compare_and_jump(condition, true_target, false_target))
  1026. return;
  1027. }
  1028. emit<Op::JumpIf>(condition, true_target, false_target);
  1029. }
  1030. ScopedOperand Generator::copy_if_needed_to_preserve_evaluation_order(ScopedOperand const& operand)
  1031. {
  1032. if (!operand.operand().is_local())
  1033. return operand;
  1034. auto new_register = allocate_register();
  1035. emit<Bytecode::Op::Mov>(new_register, operand);
  1036. return new_register;
  1037. }
  1038. ScopedOperand Generator::add_constant(Value value)
  1039. {
  1040. auto append_new_constant = [&] {
  1041. m_constants.append(value);
  1042. return ScopedOperand { *this, Operand(Operand::Type::Constant, m_constants.size() - 1) };
  1043. };
  1044. if (value.is_boolean()) {
  1045. if (value.as_bool()) {
  1046. if (!m_true_constant.has_value())
  1047. m_true_constant = append_new_constant();
  1048. return m_true_constant.value();
  1049. } else {
  1050. if (!m_false_constant.has_value())
  1051. m_false_constant = append_new_constant();
  1052. return m_false_constant.value();
  1053. }
  1054. }
  1055. if (value.is_undefined()) {
  1056. if (!m_undefined_constant.has_value())
  1057. m_undefined_constant = append_new_constant();
  1058. return m_undefined_constant.value();
  1059. }
  1060. if (value.is_null()) {
  1061. if (!m_null_constant.has_value())
  1062. m_null_constant = append_new_constant();
  1063. return m_null_constant.value();
  1064. }
  1065. if (value.is_empty()) {
  1066. if (!m_empty_constant.has_value())
  1067. m_empty_constant = append_new_constant();
  1068. return m_empty_constant.value();
  1069. }
  1070. if (value.is_int32()) {
  1071. auto as_int32 = value.as_i32();
  1072. return m_int32_constants.ensure(as_int32, [&] {
  1073. return append_new_constant();
  1074. });
  1075. }
  1076. return append_new_constant();
  1077. }
  1078. }