Reference Guide  2.5.0
fold_conditional_return_expressions_trans.py
1 # -----------------------------------------------------------------------------
2 # BSD 3-Clause License
3 #
4 # Copyright (c) 2021-2024, Science and Technology Facilities Council.
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are met:
9 #
10 # * Redistributions of source code must retain the above copyright notice, this
11 # list of conditions and the following disclaimer.
12 #
13 # * Redistributions in binary form must reproduce the above copyright notice,
14 # this list of conditions and the following disclaimer in the documentation
15 # and/or other materials provided with the distribution.
16 #
17 # * Neither the name of the copyright holder nor the names of its
18 # contributors may be used to endorse or promote products derived from
19 # this software without specific prior written permission.
20 #
21 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 # POSSIBILITY OF SUCH DAMAGE.
33 # -----------------------------------------------------------------------------
34 # Authors: S. Siso and N. Nobre, STFC Daresbury Lab
35 
36 '''This module contains the FoldConditionalReturnExpressionsTrans. '''
37 
38 from psyclone.psyir.nodes import (Routine, IfBlock, Return,
39  UnaryOperation)
40 from psyclone.psyGen import Transformation
42  TransformationError
43 
44 
46  ''' Provides a transformation that folds conditional expressions with only
47  a return statement inside so that the Return statement is moved to the end
48  of the Routine and therefore it can be safely removed. This simplifies the
49  control flow of the kernel to facilitate other transformations like kernel
50  fusions. For example, the following code:
51 
52  .. code-block:: fortran
53 
54  subroutine test(i)
55  if (i < 5) then
56  return
57  endif
58  if (i > 10) then
59  return
60  endif
61  ! CODE
62  end subroutine
63 
64  will be transformed to:
65 
66  .. code-block:: fortran
67 
68  subroutine test(i)
69  if (.not.(i < 5)) then
70  if (.not.(i > 10)) then
71  ! CODE
72  endif
73  endif
74  end subroutine
75 
76  '''
77 
78  def __str__(self):
79  return ("Re-structure kernel statements to eliminate conditional "
80  "Return expressions.")
81 
82  @property
83  def name(self):
84  '''Returns the name of this transformation as a string.'''
85  return "FoldConditionalReturnExpressionsTrans"
86 
87  def validate(self, node, options=None):
88  '''Ensure that it is valid to apply this transformation to the
89  supplied node.
90 
91  :param node: the node to validate.
92  :type node: :py:class:`psyclone.psyir.nodes.Routine`
93  :param options: a dictionary with options for transformations.
94  :type options: Optional[Dict[str, Any]]
95 
96  :raises TransformationError: if the node is not a Routine.
97 
98  '''
99  if not isinstance(node, Routine):
100  raise TransformationError(
101  f"Error in {self.name} transformation. This transformation "
102  f"can only be applied to 'Routine' nodes, but found "
103  f"'{type(node).__name__}'.")
104 
105  def apply(self, node, options=None):
106  '''Apply this transformation to the supplied node.
107 
108  :param node: the node to transform.
109  :type node: :py:class:`psyclone.psyir.nodes.Routine`
110  :param options: a dictionary with options for transformations.
111  :type options: Optional[Dict[str, Any]]
112 
113  '''
114  routine = node
115  self.validatevalidatevalidate(routine, options)
116 
117  def is_conditional_return(node):
118  '''
119  :param node: node to evaluate.
120  :type node: :py:class:`psyclone.psyir.nodes.Node`
121 
122  :returns: whether the given node represents a conditional return \
123  expression.
124  '''
125  if not isinstance(node, IfBlock):
126  return False
127  if node.else_body is not None:
128  return False
129  return isinstance(node.if_body[0], Return)
130 
131  for statement in routine[:]:
132  if is_conditional_return(statement):
133  # Reverse condition adding a NOT operator
134  new_condition = UnaryOperation.create(
135  UnaryOperation.Operator.NOT,
136  statement.condition.copy())
137  statement.children[0] = new_condition
138 
139  # Remove return statement (and any dead code inside the loop)
140  statement.if_body.children = []
141  # Then move any remaining statement after the conditional
142  # statement inside the loop body
143  while len(statement.parent.children) > statement.position + 1:
144  move = statement.parent.children.pop()
145  statement.if_body.children.insert(0, move)
146 
147 
148 # For Sphinx AutoAPI documentation generation
149 __all__ = ['FoldConditionalReturnExpressionsTrans']
def validate(self, node, options=None)
Definition: psyGen.py:2799