- if (is_unknown_jump_target(env->phase, jmp_block)) continue;
- if (has_operations(env->phase,jmp_block)) continue;
- /* jmp_block is an empty block! */
-
- if (get_Block_n_cfgpreds(jmp_block) != 1) continue;
- pred = get_Block_cfgpred(jmp_block, 0);
- exchange(jmp, pred);
- env->changed = true;
-
- /* cleanup: jmp_block might have a Keep edge! */
- pred_block = get_nodes_block(pred);
- exchange(jmp_block, pred_block);
+ if (jmp_block == block)
+ continue; /* this infinite loop cannot be optimized any further */
+ if (is_unknown_jump_target(env->phase, jmp_block))
+ continue; /* unknown jump target must not be optimized */
+ if (has_operations(env->phase,jmp_block))
+ continue; /* this block contains operations and cannot be skipped */
+ if (has_phis(env->phase,jmp_block))
+ continue; /* this block contains Phis and is not skipped */
+
+ /* jmp_block is an empty block and can be optimized! */
+
+ n_jpreds = get_Block_n_cfgpreds(jmp_block);
+ /**
+ * If the jmp block has only one predecessor this is straightforward.
+ * However, if there are more predecessors, we only handle this,
+ * if block has no Phis.
+ */
+ if (n_jpreds == 1) {
+ /* skip jmp block by rerouting its predecessor to block
+ *
+ * A A
+ * | |
+ * jmp_block => |
+ * | |
+ * block block
+ */
+ pred = get_Block_cfgpred(jmp_block, 0);
+ exchange(jmp, pred);
+
+ /* cleanup: jmp_block might have a Keep edge! */
+ pred_block = get_nodes_block(pred);
+ exchange(jmp_block, pred_block);
+ env->changed = true;
+ } else if (! has_phis(env->phase, block)) {
+ /* all predecessors can skip the jmp block, so block gets some new predecessors
+ *
+ * A B A B
+ * \ / | |
+ * jmp_block C => Bad C | |
+ * \ / \ | | /
+ * block block
+ */
+ ir_node **ins = NULL;
+ int j;
+ NEW_ARR_A(ir_node *, ins, n_preds+n_jpreds);
+ /* first copy the old predecessors, because the outer loop (i) still walks over them */
+ for (j = 0; j < n_preds; ++j) {
+ ins[j] = get_Block_cfgpred(block, j);
+ }
+ /* now append the new predecessors */
+ for (j = 0; j < n_jpreds; ++j) {
+ pred = get_Block_cfgpred(jmp_block, j);
+ ins[n_preds+j] = pred;
+ }
+ set_irn_in(block, n_preds+n_jpreds, ins);
+ /* convert the jmp_block to Bad */
+ ir_graph *irg = get_irn_irg(block);
+ exchange(jmp_block, new_r_Bad(irg, mode_BB));
+ exchange(jmp, new_r_Bad(irg, mode_X));
+ /* let the outer loop walk over the new predecessors as well */
+ n_preds += n_jpreds;
+ env->changed = true;
+ // TODO What if jmp_block had a KeepAlive edge?
+ } else {
+ /* This would involve Phis ... */
+ }