Selaa lähdekoodia

Optimize if/else if to if/elif in tree_ir

jonathanvdc 8 vuotta sitten
vanhempi
commit
9974711da9
1 muutettua tiedostoa jossa 21 lisäystä ja 8 poistoa
  1. 21 8
      kernel/modelverse_jit/tree_ir.py

+ 21 - 8
kernel/modelverse_jit/tree_ir.py

@@ -315,14 +315,15 @@ class SelectInstruction(Instruction):
         condition, if_clause, else_clause = new_children
         return SelectInstruction(condition, if_clause, else_clause)
 
-    def generate_python_def(self, code_generator):
+    def generate_python_if(self, code_generator, is_elif=False):
         """Generates Python code for this instruction."""
         if_has_result = self.has_result()
         if self.condition.has_definition():
             self.condition.generate_python_def(code_generator)
 
         code_generator.append_line(
-            'if ' + self.condition.generate_python_use(code_generator) + ':')
+            ('elif ' if is_elif else 'if ') +
+            self.condition.generate_python_use(code_generator) + ':')
         code_generator.increase_indentation()
         if if_has_result:
             code_generator.append_move_definition(self, self.if_clause)
@@ -331,13 +332,25 @@ class SelectInstruction(Instruction):
         code_generator.decrease_indentation()
         else_has_def = self.else_clause.has_definition()
         if else_has_def or if_has_result:
-            code_generator.append_line('else:')
-            code_generator.increase_indentation()
-            if if_has_result:
-                code_generator.append_move_definition(self, self.else_clause)
+            if (isinstance(self.else_clause, SelectInstruction) and
+                    not self.else_clause.condition.has_definition()):
+                self.else_clause.generate_python_if(code_generator, True)
+                if if_has_result:
+                    code_generator.increase_indentation()
+                    code_generator.append_definition(self, self.else_clause)
+                    code_generator.decrease_indentation()
             else:
-                self.else_clause.generate_python_def(code_generator)
-            code_generator.decrease_indentation()
+                code_generator.append_line('else:')
+                code_generator.increase_indentation()
+                if if_has_result:
+                    code_generator.append_move_definition(self, self.else_clause)
+                else:
+                    self.else_clause.generate_python_def(code_generator)
+                code_generator.decrease_indentation()
+
+    def generate_python_def(self, code_generator):
+        """Generates Python code for this instruction."""
+        return self.generate_python_if(code_generator)
 
 class ReturnInstruction(VoidInstruction):
     """Represents a return-instruction."""