1/*
2 * Copyright © 2010 Luca Barbieri
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24/**
25 * \file lower_jumps.cpp
26 *
27 * This pass lowers jumps (break, continue, and return) to if/else structures.
28 *
29 * It can be asked to:
30 * 1. Pull jumps out of ifs where possible
31 * 2. Remove all "continue"s, replacing them with an "execute flag"
32 * 3. Replace all "break" with a single conditional one at the end of the loop
33 * 4. Replace all "return"s with a single return at the end of the function,
34 *    for the main function and/or other functions
35 *
36 * Applying this pass gives several benefits:
37 * 1. All functions can be inlined.
38 * 2. nv40 and other pre-DX10 chips without "continue" can be supported
39 * 3. nv30 and other pre-DX10 chips with no control flow at all are better
40 *    supported
41 *
42 * Continues are lowered by adding a per-loop "execute flag", initialized to
43 * true, that when cleared inhibits all execution until the end of the loop.
44 *
45 * Breaks are lowered to continues, plus setting a "break flag" that is checked
46 * at the end of the loop, and trigger the unique "break".
47 *
48 * Returns are lowered to breaks/continues, plus adding a "return flag" that
49 * causes loops to break again out of their enclosing loops until all the
50 * loops are exited: then the "execute flag" logic will ignore everything
51 * until the end of the function.
52 *
53 * Note that "continue" and "return" can also be implemented by adding
54 * a dummy loop and using break.
55 * However, this is bad for hardware with limited nesting depth, and
56 * prevents further optimization, and thus is not currently performed.
57 */
58
59#include "compiler/glsl_types.h"
60#include <string.h>
61#include "ir.h"
62
63/**
64 * Enum recording the result of analyzing how control flow might exit
65 * an IR node.
66 *
67 * Each possible value of jump_strength indicates a strictly stronger
68 * guarantee on control flow than the previous value.
69 *
70 * The ordering of strengths roughly reflects the way jumps are
71 * lowered: jumps with higher strength tend to be lowered to jumps of
72 * lower strength.  Accordingly, strength is used as a heuristic to
73 * determine which lowering to perform first.
74 *
75 * This enum is also used by get_jump_strength() to categorize
76 * instructions as either break, continue, return, or other.  When
77 * used in this fashion, strength_always_clears_execute_flag is not
78 * used.
79 *
80 * The control flow analysis made by this optimization pass makes two
81 * simplifying assumptions:
82 *
83 * - It ignores discard instructions, since they are lowered by a
84 *   separate pass (lower_discard.cpp).
85 *
86 * - It assumes it is always possible for control to flow from a loop
87 *   to the instruction immediately following it.  Technically, this
88 *   is not true (since all execution paths through the loop might
89 *   jump back to the top, or return from the function).
90 *
91 * Both of these simplifying assumtions are safe, since they can never
92 * cause reachable code to be incorrectly classified as unreachable;
93 * they can only do the opposite.
94 */
95enum jump_strength
96{
97   /**
98    * Analysis has produced no guarantee on how control flow might
99    * exit this IR node.  It might fall out the bottom (with or
100    * without clearing the execute flag, if present), or it might
101    * continue to the top of the innermost enclosing loop, break out
102    * of it, or return from the function.
103    */
104   strength_none,
105
106   /**
107    * The only way control can fall out the bottom of this node is
108    * through a code path that clears the execute flag.  It might also
109    * continue to the top of the innermost enclosing loop, break out
110    * of it, or return from the function.
111    */
112   strength_always_clears_execute_flag,
113
114   /**
115    * Control cannot fall out the bottom of this node.  It might
116    * continue to the top of the innermost enclosing loop, break out
117    * of it, or return from the function.
118    */
119   strength_continue,
120
121   /**
122    * Control cannot fall out the bottom of this node, or continue the
123    * top of the innermost enclosing loop.  It can only break out of
124    * it or return from the function.
125    */
126   strength_break,
127
128   /**
129    * Control cannot fall out the bottom of this node, continue to the
130    * top of the innermost enclosing loop, or break out of it.  It can
131    * only return from the function.
132    */
133   strength_return
134};
135
136namespace {
137
138struct block_record
139{
140   /* minimum jump strength (of lowered IR, not pre-lowering IR)
141    *
142    * If the block ends with a jump, must be the strength of the jump.
143    * Otherwise, the jump would be dead and have been deleted before)
144    *
145    * If the block doesn't end with a jump, it can be different than strength_none if all paths before it lead to some jump
146    * (e.g. an if with a return in one branch, and a break in the other, while not lowering them)
147    * Note that identical jumps are usually unified though.
148    */
149   jump_strength min_strength;
150
151   /* can anything clear the execute flag? */
152   bool may_clear_execute_flag;
153
154   block_record()
155   {
156      this->min_strength = strength_none;
157      this->may_clear_execute_flag = false;
158   }
159};
160
161struct loop_record
162{
163   ir_function_signature* signature;
164   ir_loop* loop;
165
166   /* used to avoid lowering the break used to represent lowered breaks */
167   unsigned nesting_depth;
168   bool in_if_at_the_end_of_the_loop;
169
170   bool may_set_return_flag;
171
172   ir_variable* execute_flag; /* cleared to emulate continue */
173
174   loop_record(ir_function_signature* p_signature = 0, ir_loop* p_loop = 0)
175   {
176      this->signature = p_signature;
177      this->loop = p_loop;
178      this->nesting_depth = 0;
179      this->in_if_at_the_end_of_the_loop = false;
180      this->may_set_return_flag = false;
181      this->execute_flag = 0;
182   }
183
184   ir_variable* get_execute_flag()
185   {
186      /* also supported for the "function loop" */
187      if(!this->execute_flag) {
188         exec_list& list = this->loop ? this->loop->body_instructions : signature->body;
189         this->execute_flag = new(this->signature) ir_variable(glsl_type::bool_type, "execute_flag", ir_var_temporary);
190         list.push_head(new(this->signature) ir_assignment(new(this->signature) ir_dereference_variable(execute_flag), new(this->signature) ir_constant(true)));
191         list.push_head(this->execute_flag);
192      }
193      return this->execute_flag;
194   }
195};
196
197struct function_record
198{
199   ir_function_signature* signature;
200   ir_variable* return_flag; /* used to break out of all loops and then jump to the return instruction */
201   ir_variable* return_value;
202   bool lower_return;
203   unsigned nesting_depth;
204
205   function_record(ir_function_signature* p_signature = 0,
206                   bool lower_return = false)
207   {
208      this->signature = p_signature;
209      this->return_flag = 0;
210      this->return_value = 0;
211      this->nesting_depth = 0;
212      this->lower_return = lower_return;
213   }
214
215   ir_variable* get_return_flag()
216   {
217      if(!this->return_flag) {
218         this->return_flag = new(this->signature) ir_variable(glsl_type::bool_type, "return_flag", ir_var_temporary);
219         this->signature->body.push_head(new(this->signature) ir_assignment(new(this->signature) ir_dereference_variable(return_flag), new(this->signature) ir_constant(false)));
220         this->signature->body.push_head(this->return_flag);
221      }
222      return this->return_flag;
223   }
224
225   ir_variable* get_return_value()
226   {
227      if(!this->return_value) {
228         assert(!this->signature->return_type->is_void());
229         return_value = new(this->signature) ir_variable(this->signature->return_type, "return_value", ir_var_temporary);
230         this->signature->body.push_head(this->return_value);
231      }
232      return this->return_value;
233   }
234};
235
236struct ir_lower_jumps_visitor : public ir_control_flow_visitor {
237   /* Postconditions: on exit of any visit() function:
238    *
239    * ANALYSIS: this->block.min_strength,
240    * this->block.may_clear_execute_flag, and
241    * this->loop.may_set_return_flag are updated to reflect the
242    * characteristics of the visited statement.
243    *
244    * DEAD_CODE_ELIMINATION: If this->block.min_strength is not
245    * strength_none, the visited node is at the end of its exec_list.
246    * In other words, any unreachable statements that follow the
247    * visited statement in its exec_list have been removed.
248    *
249    * CONTAINED_JUMPS_LOWERED: If the visited statement contains other
250    * statements, then should_lower_jump() is false for all of the
251    * return, break, or continue statements it contains.
252    *
253    * Note that visiting a jump does not lower it.  That is the
254    * responsibility of the statement (or function signature) that
255    * contains the jump.
256    */
257
258   using ir_control_flow_visitor::visit;
259
260   bool progress;
261
262   struct function_record function;
263   struct loop_record loop;
264   struct block_record block;
265
266   bool pull_out_jumps;
267   bool lower_continue;
268   bool lower_sub_return;
269   bool lower_main_return;
270
271   ir_lower_jumps_visitor()
272      : progress(false),
273        pull_out_jumps(false),
274        lower_continue(false),
275        lower_sub_return(false),
276        lower_main_return(false)
277   {
278   }
279
280   void truncate_after_instruction(exec_node *ir)
281   {
282      if (!ir)
283         return;
284
285      while (!ir->get_next()->is_tail_sentinel()) {
286         ((ir_instruction *)ir->get_next())->remove();
287         this->progress = true;
288      }
289   }
290
291   void move_outer_block_inside(ir_instruction *ir, exec_list *inner_block)
292   {
293      while (!ir->get_next()->is_tail_sentinel()) {
294         ir_instruction *move_ir = (ir_instruction *)ir->get_next();
295
296         move_ir->remove();
297         inner_block->push_tail(move_ir);
298      }
299   }
300
301   /**
302    * Insert the instructions necessary to lower a return statement,
303    * before the given return instruction.
304    */
305   void insert_lowered_return(ir_return *ir)
306   {
307      ir_variable* return_flag = this->function.get_return_flag();
308      if(!this->function.signature->return_type->is_void()) {
309         ir_variable* return_value = this->function.get_return_value();
310         ir->insert_before(
311            new(ir) ir_assignment(
312               new (ir) ir_dereference_variable(return_value),
313               ir->value));
314      }
315      ir->insert_before(
316         new(ir) ir_assignment(
317            new (ir) ir_dereference_variable(return_flag),
318            new (ir) ir_constant(true)));
319      this->loop.may_set_return_flag = true;
320   }
321
322   /**
323    * If the given instruction is a return, lower it to instructions
324    * that store the return value (if there is one), set the return
325    * flag, and then break.
326    *
327    * It is safe to pass NULL to this function.
328    */
329   void lower_return_unconditionally(ir_instruction *ir)
330   {
331      if (get_jump_strength(ir) != strength_return) {
332         return;
333      }
334      insert_lowered_return((ir_return*)ir);
335      ir->replace_with(new(ir) ir_loop_jump(ir_loop_jump::jump_break));
336   }
337
338   virtual void visit(class ir_loop_jump * ir)
339   {
340      /* Eliminate all instructions after each one, since they are
341       * unreachable.  This satisfies the DEAD_CODE_ELIMINATION
342       * postcondition.
343       */
344      truncate_after_instruction(ir);
345
346      /* Set this->block.min_strength based on this instruction.  This
347       * satisfies the ANALYSIS postcondition.  It is not necessary to
348       * update this->block.may_clear_execute_flag or
349       * this->loop.may_set_return_flag, because an unlowered jump
350       * instruction can't change any flags.
351       */
352      this->block.min_strength = ir->is_break() ? strength_break : strength_continue;
353
354      /* The CONTAINED_JUMPS_LOWERED postcondition is already
355       * satisfied, because jump statements can't contain other
356       * statements.
357       */
358   }
359
360   virtual void visit(class ir_return * ir)
361   {
362      /* Eliminate all instructions after each one, since they are
363       * unreachable.  This satisfies the DEAD_CODE_ELIMINATION
364       * postcondition.
365       */
366      truncate_after_instruction(ir);
367
368      /* Set this->block.min_strength based on this instruction.  This
369       * satisfies the ANALYSIS postcondition.  It is not necessary to
370       * update this->block.may_clear_execute_flag or
371       * this->loop.may_set_return_flag, because an unlowered return
372       * instruction can't change any flags.
373       */
374      this->block.min_strength = strength_return;
375
376      /* The CONTAINED_JUMPS_LOWERED postcondition is already
377       * satisfied, because jump statements can't contain other
378       * statements.
379       */
380   }
381
382   virtual void visit(class ir_discard * ir)
383   {
384      /* Nothing needs to be done.  The ANALYSIS and
385       * DEAD_CODE_ELIMINATION postconditions are already satisfied,
386       * because discard statements are ignored by this optimization
387       * pass.  The CONTAINED_JUMPS_LOWERED postcondition is already
388       * satisfied, because discard statements can't contain other
389       * statements.
390       */
391      (void) ir;
392   }
393
394   enum jump_strength get_jump_strength(ir_instruction* ir)
395   {
396      if(!ir)
397         return strength_none;
398      else if(ir->ir_type == ir_type_loop_jump) {
399         if(((ir_loop_jump*)ir)->is_break())
400            return strength_break;
401         else
402            return strength_continue;
403      } else if(ir->ir_type == ir_type_return)
404         return strength_return;
405      else
406         return strength_none;
407   }
408
409   bool should_lower_jump(ir_jump* ir)
410   {
411      unsigned strength = get_jump_strength(ir);
412      bool lower;
413      switch(strength)
414      {
415      case strength_none:
416         lower = false; /* don't change this, code relies on it */
417         break;
418      case strength_continue:
419         lower = lower_continue;
420         break;
421      case strength_break:
422         lower = false;
423         break;
424      case strength_return:
425         /* never lower return at the end of a this->function */
426         if(this->function.nesting_depth == 0 && ir->get_next()->is_tail_sentinel())
427            lower = false;
428         else
429            lower = this->function.lower_return;
430         break;
431      }
432      return lower;
433   }
434
435   block_record visit_block(exec_list* list)
436   {
437      /* Note: since visiting a node may change that node's next
438       * pointer, we can't use visit_exec_list(), because
439       * visit_exec_list() caches the node's next pointer before
440       * visiting it.  So we use foreach_in_list() instead.
441       *
442       * foreach_in_list() isn't safe if the node being visited gets
443       * removed, but fortunately this visitor doesn't do that.
444       */
445
446      block_record saved_block = this->block;
447      this->block = block_record();
448      foreach_in_list(ir_instruction, node, list) {
449         node->accept(this);
450      }
451      block_record ret = this->block;
452      this->block = saved_block;
453      return ret;
454   }
455
456   virtual void visit(ir_if *ir)
457   {
458      if(this->loop.nesting_depth == 0 && ir->get_next()->is_tail_sentinel())
459         this->loop.in_if_at_the_end_of_the_loop = true;
460
461      ++this->function.nesting_depth;
462      ++this->loop.nesting_depth;
463
464      block_record block_records[2];
465      ir_jump* jumps[2];
466
467      /* Recursively lower nested jumps.  This satisfies the
468       * CONTAINED_JUMPS_LOWERED postcondition, except in the case of
469       * unconditional jumps at the end of ir->then_instructions and
470       * ir->else_instructions, which are handled below.
471       */
472      block_records[0] = visit_block(&ir->then_instructions);
473      block_records[1] = visit_block(&ir->else_instructions);
474
475retry: /* we get here if we put code after the if inside a branch */
476
477      /* Determine which of ir->then_instructions and
478       * ir->else_instructions end with an unconditional jump.
479       */
480      for(unsigned i = 0; i < 2; ++i) {
481         exec_list& list = i ? ir->else_instructions : ir->then_instructions;
482         jumps[i] = 0;
483         if(!list.is_empty() && get_jump_strength((ir_instruction*)list.get_tail()))
484            jumps[i] = (ir_jump*)list.get_tail();
485      }
486
487      /* Loop until we have satisfied the CONTAINED_JUMPS_LOWERED
488       * postcondition by lowering jumps in both then_instructions and
489       * else_instructions.
490       */
491      for(;;) {
492         /* Determine the types of the jumps that terminate
493          * ir->then_instructions and ir->else_instructions.
494          */
495         jump_strength jump_strengths[2];
496
497         for(unsigned i = 0; i < 2; ++i) {
498            if(jumps[i]) {
499               jump_strengths[i] = block_records[i].min_strength;
500               assert(jump_strengths[i] == get_jump_strength(jumps[i]));
501            } else
502               jump_strengths[i] = strength_none;
503         }
504
505         /* If both code paths end in a jump, and the jumps are the
506          * same, and we are pulling out jumps, replace them with a
507          * single jump that comes after the if instruction.  The new
508          * jump will be visited next, and it will be lowered if
509          * necessary by the loop or conditional that encloses it.
510          */
511         if(pull_out_jumps && jump_strengths[0] == jump_strengths[1]) {
512            bool unify = true;
513            if(jump_strengths[0] == strength_continue)
514               ir->insert_after(new(ir) ir_loop_jump(ir_loop_jump::jump_continue));
515            else if(jump_strengths[0] == strength_break)
516               ir->insert_after(new(ir) ir_loop_jump(ir_loop_jump::jump_break));
517            /* FINISHME: unify returns with identical expressions */
518            else if(jump_strengths[0] == strength_return && this->function.signature->return_type->is_void())
519               ir->insert_after(new(ir) ir_return(NULL));
520	    else
521	       unify = false;
522
523            if(unify) {
524               jumps[0]->remove();
525               jumps[1]->remove();
526               this->progress = true;
527
528               /* Update jumps[] to reflect the fact that the jumps
529                * are gone, and update block_records[] to reflect the
530                * fact that control can now flow to the next
531                * instruction.
532                */
533               jumps[0] = 0;
534               jumps[1] = 0;
535               block_records[0].min_strength = strength_none;
536               block_records[1].min_strength = strength_none;
537
538               /* The CONTAINED_JUMPS_LOWERED postcondition is now
539                * satisfied, so we can break out of the loop.
540                */
541               break;
542            }
543         }
544
545         /* lower a jump: if both need to lowered, start with the strongest one, so that
546          * we might later unify the lowered version with the other one
547          */
548         bool should_lower[2];
549         for(unsigned i = 0; i < 2; ++i)
550            should_lower[i] = should_lower_jump(jumps[i]);
551
552         int lower;
553         if(should_lower[1] && should_lower[0])
554            lower = jump_strengths[1] > jump_strengths[0];
555         else if(should_lower[0])
556            lower = 0;
557         else if(should_lower[1])
558            lower = 1;
559         else
560            /* Neither code path ends in a jump that needs to be
561             * lowered, so the CONTAINED_JUMPS_LOWERED postcondition
562             * is satisfied and we can break out of the loop.
563             */
564            break;
565
566         if(jump_strengths[lower] == strength_return) {
567            /* To lower a return, we create a return flag (if the
568             * function doesn't have one already) and add instructions
569             * that: 1. store the return value (if this function has a
570             * non-void return) and 2. set the return flag
571             */
572            insert_lowered_return((ir_return*)jumps[lower]);
573            if(this->loop.loop) {
574               /* If we are in a loop, replace the return instruction
575                * with a break instruction, and then loop so that the
576                * break instruction can be lowered if necessary.
577                */
578               ir_loop_jump* lowered = 0;
579               lowered = new(ir) ir_loop_jump(ir_loop_jump::jump_break);
580               /* Note: we must update block_records and jumps to
581                * reflect the fact that the control path has been
582                * altered from a return to a break.
583                */
584               block_records[lower].min_strength = strength_break;
585               jumps[lower]->replace_with(lowered);
586               jumps[lower] = lowered;
587            } else {
588               /* If we are not in a loop, we then proceed as we would
589                * for a continue statement (set the execute flag to
590                * false to prevent the rest of the function from
591                * executing).
592                */
593               goto lower_continue;
594            }
595            this->progress = true;
596         } else if(jump_strengths[lower] == strength_break) {
597            unreachable("no lowering of breaks any more");
598         } else if(jump_strengths[lower] == strength_continue) {
599lower_continue:
600            /* To lower a continue, we create an execute flag (if the
601             * loop doesn't have one already) and replace the continue
602             * with an instruction that clears it.
603             *
604             * Note that this code path gets exercised when lowering
605             * return statements that are not inside a loop, so
606             * this->loop must be initialized even outside of loops.
607             */
608            ir_variable* execute_flag = this->loop.get_execute_flag();
609            jumps[lower]->replace_with(new(ir) ir_assignment(new (ir) ir_dereference_variable(execute_flag), new (ir) ir_constant(false)));
610            /* Note: we must update block_records and jumps to reflect
611             * the fact that the control path has been altered to an
612             * instruction that clears the execute flag.
613             */
614            jumps[lower] = 0;
615            block_records[lower].min_strength = strength_always_clears_execute_flag;
616            block_records[lower].may_clear_execute_flag = true;
617            this->progress = true;
618
619            /* Let the loop run again, in case the other branch of the
620             * if needs to be lowered too.
621             */
622         }
623      }
624
625      /* move out a jump out if possible */
626      if(pull_out_jumps) {
627         /* If one of the branches ends in a jump, and control cannot
628          * fall out the bottom of the other branch, then we can move
629          * the jump after the if.
630          *
631          * Set move_out to the branch we are moving a jump out of.
632          */
633         int move_out = -1;
634         if(jumps[0] && block_records[1].min_strength >= strength_continue)
635            move_out = 0;
636         else if(jumps[1] && block_records[0].min_strength >= strength_continue)
637            move_out = 1;
638
639         if(move_out >= 0)
640         {
641            jumps[move_out]->remove();
642            ir->insert_after(jumps[move_out]);
643            /* Note: we must update block_records and jumps to reflect
644             * the fact that the jump has been moved out of the if.
645             */
646            jumps[move_out] = 0;
647            block_records[move_out].min_strength = strength_none;
648            this->progress = true;
649         }
650      }
651
652      /* Now satisfy the ANALYSIS postcondition by setting
653       * this->block.min_strength and
654       * this->block.may_clear_execute_flag based on the
655       * characteristics of the two branches.
656       */
657      if(block_records[0].min_strength < block_records[1].min_strength)
658         this->block.min_strength = block_records[0].min_strength;
659      else
660         this->block.min_strength = block_records[1].min_strength;
661      this->block.may_clear_execute_flag = this->block.may_clear_execute_flag || block_records[0].may_clear_execute_flag || block_records[1].may_clear_execute_flag;
662
663      /* Now we need to clean up the instructions that follow the
664       * if.
665       *
666       * If those instructions are unreachable, then satisfy the
667       * DEAD_CODE_ELIMINATION postcondition by eliminating them.
668       * Otherwise that postcondition is already satisfied.
669       */
670      if(this->block.min_strength)
671         truncate_after_instruction(ir);
672      else if(this->block.may_clear_execute_flag)
673      {
674         /* If the "if" instruction might clear the execute flag, then
675          * we need to guard any instructions that follow so that they
676          * are only executed if the execute flag is set.
677          *
678          * If one of the branches of the "if" always clears the
679          * execute flag, and the other branch never clears it, then
680          * this is easy: just move all the instructions following the
681          * "if" into the branch that never clears it.
682          */
683         int move_into = -1;
684         if(block_records[0].min_strength && !block_records[1].may_clear_execute_flag)
685            move_into = 1;
686         else if(block_records[1].min_strength && !block_records[0].may_clear_execute_flag)
687            move_into = 0;
688
689         if(move_into >= 0) {
690            assert(!block_records[move_into].min_strength && !block_records[move_into].may_clear_execute_flag); /* otherwise, we just truncated */
691
692            exec_list* list = move_into ? &ir->else_instructions : &ir->then_instructions;
693            exec_node* next = ir->get_next();
694            if(!next->is_tail_sentinel()) {
695               move_outer_block_inside(ir, list);
696
697               /* If any instructions moved, then we need to visit
698                * them (since they are now inside the "if").  Since
699                * block_records[move_into] is in its default state
700                * (see assertion above), we can safely replace
701                * block_records[move_into] with the result of this
702                * analysis.
703                */
704               exec_list list;
705               list.head_sentinel.next = next;
706               block_records[move_into] = visit_block(&list);
707
708               /*
709                * Then we need to re-start our jump lowering, since one
710                * of the instructions we moved might be a jump that
711                * needs to be lowered.
712                */
713               this->progress = true;
714               goto retry;
715            }
716         } else {
717            /* If we get here, then the simple case didn't apply; we
718             * need to actually guard the instructions that follow.
719             *
720             * To avoid creating unnecessarily-deep nesting, first
721             * look through the instructions that follow and unwrap
722             * any instructions that that are already wrapped in the
723             * appropriate guard.
724             */
725            ir_instruction* ir_after;
726            for(ir_after = (ir_instruction*)ir->get_next(); !ir_after->is_tail_sentinel();)
727            {
728               ir_if* ir_if = ir_after->as_if();
729               if(ir_if && ir_if->else_instructions.is_empty()) {
730                  ir_dereference_variable* ir_if_cond_deref = ir_if->condition->as_dereference_variable();
731                  if(ir_if_cond_deref && ir_if_cond_deref->var == this->loop.execute_flag) {
732                     ir_instruction* ir_next = (ir_instruction*)ir_after->get_next();
733                     ir_after->insert_before(&ir_if->then_instructions);
734                     ir_after->remove();
735                     ir_after = ir_next;
736                     continue;
737                  }
738               }
739               ir_after = (ir_instruction*)ir_after->get_next();
740
741               /* only set this if we find any unprotected instruction */
742               this->progress = true;
743            }
744
745            /* Then, wrap all the instructions that follow in a single
746             * guard.
747             */
748            if(!ir->get_next()->is_tail_sentinel()) {
749               assert(this->loop.execute_flag);
750               ir_if* if_execute = new(ir) ir_if(new(ir) ir_dereference_variable(this->loop.execute_flag));
751               move_outer_block_inside(ir, &if_execute->then_instructions);
752               ir->insert_after(if_execute);
753            }
754         }
755      }
756      --this->loop.nesting_depth;
757      --this->function.nesting_depth;
758   }
759
760   virtual void visit(ir_loop *ir)
761   {
762      /* Visit the body of the loop, with a fresh data structure in
763       * this->loop so that the analysis we do here won't bleed into
764       * enclosing loops.
765       *
766       * We assume that all code after a loop is reachable from the
767       * loop (see comments on enum jump_strength), so the
768       * DEAD_CODE_ELIMINATION postcondition is automatically
769       * satisfied, as is the block.min_strength portion of the
770       * ANALYSIS postcondition.
771       *
772       * The block.may_clear_execute_flag portion of the ANALYSIS
773       * postcondition is automatically satisfied because execute
774       * flags do not propagate outside of loops.
775       *
776       * The loop.may_set_return_flag portion of the ANALYSIS
777       * postcondition is handled below.
778       */
779      ++this->function.nesting_depth;
780      loop_record saved_loop = this->loop;
781      this->loop = loop_record(this->function.signature, ir);
782
783      /* Recursively lower nested jumps.  This satisfies the
784       * CONTAINED_JUMPS_LOWERED postcondition, except in the case of
785       * an unconditional continue or return at the bottom of the
786       * loop, which are handled below.
787       */
788      block_record body = visit_block(&ir->body_instructions);
789
790      /* If the loop ends in an unconditional continue, eliminate it
791       * because it is redundant.
792       */
793      ir_instruction *ir_last
794         = (ir_instruction *) ir->body_instructions.get_tail();
795      if (get_jump_strength(ir_last) == strength_continue) {
796         ir_last->remove();
797      }
798
799      /* If the loop ends in an unconditional return, and we are
800       * lowering returns, lower it.
801       */
802      if (this->function.lower_return)
803         lower_return_unconditionally(ir_last);
804
805      if(body.min_strength >= strength_break) {
806         /* FINISHME: If the min_strength of the loop body is
807          * strength_break or strength_return, that means that it
808          * isn't a loop at all, since control flow always leaves the
809          * body of the loop via break or return.  In principle the
810          * loop could be eliminated in this case.  This optimization
811          * is not implemented yet.
812          */
813      }
814
815
816      /* If the body of the loop may set the return flag, then at
817       * least one return was lowered to a break, so we need to ensure
818       * that the return flag is checked after the body of the loop is
819       * executed.
820       */
821      if(this->loop.may_set_return_flag) {
822         assert(this->function.return_flag);
823         /* Generate the if statement to check the return flag */
824         ir_if* return_if = new(ir) ir_if(new(ir) ir_dereference_variable(this->function.return_flag));
825         /* Note: we also need to propagate the knowledge that the
826          * return flag may get set to the outer context.  This
827          * satisfies the loop.may_set_return_flag part of the
828          * ANALYSIS postcondition.
829          */
830         saved_loop.may_set_return_flag = true;
831         if(saved_loop.loop)
832            /* If this loop is nested inside another one, then the if
833             * statement that we generated should break out of that
834             * loop if the return flag is set.  Caller will lower that
835             * break statement if necessary.
836             */
837            return_if->then_instructions.push_tail(new(ir) ir_loop_jump(ir_loop_jump::jump_break));
838         else {
839            /* Otherwise, ensure that the instructions that follow are only
840             * executed if the return flag is clear.  We can do that by moving
841             * those instructions into the else clause of the generated if
842             * statement.
843             */
844            move_outer_block_inside(ir, &return_if->else_instructions);
845
846            /* In case the loop is embedded inside an if add a new return to
847             * the return flag then branch and let a future pass tidy it up.
848             */
849            if (this->function.signature->return_type->is_void())
850               return_if->then_instructions.push_tail(new(ir) ir_return(NULL));
851            else {
852               assert(this->function.return_value);
853               ir_variable* return_value = this->function.return_value;
854               return_if->then_instructions.push_tail(
855                  new(ir) ir_return(new(ir) ir_dereference_variable(return_value)));
856            }
857         }
858
859         ir->insert_after(return_if);
860      }
861
862      this->loop = saved_loop;
863      --this->function.nesting_depth;
864   }
865
866   virtual void visit(ir_function_signature *ir)
867   {
868      /* these are not strictly necessary */
869      assert(!this->function.signature);
870      assert(!this->loop.loop);
871
872      bool lower_return;
873      if (strcmp(ir->function_name(), "main") == 0)
874         lower_return = lower_main_return;
875      else
876         lower_return = lower_sub_return;
877
878      function_record saved_function = this->function;
879      loop_record saved_loop = this->loop;
880      this->function = function_record(ir, lower_return);
881      this->loop = loop_record(ir);
882
883      assert(!this->loop.loop);
884
885      /* Visit the body of the function to lower any jumps that occur
886       * in it, except possibly an unconditional return statement at
887       * the end of it.
888       */
889      visit_block(&ir->body);
890
891      /* If the body ended in an unconditional return of non-void,
892       * then we don't need to lower it because it's the one canonical
893       * return.
894       *
895       * If the body ended in a return of void, eliminate it because
896       * it is redundant.
897       */
898      if (ir->return_type->is_void() &&
899          get_jump_strength((ir_instruction *) ir->body.get_tail())) {
900         ir_jump *jump = (ir_jump *) ir->body.get_tail();
901         assert (jump->ir_type == ir_type_return);
902         jump->remove();
903      }
904
905      if(this->function.return_value)
906         ir->body.push_tail(new(ir) ir_return(new (ir) ir_dereference_variable(this->function.return_value)));
907
908      this->loop = saved_loop;
909      this->function = saved_function;
910   }
911
912   virtual void visit(class ir_function * ir)
913   {
914      visit_block(&ir->signatures);
915   }
916};
917
918} /* anonymous namespace */
919
920bool
921do_lower_jumps(exec_list *instructions, bool pull_out_jumps, bool lower_sub_return, bool lower_main_return, bool lower_continue)
922{
923   ir_lower_jumps_visitor v;
924   v.pull_out_jumps = pull_out_jumps;
925   v.lower_continue = lower_continue;
926   v.lower_sub_return = lower_sub_return;
927   v.lower_main_return = lower_main_return;
928
929   bool progress_ever = false;
930   do {
931      v.progress = false;
932      visit_exec_list(instructions, &v);
933      progress_ever = v.progress || progress_ever;
934   } while (v.progress);
935
936   return progress_ever;
937}
938