1a4ea53fe1f9ecfa48455f4961f6e1c8f1283639
[mono.git] / mono / mini / branch-opts.c
1 /*
2  * branch-opts.c: Branch optimizations support 
3  *
4  * Authors:
5  *   Patrik Torstensson (Patrik.Torstesson at gmail.com)
6  *
7  * (C) 2005 Ximian, Inc.  http://www.ximian.com
8  * Copyright 2011 Xamarin Inc.  http://www.xamarin.com
9  */
10  #include "mini.h"
11
12 #ifndef DISABLE_JIT
13  
14
15 /*
16  * Returns true if @bb is a basic block which falls through the next block.
17  * TODO verify if it helps to check if the bb last ins is a branch to its successor. 
18  */
19 static gboolean
20 mono_bb_is_fall_through (MonoCompile *cfg, MonoBasicBlock *bb)
21 {
22         return  bb->next_bb && bb->next_bb->region == bb->region && /*fall throught between regions is not really interesting or useful*/
23                         (bb->last_ins == NULL || !MONO_IS_BRANCH_OP (bb->last_ins)); /*and the last op can't be a branch too*/
24 }
25
26 /*
27  * Used by the arch code to replace the exception handling
28  * with a direct branch. This is safe to do if the 
29  * exception object isn't used, no rethrow statement and
30  * no filter statement (verify).
31  *
32  */
33 MonoInst *
34 mono_branch_optimize_exception_target (MonoCompile *cfg, MonoBasicBlock *bb, const char * exname)
35 {
36         MonoMethodHeader *header = cfg->header;
37         MonoExceptionClause *clause;
38         MonoClass *exclass;
39         int i;
40
41         if (!(cfg->opt & MONO_OPT_EXCEPTION))
42                 return NULL;
43
44         if (bb->region == -1 || !MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
45                 return NULL;
46
47         exclass = mono_class_load_from_name (mono_get_corlib (), "System", exname);
48         /* search for the handler */
49         for (i = 0; i < header->num_clauses; ++i) {
50                 clause = &header->clauses [i];
51                 if (MONO_OFFSET_IN_CLAUSE (clause, bb->real_offset)) {
52                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE && clause->data.catch_class && mono_class_is_assignable_from (clause->data.catch_class, exclass)) {
53                                 MonoBasicBlock *tbb;
54
55                                 /* get the basic block for the handler and 
56                                  * check if the exception object is used.
57                                  * Flag is set during method_to_ir due to 
58                                  * pop-op is optmized away in codegen (burg).
59                                  */
60                                 tbb = cfg->cil_offset_to_bb [clause->handler_offset];
61                                 if (tbb && tbb->flags & BB_EXCEPTION_DEAD_OBJ && !(tbb->flags & BB_EXCEPTION_UNSAFE)) {
62                                         MonoBasicBlock *targetbb = tbb;
63                                         gboolean unsafe = FALSE;
64
65                                         /* Check if this catch clause is ok to optimize by
66                                          * looking for the BB_EXCEPTION_UNSAFE in every BB that
67                                          * belongs to the same region. 
68                                          *
69                                          * UNSAFE flag is set during method_to_ir (OP_RETHROW)
70                                          */
71                                         while (!unsafe && tbb->next_bb && tbb->region == tbb->next_bb->region) {
72                                                 if (tbb->next_bb->flags & BB_EXCEPTION_UNSAFE)  {
73                                                         unsafe = TRUE;
74                                                         break;
75                                                 }
76                                                 tbb = tbb->next_bb;
77                                         }
78
79                                         if (!unsafe) {
80                                                 MonoInst *jump;
81
82                                                 /* Create dummy inst to allow easier integration in
83                                                  * arch dependent code (opcode ignored)
84                                                  */
85                                                 MONO_INST_NEW (cfg, jump, OP_BR);
86
87                                                 /* Allocate memory for our branch target */
88                                                 jump->inst_i1 = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
89                                                 jump->inst_true_bb = targetbb;
90
91                                                 if (cfg->verbose_level > 2) 
92                                                         g_print ("found exception to optimize - returning branch to BB%d (%s) (instead of throw) for method %s:%s\n", targetbb->block_num, clause->data.catch_class->name, cfg->method->klass->name, cfg->method->name);
93
94                                                 return jump;
95                                         } 
96
97                                         return NULL;
98                                 } else {
99                                         /* Branching to an outer clause could skip inner clauses */
100                                         return NULL;
101                                 }
102                         } else {
103                                 /* Branching to an outer clause could skip inner clauses */
104                                 return NULL;
105                         }
106                 }
107         }
108
109         return NULL;
110 }
111
112 static const int int_cmov_opcodes [] = {
113         OP_CMOV_IEQ,
114         OP_CMOV_INE_UN,
115         OP_CMOV_ILE,
116         OP_CMOV_IGE,
117         OP_CMOV_ILT,
118         OP_CMOV_IGT,
119         OP_CMOV_ILE_UN,
120         OP_CMOV_IGE_UN,
121         OP_CMOV_ILT_UN,
122         OP_CMOV_IGT_UN
123 };
124
125 static const int long_cmov_opcodes [] = {
126         OP_CMOV_LEQ,
127         OP_CMOV_LNE_UN,
128         OP_CMOV_LLE,
129         OP_CMOV_LGE,
130         OP_CMOV_LLT,
131         OP_CMOV_LGT,
132         OP_CMOV_LLE_UN,
133         OP_CMOV_LGE_UN,
134         OP_CMOV_LLT_UN,
135         OP_CMOV_LGT_UN
136 };
137
138 static G_GNUC_UNUSED int
139 br_to_br_un (int opcode)
140 {
141         switch (opcode) {
142         case OP_IBGT:
143                 return OP_IBGT_UN;
144                 break;
145         case OP_IBLE:
146                 return OP_IBLE_UN;
147                 break;
148         case OP_LBGT:
149                 return OP_LBGT_UN;
150                 break;
151         case OP_LBLE:
152                 return OP_LBLE_UN;
153                 break;
154         default:
155                 g_assert_not_reached ();
156                 return -1;
157         }
158 }
159
160 /**
161  * mono_replace_ins:
162  *
163  *   Replace INS with its decomposition which is stored in a series of bblocks starting
164  * at FIRST_BB and ending at LAST_BB. On enter, PREV points to the predecessor of INS. 
165  * On return, it will be set to the last ins of the decomposition.
166  */
167 void
168 mono_replace_ins (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, MonoInst **prev, MonoBasicBlock *first_bb, MonoBasicBlock *last_bb)
169 {
170         MonoInst *next = ins->next;
171
172         if (next && next->opcode == OP_NOP) {
173                 /* Avoid NOPs following branches */
174                 ins->next = next->next;
175                 next = next->next;
176         }
177
178         if (first_bb == last_bb) {
179                 /* 
180                  * Only one replacement bb, merge the code into
181                  * the current bb.
182                  */
183
184                 /* Delete links between the first_bb and its successors */
185                 while (first_bb->out_count)
186                         mono_unlink_bblock (cfg, first_bb, first_bb->out_bb [0]);
187
188                 /* Head */
189                 if (*prev) {
190                         (*prev)->next = first_bb->code;
191                         first_bb->code->prev = (*prev);
192                 } else {
193                         bb->code = first_bb->code;
194                 }
195
196                 /* Tail */
197                 last_bb->last_ins->next = next;
198                 if (next)
199                         next->prev = last_bb->last_ins;
200                 else
201                         bb->last_ins = last_bb->last_ins;
202                 *prev = last_bb->last_ins;
203                 bb->has_array_access |= first_bb->has_array_access;
204         } else {
205                 int i, count;
206                 MonoBasicBlock **tmp_bblocks, *tmp;
207                 MonoInst *last;
208
209                 /* Multiple BBs */
210
211                 /* Set region */
212                 for (tmp = first_bb; tmp; tmp = tmp->next_bb)
213                         tmp->region = bb->region;
214
215                 /* Split the original bb */
216                 if (ins->next)
217                         ins->next->prev = NULL;
218                 ins->next = NULL;
219                 bb->last_ins = ins;
220
221                 /* Merge the second part of the original bb into the last bb */
222                 if (last_bb->last_ins) {
223                         last_bb->last_ins->next = next;
224                         if (next)
225                                 next->prev = last_bb->last_ins;
226                 } else {
227                         last_bb->code = next;
228                 }
229                 last_bb->has_array_access |= bb->has_array_access;
230
231                 if (next) {
232                         for (last = next; last->next != NULL; last = last->next)
233                                 ;
234                         last_bb->last_ins = last;
235                 }
236
237                 for (i = 0; i < bb->out_count; ++i)
238                         mono_link_bblock (cfg, last_bb, bb->out_bb [i]);
239
240                 /* Merge the first (dummy) bb to the original bb */
241                 if (*prev) {
242                         (*prev)->next = first_bb->code;
243                         first_bb->code->prev = (*prev);
244                 } else {
245                         bb->code = first_bb->code;
246                 }
247                 bb->last_ins = first_bb->last_ins;
248                 bb->has_array_access |= first_bb->has_array_access;
249
250                 /* Delete the links between the original bb and its successors */
251                 tmp_bblocks = bb->out_bb;
252                 count = bb->out_count;
253                 for (i = 0; i < count; ++i)
254                         mono_unlink_bblock (cfg, bb, tmp_bblocks [i]);
255
256                 /* Add links between the original bb and the first_bb's successors */
257                 for (i = 0; i < first_bb->out_count; ++i) {
258                         MonoBasicBlock *out_bb = first_bb->out_bb [i];
259
260                         mono_link_bblock (cfg, bb, out_bb);
261                 }
262                 /* Delete links between the first_bb and its successors */
263                 for (i = 0; i < bb->out_count; ++i) {
264                         MonoBasicBlock *out_bb = bb->out_bb [i];
265
266                         mono_unlink_bblock (cfg, first_bb, out_bb);
267                 }
268                 last_bb->next_bb = bb->next_bb;
269                 bb->next_bb = first_bb->next_bb;
270
271                 *prev = NULL;
272         }
273 }
274
275 void
276 mono_if_conversion (MonoCompile *cfg)
277 {
278 #ifdef MONO_ARCH_HAVE_CMOV_OPS
279         MonoBasicBlock *bb;
280         gboolean changed = FALSE;
281         int filter = FILTER_NOP | FILTER_IL_SEQ_POINT;
282
283         if (!(cfg->opt & MONO_OPT_CMOV))
284                 return;
285
286         // FIXME: Make this work with extended bblocks
287
288         /* 
289          * This pass requires somewhat optimized IR code so it should be run after
290          * local cprop/deadce. Also, it should be run before dominator computation, since
291          * it changes control flow.
292          */
293         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
294                 MonoBasicBlock *bb1, *bb2;
295
296         restart:
297                 /* Look for the IR code generated from cond ? a : b
298                  * which is:
299                  * BB:
300                  * b<cond> [BB1BB2]
301                  * BB1:
302                  * <var> <- <a>
303                  * br BB3
304                  * BB2:
305                  * <var> <- <b>
306                  * br BB3
307                  */
308                 if (!(bb->out_count == 2 && !bb->extended))
309                         continue;
310
311                 bb1 = bb->out_bb [0];
312                 bb2 = bb->out_bb [1];
313
314                 if (bb1->in_count == 1 && bb2->in_count == 1 && bb1->out_count == 1 && bb2->out_count == 1 && bb1->out_bb [0] == bb2->out_bb [0]) {
315                         MonoInst *compare, *branch, *ins1, *ins2, *cmov, *move, *tmp;
316                         MonoBasicBlock *true_bb, *false_bb;
317                         gboolean simple, ret;
318                         int dreg, tmp_reg;
319                         CompType comp_type;
320
321                         branch = mono_bb_last_inst (bb, filter);
322
323                         if (!branch || branch->opcode == OP_BR_REG || branch->opcode == OP_BR)
324                                 continue;
325
326                         /* Find the compare instruction */
327                         compare = mono_inst_prev (branch, filter);
328                         if (!compare)
329                                 continue;
330
331                         if (!MONO_IS_COND_BRANCH_OP (branch))
332                                 /* This can happen if a cond branch is optimized away */
333                                 continue;
334
335                         true_bb = branch->inst_true_bb;
336                         false_bb = branch->inst_false_bb;
337
338                         /* 
339                          * Check that bb1 and bb2 are 'simple' and both assign to the same
340                          * variable.
341                          */
342                         /* FIXME: Get rid of the nops earlier */
343                         ins1 = mono_bb_first_inst (true_bb, filter);
344                         ins2 = mono_bb_first_inst (false_bb, filter);
345
346                         if (!(ins1 && ins2 && ins1->dreg == ins2->dreg && ins1->dreg != -1))
347                                 continue;
348
349                         simple = TRUE;
350                         for (tmp = ins1->next; tmp; tmp = tmp->next)
351                                 if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_IL_SEQ_POINT) || (tmp->opcode == OP_BR)))
352                                         simple = FALSE;
353                                         
354                         for (tmp = ins2->next; tmp; tmp = tmp->next)
355                                 if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_IL_SEQ_POINT) || (tmp->opcode == OP_BR)))
356                                         simple = FALSE;
357
358                         if (!simple)
359                                 continue;
360
361                         /* We move ins1/ins2 before the compare so they should have no side effect */
362                         if (!(MONO_INS_HAS_NO_SIDE_EFFECT (ins1) && MONO_INS_HAS_NO_SIDE_EFFECT (ins2)))
363                                 continue;
364
365                         /* Moving ins1/ins2 could change the comparison */
366                         /* FIXME: */
367                         if (!((compare->sreg1 != ins1->dreg) && (compare->sreg2 != ins1->dreg)))
368                                 continue;
369
370                         /* FIXME: */
371                         comp_type = mono_opcode_to_type (branch->opcode, compare->opcode);
372                         if (!((comp_type == CMP_TYPE_I) || (comp_type == CMP_TYPE_L)))
373                                 continue;
374
375                         /* FIXME: */
376                         /* ins->type might not be set */
377                         if (INS_INFO (ins1->opcode) [MONO_INST_DEST] != 'i')
378                                 continue;
379
380                         if (cfg->verbose_level > 2) {
381                                 printf ("\tBranch -> CMove optimization in BB%d on\n", bb->block_num);
382                                 printf ("\t\t"); mono_print_ins (compare);
383                                 printf ("\t\t"); mono_print_ins (mono_inst_next (compare, filter));
384                                 printf ("\t\t"); mono_print_ins (ins1);
385                                 printf ("\t\t"); mono_print_ins (ins2);
386                         }
387
388                         changed = TRUE;
389
390                         //printf ("HIT!\n");
391
392                         /* Assignments to the return register must remain at the end of bbs */
393                         if (cfg->ret)
394                                 ret = ins1->dreg == cfg->ret->dreg;
395                         else
396                                 ret = FALSE;
397
398                         tmp_reg = mono_alloc_dreg (cfg, STACK_I4);
399                         dreg = ins1->dreg;
400
401                         /* Rewrite ins1 to emit to tmp_reg */
402                         ins1->dreg = tmp_reg;
403
404                         if (ret) {
405                                 dreg = mono_alloc_dreg (cfg, STACK_I4);
406                                 ins2->dreg = dreg;
407                         }
408
409                         /* Remove ins1/ins2 from bb1/bb2 */
410                         MONO_REMOVE_INS (true_bb, ins1);
411                         MONO_REMOVE_INS (false_bb, ins2);
412
413                         /* Move ins1 and ins2 before the comparison */
414                         /* ins1 comes first to avoid ins1 overwriting an argument of ins2 */
415                         mono_bblock_insert_before_ins (bb, compare, ins2);
416                         mono_bblock_insert_before_ins (bb, ins2, ins1);
417
418                         /* Add cmov instruction */
419                         MONO_INST_NEW (cfg, cmov, OP_NOP);
420                         cmov->dreg = dreg;
421                         cmov->sreg1 = dreg;
422                         cmov->sreg2 = tmp_reg;
423                         switch (mono_opcode_to_type (branch->opcode, compare->opcode)) {
424                         case CMP_TYPE_I:
425                                 cmov->opcode = int_cmov_opcodes [mono_opcode_to_cond (branch->opcode)];
426                                 break;
427                         case CMP_TYPE_L:
428                                 cmov->opcode = long_cmov_opcodes [mono_opcode_to_cond (branch->opcode)];
429                                 break;
430                         default:
431                                 g_assert_not_reached ();
432                         }
433                         mono_bblock_insert_after_ins (bb, compare, cmov);
434
435                         if (ret) {
436                                 /* Add an extra move */
437                                 MONO_INST_NEW (cfg, move, OP_MOVE);
438                                 move->dreg = cfg->ret->dreg;
439                                 move->sreg1 = dreg;
440                                 mono_bblock_insert_after_ins (bb, cmov, move);
441                         }
442
443                         /* Rewrite the branch */
444                         branch->opcode = OP_BR;
445                         branch->inst_target_bb = true_bb->out_bb [0];
446                         mono_link_bblock (cfg, bb, branch->inst_target_bb);
447
448                         /* Reorder bblocks */
449                         mono_unlink_bblock (cfg, bb, true_bb);
450                         mono_unlink_bblock (cfg, bb, false_bb);
451                         mono_unlink_bblock (cfg, true_bb, true_bb->out_bb [0]);
452                         mono_unlink_bblock (cfg, false_bb, false_bb->out_bb [0]);
453                         mono_remove_bblock (cfg, true_bb);
454                         mono_remove_bblock (cfg, false_bb);
455
456                         /* Merge bb and its successor if possible */
457                         if ((bb->out_bb [0]->in_count == 1) && (bb->out_bb [0] != cfg->bb_exit) &&
458                                 (bb->region == bb->out_bb [0]->region)) {
459                                 mono_merge_basic_blocks (cfg, bb, bb->out_bb [0]);
460                                 goto restart;
461                         }
462                 }
463
464                 /* Look for the IR code generated from if (cond) <var> <- <a>
465                  * which is:
466                  * BB:
467                  * b<cond> [BB1BB2]
468                  * BB1:
469                  * <var> <- <a>
470                  * br BB2
471                  */
472
473                 if ((bb2->in_count == 1 && bb2->out_count == 1 && bb2->out_bb [0] == bb1) ||
474                         (bb1->in_count == 1 && bb1->out_count == 1 && bb1->out_bb [0] == bb2)) {
475                         MonoInst *compare, *branch, *ins1, *cmov, *tmp;
476                         gboolean simple;
477                         int dreg, tmp_reg;
478                         CompType comp_type;
479                         CompRelation cond;
480                         MonoBasicBlock *next_bb, *code_bb;
481
482                         /* code_bb is the bblock containing code, next_bb is the successor bblock */
483                         if (bb2->in_count == 1 && bb2->out_count == 1 && bb2->out_bb [0] == bb1) {
484                                 code_bb = bb2;
485                                 next_bb = bb1;
486                         } else {
487                                 code_bb = bb1;
488                                 next_bb = bb2;
489                         }
490
491                         ins1 = mono_bb_first_inst (code_bb, filter);
492
493                         if (!ins1)
494                                 continue;
495
496                         /* Check that code_bb is simple */
497                         simple = TRUE;
498                         for (tmp = ins1; tmp; tmp = tmp->next)
499                                 if (!((tmp->opcode == OP_NOP) || (tmp->opcode == OP_IL_SEQ_POINT) || (tmp->opcode == OP_BR)))
500                                         simple = FALSE;
501
502                         if (!simple)
503                                 continue;
504
505                         /* We move ins1 before the compare so it should have no side effect */
506                         if (!MONO_INS_HAS_NO_SIDE_EFFECT (ins1))
507                                 continue;
508
509                         branch = mono_bb_last_inst (bb, filter);
510
511                         if (!branch || branch->opcode == OP_BR_REG)
512                                 continue;
513
514                         /* Find the compare instruction */
515                         compare = mono_inst_prev (branch, filter);
516                         if (!compare)
517                                 continue;
518
519                         if (!MONO_IS_COND_BRANCH_OP (branch))
520                                 /* This can happen if a cond branch is optimized away */
521                                 continue;
522
523                         /* FIXME: */
524                         comp_type = mono_opcode_to_type (branch->opcode, compare->opcode);
525                         if (!((comp_type == CMP_TYPE_I) || (comp_type == CMP_TYPE_L)))
526                                 continue;
527
528                         /* FIXME: */
529                         /* ins->type might not be set */
530                         if (INS_INFO (ins1->opcode) [MONO_INST_DEST] != 'i')
531                                 continue;
532
533                         /* FIXME: */
534                         if (cfg->ret && ins1->dreg == cfg->ret->dreg)
535                                 continue;
536
537                         if (!(cfg->opt & MONO_OPT_DEADCE))
538                                 /* 
539                                  * It is possible that dreg is never set before, so we can't use
540                                  * it as an sreg of the cmov instruction (#582322).
541                                  */
542                                 continue;
543
544                         if (cfg->verbose_level > 2) {
545                                 printf ("\tBranch -> CMove optimization (2) in BB%d on\n", bb->block_num);
546                                 printf ("\t\t"); mono_print_ins (compare);
547                                 printf ("\t\t"); mono_print_ins (mono_inst_next (compare, filter));
548                                 printf ("\t\t"); mono_print_ins (ins1);
549                         }
550
551                         changed = TRUE;
552
553                         //printf ("HIT!\n");
554
555                         tmp_reg = mono_alloc_dreg (cfg, STACK_I4);
556                         dreg = ins1->dreg;
557
558                         /* Rewrite ins1 to emit to tmp_reg */
559                         ins1->dreg = tmp_reg;
560
561                         /* Remove ins1 from code_bb */
562                         MONO_REMOVE_INS (code_bb, ins1);
563
564                         /* Move ins1 before the comparison */
565                         mono_bblock_insert_before_ins (bb, compare, ins1);
566
567                         /* Add cmov instruction */
568                         MONO_INST_NEW (cfg, cmov, OP_NOP);
569                         cmov->dreg = dreg;
570                         cmov->sreg1 = dreg;
571                         cmov->sreg2 = tmp_reg;
572                         cond = mono_opcode_to_cond (branch->opcode);
573                         if (branch->inst_false_bb == code_bb)
574                                 cond = mono_negate_cond (cond);
575                         switch (mono_opcode_to_type (branch->opcode, compare->opcode)) {
576                         case CMP_TYPE_I:
577                                 cmov->opcode = int_cmov_opcodes [cond];
578                                 break;
579                         case CMP_TYPE_L:
580                                 cmov->opcode = long_cmov_opcodes [cond];
581                                 break;
582                         default:
583                                 g_assert_not_reached ();
584                         }
585                         mono_bblock_insert_after_ins (bb, compare, cmov);
586
587                         /* Rewrite the branch */
588                         branch->opcode = OP_BR;
589                         branch->inst_target_bb = next_bb;
590                         mono_link_bblock (cfg, bb, branch->inst_target_bb);
591
592                         /* Nullify the branch at the end of code_bb */
593                         if (code_bb->code) {
594                                 branch = code_bb->code;
595                                 MONO_DELETE_INS (code_bb, branch);
596                         }
597
598                         /* Reorder bblocks */
599                         mono_unlink_bblock (cfg, bb, code_bb);
600                         mono_unlink_bblock (cfg, code_bb, next_bb);
601
602                         /* Merge bb and its successor if possible */
603                         if ((bb->out_bb [0]->in_count == 1) && (bb->out_bb [0] != cfg->bb_exit) &&
604                                 (bb->region == bb->out_bb [0]->region)) {
605                                 mono_merge_basic_blocks (cfg, bb, bb->out_bb [0]);
606
607                                 /* 
608                                  * bbn might have fallen through to the next bb without a branch, 
609                                  * have to add one now (#474718).
610                                  * FIXME: Maybe need to do this more generally in 
611                                  * merge_basic_blocks () ?
612                                  */
613                                 if (!(bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) && bb->out_count) {
614                                         MONO_INST_NEW (cfg, ins1, OP_BR);
615                                         ins1->inst_target_bb = bb->out_bb [0];
616                                         MONO_ADD_INS (bb, ins1);
617                                 }
618                                 goto restart;
619                         }
620                 }
621         }
622
623         /*
624          * Optimize checks like: if (v < 0 || v > limit) by changing then to unsigned
625          * compares. This isn't really if conversion, but it easier to do here than in
626          * optimize_branches () since the IR is already optimized.
627          */
628         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
629                 MonoBasicBlock *bb1, *bb2, *next_bb;
630                 MonoInst *branch1, *branch2, *compare1, *ins, *next;
631
632                 /* Look for the IR code generated from if (<var> < 0 || v > <limit>)
633                  * after branch opts which is:
634                  * BB:
635                  * icompare_imm R [0]
636                  * int_blt [BB1BB2]
637                  * BB2:
638                  * icompare_imm R [<limit>]
639                  * int_ble [BB3BB1]
640                  */
641                 if (!(bb->out_count == 2 && !bb->extended))
642                         continue;
643
644                 bb1 = bb->out_bb [0];
645                 bb2 = bb->out_bb [1];
646
647                 // FIXME: Add more cases
648
649                 /* Check structure */
650                 if (!(bb1->in_count == 2 && bb1->in_bb [0] == bb && bb1->in_bb [1] == bb2 && bb2->in_count == 1 && bb2->out_count == 2))
651                         continue;
652
653                 next_bb = bb2;
654
655                 /* Check first branch */
656                 branch1 = mono_bb_last_inst (bb, filter);
657                 if (!(branch1 && ((branch1->opcode == OP_IBLT) || (branch1->opcode == OP_LBLT)) && (branch1->inst_false_bb == next_bb)))
658                         continue;
659
660                 /* Check second branch */
661                 branch2 = mono_bb_last_inst (next_bb, filter);
662                 if (!branch2)
663                         continue;
664
665                 /* mcs sometimes generates inverted branches */
666                 if (((branch2->opcode == OP_IBGT) || (branch2->opcode == OP_LBGT)) && branch2->inst_true_bb == branch1->inst_true_bb)
667                         ;
668                 else if (((branch2->opcode == OP_IBLE) || (branch2->opcode == OP_LBLE)) && branch2->inst_false_bb == branch1->inst_true_bb)
669                         ;
670                 else
671                         continue;
672
673                 /* Check first compare */
674                 compare1 = mono_inst_prev (mono_bb_last_inst (bb, filter), filter);
675                 if (!(compare1 && ((compare1->opcode == OP_ICOMPARE_IMM) || (compare1->opcode == OP_LCOMPARE_IMM)) && compare1->inst_imm == 0))
676                         continue;
677
678                 /* Check second bblock */
679                 ins = mono_bb_first_inst (next_bb, filter);
680                 if (!ins)
681                         continue;
682                 next = mono_inst_next (ins, filter);
683                 if (((ins->opcode == OP_ICOMPARE_IMM) || (ins->opcode == OP_LCOMPARE_IMM)) && ins->sreg1 == compare1->sreg1 && next == branch2) {
684                         /* The second arg must be positive */
685                         if (ins->inst_imm < 0)
686                                 continue;
687                 } else if (((ins->opcode == OP_LDLEN) || (ins->opcode == OP_STRLEN)) && ins->dreg != compare1->sreg1 && next && next->opcode == OP_ICOMPARE && next->sreg1 == compare1->sreg1 && next->sreg2 == ins->dreg && mono_inst_next (next, filter) == branch2) {
688                         /* Another common case: if (index < 0 || index > arr.Length) */
689                 } else {
690                         continue;
691                 }
692
693                 if (cfg->verbose_level > 2) {
694                         printf ("\tSigned->unsigned compare optimization in BB%d on\n", bb->block_num);
695                         printf ("\t\t"); mono_print_ins (compare1);
696                         printf ("\t\t"); mono_print_ins (mono_inst_next (compare1, filter));
697                         printf ("\t\t"); mono_print_ins (ins);
698                 }
699
700                 /* Rewrite the first compare+branch */
701                 MONO_DELETE_INS (bb, compare1);
702                 branch1->opcode = OP_BR;
703                 mono_unlink_bblock (cfg, bb, branch1->inst_true_bb);
704                 mono_unlink_bblock (cfg, bb, branch1->inst_false_bb);
705                 branch1->inst_target_bb = next_bb;
706                 mono_link_bblock (cfg, bb, next_bb);            
707
708                 /* Rewrite the second branch */
709                 branch2->opcode = br_to_br_un (branch2->opcode);
710
711                 mono_merge_basic_blocks (cfg, bb, next_bb);
712         }
713
714 #if 0
715         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
716                 MonoBasicBlock *bb1, *bb2;
717                 MonoInst *prev, *compare, *branch, *ins1, *ins2, *cmov, *move, *tmp;
718                 gboolean simple, ret;
719                 int dreg, tmp_reg;
720                 CompType comp_type;
721
722                 /* Look for the IR code generated from if (cond) <var> <- <a>
723                  * after branch opts which is:
724                  * BB:
725                  * compare
726                  * b<cond> [BB1]
727                  * <var> <- <a>
728                  * BB1:
729                  */
730                 if (!(bb->out_count == 1 && bb->extended && bb->code && bb->code->next && bb->code->next->next))
731                         continue;
732
733                 mono_print_bb (bb, "");
734
735                 /* Find the compare instruction */
736                 prev = NULL;
737                 compare = bb->code;
738                 g_assert (compare);
739                 while (compare->next->next && compare->next->next != bb->last_ins) {
740                         prev = compare;
741                         compare = compare->next;
742                 }
743                 branch = compare->next;
744                 if (!MONO_IS_COND_BRANCH_OP (branch))
745                         continue;
746         }
747 #endif
748
749         if (changed) {
750                 if (cfg->opt & MONO_OPT_BRANCH)
751                         mono_optimize_branches (cfg);
752                 /* Merging bblocks could make some variables local */
753                 mono_handle_global_vregs (cfg);
754                 if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
755                         mono_local_cprop (cfg);
756                 if (cfg->opt & MONO_OPT_DEADCE)
757                         mono_local_deadce (cfg);
758         }
759 #endif
760 }
761
762 void
763 mono_nullify_basic_block (MonoBasicBlock *bb) 
764 {
765         bb->in_count = 0;
766         bb->out_count = 0;
767         bb->in_bb = NULL;
768         bb->out_bb = NULL;
769         bb->next_bb = NULL;
770         bb->code = bb->last_ins = NULL;
771         bb->cil_code = NULL;
772 }
773
774 static void 
775 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
776 {
777         int i;
778
779         for (i = 0; i < bb->out_count; i++) {
780                 MonoBasicBlock *ob = bb->out_bb [i];
781                 if (ob == orig) {
782                         if (!repl) {
783                                 if (bb->out_count > 1) {
784                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
785                                 }
786                                 bb->out_count--;
787                         } else {
788                                 bb->out_bb [i] = repl;
789                         }
790                 }
791         }
792 }
793
794 static void 
795 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
796 {
797         int i;
798
799         for (i = 0; i < bb->in_count; i++) {
800                 MonoBasicBlock *ib = bb->in_bb [i];
801                 if (ib == orig) {
802                         if (!repl) {
803                                 if (bb->in_count > 1) {
804                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
805                                 }
806                                 bb->in_count--;
807                         } else {
808                                 bb->in_bb [i] = repl;
809                         }
810                 }
811         }
812 }
813
814 static void
815 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
816         MonoInst *ins;
817
818 #if defined(__native_client_codegen__)
819         /* Need to maintain this flag for the new block because */
820         /* we can't jump indirectly to a non-aligned block.     */
821         if (orig->flags & BB_INDIRECT_JUMP_TARGET)
822         {
823                 repl->flags |= BB_INDIRECT_JUMP_TARGET;
824         }
825 #endif
826         
827         for (ins = bb->code; ins != NULL; ins = ins->next) {
828                 switch (ins->opcode) {
829                 case OP_BR:
830                         if (ins->inst_target_bb == orig)
831                                 ins->inst_target_bb = repl;
832                         break;
833                 case OP_CALL_HANDLER:
834                         if (ins->inst_target_bb == orig)
835                                 ins->inst_target_bb = repl;
836                         break;
837                 case OP_SWITCH: {
838                         int i;
839                         int n = GPOINTER_TO_INT (ins->klass);
840                         for (i = 0; i < n; i++ ) {
841                                 if (ins->inst_many_bb [i] == orig)
842                                         ins->inst_many_bb [i] = repl;
843                         }
844                         break;
845                 }
846                 default:
847                         if (MONO_IS_COND_BRANCH_OP (ins)) {
848                                 if (ins->inst_true_bb == orig)
849                                         ins->inst_true_bb = repl;
850                                 if (ins->inst_false_bb == orig)
851                                         ins->inst_false_bb = repl;
852                         } else if (MONO_IS_JUMP_TABLE (ins)) {
853                                 int i;
854                                 MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)MONO_JUMP_TABLE_FROM_INS (ins);
855                                 for (i = 0; i < table->table_size; i++ ) {
856                                         if (table->table [i] == orig)
857                                                 table->table [i] = repl;
858                                 }
859                         }
860
861                         break;
862                 }
863         }
864 }
865
866 /**
867   * Check if a bb is useless (is just made of NOPs and ends with an
868   * unconditional branch, or nothing).
869   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
870   * Otherwise, return FALSE;
871   */
872 static gboolean
873 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
874         MonoBasicBlock *target_bb = NULL;
875         MonoInst *inst;
876
877         /* Do not touch handlers */
878         if (bb->region != -1) {
879                 bb->not_useless = TRUE;
880                 return FALSE;
881         }
882         
883         MONO_BB_FOR_EACH_INS (bb, inst) {
884                 switch (inst->opcode) {
885                 case OP_NOP:
886                 case OP_IL_SEQ_POINT:
887                         break;
888                 case OP_BR:
889                         target_bb = inst->inst_target_bb;
890                         break;
891                 default:
892                         bb->not_useless = TRUE;
893                         return FALSE;
894                 }
895         }
896         
897         if (target_bb == NULL) {
898                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
899                         target_bb = bb->next_bb;
900                 } else {
901                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
902                         return FALSE;
903                 }
904         }
905         
906         /* Do not touch BBs following a switch (they are the "default" branch) */
907         if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == OP_SWITCH)) {
908                 return FALSE;
909         }
910         
911         /* Do not touch BBs following the entry BB and jumping to something that is not */
912         /* thiry "next" bb (the entry BB cannot contain the branch) */
913         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
914                 return FALSE;
915         }
916
917         /* 
918          * Do not touch BBs following a try block as the code in 
919          * mini_method_compile needs them to compute the length of the try block.
920          */
921         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
922                 return FALSE;
923         
924         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
925         if ((target_bb != NULL) && (target_bb != bb)) {
926                 int i;
927
928                 if (cfg->verbose_level > 1) {
929                         printf ("remove_block_if_useless, removed BB%d\n", bb->block_num);
930                 }
931                 
932                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
933                 while (bb->in_count) {
934                         MonoBasicBlock *in_bb = bb->in_bb [0];
935                         mono_unlink_bblock (cfg, in_bb, bb);
936                         mono_link_bblock (cfg, in_bb, target_bb);
937                         replace_out_block_in_code (in_bb, bb, target_bb);
938                 }
939                 
940                 mono_unlink_bblock (cfg, bb, target_bb);
941                 if (previous_bb != cfg->bb_entry && mono_bb_is_fall_through (cfg, previous_bb)) {
942                         for (i = 0; i < previous_bb->out_count; i++) {
943                                 if (previous_bb->out_bb [i] == target_bb) {
944                                         MonoInst *jump;
945                                         MONO_INST_NEW (cfg, jump, OP_BR);
946                                         MONO_ADD_INS (previous_bb, jump);
947                                         jump->cil_code = previous_bb->cil_code;
948                                         jump->inst_target_bb = target_bb;
949                                         break;
950                                 }
951                         }
952                 }
953                 
954                 previous_bb->next_bb = bb->next_bb;
955                 mono_nullify_basic_block (bb);
956                 
957                 return TRUE;
958         } else {
959                 return FALSE;
960         }
961 }
962
963 void
964 mono_merge_basic_blocks (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *bbn) 
965 {
966         MonoInst *inst;
967         MonoBasicBlock *prev_bb;
968         int i;
969
970         bb->has_array_access |= bbn->has_array_access;
971         bb->extended |= bbn->extended;
972
973         /* Compute prev_bb if possible to avoid the linear search below */
974         prev_bb = NULL;
975         for (i = 0; i < bbn->in_count; ++i)
976                 if (bbn->in_bb [0]->next_bb == bbn)
977                         prev_bb = bbn->in_bb [0];
978
979         mono_unlink_bblock (cfg, bb, bbn);
980         for (i = 0; i < bbn->out_count; ++i)
981                 mono_link_bblock (cfg, bb, bbn->out_bb [i]);
982         while (bbn->out_count)
983                 mono_unlink_bblock (cfg, bbn, bbn->out_bb [0]);
984
985         /* Handle the branch at the end of the bb */
986         if (bb->has_call_handler) {
987                 for (inst = bb->code; inst != NULL; inst = inst->next) {
988                         if (inst->opcode == OP_CALL_HANDLER) {
989                                 g_assert (inst->inst_target_bb == bbn);
990                                 NULLIFY_INS (inst);
991                         }
992                 }
993         }
994         if (bb->has_jump_table) {
995                 for (inst = bb->code; inst != NULL; inst = inst->next) {
996                         if (MONO_IS_JUMP_TABLE (inst)) {
997                                 int i;
998                                 MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)MONO_JUMP_TABLE_FROM_INS (inst);
999                                 for (i = 0; i < table->table_size; i++ ) {
1000                                         /* Might be already NULL from a previous merge */
1001                                         if (table->table [i])
1002                                                 g_assert (table->table [i] == bbn);
1003                                         table->table [i] = NULL;
1004                                 }
1005                                 /* Can't nullify this as later instructions depend on it */
1006                         }
1007                 }
1008         }
1009         if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
1010                 g_assert (bb->last_ins->inst_false_bb == bbn);
1011                 bb->last_ins->inst_false_bb = NULL;
1012                 bb->extended = TRUE;
1013         } else if (bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) {
1014                 NULLIFY_INS (bb->last_ins);
1015         }
1016
1017         bb->has_call_handler |= bbn->has_call_handler;
1018         bb->has_jump_table |= bbn->has_jump_table;
1019
1020         if (bb->last_ins) {
1021                 if (bbn->code) {
1022                         bb->last_ins->next = bbn->code;
1023                         bbn->code->prev = bb->last_ins;
1024                         bb->last_ins = bbn->last_ins;
1025                 }
1026         } else {
1027                 bb->code = bbn->code;
1028                 bb->last_ins = bbn->last_ins;
1029         }
1030
1031         if (!prev_bb) {
1032                 for (prev_bb = cfg->bb_entry; prev_bb && prev_bb->next_bb != bbn; prev_bb = prev_bb->next_bb)
1033                         ;
1034         }
1035         if (prev_bb) {
1036                 prev_bb->next_bb = bbn->next_bb;
1037         } else {
1038                 /* bbn might not be in the bb list yet */
1039                 if (bb->next_bb == bbn)
1040                         bb->next_bb = bbn->next_bb;
1041         }
1042         mono_nullify_basic_block (bbn);
1043
1044         /* 
1045          * If bbn fell through to its next bblock, have to add a branch, since bb
1046          * will not fall though to the same bblock (#513931).
1047          */
1048         if (bb->last_ins && bb->out_count == 1 && bb->out_bb [0] != bb->next_bb && !MONO_IS_BRANCH_OP (bb->last_ins)) {
1049                 MONO_INST_NEW (cfg, inst, OP_BR);
1050                 inst->inst_target_bb = bb->out_bb [0];
1051                 MONO_ADD_INS (bb, inst);
1052         }
1053 }
1054
1055 static void
1056 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
1057 {
1058         MonoBasicBlock *bbn, *next;
1059
1060         next = bb->next_bb;
1061
1062         /* Find the previous */
1063         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
1064                 ;
1065         if (bbn->next_bb) {
1066                 bbn->next_bb = bb->next_bb;
1067         }
1068
1069         /* Find the last */
1070         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
1071                 ;
1072         bbn->next_bb = bb;
1073         bb->next_bb = NULL;
1074
1075         /* Add a branch */
1076         if (next && (!bb->last_ins || ((bb->last_ins->opcode != OP_NOT_REACHED) && (bb->last_ins->opcode != OP_BR) && (bb->last_ins->opcode != OP_BR_REG) && (!MONO_IS_COND_BRANCH_OP (bb->last_ins))))) {
1077                 MonoInst *ins;
1078
1079                 MONO_INST_NEW (cfg, ins, OP_BR);
1080                 MONO_ADD_INS (bb, ins);
1081                 mono_link_bblock (cfg, bb, next);
1082                 ins->inst_target_bb = next;
1083         }               
1084 }
1085
1086 /*
1087  * mono_remove_block:
1088  *
1089  *   Remove BB from the control flow graph
1090  */
1091 void
1092 mono_remove_bblock (MonoCompile *cfg, MonoBasicBlock *bb) 
1093 {
1094         MonoBasicBlock *tmp_bb;
1095
1096         for (tmp_bb = cfg->bb_entry; tmp_bb && tmp_bb->next_bb != bb; tmp_bb = tmp_bb->next_bb)
1097                 ;
1098
1099         g_assert (tmp_bb);
1100         tmp_bb->next_bb = bb->next_bb;
1101 }
1102
1103 void
1104 mono_remove_critical_edges (MonoCompile *cfg)
1105 {
1106         MonoBasicBlock *bb;
1107         MonoBasicBlock *previous_bb;
1108         
1109         if (cfg->verbose_level > 3) {
1110                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1111                         int i;
1112                         printf ("remove_critical_edges, BEFORE BB%d (in:", bb->block_num);
1113                         for (i = 0; i < bb->in_count; i++) {
1114                                 printf (" %d", bb->in_bb [i]->block_num);
1115                         }
1116                         printf (") (out:");
1117                         for (i = 0; i < bb->out_count; i++) {
1118                                 printf (" %d", bb->out_bb [i]->block_num);
1119                         }
1120                         printf (")");
1121                         if (bb->last_ins != NULL) {
1122                                 printf (" ");
1123                                 mono_print_ins (bb->last_ins);
1124                         }
1125                         printf ("\n");
1126                 }
1127         }
1128         
1129         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
1130                 if (bb->in_count > 1) {
1131                         int in_bb_index;
1132                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
1133                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
1134                                 /* 
1135                                  * Have to remove non-critical edges whose source ends with a BR_REG
1136                                  * ins too, since inserting a computation before the BR_REG could 
1137                                  * overwrite the sreg1 of the ins.
1138                                  */
1139                                 if ((in_bb->out_count > 1) || (in_bb->out_count == 1 && in_bb->last_ins && in_bb->last_ins->opcode == OP_BR_REG)) {
1140                                         MonoBasicBlock *new_bb = (MonoBasicBlock *)mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
1141                                         new_bb->block_num = cfg->num_bblocks++;
1142 //                                      new_bb->real_offset = bb->real_offset;
1143                                         new_bb->region = bb->region;
1144                                         
1145                                         /* Do not alter the CFG while altering the BB list */
1146                                         if (mono_bb_is_fall_through (cfg, previous_bb)) {
1147                                                 if (previous_bb != cfg->bb_entry) {
1148                                                         int i;
1149                                                         /* Make sure previous_bb really falls through bb */
1150                                                         for (i = 0; i < previous_bb->out_count; i++) {
1151                                                                 if (previous_bb->out_bb [i] == bb) {
1152                                                                         MonoInst *jump;
1153                                                                         MONO_INST_NEW (cfg, jump, OP_BR);
1154                                                                         MONO_ADD_INS (previous_bb, jump);
1155                                                                         jump->cil_code = previous_bb->cil_code;
1156                                                                         jump->inst_target_bb = bb;
1157                                                                         break;
1158                                                                 }
1159                                                         }
1160                                                 } else {
1161                                                         /* We cannot add any inst to the entry BB, so we must */
1162                                                         /* put a new BB in the middle to hold the OP_BR */
1163                                                         MonoInst *jump;
1164                                                         MonoBasicBlock *new_bb_after_entry = (MonoBasicBlock *)mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
1165                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
1166 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
1167                                                         new_bb_after_entry->region = bb->region;
1168                                                         
1169                                                         MONO_INST_NEW (cfg, jump, OP_BR);
1170                                                         MONO_ADD_INS (new_bb_after_entry, jump);
1171                                                         jump->cil_code = bb->cil_code;
1172                                                         jump->inst_target_bb = bb;
1173
1174                                                         mono_unlink_bblock (cfg, previous_bb, bb);
1175                                                         mono_link_bblock (cfg, new_bb_after_entry, bb);
1176                                                         mono_link_bblock (cfg, previous_bb, new_bb_after_entry);
1177                                                         
1178                                                         previous_bb->next_bb = new_bb_after_entry;
1179                                                         previous_bb = new_bb_after_entry;
1180
1181                                                         if (cfg->verbose_level > 2) {
1182                                                                 printf ("remove_critical_edges, added helper BB%d jumping to BB%d\n", new_bb_after_entry->block_num, bb->block_num);
1183                                                         }
1184                                                 }
1185                                         }
1186                                         
1187                                         /* Insert new_bb in the BB list */
1188                                         previous_bb->next_bb = new_bb;
1189                                         new_bb->next_bb = bb;
1190                                         previous_bb = new_bb;
1191                                         
1192                                         /* Setup in_bb and out_bb */
1193                                         new_bb->in_bb = (MonoBasicBlock **)mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
1194                                         new_bb->in_bb [0] = in_bb;
1195                                         new_bb->in_count = 1;
1196                                         new_bb->out_bb = (MonoBasicBlock **)mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
1197                                         new_bb->out_bb [0] = bb;
1198                                         new_bb->out_count = 1;
1199                                         
1200                                         /* Relink in_bb and bb to (from) new_bb */
1201                                         replace_out_block (in_bb, bb, new_bb);
1202                                         replace_out_block_in_code (in_bb, bb, new_bb);
1203                                         replace_in_block (bb, in_bb, new_bb);
1204                                         
1205                                         if (cfg->verbose_level > 2) {
1206                                                 printf ("remove_critical_edges, removed critical edge from BB%d to BB%d (added BB%d)\n", in_bb->block_num, bb->block_num, new_bb->block_num);
1207                                         }
1208                                 }
1209                         }
1210                 }
1211         }
1212         
1213         if (cfg->verbose_level > 3) {
1214                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1215                         int i;
1216                         printf ("remove_critical_edges, AFTER BB%d (in:", bb->block_num);
1217                         for (i = 0; i < bb->in_count; i++) {
1218                                 printf (" %d", bb->in_bb [i]->block_num);
1219                         }
1220                         printf (") (out:");
1221                         for (i = 0; i < bb->out_count; i++) {
1222                                 printf (" %d", bb->out_bb [i]->block_num);
1223                         }
1224                         printf (")");
1225                         if (bb->last_ins != NULL) {
1226                                 printf (" ");
1227                                 mono_print_ins (bb->last_ins);
1228                         }
1229                         printf ("\n");
1230                 }
1231         }
1232 }
1233
1234 /*
1235  * Optimizes the branches on the Control Flow Graph
1236  *
1237  */
1238 void
1239 mono_optimize_branches (MonoCompile *cfg)
1240 {
1241         int i, count = 0, changed = FALSE;
1242         MonoBasicBlock *bb, *bbn;
1243         guint32 niterations;
1244         MonoInst *bbn_first_inst;
1245         int filter = FILTER_IL_SEQ_POINT;
1246
1247         /*
1248          * Some crazy loops could cause the code below to go into an infinite
1249          * loop, see bug #53003 for an example. To prevent this, we put an upper
1250          * bound on the number of iterations.
1251          */
1252         if (cfg->num_bblocks > 1000)
1253                 niterations = cfg->num_bblocks * 2;
1254         else
1255                 niterations = 1000;
1256         
1257         do {
1258                 MonoBasicBlock *previous_bb;
1259                 changed = FALSE;
1260                 niterations --;
1261
1262                 /* we skip the entry block (exit is handled specially instead ) */
1263                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
1264                         count ++;
1265                         if (count == 1000) {
1266                                 mono_threads_safepoint ();
1267                                 count = 0;
1268                         }
1269                         /* dont touch code inside exception clauses */
1270                         if (bb->region != -1)
1271                                 continue;
1272
1273                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
1274                                 changed = TRUE;
1275                                 continue;
1276                         }
1277
1278                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bbn != cfg->bb_exit && bb->region == bbn->region) {
1279                                 if (cfg->verbose_level > 2)
1280                                         g_print ("nullify block triggered %d\n", bbn->block_num);
1281
1282                                 bb->next_bb = bbn->next_bb;
1283
1284                                 for (i = 0; i < bbn->out_count; i++)
1285                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
1286
1287                                 mono_nullify_basic_block (bbn);                 
1288                                 changed = TRUE;
1289                         }
1290
1291                         if (bb->out_count == 1) {
1292                                 bbn = bb->out_bb [0];
1293
1294                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
1295                                 if (bb->last_ins && (bb->last_ins->opcode != OP_BR) && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
1296                                         bb->last_ins->opcode = OP_BR;
1297                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
1298                                         changed = TRUE;
1299                                         if (cfg->verbose_level > 2)
1300                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
1301                                 }
1302
1303                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
1304                                         /* the block are in sequence anyway ... */
1305
1306                                         /* branches to the following block can be removed */
1307                                         if (bb->last_ins && bb->last_ins->opcode == OP_BR && !bbn->out_of_line) {
1308                                                 NULLIFY_INS (bb->last_ins);
1309                                                 changed = TRUE;
1310                                                 if (cfg->verbose_level > 2)
1311                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
1312                                         }
1313
1314                                         if (bbn->in_count == 1 && !bb->extended) {
1315                                                 if (bbn != cfg->bb_exit) {
1316                                                         if (cfg->verbose_level > 2)
1317                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
1318                                                         mono_merge_basic_blocks (cfg, bb, bbn);
1319                                                         changed = TRUE;
1320                                                         continue;
1321                                                 }
1322
1323                                                 //mono_print_bb_code (bb);
1324                                         }
1325                                 }
1326                         }
1327
1328                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bbn != cfg->bb_exit && bb->region == bbn->region) {
1329                                 if (cfg->verbose_level > 2) {
1330                                         g_print ("nullify block triggered %d\n", bbn->block_num);
1331                                 }
1332                                 bb->next_bb = bbn->next_bb;
1333
1334                                 for (i = 0; i < bbn->out_count; i++)
1335                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
1336
1337                                 mono_nullify_basic_block (bbn);                 
1338                                 changed = TRUE;
1339                                 continue;
1340                         }
1341
1342                         if (bb->out_count == 1) {
1343                                 bbn = bb->out_bb [0];
1344
1345                                 if (bb->last_ins && bb->last_ins->opcode == OP_BR) {
1346                                         bbn = bb->last_ins->inst_target_bb;
1347                                         bbn_first_inst = mono_bb_first_inst (bbn, filter);
1348                                         if (bb->region == bbn->region && bbn_first_inst && bbn_first_inst->opcode == OP_BR &&
1349                                                 bbn_first_inst->inst_target_bb != bbn &&
1350                                                 bbn_first_inst->inst_target_bb->region == bb->region) {
1351                                                 
1352                                                 if (cfg->verbose_level > 2)
1353                                                         g_print ("branch to branch triggered %d -> %d -> %d\n", bb->block_num, bbn->block_num, bbn_first_inst->inst_target_bb->block_num);
1354
1355                                                 replace_in_block (bbn, bb, NULL);
1356                                                 replace_out_block (bb, bbn, bbn_first_inst->inst_target_bb);
1357                                                 mono_link_bblock (cfg, bb, bbn_first_inst->inst_target_bb);
1358                                                 bb->last_ins->inst_target_bb = bbn_first_inst->inst_target_bb;
1359                                                 changed = TRUE;
1360                                                 continue;
1361                                         }
1362                                 }
1363                         } else if (bb->out_count == 2) {
1364                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
1365                                         int branch_result;
1366                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
1367
1368                                         if (bb->last_ins->flags & MONO_INST_CFOLD_TAKEN)
1369                                                 branch_result = BRANCH_TAKEN;
1370                                         else if (bb->last_ins->flags & MONO_INST_CFOLD_NOT_TAKEN)
1371                                                 branch_result = BRANCH_NOT_TAKEN;
1372                                         else
1373                                                 branch_result = BRANCH_UNDEF;
1374
1375                                         if (branch_result == BRANCH_TAKEN) {
1376                                                 taken_branch_target = bb->last_ins->inst_true_bb;
1377                                                 untaken_branch_target = bb->last_ins->inst_false_bb;
1378                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
1379                                                 taken_branch_target = bb->last_ins->inst_false_bb;
1380                                                 untaken_branch_target = bb->last_ins->inst_true_bb;
1381                                         }
1382                                         if (taken_branch_target) {
1383                                                 /* if mono_eval_cond_branch () is ever taken to handle 
1384                                                  * non-constant values to compare, issue a pop here.
1385                                                  */
1386                                                 bb->last_ins->opcode = OP_BR;
1387                                                 bb->last_ins->inst_target_bb = taken_branch_target;
1388                                                 if (!bb->extended)
1389                                                         mono_unlink_bblock (cfg, bb, untaken_branch_target);
1390                                                 changed = TRUE;
1391                                                 continue;
1392                                         }
1393                                         bbn = bb->last_ins->inst_true_bb;
1394                                         bbn_first_inst = mono_bb_first_inst (bbn, filter);
1395                                         if (bb->region == bbn->region && bbn_first_inst && bbn_first_inst->opcode == OP_BR &&
1396                                             bbn_first_inst->inst_target_bb->region == bb->region) {
1397                                                 if (cfg->verbose_level > 2)             
1398                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
1399                                                                  bb->block_num, bbn->block_num, bbn_first_inst->inst_target_bb->block_num, 
1400                                                                  bbn_first_inst->opcode);
1401
1402                                                 /* 
1403                                                  * Unlink, then relink bblocks to avoid various
1404                                                  * tricky situations when the two targets of the branch
1405                                                  * are equal, or will become equal after the change.
1406                                                  */
1407                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1408                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1409
1410                                                 bb->last_ins->inst_true_bb = bbn_first_inst->inst_target_bb;
1411
1412                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1413                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1414
1415                                                 changed = TRUE;
1416                                                 continue;
1417                                         }
1418
1419                                         bbn = bb->last_ins->inst_false_bb;
1420                                         bbn_first_inst = mono_bb_first_inst (bbn, filter);
1421                                         if (bbn && bb->region == bbn->region && bbn_first_inst && bbn_first_inst->opcode == OP_BR &&
1422                                                 bbn_first_inst->inst_target_bb->region == bb->region) {
1423                                                 if (cfg->verbose_level > 2)
1424                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
1425                                                                  bb->block_num, bbn->block_num, bbn_first_inst->inst_target_bb->block_num, 
1426                                                                  bbn_first_inst->opcode);
1427
1428                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1429                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1430
1431                                                 bb->last_ins->inst_false_bb = bbn_first_inst->inst_target_bb;
1432
1433                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
1434                                                 mono_link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
1435
1436                                                 changed = TRUE;
1437                                                 continue;
1438                                         }
1439
1440                                         bbn = bb->last_ins->inst_false_bb;
1441                                         /*
1442                                          * If bb is an extended bb, it could contain an inside branch to bbn.
1443                                          * FIXME: Enable the optimization if that is not true.
1444                                          * If bblocks_linked () is true, then merging bb and bbn
1445                                          * would require addition of an extra branch at the end of bbn 
1446                                          * slowing down loops.
1447                                          */
1448                                         if (bbn && bb->region == bbn->region && bbn->in_count == 1 && cfg->enable_extended_bblocks && bbn != cfg->bb_exit && !bb->extended && !bbn->out_of_line && !mono_bblocks_linked (bbn, bb)) {
1449                                                 g_assert (bbn->in_bb [0] == bb);
1450                                                 if (cfg->verbose_level > 2)
1451                                                         g_print ("merge false branch target triggered BB%d -> BB%d\n", bb->block_num, bbn->block_num);
1452                                                 mono_merge_basic_blocks (cfg, bb, bbn);
1453                                                 changed = TRUE;
1454                                                 continue;
1455                                         }
1456                                 }
1457
1458                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
1459                                         if (bb->last_ins->inst_false_bb && bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region) && !cfg->disable_out_of_line_bblocks) {
1460                                                 /* Reverse the branch */
1461                                                 bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
1462                                                 bbn = bb->last_ins->inst_false_bb;
1463                                                 bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb;
1464                                                 bb->last_ins->inst_true_bb = bbn;
1465
1466                                                 move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb);
1467                                                 if (cfg->verbose_level > 2)
1468                                                         g_print ("cbranch to throw block triggered %d.\n", 
1469                                                                          bb->block_num);
1470                                         }
1471                                 }
1472                         }
1473                 }
1474         } while (changed && (niterations > 0));
1475 }
1476
1477 #endif /* DISABLE_JIT */