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