RegexOptimizer.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <AK/RedBlackTree.h>
  8. #include <AK/Stack.h>
  9. #include <LibRegex/Regex.h>
  10. #include <LibRegex/RegexBytecodeStreamOptimizer.h>
  11. #if REGEX_DEBUG
  12. # include <AK/ScopeGuard.h>
  13. # include <AK/ScopeLogger.h>
  14. #endif
  15. namespace regex {
  16. using Detail::Block;
  17. template<typename Parser>
  18. void Regex<Parser>::run_optimization_passes()
  19. {
  20. parser_result.bytecode.flatten();
  21. // Rewrite fork loops as atomic groups
  22. // e.g. a*b -> (ATOMIC a*)b
  23. attempt_rewrite_loops_as_atomic_groups(split_basic_blocks(parser_result.bytecode));
  24. parser_result.bytecode.flatten();
  25. }
  26. template<typename Parser>
  27. typename Regex<Parser>::BasicBlockList Regex<Parser>::split_basic_blocks(ByteCode const& bytecode)
  28. {
  29. BasicBlockList block_boundaries;
  30. size_t end_of_last_block = 0;
  31. auto bytecode_size = bytecode.size();
  32. MatchState state;
  33. state.instruction_position = 0;
  34. auto check_jump = [&]<typename T>(OpCode const& opcode) {
  35. auto& op = static_cast<T const&>(opcode);
  36. ssize_t jump_offset = op.size() + op.offset();
  37. if (jump_offset >= 0) {
  38. block_boundaries.append({ end_of_last_block, state.instruction_position });
  39. end_of_last_block = state.instruction_position + opcode.size();
  40. } else {
  41. // This op jumps back, see if that's within this "block".
  42. if (jump_offset + state.instruction_position > end_of_last_block) {
  43. // Split the block!
  44. block_boundaries.append({ end_of_last_block, jump_offset + state.instruction_position });
  45. block_boundaries.append({ jump_offset + state.instruction_position, state.instruction_position });
  46. end_of_last_block = state.instruction_position + opcode.size();
  47. } else {
  48. // Nope, it's just a jump to another block
  49. block_boundaries.append({ end_of_last_block, state.instruction_position });
  50. end_of_last_block = state.instruction_position + opcode.size();
  51. }
  52. }
  53. };
  54. for (;;) {
  55. auto& opcode = bytecode.get_opcode(state);
  56. switch (opcode.opcode_id()) {
  57. case OpCodeId::Jump:
  58. check_jump.template operator()<OpCode_Jump>(opcode);
  59. break;
  60. case OpCodeId::JumpNonEmpty:
  61. check_jump.template operator()<OpCode_JumpNonEmpty>(opcode);
  62. break;
  63. case OpCodeId::ForkJump:
  64. check_jump.template operator()<OpCode_ForkJump>(opcode);
  65. break;
  66. case OpCodeId::ForkStay:
  67. check_jump.template operator()<OpCode_ForkStay>(opcode);
  68. break;
  69. case OpCodeId::FailForks:
  70. block_boundaries.append({ end_of_last_block, state.instruction_position });
  71. end_of_last_block = state.instruction_position + opcode.size();
  72. break;
  73. case OpCodeId::Repeat: {
  74. // Repeat produces two blocks, one containing its repeated expr, and one after that.
  75. auto repeat_start = state.instruction_position - static_cast<OpCode_Repeat const&>(opcode).offset();
  76. if (repeat_start > end_of_last_block)
  77. block_boundaries.append({ end_of_last_block, repeat_start });
  78. block_boundaries.append({ repeat_start, state.instruction_position });
  79. end_of_last_block = state.instruction_position + opcode.size();
  80. break;
  81. }
  82. default:
  83. break;
  84. }
  85. auto next_ip = state.instruction_position + opcode.size();
  86. if (next_ip < bytecode_size)
  87. state.instruction_position = next_ip;
  88. else
  89. break;
  90. }
  91. if (end_of_last_block < bytecode_size)
  92. block_boundaries.append({ end_of_last_block, bytecode_size });
  93. quick_sort(block_boundaries, [](auto& a, auto& b) { return a.start < b.start; });
  94. return block_boundaries;
  95. }
  96. static bool has_overlap(Vector<CompareTypeAndValuePair> const& lhs, Vector<CompareTypeAndValuePair> const& rhs)
  97. {
  98. // We have to fully interpret the two sequences to determine if they overlap (that is, keep track of inversion state and what ranges they cover).
  99. bool inverse { false };
  100. bool temporary_inverse { false };
  101. bool reset_temporary_inverse { false };
  102. auto current_lhs_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  103. RedBlackTree<u32, u32> lhs_ranges;
  104. RedBlackTree<u32, u32> lhs_negated_ranges;
  105. HashTable<CharClass> lhs_char_classes;
  106. HashTable<CharClass> lhs_negated_char_classes;
  107. auto range_contains = [&]<typename T>(T& value) -> bool {
  108. u32 start;
  109. u32 end;
  110. if constexpr (IsSame<T, CharRange>) {
  111. start = value.from;
  112. end = value.to;
  113. } else {
  114. start = value;
  115. end = value;
  116. }
  117. auto* max = lhs_ranges.find_smallest_not_below(start);
  118. return max && *max <= end;
  119. };
  120. auto char_class_contains = [&](CharClass const& value) -> bool {
  121. if (lhs_char_classes.contains(value))
  122. return true;
  123. if (lhs_negated_char_classes.contains(value))
  124. return false;
  125. // This char class might match something in the ranges we have, and checking that is far too expensive, so just bail out.
  126. return true;
  127. };
  128. for (auto const& pair : lhs) {
  129. if (reset_temporary_inverse) {
  130. reset_temporary_inverse = false;
  131. temporary_inverse = false;
  132. } else {
  133. reset_temporary_inverse = true;
  134. }
  135. switch (pair.type) {
  136. case CharacterCompareType::Inverse:
  137. inverse = !inverse;
  138. break;
  139. case CharacterCompareType::TemporaryInverse:
  140. temporary_inverse = true;
  141. reset_temporary_inverse = true;
  142. break;
  143. case CharacterCompareType::AnyChar:
  144. // Special case: if not inverted, AnyChar is always in the range.
  145. if (!current_lhs_inversion_state())
  146. return true;
  147. break;
  148. case CharacterCompareType::Char:
  149. if (!current_lhs_inversion_state())
  150. lhs_ranges.insert(pair.value, pair.value);
  151. else
  152. lhs_negated_ranges.insert(pair.value, pair.value);
  153. break;
  154. case CharacterCompareType::String:
  155. // FIXME: We just need to look at the last character of this string, but we only have the first character here.
  156. // Just bail out to avoid false positives.
  157. return true;
  158. case CharacterCompareType::CharClass:
  159. if (!current_lhs_inversion_state())
  160. lhs_char_classes.set(static_cast<CharClass>(pair.value));
  161. else
  162. lhs_negated_char_classes.set(static_cast<CharClass>(pair.value));
  163. break;
  164. case CharacterCompareType::CharRange: {
  165. auto range = CharRange(pair.value);
  166. if (!current_lhs_inversion_state())
  167. lhs_ranges.insert(range.from, range.to);
  168. else
  169. lhs_negated_ranges.insert(range.from, range.to);
  170. break;
  171. }
  172. case CharacterCompareType::LookupTable:
  173. // We've transformed this into a series of ranges in flat_compares(), so bail out if we see it.
  174. return true;
  175. case CharacterCompareType::Reference:
  176. // We've handled this before coming here.
  177. break;
  178. case CharacterCompareType::Property:
  179. case CharacterCompareType::GeneralCategory:
  180. case CharacterCompareType::Script:
  181. case CharacterCompareType::ScriptExtension:
  182. // FIXME: These are too difficult to handle, so bail out.
  183. return true;
  184. case CharacterCompareType::Undefined:
  185. case CharacterCompareType::RangeExpressionDummy:
  186. // These do not occur in valid bytecode.
  187. VERIFY_NOT_REACHED();
  188. }
  189. }
  190. if constexpr (REGEX_DEBUG) {
  191. dbgln("lhs ranges:");
  192. for (auto it = lhs_ranges.begin(); it != lhs_ranges.end(); ++it)
  193. dbgln(" {}..{}", it.key(), *it);
  194. dbgln("lhs negated ranges:");
  195. for (auto it = lhs_negated_ranges.begin(); it != lhs_negated_ranges.end(); ++it)
  196. dbgln(" {}..{}", it.key(), *it);
  197. }
  198. for (auto const& pair : rhs) {
  199. if (reset_temporary_inverse) {
  200. reset_temporary_inverse = false;
  201. temporary_inverse = false;
  202. } else {
  203. reset_temporary_inverse = true;
  204. }
  205. dbgln_if(REGEX_DEBUG, "check {} ({})...", character_compare_type_name(pair.type), pair.value);
  206. switch (pair.type) {
  207. case CharacterCompareType::Inverse:
  208. inverse = !inverse;
  209. break;
  210. case CharacterCompareType::TemporaryInverse:
  211. temporary_inverse = true;
  212. reset_temporary_inverse = true;
  213. break;
  214. case CharacterCompareType::AnyChar:
  215. // Special case: if not inverted, AnyChar is always in the range.
  216. if (!current_lhs_inversion_state())
  217. return true;
  218. break;
  219. case CharacterCompareType::Char:
  220. if (!current_lhs_inversion_state() && range_contains(pair.value))
  221. return true;
  222. break;
  223. case CharacterCompareType::String:
  224. // FIXME: We just need to look at the last character of this string, but we only have the first character here.
  225. // Just bail out to avoid false positives.
  226. return true;
  227. case CharacterCompareType::CharClass:
  228. if (!current_lhs_inversion_state() && char_class_contains(static_cast<CharClass>(pair.value)))
  229. return true;
  230. break;
  231. case CharacterCompareType::CharRange: {
  232. auto range = CharRange(pair.value);
  233. if (!current_lhs_inversion_state() && range_contains(range))
  234. return true;
  235. break;
  236. }
  237. case CharacterCompareType::LookupTable:
  238. // We've transformed this into a series of ranges in flat_compares(), so bail out if we see it.
  239. return true;
  240. case CharacterCompareType::Reference:
  241. // We've handled this before coming here.
  242. break;
  243. case CharacterCompareType::Property:
  244. case CharacterCompareType::GeneralCategory:
  245. case CharacterCompareType::Script:
  246. case CharacterCompareType::ScriptExtension:
  247. // FIXME: These are too difficult to handle, so bail out.
  248. return true;
  249. case CharacterCompareType::Undefined:
  250. case CharacterCompareType::RangeExpressionDummy:
  251. // These do not occur in valid bytecode.
  252. VERIFY_NOT_REACHED();
  253. }
  254. }
  255. return false;
  256. }
  257. enum class AtomicRewritePreconditionResult {
  258. SatisfiedWithProperHeader,
  259. SatisfiedWithEmptyHeader,
  260. NotSatisfied,
  261. };
  262. static AtomicRewritePreconditionResult block_satisfies_atomic_rewrite_precondition(ByteCode const& bytecode, Block const& repeated_block, Block const& following_block)
  263. {
  264. Vector<Vector<CompareTypeAndValuePair>> repeated_values;
  265. HashTable<size_t> active_capture_groups;
  266. MatchState state;
  267. for (state.instruction_position = repeated_block.start; state.instruction_position < repeated_block.end;) {
  268. auto& opcode = bytecode.get_opcode(state);
  269. switch (opcode.opcode_id()) {
  270. case OpCodeId::Compare: {
  271. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  272. if (repeated_values.is_empty() && any_of(compares, [](auto& compare) { return compare.type == CharacterCompareType::AnyChar; }))
  273. return AtomicRewritePreconditionResult::NotSatisfied;
  274. repeated_values.append(move(compares));
  275. break;
  276. }
  277. case OpCodeId::CheckBegin:
  278. case OpCodeId::CheckEnd:
  279. if (repeated_values.is_empty())
  280. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  281. break;
  282. case OpCodeId::CheckBoundary:
  283. // FIXME: What should we do with these? for now, let's fail.
  284. return AtomicRewritePreconditionResult::NotSatisfied;
  285. case OpCodeId::Restore:
  286. case OpCodeId::GoBack:
  287. return AtomicRewritePreconditionResult::NotSatisfied;
  288. case OpCodeId::SaveRightCaptureGroup:
  289. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  290. break;
  291. case OpCodeId::SaveLeftCaptureGroup:
  292. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  293. break;
  294. default:
  295. break;
  296. }
  297. state.instruction_position += opcode.size();
  298. }
  299. dbgln_if(REGEX_DEBUG, "Found {} entries in reference", repeated_values.size());
  300. dbgln_if(REGEX_DEBUG, "Found {} active capture groups", active_capture_groups.size());
  301. bool following_block_has_at_least_one_compare = false;
  302. // Find the first compare in the following block, it must NOT match any of the values in `repeated_values'.
  303. for (state.instruction_position = following_block.start; state.instruction_position < following_block.end;) {
  304. auto& opcode = bytecode.get_opcode(state);
  305. switch (opcode.opcode_id()) {
  306. // Note: These have to exist since we're effectively repeating the following block as well
  307. case OpCodeId::SaveRightCaptureGroup:
  308. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  309. break;
  310. case OpCodeId::SaveLeftCaptureGroup:
  311. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  312. break;
  313. case OpCodeId::Compare: {
  314. following_block_has_at_least_one_compare = true;
  315. // We found a compare, let's see what it has.
  316. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  317. if (compares.is_empty())
  318. break;
  319. if (any_of(compares, [&](auto& compare) {
  320. return compare.type == CharacterCompareType::AnyChar
  321. || (compare.type == CharacterCompareType::Reference && active_capture_groups.contains(compare.value));
  322. }))
  323. return AtomicRewritePreconditionResult::NotSatisfied;
  324. if (any_of(repeated_values, [&](auto& repeated_value) { return has_overlap(compares, repeated_value); }))
  325. return AtomicRewritePreconditionResult::NotSatisfied;
  326. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  327. }
  328. case OpCodeId::CheckBegin:
  329. case OpCodeId::CheckEnd:
  330. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader; // Nothing can match the end!
  331. case OpCodeId::CheckBoundary:
  332. // FIXME: What should we do with these? For now, consider them a failure.
  333. return AtomicRewritePreconditionResult::NotSatisfied;
  334. default:
  335. break;
  336. }
  337. state.instruction_position += opcode.size();
  338. }
  339. if (following_block_has_at_least_one_compare)
  340. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  341. return AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader;
  342. }
  343. template<typename Parser>
  344. void Regex<Parser>::attempt_rewrite_loops_as_atomic_groups(BasicBlockList const& basic_blocks)
  345. {
  346. auto& bytecode = parser_result.bytecode;
  347. if constexpr (REGEX_DEBUG) {
  348. RegexDebug dbg;
  349. dbg.print_bytecode(*this);
  350. for (auto const& block : basic_blocks)
  351. dbgln("block from {} to {}", block.start, block.end);
  352. }
  353. // A pattern such as:
  354. // bb0 | RE0
  355. // | ForkX bb0
  356. // -------------------------
  357. // bb1 | RE1
  358. // can be rewritten as:
  359. // -------------------------
  360. // bb0 | RE0
  361. // | ForkReplaceX bb0
  362. // -------------------------
  363. // bb1 | RE1
  364. // provided that first(RE1) not-in end(RE0), which is to say
  365. // that RE1 cannot start with whatever RE0 has matched (ever).
  366. //
  367. // Alternatively, a second form of this pattern can also occur:
  368. // bb0 | *
  369. // | ForkX bb2
  370. // ------------------------
  371. // bb1 | RE0
  372. // | Jump bb0
  373. // ------------------------
  374. // bb2 | RE1
  375. // which can be transformed (with the same preconditions) to:
  376. // bb0 | *
  377. // | ForkReplaceX bb2
  378. // ------------------------
  379. // bb1 | RE0
  380. // | Jump bb0
  381. // ------------------------
  382. // bb2 | RE1
  383. enum class AlternateForm {
  384. DirectLoopWithoutHeader, // loop without proper header, a block forking to itself. i.e. the first form.
  385. DirectLoopWithoutHeaderAndEmptyFollow, // loop without proper header, a block forking to itself. i.e. the first form but with RE1 being empty.
  386. DirectLoopWithHeader, // loop with proper header, i.e. the second form.
  387. };
  388. struct CandidateBlock {
  389. Block forking_block;
  390. Optional<Block> new_target_block;
  391. AlternateForm form;
  392. };
  393. Vector<CandidateBlock> candidate_blocks;
  394. auto is_an_eligible_jump = [](OpCode const& opcode, size_t ip, size_t block_start, AlternateForm alternate_form) {
  395. switch (opcode.opcode_id()) {
  396. case OpCodeId::JumpNonEmpty: {
  397. auto const& op = static_cast<OpCode_JumpNonEmpty const&>(opcode);
  398. auto form = op.form();
  399. if (form != OpCodeId::Jump && alternate_form == AlternateForm::DirectLoopWithHeader)
  400. return false;
  401. if (form != OpCodeId::ForkJump && form != OpCodeId::ForkStay && alternate_form == AlternateForm::DirectLoopWithoutHeader)
  402. return false;
  403. return op.offset() + ip + opcode.size() == block_start;
  404. }
  405. case OpCodeId::ForkJump:
  406. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  407. return false;
  408. return static_cast<OpCode_ForkJump const&>(opcode).offset() + ip + opcode.size() == block_start;
  409. case OpCodeId::ForkStay:
  410. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  411. return false;
  412. return static_cast<OpCode_ForkStay const&>(opcode).offset() + ip + opcode.size() == block_start;
  413. case OpCodeId::Jump:
  414. // Infinite loop does *not* produce forks.
  415. if (alternate_form == AlternateForm::DirectLoopWithoutHeader)
  416. return false;
  417. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  418. return static_cast<OpCode_Jump const&>(opcode).offset() + ip + opcode.size() == block_start;
  419. VERIFY_NOT_REACHED();
  420. default:
  421. return false;
  422. }
  423. };
  424. for (size_t i = 0; i < basic_blocks.size(); ++i) {
  425. auto forking_block = basic_blocks[i];
  426. Optional<Block> fork_fallback_block;
  427. if (i + 1 < basic_blocks.size())
  428. fork_fallback_block = basic_blocks[i + 1];
  429. MatchState state;
  430. // Check if the last instruction in this block is a jump to the block itself:
  431. {
  432. state.instruction_position = forking_block.end;
  433. auto& opcode = bytecode.get_opcode(state);
  434. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithoutHeader)) {
  435. // We've found RE0 (and RE1 is just the following block, if any), let's see if the precondition applies.
  436. // if RE1 is empty, there's no first(RE1), so this is an automatic pass.
  437. if (!fork_fallback_block.has_value() || fork_fallback_block->end == fork_fallback_block->start) {
  438. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  439. break;
  440. }
  441. auto precondition = block_satisfies_atomic_rewrite_precondition(bytecode, forking_block, *fork_fallback_block);
  442. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithProperHeader) {
  443. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  444. break;
  445. }
  446. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader) {
  447. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeaderAndEmptyFollow });
  448. break;
  449. }
  450. }
  451. }
  452. // Check if the last instruction in the last block is a direct jump to this block
  453. if (fork_fallback_block.has_value()) {
  454. state.instruction_position = fork_fallback_block->end;
  455. auto& opcode = bytecode.get_opcode(state);
  456. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithHeader)) {
  457. // We've found bb1 and bb0, let's just make sure that bb0 forks to bb2.
  458. state.instruction_position = forking_block.end;
  459. auto& opcode = bytecode.get_opcode(state);
  460. if (opcode.opcode_id() == OpCodeId::ForkJump || opcode.opcode_id() == OpCodeId::ForkStay) {
  461. Optional<Block> block_following_fork_fallback;
  462. if (i + 2 < basic_blocks.size())
  463. block_following_fork_fallback = basic_blocks[i + 2];
  464. if (!block_following_fork_fallback.has_value()
  465. || block_satisfies_atomic_rewrite_precondition(bytecode, *fork_fallback_block, *block_following_fork_fallback) != AtomicRewritePreconditionResult::NotSatisfied) {
  466. candidate_blocks.append({ forking_block, {}, AlternateForm::DirectLoopWithHeader });
  467. break;
  468. }
  469. }
  470. }
  471. }
  472. }
  473. dbgln_if(REGEX_DEBUG, "Found {} candidate blocks", candidate_blocks.size());
  474. if (candidate_blocks.is_empty()) {
  475. dbgln_if(REGEX_DEBUG, "Failed to find anything for {}", pattern_value);
  476. return;
  477. }
  478. RedBlackTree<size_t, size_t> needed_patches;
  479. // Reverse the blocks, so we can patch the bytecode without messing with the latter patches.
  480. quick_sort(candidate_blocks, [](auto& a, auto& b) { return b.forking_block.start > a.forking_block.start; });
  481. for (auto& candidate : candidate_blocks) {
  482. // Note that both forms share a ForkReplace patch in forking_block.
  483. // Patch the ForkX in forking_block to be a ForkReplaceX instead.
  484. auto& opcode_id = bytecode[candidate.forking_block.end];
  485. if (opcode_id == (ByteCodeValueType)OpCodeId::ForkStay) {
  486. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  487. } else if (opcode_id == (ByteCodeValueType)OpCodeId::ForkJump) {
  488. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  489. } else if (opcode_id == (ByteCodeValueType)OpCodeId::JumpNonEmpty) {
  490. auto& jump_opcode_id = bytecode[candidate.forking_block.end + 3];
  491. if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkStay)
  492. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  493. else if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkJump)
  494. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  495. else
  496. VERIFY_NOT_REACHED();
  497. } else {
  498. VERIFY_NOT_REACHED();
  499. }
  500. }
  501. if (!needed_patches.is_empty()) {
  502. MatchState state;
  503. auto bytecode_size = bytecode.size();
  504. state.instruction_position = 0;
  505. struct Patch {
  506. ssize_t value;
  507. size_t offset;
  508. bool should_negate { false };
  509. };
  510. for (;;) {
  511. if (state.instruction_position >= bytecode_size)
  512. break;
  513. auto& opcode = bytecode.get_opcode(state);
  514. Stack<Patch, 2> patch_points;
  515. switch (opcode.opcode_id()) {
  516. case OpCodeId::Jump:
  517. patch_points.push({ static_cast<OpCode_Jump const&>(opcode).offset(), state.instruction_position + 1 });
  518. break;
  519. case OpCodeId::JumpNonEmpty:
  520. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).offset(), state.instruction_position + 1 });
  521. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).checkpoint(), state.instruction_position + 2 });
  522. break;
  523. case OpCodeId::ForkJump:
  524. patch_points.push({ static_cast<OpCode_ForkJump const&>(opcode).offset(), state.instruction_position + 1 });
  525. break;
  526. case OpCodeId::ForkStay:
  527. patch_points.push({ static_cast<OpCode_ForkStay const&>(opcode).offset(), state.instruction_position + 1 });
  528. break;
  529. case OpCodeId::Repeat:
  530. patch_points.push({ -(ssize_t) static_cast<OpCode_Repeat const&>(opcode).offset(), state.instruction_position + 1, true });
  531. break;
  532. default:
  533. break;
  534. }
  535. while (!patch_points.is_empty()) {
  536. auto& patch_point = patch_points.top();
  537. auto target_offset = patch_point.value + state.instruction_position + opcode.size();
  538. constexpr auto do_patch = [](auto& patch_it, auto& patch_point, auto& target_offset, auto& bytecode, auto ip) {
  539. if (patch_it.key() == ip)
  540. return;
  541. if (patch_point.value < 0 && target_offset <= patch_it.key() && ip > patch_it.key())
  542. bytecode[patch_point.offset] += (patch_point.should_negate ? 1 : -1) * (*patch_it);
  543. else if (patch_point.value > 0 && target_offset >= patch_it.key() && ip < patch_it.key())
  544. bytecode[patch_point.offset] += (patch_point.should_negate ? -1 : 1) * (*patch_it);
  545. };
  546. if (auto patch_it = needed_patches.find_largest_not_above_iterator(target_offset); !patch_it.is_end())
  547. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  548. else if (auto patch_it = needed_patches.find_largest_not_above_iterator(state.instruction_position); !patch_it.is_end())
  549. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  550. patch_points.pop();
  551. }
  552. state.instruction_position += opcode.size();
  553. }
  554. }
  555. if constexpr (REGEX_DEBUG) {
  556. warnln("Transformed to:");
  557. RegexDebug dbg;
  558. dbg.print_bytecode(*this);
  559. }
  560. }
  561. void Optimizer::append_alternation(ByteCode& target, ByteCode&& left, ByteCode&& right)
  562. {
  563. Array<ByteCode, 2> alternatives;
  564. alternatives[0] = move(left);
  565. alternatives[1] = move(right);
  566. append_alternation(target, alternatives);
  567. }
  568. void Optimizer::append_alternation(ByteCode& target, Span<ByteCode> alternatives)
  569. {
  570. if (alternatives.size() == 0)
  571. return;
  572. if (alternatives.size() == 1)
  573. return target.extend(move(alternatives[0]));
  574. if (all_of(alternatives, [](auto& x) { return x.is_empty(); }))
  575. return;
  576. for (auto& entry : alternatives)
  577. entry.flatten();
  578. #if REGEX_DEBUG
  579. ScopeLogger<true> log;
  580. warnln("Alternations:");
  581. RegexDebug dbg;
  582. for (auto& entry : alternatives) {
  583. warnln("----------");
  584. dbg.print_bytecode(entry);
  585. }
  586. ScopeGuard print_at_end {
  587. [&] {
  588. warnln("======================");
  589. RegexDebug dbg;
  590. dbg.print_bytecode(target);
  591. }
  592. };
  593. #endif
  594. Vector<Vector<Detail::Block>> basic_blocks;
  595. basic_blocks.ensure_capacity(alternatives.size());
  596. for (auto& entry : alternatives)
  597. basic_blocks.append(Regex<PosixBasicParser>::split_basic_blocks(entry));
  598. size_t left_skip = 0;
  599. size_t shared_block_count = basic_blocks.first().size();
  600. for (auto& entry : basic_blocks)
  601. shared_block_count = min(shared_block_count, entry.size());
  602. MatchState state;
  603. for (size_t block_index = 0; block_index < shared_block_count; block_index++) {
  604. auto& left_block = basic_blocks.first()[block_index];
  605. auto left_end = block_index + 1 == basic_blocks.first().size() ? left_block.end : basic_blocks.first()[block_index + 1].start;
  606. auto can_continue = true;
  607. for (size_t i = 1; i < alternatives.size(); ++i) {
  608. auto& right_blocks = basic_blocks[i];
  609. auto& right_block = right_blocks[block_index];
  610. auto right_end = block_index + 1 == right_blocks.size() ? right_block.end : right_blocks[block_index + 1].start;
  611. if (left_end - left_block.start != right_end - right_block.start) {
  612. can_continue = false;
  613. break;
  614. }
  615. if (alternatives[0].spans().slice(left_block.start, left_end - left_block.start) != alternatives[i].spans().slice(right_block.start, right_end - right_block.start)) {
  616. can_continue = false;
  617. break;
  618. }
  619. }
  620. if (!can_continue)
  621. break;
  622. size_t i = 0;
  623. for (auto& entry : alternatives) {
  624. auto& blocks = basic_blocks[i];
  625. auto& block = blocks[block_index];
  626. auto end = block_index + 1 == blocks.size() ? block.end : blocks[block_index + 1].start;
  627. state.instruction_position = block.start;
  628. size_t skip = 0;
  629. while (state.instruction_position < end) {
  630. auto& opcode = entry.get_opcode(state);
  631. state.instruction_position += opcode.size();
  632. skip = state.instruction_position;
  633. }
  634. left_skip = min(skip, left_skip);
  635. }
  636. }
  637. dbgln_if(REGEX_DEBUG, "Skipping {}/{} bytecode entries from {}", left_skip, 0, alternatives[0].size());
  638. if (left_skip > 0) {
  639. target.extend(alternatives[0].release_slice(basic_blocks.first().first().start, left_skip));
  640. auto first = true;
  641. for (auto& entry : alternatives) {
  642. if (first) {
  643. first = false;
  644. continue;
  645. }
  646. entry = entry.release_slice(left_skip);
  647. }
  648. }
  649. if (all_of(alternatives, [](auto& entry) { return entry.is_empty(); }))
  650. return;
  651. size_t patch_start = target.size();
  652. for (size_t i = 1; i < alternatives.size(); ++i) {
  653. target.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  654. target.empend(0u); // To be filled later.
  655. }
  656. size_t size_to_jump = 0;
  657. bool seen_one_empty = false;
  658. for (size_t i = alternatives.size(); i > 0; --i) {
  659. auto& entry = alternatives[i - 1];
  660. if (entry.is_empty()) {
  661. if (seen_one_empty)
  662. continue;
  663. seen_one_empty = true;
  664. }
  665. auto is_first = i == 1;
  666. auto instruction_size = entry.size() + (is_first ? 0 : 2); // Jump; -> +2
  667. size_to_jump += instruction_size;
  668. if (!is_first)
  669. target[patch_start + (i - 2) * 2 + 1] = size_to_jump + (alternatives.size() - i) * 2;
  670. dbgln_if(REGEX_DEBUG, "{} size = {}, cum={}", i - 1, instruction_size, size_to_jump);
  671. }
  672. seen_one_empty = false;
  673. for (size_t i = alternatives.size(); i > 0; --i) {
  674. auto& chunk = alternatives[i - 1];
  675. if (chunk.is_empty()) {
  676. if (seen_one_empty)
  677. continue;
  678. seen_one_empty = true;
  679. }
  680. ByteCode* previous_chunk = nullptr;
  681. size_t j = i - 1;
  682. auto seen_one_empty_before = chunk.is_empty();
  683. while (j >= 1) {
  684. --j;
  685. auto& candidate_chunk = alternatives[j];
  686. if (candidate_chunk.is_empty()) {
  687. if (seen_one_empty_before)
  688. continue;
  689. }
  690. previous_chunk = &candidate_chunk;
  691. break;
  692. }
  693. size_to_jump -= chunk.size() + (previous_chunk ? 2 : 0);
  694. target.extend(move(chunk));
  695. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Jump));
  696. target.empend(size_to_jump); // Jump to the _END label
  697. }
  698. }
  699. enum class LookupTableInsertionOutcome {
  700. Successful,
  701. ReplaceWithAnyChar,
  702. TemporaryInversionNeeded,
  703. PermanentInversionNeeded,
  704. CannotPlaceInTable,
  705. };
  706. static LookupTableInsertionOutcome insert_into_lookup_table(RedBlackTree<ByteCodeValueType, CharRange>& table, CompareTypeAndValuePair pair)
  707. {
  708. switch (pair.type) {
  709. case CharacterCompareType::Inverse:
  710. return LookupTableInsertionOutcome::PermanentInversionNeeded;
  711. case CharacterCompareType::TemporaryInverse:
  712. return LookupTableInsertionOutcome::TemporaryInversionNeeded;
  713. case CharacterCompareType::AnyChar:
  714. return LookupTableInsertionOutcome::ReplaceWithAnyChar;
  715. case CharacterCompareType::CharClass:
  716. return LookupTableInsertionOutcome::CannotPlaceInTable;
  717. case CharacterCompareType::Char:
  718. table.insert(pair.value, { (u32)pair.value, (u32)pair.value });
  719. break;
  720. case CharacterCompareType::CharRange: {
  721. CharRange range { pair.value };
  722. table.insert(range.from, range);
  723. break;
  724. }
  725. case CharacterCompareType::Reference:
  726. case CharacterCompareType::Property:
  727. case CharacterCompareType::GeneralCategory:
  728. case CharacterCompareType::Script:
  729. case CharacterCompareType::ScriptExtension:
  730. return LookupTableInsertionOutcome::CannotPlaceInTable;
  731. case CharacterCompareType::Undefined:
  732. case CharacterCompareType::RangeExpressionDummy:
  733. case CharacterCompareType::String:
  734. case CharacterCompareType::LookupTable:
  735. VERIFY_NOT_REACHED();
  736. }
  737. return LookupTableInsertionOutcome::Successful;
  738. }
  739. void Optimizer::append_character_class(ByteCode& target, Vector<CompareTypeAndValuePair>&& pairs)
  740. {
  741. ByteCode arguments;
  742. size_t argument_count = 0;
  743. if (pairs.size() <= 1) {
  744. for (auto& pair : pairs) {
  745. arguments.append(to_underlying(pair.type));
  746. if (pair.type != CharacterCompareType::AnyChar && pair.type != CharacterCompareType::TemporaryInverse && pair.type != CharacterCompareType::Inverse)
  747. arguments.append(pair.value);
  748. ++argument_count;
  749. }
  750. } else {
  751. RedBlackTree<ByteCodeValueType, CharRange> table;
  752. RedBlackTree<ByteCodeValueType, CharRange> inverted_table;
  753. auto* current_table = &table;
  754. auto* current_inverted_table = &inverted_table;
  755. bool invert_for_next_iteration = false;
  756. bool is_currently_inverted = false;
  757. auto flush_tables = [&] {
  758. auto append_table = [&](auto& table) {
  759. ++argument_count;
  760. arguments.append(to_underlying(CharacterCompareType::LookupTable));
  761. auto size_index = arguments.size();
  762. arguments.append(0);
  763. Optional<CharRange> active_range;
  764. size_t range_count = 0;
  765. for (auto& range : table) {
  766. if (!active_range.has_value()) {
  767. active_range = range;
  768. continue;
  769. }
  770. if (range.from <= active_range->to + 1 && range.to + 1 >= active_range->from) {
  771. active_range = CharRange { min(range.from, active_range->from), max(range.to, active_range->to) };
  772. } else {
  773. ++range_count;
  774. arguments.append(active_range.release_value());
  775. active_range = range;
  776. }
  777. }
  778. if (active_range.has_value()) {
  779. ++range_count;
  780. arguments.append(active_range.release_value());
  781. }
  782. arguments[size_index] = range_count;
  783. };
  784. auto contains_regular_table = !table.is_empty();
  785. auto contains_inverted_table = !inverted_table.is_empty();
  786. if (contains_regular_table)
  787. append_table(table);
  788. if (contains_inverted_table) {
  789. ++argument_count;
  790. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  791. append_table(inverted_table);
  792. }
  793. };
  794. for (auto& value : pairs) {
  795. auto should_invert_after_this_iteration = invert_for_next_iteration;
  796. invert_for_next_iteration = false;
  797. auto insertion_result = insert_into_lookup_table(*current_table, value);
  798. switch (insertion_result) {
  799. case LookupTableInsertionOutcome::Successful:
  800. break;
  801. case LookupTableInsertionOutcome::ReplaceWithAnyChar: {
  802. table.clear();
  803. inverted_table.clear();
  804. arguments.append(to_underlying(CharacterCompareType::AnyChar));
  805. ++argument_count;
  806. break;
  807. }
  808. case LookupTableInsertionOutcome::TemporaryInversionNeeded:
  809. swap(current_table, current_inverted_table);
  810. invert_for_next_iteration = true;
  811. is_currently_inverted = !is_currently_inverted;
  812. break;
  813. case LookupTableInsertionOutcome::PermanentInversionNeeded:
  814. flush_tables();
  815. arguments.append(to_underlying(CharacterCompareType::Inverse));
  816. ++argument_count;
  817. break;
  818. case LookupTableInsertionOutcome::CannotPlaceInTable:
  819. if (is_currently_inverted) {
  820. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  821. ++argument_count;
  822. }
  823. arguments.append(to_underlying(value.type));
  824. arguments.append(value.value);
  825. ++argument_count;
  826. break;
  827. }
  828. if (should_invert_after_this_iteration) {
  829. swap(current_table, current_inverted_table);
  830. is_currently_inverted = !is_currently_inverted;
  831. }
  832. }
  833. flush_tables();
  834. }
  835. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Compare));
  836. target.empend(argument_count); // number of arguments
  837. target.empend(arguments.size()); // size of arguments
  838. target.extend(move(arguments));
  839. }
  840. template void Regex<PosixBasicParser>::run_optimization_passes();
  841. template void Regex<PosixExtendedParser>::run_optimization_passes();
  842. template void Regex<ECMA262Parser>::run_optimization_passes();
  843. }