Generator.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/AST.h>
  7. #include <LibJS/Bytecode/BasicBlock.h>
  8. #include <LibJS/Bytecode/Generator.h>
  9. #include <LibJS/Bytecode/Instruction.h>
  10. #include <LibJS/Bytecode/Op.h>
  11. #include <LibJS/Bytecode/Register.h>
  12. namespace JS::Bytecode {
  13. Generator::Generator()
  14. : m_string_table(make<StringTable>())
  15. , m_identifier_table(make<IdentifierTable>())
  16. , m_regex_table(make<RegexTable>())
  17. {
  18. }
  19. CodeGenerationErrorOr<NonnullOwnPtr<Executable>> Generator::generate(ASTNode const& node, FunctionKind enclosing_function_kind)
  20. {
  21. Generator generator;
  22. generator.switch_to_basic_block(generator.make_block());
  23. generator.m_enclosing_function_kind = enclosing_function_kind;
  24. if (generator.is_in_generator_or_async_function()) {
  25. // Immediately yield with no value.
  26. auto& start_block = generator.make_block();
  27. generator.emit<Bytecode::Op::Yield>(Label { start_block });
  28. generator.switch_to_basic_block(start_block);
  29. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  30. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  31. }
  32. TRY(node.generate_bytecode(generator));
  33. if (generator.is_in_generator_or_async_function()) {
  34. // Terminate all unterminated blocks with yield return
  35. for (auto& block : generator.m_root_basic_blocks) {
  36. if (block->is_terminated())
  37. continue;
  38. generator.switch_to_basic_block(*block);
  39. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  40. generator.emit<Bytecode::Op::Yield>(nullptr);
  41. }
  42. }
  43. bool is_strict_mode = false;
  44. if (is<Program>(node))
  45. is_strict_mode = static_cast<Program const&>(node).is_strict_mode();
  46. else if (is<FunctionBody>(node))
  47. is_strict_mode = static_cast<FunctionBody const&>(node).in_strict_mode();
  48. else if (is<FunctionDeclaration>(node))
  49. is_strict_mode = static_cast<FunctionDeclaration const&>(node).is_strict_mode();
  50. else if (is<FunctionExpression>(node))
  51. is_strict_mode = static_cast<FunctionExpression const&>(node).is_strict_mode();
  52. Vector<PropertyLookupCache> property_lookup_caches;
  53. property_lookup_caches.resize(generator.m_next_property_lookup_cache);
  54. Vector<GlobalVariableCache> global_variable_caches;
  55. global_variable_caches.resize(generator.m_next_global_variable_cache);
  56. return adopt_own(*new Executable {
  57. .name = {},
  58. .property_lookup_caches = move(property_lookup_caches),
  59. .global_variable_caches = move(global_variable_caches),
  60. .basic_blocks = move(generator.m_root_basic_blocks),
  61. .string_table = move(generator.m_string_table),
  62. .identifier_table = move(generator.m_identifier_table),
  63. .regex_table = move(generator.m_regex_table),
  64. .number_of_registers = generator.m_next_register,
  65. .is_strict_mode = is_strict_mode,
  66. });
  67. }
  68. void Generator::grow(size_t additional_size)
  69. {
  70. VERIFY(m_current_basic_block);
  71. m_current_basic_block->grow(additional_size);
  72. }
  73. void* Generator::next_slot()
  74. {
  75. VERIFY(m_current_basic_block);
  76. return m_current_basic_block->next_slot();
  77. }
  78. Register Generator::allocate_register()
  79. {
  80. VERIFY(m_next_register != NumericLimits<u32>::max());
  81. return Register { m_next_register++ };
  82. }
  83. Label Generator::nearest_continuable_scope() const
  84. {
  85. return m_continuable_scopes.last().bytecode_target;
  86. }
  87. void Generator::block_declaration_instantiation(ScopeNode const& scope_node)
  88. {
  89. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  90. emit<Bytecode::Op::BlockDeclarationInstantiation>(scope_node);
  91. }
  92. void Generator::begin_variable_scope()
  93. {
  94. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  95. emit<Bytecode::Op::CreateLexicalEnvironment>();
  96. }
  97. void Generator::end_variable_scope()
  98. {
  99. end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  100. if (!m_current_basic_block->is_terminated()) {
  101. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  102. }
  103. }
  104. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  105. {
  106. m_continuable_scopes.append({ continue_target, language_label_set });
  107. start_boundary(BlockBoundaryType::Continue);
  108. }
  109. void Generator::end_continuable_scope()
  110. {
  111. m_continuable_scopes.take_last();
  112. end_boundary(BlockBoundaryType::Continue);
  113. }
  114. Label Generator::nearest_breakable_scope() const
  115. {
  116. return m_breakable_scopes.last().bytecode_target;
  117. }
  118. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  119. {
  120. m_breakable_scopes.append({ breakable_target, language_label_set });
  121. start_boundary(BlockBoundaryType::Break);
  122. }
  123. void Generator::end_breakable_scope()
  124. {
  125. m_breakable_scopes.take_last();
  126. end_boundary(BlockBoundaryType::Break);
  127. }
  128. CodeGenerationErrorOr<Generator::ReferenceRegisters> Generator::emit_super_reference(MemberExpression const& expression)
  129. {
  130. VERIFY(is<SuperExpression>(expression.object()));
  131. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  132. // 1. Let env be GetThisEnvironment().
  133. // 2. Let actualThis be ? env.GetThisBinding().
  134. auto actual_this_register = allocate_register();
  135. emit<Bytecode::Op::ResolveThisBinding>();
  136. emit<Bytecode::Op::Store>(actual_this_register);
  137. Optional<Bytecode::Register> computed_property_value_register;
  138. if (expression.is_computed()) {
  139. // SuperProperty : super [ Expression ]
  140. // 3. Let propertyNameReference be ? Evaluation of Expression.
  141. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  142. TRY(expression.property().generate_bytecode(*this));
  143. computed_property_value_register = allocate_register();
  144. emit<Bytecode::Op::Store>(*computed_property_value_register);
  145. }
  146. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  147. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  148. // 1. Let env be GetThisEnvironment().
  149. // 2. Assert: env.HasSuperBinding() is true.
  150. // 3. Let baseValue be ? env.GetSuperBase().
  151. auto super_base_register = allocate_register();
  152. emit<Bytecode::Op::ResolveSuperBase>();
  153. emit<Bytecode::Op::Store>(super_base_register);
  154. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  155. return ReferenceRegisters {
  156. .base = super_base_register,
  157. .referenced_name = move(computed_property_value_register),
  158. .this_value = actual_this_register,
  159. };
  160. }
  161. CodeGenerationErrorOr<void> Generator::emit_load_from_reference(JS::ASTNode const& node)
  162. {
  163. if (is<Identifier>(node)) {
  164. auto& identifier = static_cast<Identifier const&>(node);
  165. TRY(identifier.generate_bytecode(*this));
  166. return {};
  167. }
  168. if (is<MemberExpression>(node)) {
  169. auto& expression = static_cast<MemberExpression const&>(node);
  170. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  171. if (is<SuperExpression>(expression.object())) {
  172. auto super_reference = TRY(emit_super_reference(expression));
  173. if (super_reference.referenced_name.has_value()) {
  174. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  175. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  176. emit<Bytecode::Op::Load>(*super_reference.referenced_name);
  177. emit<Bytecode::Op::GetByValueWithThis>(super_reference.base, super_reference.this_value);
  178. } else {
  179. // 3. Let propertyKey be StringValue of IdentifierName.
  180. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  181. emit_get_by_id_with_this(identifier_table_ref, super_reference.this_value);
  182. }
  183. } else {
  184. TRY(expression.object().generate_bytecode(*this));
  185. if (expression.is_computed()) {
  186. auto object_reg = allocate_register();
  187. emit<Bytecode::Op::Store>(object_reg);
  188. TRY(expression.property().generate_bytecode(*this));
  189. emit<Bytecode::Op::GetByValue>(object_reg);
  190. } else if (expression.property().is_identifier()) {
  191. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  192. emit_get_by_id(identifier_table_ref);
  193. } else if (expression.property().is_private_identifier()) {
  194. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  195. emit<Bytecode::Op::GetPrivateById>(identifier_table_ref);
  196. } else {
  197. return CodeGenerationError {
  198. &expression,
  199. "Unimplemented non-computed member expression"sv
  200. };
  201. }
  202. }
  203. return {};
  204. }
  205. VERIFY_NOT_REACHED();
  206. }
  207. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node)
  208. {
  209. if (is<Identifier>(node)) {
  210. auto& identifier = static_cast<Identifier const&>(node);
  211. emit_set_variable(identifier);
  212. return {};
  213. }
  214. if (is<MemberExpression>(node)) {
  215. // NOTE: The value is in the accumulator, so we have to store that away first.
  216. auto value_reg = allocate_register();
  217. emit<Bytecode::Op::Store>(value_reg);
  218. auto& expression = static_cast<MemberExpression const&>(node);
  219. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  220. if (is<SuperExpression>(expression.object())) {
  221. auto super_reference = TRY(emit_super_reference(expression));
  222. emit<Bytecode::Op::Load>(value_reg);
  223. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  224. if (super_reference.referenced_name.has_value()) {
  225. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  226. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  227. emit<Bytecode::Op::PutByValueWithThis>(super_reference.base, *super_reference.referenced_name, super_reference.this_value);
  228. } else {
  229. // 3. Let propertyKey be StringValue of IdentifierName.
  230. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  231. emit<Bytecode::Op::PutByIdWithThis>(super_reference.base, super_reference.this_value, identifier_table_ref);
  232. }
  233. } else {
  234. TRY(expression.object().generate_bytecode(*this));
  235. auto object_reg = allocate_register();
  236. emit<Bytecode::Op::Store>(object_reg);
  237. if (expression.is_computed()) {
  238. TRY(expression.property().generate_bytecode(*this));
  239. auto property_reg = allocate_register();
  240. emit<Bytecode::Op::Store>(property_reg);
  241. emit<Bytecode::Op::Load>(value_reg);
  242. emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  243. } else if (expression.property().is_identifier()) {
  244. emit<Bytecode::Op::Load>(value_reg);
  245. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  246. emit<Bytecode::Op::PutById>(object_reg, identifier_table_ref);
  247. } else if (expression.property().is_private_identifier()) {
  248. emit<Bytecode::Op::Load>(value_reg);
  249. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  250. emit<Bytecode::Op::PutPrivateById>(object_reg, identifier_table_ref);
  251. } else {
  252. return CodeGenerationError {
  253. &expression,
  254. "Unimplemented non-computed member expression"sv
  255. };
  256. }
  257. }
  258. return {};
  259. }
  260. return CodeGenerationError {
  261. &node,
  262. "Unimplemented/invalid node used a reference"sv
  263. };
  264. }
  265. CodeGenerationErrorOr<void> Generator::emit_delete_reference(JS::ASTNode const& node)
  266. {
  267. if (is<Identifier>(node)) {
  268. auto& identifier = static_cast<Identifier const&>(node);
  269. if (identifier.is_local())
  270. emit<Bytecode::Op::LoadImmediate>(Value(false));
  271. else
  272. emit<Bytecode::Op::DeleteVariable>(intern_identifier(identifier.string()));
  273. return {};
  274. }
  275. if (is<MemberExpression>(node)) {
  276. auto& expression = static_cast<MemberExpression const&>(node);
  277. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  278. if (is<SuperExpression>(expression.object())) {
  279. auto super_reference = TRY(emit_super_reference(expression));
  280. if (super_reference.referenced_name.has_value()) {
  281. emit<Bytecode::Op::DeleteByValueWithThis>(super_reference.this_value, *super_reference.referenced_name);
  282. } else {
  283. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  284. emit<Bytecode::Op::DeleteByIdWithThis>(super_reference.this_value, identifier_table_ref);
  285. }
  286. return {};
  287. }
  288. TRY(expression.object().generate_bytecode(*this));
  289. if (expression.is_computed()) {
  290. auto object_reg = allocate_register();
  291. emit<Bytecode::Op::Store>(object_reg);
  292. TRY(expression.property().generate_bytecode(*this));
  293. emit<Bytecode::Op::DeleteByValue>(object_reg);
  294. } else if (expression.property().is_identifier()) {
  295. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  296. emit<Bytecode::Op::DeleteById>(identifier_table_ref);
  297. } else {
  298. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  299. return CodeGenerationError {
  300. &expression,
  301. "Unimplemented non-computed member expression"sv
  302. };
  303. }
  304. return {};
  305. }
  306. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  307. // For example: delete a(); delete ++c.b; etc.
  308. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  309. // 1. Let ref be the result of evaluating UnaryExpression.
  310. // 2. ReturnIfAbrupt(ref).
  311. TRY(node.generate_bytecode(*this));
  312. // 3. If ref is not a Reference Record, return true.
  313. emit<Bytecode::Op::LoadImmediate>(Value(true));
  314. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  315. return {};
  316. }
  317. void Generator::emit_set_variable(JS::Identifier const& identifier, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Op::EnvironmentMode mode)
  318. {
  319. if (identifier.is_local()) {
  320. emit<Bytecode::Op::SetLocal>(identifier.local_variable_index());
  321. } else {
  322. emit<Bytecode::Op::SetVariable>(intern_identifier(identifier.string()), initialization_mode, mode);
  323. }
  324. }
  325. void Generator::generate_scoped_jump(JumpType type)
  326. {
  327. bool last_was_finally = false;
  328. for (size_t i = m_boundaries.size(); i > 0; --i) {
  329. auto boundary = m_boundaries[i - 1];
  330. using enum BlockBoundaryType;
  331. switch (boundary) {
  332. case Break:
  333. if (type == JumpType::Break) {
  334. emit<Op::Jump>().set_targets(nearest_breakable_scope(), {});
  335. return;
  336. }
  337. break;
  338. case Continue:
  339. if (type == JumpType::Continue) {
  340. emit<Op::Jump>().set_targets(nearest_continuable_scope(), {});
  341. return;
  342. }
  343. break;
  344. case Unwind:
  345. if (!last_was_finally)
  346. emit<Bytecode::Op::LeaveUnwindContext>();
  347. last_was_finally = false;
  348. break;
  349. case LeaveLexicalEnvironment:
  350. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  351. break;
  352. case ReturnToFinally: {
  353. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  354. auto& block = make_block(DeprecatedString::formatted("{}.{}", current_block().name(), jump_type_name));
  355. emit<Op::ScheduleJump>(Label { block });
  356. switch_to_basic_block(block);
  357. last_was_finally = true;
  358. break;
  359. };
  360. }
  361. }
  362. VERIFY_NOT_REACHED();
  363. }
  364. void Generator::generate_break()
  365. {
  366. generate_scoped_jump(JumpType::Break);
  367. }
  368. void Generator::generate_break(DeprecatedFlyString const& break_label)
  369. {
  370. size_t current_boundary = m_boundaries.size();
  371. bool last_was_finally = false;
  372. for (auto const& breakable_scope : m_breakable_scopes.in_reverse()) {
  373. for (; current_boundary > 0; --current_boundary) {
  374. auto boundary = m_boundaries[current_boundary - 1];
  375. if (boundary == BlockBoundaryType::Unwind) {
  376. if (!last_was_finally)
  377. emit<Bytecode::Op::LeaveUnwindContext>();
  378. last_was_finally = false;
  379. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  380. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  381. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  382. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  383. emit<Op::ScheduleJump>(Label { block });
  384. switch_to_basic_block(block);
  385. last_was_finally = true;
  386. } else if (boundary == BlockBoundaryType::Break) {
  387. // Make sure we don't process this boundary twice if the current breakable scope doesn't contain the target label.
  388. --current_boundary;
  389. break;
  390. }
  391. }
  392. if (breakable_scope.language_label_set.contains_slow(break_label)) {
  393. emit<Op::Jump>().set_targets(breakable_scope.bytecode_target, {});
  394. return;
  395. }
  396. }
  397. // We must have a breakable scope available that contains the label, as this should be enforced by the parser.
  398. VERIFY_NOT_REACHED();
  399. }
  400. void Generator::generate_continue()
  401. {
  402. generate_scoped_jump(JumpType::Continue);
  403. }
  404. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  405. {
  406. size_t current_boundary = m_boundaries.size();
  407. bool last_was_finally = false;
  408. for (auto const& continuable_scope : m_continuable_scopes.in_reverse()) {
  409. for (; current_boundary > 0; --current_boundary) {
  410. auto boundary = m_boundaries[current_boundary - 1];
  411. if (boundary == BlockBoundaryType::Unwind) {
  412. if (!last_was_finally)
  413. emit<Bytecode::Op::LeaveUnwindContext>();
  414. last_was_finally = false;
  415. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  416. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  417. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  418. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  419. emit<Op::ScheduleJump>(Label { block });
  420. switch_to_basic_block(block);
  421. last_was_finally = true;
  422. } else if (boundary == BlockBoundaryType::Continue) {
  423. // Make sure we don't process this boundary twice if the current continuable scope doesn't contain the target label.
  424. --current_boundary;
  425. break;
  426. }
  427. }
  428. if (continuable_scope.language_label_set.contains_slow(continue_label)) {
  429. emit<Op::Jump>().set_targets(continuable_scope.bytecode_target, {});
  430. return;
  431. }
  432. }
  433. // We must have a continuable scope available that contains the label, as this should be enforced by the parser.
  434. VERIFY_NOT_REACHED();
  435. }
  436. void Generator::push_home_object(Register register_)
  437. {
  438. m_home_objects.append(register_);
  439. }
  440. void Generator::pop_home_object()
  441. {
  442. m_home_objects.take_last();
  443. }
  444. void Generator::emit_new_function(FunctionExpression const& function_node, Optional<IdentifierTableIndex> lhs_name)
  445. {
  446. if (m_home_objects.is_empty())
  447. emit<Op::NewFunction>(function_node, lhs_name);
  448. else
  449. emit<Op::NewFunction>(function_node, lhs_name, m_home_objects.last());
  450. }
  451. CodeGenerationErrorOr<void> Generator::emit_named_evaluation_if_anonymous_function(Expression const& expression, Optional<IdentifierTableIndex> lhs_name)
  452. {
  453. if (is<FunctionExpression>(expression)) {
  454. auto const& function_expression = static_cast<FunctionExpression const&>(expression);
  455. if (!function_expression.has_name()) {
  456. TRY(function_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name)));
  457. return {};
  458. }
  459. }
  460. if (is<ClassExpression>(expression)) {
  461. auto const& class_expression = static_cast<ClassExpression const&>(expression);
  462. if (!class_expression.has_name()) {
  463. TRY(class_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name)));
  464. return {};
  465. }
  466. }
  467. TRY(expression.generate_bytecode(*this));
  468. return {};
  469. }
  470. void Generator::emit_get_by_id(IdentifierTableIndex id)
  471. {
  472. emit<Op::GetById>(id, m_next_property_lookup_cache++);
  473. }
  474. void Generator::emit_get_by_id_with_this(IdentifierTableIndex id, Register this_reg)
  475. {
  476. emit<Op::GetByIdWithThis>(id, this_reg, m_next_property_lookup_cache++);
  477. }
  478. }