From 491aa659dfe914b1f107e2507b5b2eb24ef985b4 Mon Sep 17 00:00:00 2001 From: Stefan Behnel Date: Tue, 27 Apr 2010 20:37:32 +0200 Subject: [PATCH] avoid generating code for 'if' conditions that are known to be False --- Cython/Compiler/Nodes.py | 44 +++++++++++++++++++++++++++++++--------- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/Cython/Compiler/Nodes.py b/Cython/Compiler/Nodes.py index 49d13762..00ac4463 100644 --- a/Cython/Compiler/Nodes.py +++ b/Cython/Compiler/Nodes.py @@ -3871,18 +3871,36 @@ class IfStatNode(StatNode): if_clause.analyse_expressions(env) if self.else_clause: self.else_clause.analyse_expressions(env) - + + # eliminate dead code based on constant condition results + if_clauses = [] + condition_result = None + for if_clause in self.if_clauses: + condition_result = if_clause.get_constant_condition_result() + if condition_result != False: + if_clauses.append(if_clause) + if condition_result == True: + # other conditions can no longer apply + self.else_clause = None + break + self.if_clauses = if_clauses + # FIXME: if only one active code body is left here, we can + # replace the whole node + def generate_execution_code(self, code): code.mark_pos(self.pos) - end_label = code.new_label() - for if_clause in self.if_clauses: - if_clause.generate_execution_code(code, end_label) - if self.else_clause: - code.putln("/*else*/ {") + if self.if_clauses: + end_label = code.new_label() + for if_clause in self.if_clauses: + if_clause.generate_execution_code(code, end_label) + if self.else_clause: + code.putln("/*else*/ {") + self.else_clause.generate_execution_code(code) + code.putln("}") + code.put_label(end_label) + elif self.else_clause: self.else_clause.generate_execution_code(code) - code.putln("}") - code.put_label(end_label) - + def annotate(self, code): for if_clause in self.if_clauses: if_clause.annotate(code) @@ -3909,7 +3927,13 @@ class IfClauseNode(Node): self.condition = \ self.condition.analyse_temp_boolean_expression(env) self.body.analyse_expressions(env) - + + def get_constant_condition_result(self): + if self.condition.has_constant_result(): + return self.condition.constant_result + else: + return None + def generate_execution_code(self, code, end_label): self.condition.generate_evaluation_code(code) code.putln( -- 2.26.2