loop_transformer.py 26.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import copy
from collections import defaultdict
17

18
from paddle.fluid import unique_name
19 20 21 22 23 24 25 26
from paddle.utils import gast

from .base_transformer import (
    BaseTransformer,
    ForLoopTuplePreTransformer,
    ForNodeVisitor,
)
from .ifelse_transformer import ARGS_NAME
27
from .static_analysis import NodeVarType, StaticAnalysisVisitor
28
from .utils import (
29 30 31 32
    FOR_BODY_PREFIX,
    FOR_CONDITION_PREFIX,
    WHILE_BODY_PREFIX,
    WHILE_CONDITION_PREFIX,
33
    FunctionNameLivenessAnalysis,
34
    GetterSetterHelper,
35 36
    ast_to_source_code,
    create_get_args_node,
37
    create_name_str,
38 39 40
    create_nonlocal_stmt_nodes,
    create_set_args_node,
    get_attribute_full_name,
41
)
42

43
__all__ = []
44 45


46 47 48 49 50 51 52 53
def create_while_nodes(
    condition_name,
    body_name,
    loop_var_names,
    push_pop_names,
    getter_name,
    setter_name,
):
54 55 56 57 58 59 60 61 62 63 64
    """
    Returns a list of gast.Node which represents the calling of Paddle
    controlflow while_loop.

    Usually, the list just contain 1 statement such as:

    [a, b, c] = paddle.jit.dy2static.convert_while_loop(
            condition_name, body_name, [a, b, c])

    where a, b, c are in loop_var_names.

H
Huihuang Zheng 已提交
65 66
    However, if loop_var_names contains property such as foo.x, we cannot
    assign the property as output of convert_while_loop because Python
67 68 69 70 71 72 73 74 75 76 77 78
    property is a kind of read-only attribute. To handle the case, we replace
    the attributes which are output of convert_while_loop with generated
    variables, then if we know the attribute is not read-only at runtime, we
    assign the attribute. The created statements are like:

    [a, b, __attribute_variable_1] = paddle.jit.dy2static.convert_while_loop(
            condition_name, body_name, [a, b, foo.x])
    if not isinstance(getattr(type(foo), x, None), property): foo.x = __attribute_variable_1

    The number of above statements is not only 1, that's why the return type is
    a list of gast.Node.
    """
79 80 81 82 83 84
    # NOTE(liym27):
    # It's better to parse the source code into an AST node than to customize an AST node
    # including child nodes, because it is easy to mistake the ast node type when customizing the node.
    #
    # For example: loop_var_names = [a, b, foo.x], the type of `a` or `b` is gast.Name,
    # but the type of `foo.x` gast.Attribute.
85 86 87 88
    # We have to make loop_var_names and assign_loop_var_names with same order
    # set doesn't have order so we convert it to list
    loop_var_names = list(loop_var_names)
    assign_loop_var_names = []
89
    for name in loop_var_names:
90
        assign_loop_var_names.append(name)
91

92
    while_func_name = "_jst.While"
93 94 95 96 97 98 99 100 101 102 103
    while_node_str = (
        "{}({}, {}, {}, {}, return_name_ids={}, push_pop_names={})".format(
            while_func_name,
            condition_name,
            body_name,
            getter_name,
            setter_name,
            create_name_str(loop_var_names),
            create_name_str(push_pop_names),
        )
    )
104 105
    while_node = gast.parse(while_node_str).body[0]

106 107
    ret = [while_node]
    return ret
108 109 110 111 112 113 114 115


class NameVisitor(gast.NodeVisitor):
    '''
    Analysis name liveness for loop transformer
    '''

    def __init__(self, root_node):
116
        # Set of gast.Name or gast.Attribute for variables
117
        self.current_seen_vars = set()
118

119 120 121
        # List of gast.While/gast.For nodes
        self.current_loop = []

122 123 124 125
        # List of nodes that have scope of variables.
        self.nodes_with_scope = []
        self.blacklist_names = {"False", "True", "None"}

126 127
        # Mapping from gast.While/gast.For to variable nodes
        self.before_loop_body_vars = defaultdict(set)
128 129
        # NOTE: Use ordered list as dict value
        self.in_loop_vars = defaultdict(list)
130

131 132 133 134 135 136
        # Mapping from gast.While/gast.For to variable nodes which is condition
        # of loop or being modified during the loop
        self.write_in_loop = defaultdict(set)
        self.condition_vars = defaultdict(set)
        self.in_condition = False

137 138 139
        # Some names are types, we shouldn't record them as loop var names.
        self.type_vars = set()

140
        self.static_analysis_visitor = StaticAnalysisVisitor(root_node)
141 142
        self.node_to_wrapper_map = (
            self.static_analysis_visitor.get_node_to_wrapper_map()
143 144
        )

145 146 147
        self.visit(root_node)

    def get_loop_var_names(self, node):
148
        assert isinstance(
149 150
            node, (gast.While, gast.For)
        ), "Input node is not gast loop node"
151 152
        loop_var_names = set()
        create_var_names = set()
H
Huihuang Zheng 已提交
153
        read_context = {type(gast.Load()), type(gast.AugLoad())}
154

155 156 157 158 159 160
        in_loop_vars_list = self.in_loop_vars[node]

        # get dict `var_name_to_ctxs`
        var_name_to_ctxs = defaultdict(list)
        for var_node in in_loop_vars_list:
            var_name_to_ctxs[self._var_node_to_name(var_node)].append(
161 162
                var_node.ctx
            )
163 164

        in_loop_vars = set(in_loop_vars_list)
165
        in_loop_vars = self._remove_unnecessary_vars(in_loop_vars, node)
166
        in_loop_name_strs = self._var_nodes_to_names(in_loop_vars)
167

168
        before_loop_body_vars = self.before_loop_body_vars[node]
169
        before_loop_body_vars = self._remove_unnecessary_vars(
170 171
            before_loop_body_vars, node
        )
172
        before_loop_name_strs = self._var_nodes_to_names(before_loop_body_vars)
173

174 175 176
        after_loop_vars = (
            self.current_seen_vars - before_loop_body_vars - in_loop_vars
        )
177
        after_loop_vars = self._remove_unnecessary_vars(after_loop_vars, node)
178 179 180
        after_loop_name_strs = self._var_nodes_to_names(
            after_loop_vars, read_context
        )
181 182
        condition_vars = self.condition_vars[node]
        condition_names = self._var_nodes_to_names(condition_vars)
183

184 185 186 187 188 189 190
        write_vars = self.write_in_loop[node]
        write_names = self._var_nodes_to_names(write_vars)

        name_to_type = {}
        for var in in_loop_vars:
            wrapper = self.node_to_wrapper_map[var]
            name_to_type[self._var_node_to_name(var)] = wrapper.node_var_type
191 192
        for name in in_loop_name_strs:
            if name in before_loop_name_strs:
193 194 195 196 197
                # If a variable is used in loop and created before loop

                # If this var is a basic variable and read-only and not
                # condition var, it may not be loop_var else it should
                # be in loop_var as input
198
                if (name not in condition_names) and (name not in write_names):
199
                    continue
200
                loop_var_names.add(name)
201

202 203 204
            elif name in after_loop_name_strs:
                # If a variable is created in the while loop and read after
                # loop, it should be in loop_var and we should create it
205 206 207 208

                # because name in after_loop_name must be initialized in loop
                # So it is write-only, we don't have to filter read-only basic
                # vars out
209 210
                loop_var_names.add(name)
                create_var_names.add(name)
211 212 213 214 215 216 217 218 219 220 221 222 223
            else:
                # If a variable is used and created in loop, but used before created,
                # it should be in loop_var and we should create it.

                # For example, `var_a` should be in loop_var and we should create it.
                #
                #   res = 0
                #   for i, x in enumerate(x_array):
                #       if i > 2:
                #           x = func1(var_a)
                #       var_a = func2(x)
                #

224 225 226 227 228
                is_created = False
                for ctx in var_name_to_ctxs[name]:
                    if isinstance(ctx, gast.Store):
                        is_created = True

229 230 231 232
                if (
                    isinstance(var_name_to_ctxs[name][0], gast.Load)
                    and is_created
                ):
233 234
                    loop_var_names.add(name)
                    create_var_names.add(name)
235

236 237 238
        return loop_var_names, create_var_names

    def visit_Name(self, node):
239 240 241
        if self._is_call_func_name_node(node):
            self.generic_visit(node)
            return
242
        if node.id in self.blacklist_names:
243 244
            self.generic_visit(node)
            return
245

246
        self.current_seen_vars.add(node)
247
        write_context = {
248 249
            type(gast.Store()),
            type(gast.AugStore()),
250
            type(gast.Del()),
251
        }
252

253
        for loop_node in self.current_loop:
254
            self.in_loop_vars[loop_node].append(node)
255 256
            if type(node.ctx) in write_context:
                self.write_in_loop[loop_node].add(node)
257 258
        if self.in_condition:
            self.condition_vars[loop_node].add(node)
259 260
        self.generic_visit(node)

261 262 263
    def visit_FunctionDef(self, node):
        self.nodes_with_scope.append(node)
        self.blacklist_names.add(node.name)
264

265 266 267 268 269 270 271 272 273 274
        # The variables in the function are not visible to the outside scope.
        before_func_seen_vars = copy.copy(self.current_seen_vars)

        self.generic_visit(node)
        self.nodes_with_scope.pop()
        # After exiting the scope of the node, variables in this scope
        # should be removed from self.current_seen_vars.
        if self.nodes_with_scope:
            self.current_seen_vars = before_func_seen_vars

275 276 277 278 279 280 281 282 283 284
    def visit(self, node):
        method = 'visit_' + node.__class__.__name__
        visitor = getattr(self, method, self.generic_visit)
        ret = visitor(node)
        return ret

    def visit_Attribute(self, node):
        if self._is_call_func_name_node(node):
            return
        attr_full_name = get_attribute_full_name(node)
285 286 287 288 289 290 291 292 293 294
        # Class variables are not allowed to appear in the arguments list
        # of defined function under class methods in Python.
        """
        def class_func(self):
            def while_loop_body(self.x, y) # `self.x` is illegal.
        """
        # TODO: If do change the variable with `self.var`, need a better
        # way to deal with this case.
        if attr_full_name.startswith("self."):
            return
295
        self.current_seen_vars.add(node)
296

297
        for loop_node in self.current_loop:
298
            self.in_loop_vars[loop_node].append(node)
299

300 301 302
        # sub-nodes are visited during get_attribute_full_name and we shouldn't
        # visit again

303 304
    def visit_For(self, node):
        self.current_loop.append(node)
305
        self.in_condition = True
306
        self.visit(node.target)
307 308
        self.visit(node.iter)
        self.in_condition = False
309
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
310 311 312 313 314
        self.generic_visit(node)
        self.current_loop.pop()

    def visit_While(self, node):
        self.current_loop.append(node)
315
        self.in_condition = True
316
        self.visit(node.test)
317
        self.in_condition = False
318
        self.before_loop_body_vars[node] = copy.copy(self.current_seen_vars)
319 320 321
        self.generic_visit(node)
        self.current_loop.pop()

322 323 324 325 326 327 328
    def visit_Call(self, node):
        # Store type var names such as "isinstance(x, some_type_names)" and
        # Remove them later
        if isinstance(node.func, gast.Name) and node.func.id == 'isinstance':
            type_node = node.args[1]
            if isinstance(type_node, gast.Tuple):
                for element in type_node.elts:
329
                    self.type_vars.add(ast_to_source_code(element).strip())
330
            else:
331
                self.type_vars.add(ast_to_source_code(type_node).strip())
332 333
        self.generic_visit(node)

334 335 336 337
    def _var_nodes_to_names(self, node_set, ctx_filter_set=None):
        ret = set()
        for node in node_set:
            if ctx_filter_set is None or type(node.ctx) in ctx_filter_set:
338
                ret.add(self._var_node_to_name(node))
339 340
        return ret

341 342 343 344 345 346 347 348
    def _var_node_to_name(self, node):
        if isinstance(node, gast.Name):
            return node.id
        elif isinstance(node, gast.Attribute):
            return get_attribute_full_name(node)

    def _node_var_type_is_basic(self, node_var_type):
        basic_types = {
349 350 351 352
            NodeVarType.BOOLEAN,
            NodeVarType.INT,
            NodeVarType.FLOAT,
            NodeVarType.STRING,
353 354 355 356 357 358
        }
        for t in node_var_type:
            if t in basic_types:
                return True
        return False

359
    def _is_call_func_name_node(self, node):
360
        parent_node = self._get_parent_node(node)
361 362
        if isinstance(parent_node, gast.Call) and parent_node.func == node:
            return True
363 364
        return False

365 366 367
    def _is_global_or_nonlocal(self, node):
        return False

368 369 370 371 372 373 374 375 376
    def _is_ancestor_node(self, ancestor_node, node):
        parent_node = self._get_parent_node(node)

        while parent_node is not None:
            if parent_node == ancestor_node:
                return True
            parent_node = self._get_parent_node(parent_node)
        return False

377 378 379
    def _get_parent_node(self, node):
        wrapper_node = self.node_to_wrapper_map.get(node)
        if wrapper_node:
380 381 382
            if wrapper_node.parent:
                parent_node = wrapper_node.parent.node
                return parent_node
383 384
        return None

385
    def _remove_unnecessary_vars(self, loop_vars, loop_node):
386
        """
387 388 389
        Remove unnecessary vars from before_loop_vars, after_loop_vars or in_loop_vars about loop_node.
            1. Remove target vars of gast.For from before_loop_vars or after_loop_vars.
            2. Remove vars only in gast.comprehension.
390
            3. Remove vars that are type names, for example: "isinstance(x, var_type_name)"
391
        :param loop_vars: before_loop_vars, after_loop_vars or in_loop_vars of loop_node.
392 393 394
        :param loop_node: Current loop node.
        """

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        def filter_name_nodes_from(root_node, target_var_names):
            """
            Filter children with gast.Name type from node.(inclusivly)
            """
            name_nodes = set()
            if isinstance(root_node, gast.Name):
                if node.id in target_var_names:
                    name_nodes.add(root_node)
            for child_node in gast.walk(root_node):
                if isinstance(child_node, gast.Name):
                    if child_node.id in target_var_names:
                        name_nodes.add(child_node)

            return name_nodes

410 411 412 413
        vars_of_list_generator = set()
        target_vars_of_for_node = set()

        for name_node in loop_vars:
414 415 416 417 418
            if not isinstance(name_node, gast.Name):
                continue

            parent_node = self._get_parent_node(name_node)

419 420 421 422
            # NOTE: gast.For.target or gast.comprehension.target can be gast.Tuple.
            #  For examples:
            #   1) `for i, j in enumerate(x)` has two target vars: i and j
            #   2) `[x for x,y in array]` has two target vars: x and y
423 424 425
            if isinstance(parent_node, gast.Tuple):
                parent_node = self._get_parent_node(parent_node)

426 427 428 429 430 431 432
            # 1. Get vars only in gast.comprehension.
            # For examples:
            #  1) [x for x,y in array] -> x, x, y
            #  2) [f(x) for x in array] -> x
            #  3) [func(x, y) for x in array] -> x, x
            if isinstance(parent_node, gast.comprehension):
                # 1.1 target vars in list/set comprehensions
433 434 435 436 437 438
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]

439
                vars_of_list_generator = vars_of_list_generator | set(
440 441
                    target_vars
                )
442 443 444

                # 1.2 vars from target vars used in elt_node
                target_var_names = {var.id for var in target_vars}
445 446 447 448 449 450 451 452 453
                comp_node = self._get_parent_node(parent_node)
                elt_nodes = []
                if isinstance(comp_node, gast.ListComp):
                    elt_nodes.append(comp_node.elt)
                elif isinstance(comp_node, gast.DictComp):
                    elt_nodes.extend([comp_node.key, comp_node.value])

                for node in elt_nodes:
                    vars_of_list_generator |= filter_name_nodes_from(
454 455
                        node, target_var_names
                    )
456

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
            # 2. Get target vars or vars from target vars used in for-loop but the for-loop is
            #   1) not the "loop_node" itself
            #   2) not the ancestor of the "loop_node"
            #
            # For examples:
            #   for k in range(x):   # if it's this "loop_node", i or j both should be target vars.
            #      # do something
            #
            #   for i in range(a):   # if it's this "loop_node", k or j should be in target vars but i should not.
            #     for j in range(a): # if it's this "loop_node", k should be in target_vars but i or j should not.
            #       x = i+j
            elif isinstance(parent_node, gast.For):
                if parent_node is loop_node:
                    continue
                if self._is_ancestor_node(parent_node, loop_node):
                    continue
473 474 475 476 477 478
                # 2.1 target vars in gast.For node.
                target_node = parent_node.target
                if isinstance(target_node, gast.Tuple):
                    target_vars = target_node.elts
                else:
                    target_vars = [target_node]
479

480
                target_vars_of_for_node = target_vars_of_for_node | set(
481 482
                    target_vars
                )
483

484 485 486
        # 2.2 vars from target vars used in for-loop
        target_vars_name_strs = {var.id for var in target_vars_of_for_node}
        for var in loop_vars:
487 488
            if not isinstance(var, gast.Name):
                continue
489 490 491 492
            if (
                var.id in target_vars_name_strs
                and var not in self.condition_vars[loop_node]
            ):
493
                target_vars_of_for_node.add(var)
494

495
        removed_vars = target_vars_of_for_node | vars_of_list_generator
496 497 498

        # 3. Remove var type names which are stored in self.type_vars
        for var in loop_vars:
499
            if ast_to_source_code(var).strip() in self.type_vars:
500 501
                removed_vars.add(var)

502
        return loop_vars - removed_vars
503

504

505
class LoopTransformer(BaseTransformer):
506 507 508 509
    """
    This class transforms python while/for statement into Static Graph Ast
    """

510 511
    def __init__(self, root):
        self.root = root
512
        FunctionNameLivenessAnalysis(self.root)
513 514

    def transform(self):
515
        ForLoopTuplePreTransformer(self.root).transform()
516 517
        self.visit(self.root)

518 519 520 521 522 523
    def visit_While(self, node):
        self.generic_visit(node)
        new_stmts = self.get_while_stmt_nodes(node)
        return new_stmts

    def visit_For(self, node):
524
        self.generic_visit(node)
525 526
        new_stmts = self.get_for_stmt_nodes(node)
        return new_stmts
527 528 529 530 531 532 533 534 535

    def replace_stmt_list(self, body_list):
        if not isinstance(body_list, list):
            return

        i = 0
        while i < len(body_list):
            if isinstance(body_list[i], gast.While):
                new_stmts = self.get_while_stmt_nodes(body_list[i])
536
                body_list[i : i + 1] = new_stmts
537 538
                i += len(new_stmts)
            elif isinstance(body_list[i], gast.For):
539
                new_stmts = self.get_for_stmt_nodes(body_list[i])
540
                body_list[i : i + 1] = new_stmts
541
                i += len(new_stmts)
542 543 544
            else:
                i += 1

545 546 547
    def get_for_stmt_nodes(self, node):
        # TODO: consider for - else in python

548 549
        # 1. get key statements for different cases
        # NOTE 1: three key statements:
550 551 552 553
        #   1). init_stmts: list[node], prepare nodes of for loop, may not only one
        #   2). cond_stmt: node, condition node to judge whether continue loop
        #   3). body_stmts: list[node], updated loop body, sometimes we should change
        #       the original statement in body, not just append new statement
554 555 556 557 558 559
        #
        # NOTE 2: The following `for` statements will be transformed to `while` statements:
        #   1). for x in range(*)
        #   2). for x in iter_var
        #   3). for i, x in enumerate(*)

560
        current_for_node_parser = ForNodeVisitor(node)
561 562
        stmts_tuple = current_for_node_parser.parse()
        if stmts_tuple is None:
563
            return [node]
564
        init_stmts, cond_stmt, body_stmts = stmts_tuple
565
        # 2. get original loop vars
566 567 568 569
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
570
        push_pop_names = list(node.pd_scope.variadic_length_vars())
571
        # TODO: Remove the bunch of code?  We have the unique format `for A in B:`
572 573 574 575
        # NOTE: in 'for x in var' or 'for i, x in enumerate(var)' cases,
        # we need append new loop var & remove useless loop var
        #   1. for x in var -> x is no need
        #   2. for i, x in enumerate(var) -> x is no need
576
        if current_for_node_parser.is_for_iter():
577 578 579
            iter_var_name = current_for_node_parser.iter_var_name
            iter_idx_name = current_for_node_parser.iter_idx_name
            loop_var_names.add(iter_idx_name)
580 581
            if current_for_node_parser.enum_idx_name is not None:
                loop_var_names.add(current_for_node_parser.enum_idx_name)
582

583
        # 3. prepare result statement list
584 585 586 587 588 589 590
        new_stmts = []
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # for x in range(10):
        #     y += x
        # print(x) # x = 10
        #
591 592
        # We don't need to create static variable for them, because
        # we do this in CreateUndefinedVarTransformer
593 594 595 596 597 598 599 600

        # create non-local statement for body and cond.
        nonlocal_names = list(loop_var_names | create_var_names)
        nonlocal_names.sort()
        # TODO(dev): Need a better way to deal this.
        if ARGS_NAME in nonlocal_names:
            nonlocal_names.remove(ARGS_NAME)

601
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
602

603
        # 4. append init statements
604
        new_stmts.extend(init_stmts)
605

606
        # 5. create & append condition function node
607 608
        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_CONDITION_PREFIX),
609 610 611 612 613 614 615 616 617
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
618
            body=nonlocal_stmt_node + [gast.Return(value=cond_stmt)],
619 620
            decorator_list=[],
            returns=None,
621 622
            type_comment=None,
        )
623 624
        new_stmts.append(condition_func_node)

625
        # 6. create & append loop body function node
626
        # append return values for loop body
627 628
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(FOR_BODY_PREFIX),
629 630 631 632 633 634 635 636 637
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
638
            body=nonlocal_stmt_node + body_stmts,
639 640
            decorator_list=[],
            returns=None,
641 642
            type_comment=None,
        )
643 644
        new_stmts.append(body_func_node)

645 646 647
        helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names)
        get_args_node = create_get_args_node(helper.union())
        set_args_node = create_set_args_node(helper.union())
648
        # 7. create & append while loop node
649 650 651 652 653 654 655 656
        while_loop_nodes = create_while_nodes(
            condition_func_node.name,
            body_func_node.name,
            nonlocal_names,
            push_pop_names,
            get_args_node.name,
            set_args_node.name,
        )
657
        new_stmts.extend([get_args_node, set_args_node])
658
        new_stmts.extend(while_loop_nodes)
659 660 661

        return new_stmts

662
    def get_while_stmt_nodes(self, node):
663 664 665 666
        loop_var_names, create_var_names = (
            node.pd_scope.modified_vars(),
            node.pd_scope.created_vars(),
        )
667
        push_pop_names = list(node.pd_scope.variadic_length_vars())
668 669
        new_stmts = []

670 671 672 673 674 675 676
        # create non-local statement for body and cond.
        nonlocal_names = list(loop_var_names | create_var_names)
        nonlocal_names.sort()
        # TODO(dev): Need a better way to deal this.
        if ARGS_NAME in nonlocal_names:
            nonlocal_names.remove(ARGS_NAME)

677
        nonlocal_stmt_node = create_nonlocal_stmt_nodes(nonlocal_names)
678

679 680 681 682 683 684 685
        # Python can create variable in loop and use it out of loop, E.g.
        #
        # while x < 10:
        #     x += 1
        #     y = x
        # z = y
        #
686 687
        # We don't need to create static variable for those variables, because
        # we do this in CreateUndefinedVarTransformer
688 689 690

        condition_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_CONDITION_PREFIX),
691 692 693 694 695 696 697 698 699
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
700
            body=nonlocal_stmt_node + [gast.Return(value=node.test)],
701 702
            decorator_list=[],
            returns=None,
703 704
            type_comment=None,
        )
705

706 707 708 709 710
        new_stmts.append(condition_func_node)

        new_body = node.body
        body_func_node = gast.FunctionDef(
            name=unique_name.generate(WHILE_BODY_PREFIX),
711 712 713 714 715 716 717 718 719
            args=gast.arguments(
                args=[],
                posonlyargs=[],
                vararg=None,
                kwonlyargs=[],
                kw_defaults=None,
                kwarg=None,
                defaults=[],
            ),
720
            body=nonlocal_stmt_node + new_body,
721 722
            decorator_list=[],
            returns=None,
723 724
            type_comment=None,
        )
725
        new_stmts.append(body_func_node)
726 727 728 729

        helper = GetterSetterHelper(None, None, nonlocal_names, push_pop_names)
        get_args_node = create_get_args_node(helper.union())
        set_args_node = create_set_args_node(helper.union())
730

731 732 733 734 735 736 737 738
        while_loop_nodes = create_while_nodes(
            condition_func_node.name,
            body_func_node.name,
            nonlocal_names,
            push_pop_names,
            get_args_node.name,
            set_args_node.name,
        )
739
        new_stmts.extend([get_args_node, set_args_node])
740
        new_stmts.extend(while_loop_nodes)
741
        return new_stmts