next up previous
Next: Loop Peeling: A MIR Up: Loop Peeling: An Example Previous: Node * peel_for_loop (forNode

Discussion

There are some details in the code that aren't immediately obvious.

We must have the Changer traverse the tree in postorder. We are changing loops into blocks of statements that contain loops. When we return a block in the place of a loop, a preorder traversal, having not visited the ``next" statement in that block (indeed, it didn't exist before we created it) would march down to the loop inside the block we just created. Since our policy is to unpeel all loops (or let someone subclass off of us and make up their own policy), this would cause an infinite loop in which we keep peeling the same loops over and over again.

Note that we often make copies of Nodes. This is usually because we want the AST to remain a tree. If we use the same loop body (i.e., the same Node*) outside and inside a loop, then we are asking for trouble; later on, someone may decide to change something in the loop body, and that change will unintentionally occur outside the loop, too.

The following line

        whilebody->stmts().push_back (new exprstmtNode (
                (exprNode *) ref_clone_changer::clone(p->next(), false)));

occurs in the code for for. Here, we are making a copy of the ``next'' expression of the for, and then turning it into a statement by constructing an exprstmtNode from it. An exprstmtNode is required because exprNode is not a subclass of stmtNode. When the C-Breeze AST expects a stmtNode, the retuned node must be a subclass of stmtNode. An expression can be a statement in C, but can also occur in contexts where a statement isn't allowed (such as a condition in a while loop). So we keep expressions that are statements in special exprstmtNodes. Note that if you don't convert the expression into a statement (it's easy to forget), C-Breeze might not immediately complain, but you will be introducing a bug into your program that will eventually catch up to you later on.


next up previous
Next: Loop Peeling: A MIR Up: Loop Peeling: An Example Previous: Node * peel_for_loop (forNode
Adam C. Brown 2006-01-26