Skip to content

Commit 30d1e9f

Browse files
DinoVfacebook-github-bot
authored andcommitted
TO_BOOL optimizations
Summary: There's a number of optimizations that can be applied to `TO_BOOL`. If we're doing a `LOAD_CONST` and then `TO_BOOL` it can be calculated statically. If we're doing a compare then there's a special form that ensures a bool is pushed instead of doing the conversion in the byte code. Reviewed By: alexmalyshev Differential Revision: D80763700 fbshipit-source-id: 4ad34ff26055b4ddb1ec7c3c9184d3bb2d9112dc
1 parent 41f4b91 commit 30d1e9f

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

cinderx/PythonLib/cinderx/compiler/flow_graph_optimizer.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -761,7 +761,17 @@ def opt_load_const(
761761
instr.ioparg = instr.oparg
762762
instr.opname = "LOAD_SMALL_INT"
763763

764-
if next_instr is not None and next_instr.opname == "IS_OP":
764+
if next_instr is None:
765+
return
766+
767+
if next_instr.opname == "TO_BOOL":
768+
val = bool(instr.oparg)
769+
index = self.graph.convertArg("LOAD_CONST", val)
770+
instr.set_to_nop_no_loc()
771+
next_instr.opname = "LOAD_CONST"
772+
next_instr.oparg = val
773+
next_instr.ioparg = index
774+
elif next_instr.opname == "IS_OP":
765775
return self.opt_load_const_is(instr_index, instr, next_instr, target, block)
766776
else:
767777
# The rest of the optimizations are common to 3.10 and 3.12
@@ -887,11 +897,24 @@ def fold_tuple_on_constants(
887897
instr.oparg = newconst
888898
instr.ioparg = self.graph.convertArg("LOAD_CONST", newconst)
889899

900+
def optimize_compare_op(
901+
self: FlowGraphOptimizer,
902+
instr_index: int,
903+
instr: Instruction,
904+
next_instr: Instruction | None,
905+
target: Instruction | None,
906+
block: Block,
907+
) -> int | None:
908+
if next_instr and next_instr.opname == "TO_BOOL":
909+
instr.ioparg |= 16
910+
next_instr.set_to_nop()
911+
890912
handlers: dict[str, Handler] = {
891913
**FlowGraphOptimizer312.handlers,
892914
"LOAD_CONST": opt_load_const,
893915
"JUMP_IF_FALSE": opt_jump_if,
894916
"JUMP_IF_TRUE": opt_jump_if,
895917
"BUILD_LIST": optimize_lists_and_sets,
896918
"BUILD_SET": optimize_lists_and_sets,
919+
"COMPARE_OP": optimize_compare_op,
897920
}

0 commit comments

Comments
 (0)