Merge pull request #2311 from mlancione/master
[mono.git] / mono / mini / ssa.c
1 /*
2  * ssa.c: Static single assign form support for the JIT compiler.
3  *
4  * Author:
5  *    Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2003 Ximian, Inc.
8  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9  */
10 #include <config.h>
11 #include <string.h>
12 #include <mono/metadata/debug-helpers.h>
13 #include <mono/metadata/mempool.h>
14 #include <mono/metadata/mempool-internals.h>
15
16 #ifndef DISABLE_JIT
17
18 #include "mini.h"
19 #ifdef HAVE_ALLOCA_H
20 #include <alloca.h>
21 #endif
22
23 #define CREATE_PRUNED_SSA
24
25 //#define DEBUG_SSA 1
26
27 #define NEW_PHI(cfg,dest,val) do {      \
28         MONO_INST_NEW ((cfg), (dest), OP_PHI); \
29         (dest)->inst_c0 = (val);                                                           \
30         } while (0)
31
32 typedef struct {
33         MonoBasicBlock *bb;
34         MonoInst *inst;
35 } MonoVarUsageInfo;
36
37 static void 
38 unlink_target (MonoBasicBlock *bb, MonoBasicBlock *target)
39 {
40         int i;
41
42         for (i = 0; i < bb->out_count; i++) {
43                 if (bb->out_bb [i] == target) {
44                         bb->out_bb [i] = bb->out_bb [--bb->out_count];
45                         break;
46                 }
47         }
48         for (i = 0; i < target->in_count; i++) {
49                 if (target->in_bb [i] == bb) {
50                         target->in_bb [i] = target->in_bb [--target->in_count];
51                         break;
52                         
53                 }
54         }
55 }
56
57 static void
58 unlink_unused_bblocks (MonoCompile *cfg) 
59 {
60         int i, j;
61         MonoBasicBlock *bb;
62
63         g_assert (cfg->comp_done & MONO_COMP_REACHABILITY);
64
65         if (G_UNLIKELY (cfg->verbose_level > 1))
66                 printf ("\nUNLINK UNUSED BBLOCKS:\n");
67
68         for (bb = cfg->bb_entry; bb && bb->next_bb;) {
69                 if (!(bb->next_bb->flags & BB_REACHABLE)) {
70                         bb->next_bb = bb->next_bb->next_bb;
71                 } else 
72                         bb = bb->next_bb;
73         }
74
75         for (i = 1; i < cfg->num_bblocks; i++) {
76                 bb = cfg->bblocks [i];
77                
78                 if (!(bb->flags & BB_REACHABLE)) {
79                         for (j = 0; j < bb->in_count; j++) {
80                                 unlink_target (bb->in_bb [j], bb);      
81                         }
82                         for (j = 0; j < bb->out_count; j++) {
83                                 unlink_target (bb, bb->out_bb [j]);     
84                         }
85                         if (G_UNLIKELY (cfg->verbose_level > 1))
86                                 printf ("\tUnlinked BB%d\n", bb->block_num);
87                 }
88  
89         }
90 }
91
92 /**
93  * remove_bb_from_phis:
94  *
95  *   Remove BB from the PHI statements in TARGET.
96  */
97 static void
98 remove_bb_from_phis (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *target)
99 {
100         MonoInst *ins;
101         int i, j;
102
103         for (i = 0; i < target->in_count; i++) {
104                 if (target->in_bb [i] == bb) {
105                         break;
106                 }
107         }
108         g_assert (i < target->in_count);
109
110         for (ins = target->code; ins; ins = ins->next) {
111                 if (MONO_IS_PHI (ins)) {
112                         for (j = i; j < ins->inst_phi_args [0] - 1; ++j)
113                                 ins->inst_phi_args [j + 1] = ins->inst_phi_args [j + 2];
114                         ins->inst_phi_args [0] --;
115                 }
116                 else
117                         break;
118         }
119 }
120
121 static inline int
122 op_phi_to_move (int opcode)
123 {
124         switch (opcode) {
125         case OP_PHI:
126                 return OP_MOVE;
127         case OP_FPHI:
128                 return OP_FMOVE;
129         case OP_VPHI:
130                 return OP_VMOVE;
131         case OP_XPHI:
132                 return OP_XMOVE;
133         default:
134                 g_assert_not_reached ();
135         }
136
137         return -1;
138 }
139
140 static inline void
141 record_use (MonoCompile *cfg, MonoInst *var, MonoBasicBlock *bb, MonoInst *ins)
142 {
143         MonoMethodVar *info;
144         MonoVarUsageInfo *ui = (MonoVarUsageInfo *)mono_mempool_alloc (cfg->mempool, sizeof (MonoVarUsageInfo));
145
146         info = MONO_VARINFO (cfg, var->inst_c0);
147         
148         ui->bb = bb;
149         ui->inst = ins;
150         info->uses = g_list_prepend_mempool (cfg->mempool, info->uses, ui);
151 }       
152
153 typedef struct {
154         MonoInst *var;
155         int idx;
156 } RenameInfo;
157
158 /**
159  * mono_ssa_rename_vars:
160  *
161  *  Implement renaming of SSA variables. Also compute def-use information in parallel.
162  * @stack_history points to an area of memory which can be used for storing changes 
163  * made to the stack, so they can be reverted later.
164  */
165 static void
166 mono_ssa_rename_vars (MonoCompile *cfg, int max_vars, MonoBasicBlock *bb, gboolean *originals_used, MonoInst **stack,   guint32 *lvreg_stack, gboolean *lvreg_defined, RenameInfo *stack_history, int stack_history_size) 
167 {
168         MonoInst *ins, *new_var;
169         int i, j, idx;
170         GSList *tmp;
171         int stack_history_len = 0;
172
173         if (cfg->verbose_level >= 4)
174                 printf ("\nRENAME VARS BLOCK %d:\n", bb->block_num);
175
176         /* First pass: Create new vars */
177         for (ins = bb->code; ins; ins = ins->next) {
178                 const char *spec = INS_INFO (ins->opcode);
179                 int num_sregs;
180                 int sregs [MONO_MAX_SRC_REGS];
181
182 #ifdef DEBUG_SSA
183                 printf ("\tProcessing "); mono_print_ins (ins);
184 #endif
185                 if (ins->opcode == OP_NOP)
186                         continue;
187
188                 /* SREGs */
189                 num_sregs = mono_inst_get_src_registers (ins, sregs);
190                 for (i = 0; i < num_sregs; ++i) {
191                         if (spec [MONO_INST_SRC1 + i] != ' ') {
192                                 MonoInst *var = get_vreg_to_inst (cfg, sregs [i]);
193                                 if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
194                                         int idx = var->inst_c0;
195                                         if (stack [idx]) {
196                                                 if (var->opcode != OP_ARG)
197                                                         g_assert (stack [idx]);
198                                                 sregs [i] = stack [idx]->dreg;
199                                                 record_use (cfg, stack [idx], bb, ins);
200                                         }
201                                         else
202                                                 record_use (cfg, var, bb, ins);
203                                 }
204                                 else if (G_UNLIKELY (!var && lvreg_stack [sregs [i]]))
205                                         sregs [i] = lvreg_stack [sregs [i]];
206                         }
207                 }
208                 mono_inst_set_src_registers (ins, sregs);
209
210                 if (MONO_IS_STORE_MEMBASE (ins)) {
211                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
212                         if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
213                                 int idx = var->inst_c0;
214                                 if (stack [idx]) {
215                                         if (var->opcode != OP_ARG)
216                                                 g_assert (stack [idx]);
217                                         ins->dreg = stack [idx]->dreg;
218                                         record_use (cfg, stack [idx], bb, ins);
219                                 }
220                                 else
221                                         record_use (cfg, var, bb, ins);
222                         }
223                         else if (G_UNLIKELY (!var && lvreg_stack [ins->dreg]))
224                                 ins->dreg = lvreg_stack [ins->dreg];
225                 }
226
227                 /* DREG */
228                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
229                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
230                         MonoMethodVar *info;
231
232                         if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
233                                 idx = var->inst_c0;
234                                 g_assert (idx < max_vars);
235
236                                 if (var->opcode == OP_ARG)
237                                         originals_used [idx] = TRUE;
238
239                                 /* FIXME: */
240                                 g_assert (stack_history_len < stack_history_size);
241                                 stack_history [stack_history_len].var = stack [idx];
242                                 stack_history [stack_history_len].idx = idx;
243                                 stack_history_len ++;
244
245                                 if (originals_used [idx]) {
246                                         new_var = mono_compile_create_var (cfg, var->inst_vtype, OP_LOCAL);
247                                         new_var->flags = var->flags;
248                                         MONO_VARINFO (cfg, new_var->inst_c0)->reg = idx;
249
250                                         if (cfg->verbose_level >= 4)
251                                                 printf ("  R%d -> R%d\n", var->dreg, new_var->dreg);
252
253                                         stack [idx] = new_var;
254
255                                         ins->dreg = new_var->dreg;
256                                         var = new_var;
257                                 }
258                                 else {
259                                         stack [idx] = var;
260                                         originals_used [idx] = TRUE;
261                                 }
262
263                                 info = MONO_VARINFO (cfg, var->inst_c0);
264                                 info->def = ins;
265                                 info->def_bb = bb;
266                         }
267                         else if (G_UNLIKELY (!var && lvreg_defined [ins->dreg] && (ins->dreg >= MONO_MAX_IREGS))) {
268                                 /* Perform renaming for local vregs */
269                                 lvreg_stack [ins->dreg] = vreg_is_ref (cfg, ins->dreg) ? mono_alloc_ireg_ref (cfg) : mono_alloc_preg (cfg);
270                                 ins->dreg = lvreg_stack [ins->dreg];
271                         }
272                         else
273                                 lvreg_defined [ins->dreg] = TRUE;
274                 }
275
276 #ifdef DEBUG_SSA
277                 printf ("\tAfter processing "); mono_print_ins (ins);
278 #endif
279
280         }
281
282         /* Rename PHI arguments in succeeding bblocks */
283         for (i = 0; i < bb->out_count; i++) {
284                 MonoBasicBlock *n = bb->out_bb [i];
285
286                 for (j = 0; j < n->in_count; j++)
287                         if (n->in_bb [j] == bb)
288                                 break;
289                 
290                 for (ins = n->code; ins; ins = ins->next) {
291                         if (MONO_IS_PHI (ins)) {
292                                 idx = ins->inst_c0;
293                                 if (stack [idx])
294                                         new_var = stack [idx];
295                                 else
296                                         new_var = cfg->varinfo [idx];
297 #ifdef DEBUG_SSA
298                                 printf ("FOUND PHI %d (%d, %d)\n", idx, j, new_var->inst_c0);
299 #endif
300                                 ins->inst_phi_args [j + 1] = new_var->dreg;
301                                 record_use (cfg,  new_var, n, ins);                             
302                                 if (G_UNLIKELY (cfg->verbose_level >= 4))
303                                         printf ("\tAdd PHI R%d <- R%d to BB%d\n", ins->dreg, new_var->dreg, n->block_num);
304                         }
305                         else
306                                 /* The phi nodes are at the beginning of the bblock */
307                                 break;
308                 }
309         }
310
311         if (bb->dominated) {
312                 for (tmp = bb->dominated; tmp; tmp = tmp->next) {
313                         mono_ssa_rename_vars (cfg, max_vars, (MonoBasicBlock *)tmp->data, originals_used, stack, lvreg_stack, lvreg_defined, stack_history + stack_history_len, stack_history_size - stack_history_len);
314                 }
315         }
316
317         /* Restore stack */
318         for (i = stack_history_len - 1; i >= 0; i--) {
319                 stack [stack_history [i].idx] = stack_history [i].var;
320         }
321
322         cfg->comp_done |= MONO_COMP_SSA_DEF_USE;
323 }
324
325 void
326 mono_ssa_compute (MonoCompile *cfg)
327 {
328         int i, j, idx, bitsize;
329         MonoBitSet *set;
330         MonoMethodVar *vinfo = g_new0 (MonoMethodVar, cfg->num_varinfo);
331         MonoInst *ins, **stack;
332         guint8 *buf, *buf_start;
333         RenameInfo *stack_history;
334         int stack_history_size;
335         gboolean *originals;
336         guint32 *lvreg_stack;
337         gboolean *lvreg_defined;
338
339         g_assert (!(cfg->comp_done & MONO_COMP_SSA));
340
341         g_assert (!cfg->disable_ssa);
342
343         if (cfg->verbose_level >= 4)
344                 printf ("\nCOMPUTE SSA %d (R%d-)\n\n", cfg->num_varinfo, cfg->next_vreg);
345
346 #ifdef CREATE_PRUNED_SSA
347         /* we need liveness for pruned SSA */
348         if (!(cfg->comp_done & MONO_COMP_LIVENESS))
349                 mono_analyze_liveness (cfg);
350 #endif
351
352         mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM | MONO_COMP_DFRONTIER);
353
354         bitsize = mono_bitset_alloc_size (cfg->num_bblocks, 0);
355         buf = buf_start = (guint8 *)g_malloc0 (mono_bitset_alloc_size (cfg->num_bblocks, 0) * cfg->num_varinfo);
356
357         for (i = 0; i < cfg->num_varinfo; ++i) {
358                 vinfo [i].def_in = mono_bitset_mem_new (buf, cfg->num_bblocks, 0);
359                 buf += bitsize;
360                 vinfo [i].idx = i;
361                 /* implicit reference at start */
362                 if (cfg->varinfo [i]->opcode == OP_ARG)
363                         mono_bitset_set_fast (vinfo [i].def_in, 0);
364         }
365
366         for (i = 0; i < cfg->num_bblocks; ++i) {
367                 MONO_BB_FOR_EACH_INS (cfg->bblocks [i], ins) {
368                         if (ins->opcode == OP_NOP)
369                                 continue;
370
371                         if (!MONO_IS_STORE_MEMBASE (ins) && get_vreg_to_inst (cfg, ins->dreg)) {
372                                 mono_bitset_set_fast (vinfo [get_vreg_to_inst (cfg, ins->dreg)->inst_c0].def_in, i);
373                         }
374                 }
375         }
376
377         /* insert phi functions */
378         for (i = 0; i < cfg->num_varinfo; ++i) {
379                 MonoInst *var = cfg->varinfo [i];
380
381 #if SIZEOF_REGISTER == 4
382                 if (var->type == STACK_I8 && !COMPILE_LLVM (cfg))
383                         continue;
384 #endif
385                 if (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
386                         continue;
387
388                 /* Most variables have only one definition */
389                 if (mono_bitset_count (vinfo [i].def_in) <= 1)
390                         continue;
391
392                 set = mono_compile_iterated_dfrontier (cfg, vinfo [i].def_in);
393
394                 if (cfg->verbose_level >= 4) {
395                         if (mono_bitset_count (set) > 0) {
396                                 printf ("\tR%d needs PHI functions in ", var->dreg);
397                                 mono_blockset_print (cfg, set, "", -1);
398                         }
399                 }
400                         
401                 mono_bitset_foreach_bit (set, idx, cfg->num_bblocks) {
402                         MonoBasicBlock *bb = cfg->bblocks [idx];
403
404                         /* fixme: create pruned SSA? we would need liveness information for that */
405
406                         if (bb == cfg->bb_exit && !COMPILE_LLVM (cfg))
407                                 continue;
408
409                         if ((cfg->comp_done & MONO_COMP_LIVENESS) && !mono_bitset_test_fast (bb->live_in_set, i)) {
410                                 //printf ("%d is not live in BB%d %s\n", i, bb->block_num, mono_method_full_name (cfg->method, TRUE));
411                                 continue;
412                         }
413
414                         NEW_PHI (cfg, ins, i);
415
416                         switch (var->type) {
417                         case STACK_I4:
418                         case STACK_I8:
419                         case STACK_PTR:
420                         case STACK_MP:
421                         case STACK_OBJ:
422                                 ins->opcode = OP_PHI;
423                                 break;
424                         case STACK_R8:
425                                 ins->opcode = OP_FPHI;
426                                 break;
427                         case STACK_VTYPE:
428                                 ins->opcode = MONO_CLASS_IS_SIMD (cfg, var->klass) ? OP_XPHI : OP_VPHI;
429                                 break;
430                         }
431
432                         if (var->inst_vtype->byref)
433                                 ins->klass = mono_defaults.int_class;
434                         else
435                                 ins->klass = var->klass;
436
437                         ins->inst_phi_args = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * (cfg->bblocks [idx]->in_count + 1));
438                         ins->inst_phi_args [0] = cfg->bblocks [idx]->in_count;
439
440                         /* For debugging */
441                         for (j = 0; j < cfg->bblocks [idx]->in_count; ++j)
442                                 ins->inst_phi_args [j + 1] = -1;
443
444                         ins->dreg = cfg->varinfo [i]->dreg;
445
446                         mono_bblock_insert_before_ins (bb, bb->code, ins);
447
448 #ifdef DEBUG_SSA
449                         printf ("ADD PHI BB%d %s\n", cfg->bblocks [idx]->block_num, mono_method_full_name (cfg->method, TRUE));
450 #endif
451                 }
452         }
453
454         /* free the stuff */
455         g_free (vinfo);
456         g_free (buf_start);
457
458         /* Renaming phase */
459
460         stack = (MonoInst **)alloca (sizeof (MonoInst *) * cfg->num_varinfo);
461         memset (stack, 0, sizeof (MonoInst *) * cfg->num_varinfo);
462
463         lvreg_stack = g_new0 (guint32, cfg->next_vreg);
464         lvreg_defined = g_new0 (gboolean, cfg->next_vreg);
465         stack_history_size = 10240;
466         stack_history = g_new (RenameInfo, stack_history_size);
467         originals = g_new0 (gboolean, cfg->num_varinfo);
468         mono_ssa_rename_vars (cfg, cfg->num_varinfo, cfg->bb_entry, originals, stack, lvreg_stack, lvreg_defined, stack_history, stack_history_size);
469         g_free (stack_history);
470         g_free (originals);
471         g_free (lvreg_stack);
472         g_free (lvreg_defined);
473
474         if (cfg->verbose_level >= 4)
475                 printf ("\nEND COMPUTE SSA.\n\n");
476
477         cfg->comp_done |= MONO_COMP_SSA;
478 }
479
480 void
481 mono_ssa_remove (MonoCompile *cfg)
482 {
483         MonoInst *ins, *var, *move;
484         int bbindex, i, j, first;
485
486         g_assert (cfg->comp_done & MONO_COMP_SSA);
487
488         for (i = 0; i < cfg->num_bblocks; ++i) {
489                 MonoBasicBlock *bb = cfg->bblocks [i];
490
491                 if (cfg->verbose_level >= 4)
492                         printf ("\nREMOVE SSA %d:\n", bb->block_num);
493
494                 for (ins = bb->code; ins; ins = ins->next) {
495                         if (MONO_IS_PHI (ins)) {
496                                 g_assert (ins->inst_phi_args [0] == bb->in_count);
497                                 var = get_vreg_to_inst (cfg, ins->dreg);
498
499                                 /* Check for PHI nodes where all the inputs are the same */
500                                 first = ins->inst_phi_args [1];
501
502                                 for (j = 1; j < bb->in_count; ++j)
503                                         if (first != ins->inst_phi_args [j + 1])
504                                                 break;
505
506                                 if ((bb->in_count > 1) && (j == bb->in_count)) {
507                                         ins->opcode = op_phi_to_move (ins->opcode);
508                                         if (ins->opcode == OP_VMOVE)
509                                                 g_assert (ins->klass);
510                                         ins->sreg1 = first;
511                                 } else {
512                                         for (j = 0; j < bb->in_count; j++) {
513                                                 MonoBasicBlock *pred = bb->in_bb [j];
514                                                 int sreg = ins->inst_phi_args [j + 1];
515
516                                                 if (cfg->verbose_level >= 4)
517                                                         printf ("\tADD R%d <- R%d in BB%d\n", var->dreg, sreg, pred->block_num);
518                                                 if (var->dreg != sreg) {
519                                                         MONO_INST_NEW (cfg, move, op_phi_to_move (ins->opcode));
520                                                         if (move->opcode == OP_VMOVE) {
521                                                                 g_assert (ins->klass);
522                                                                 move->klass = ins->klass;
523                                                         }
524                                                         move->dreg = var->dreg;
525                                                         move->sreg1 = sreg;
526                                                         mono_add_ins_to_end (pred, move);
527                                                 }
528                                         }
529
530                                         NULLIFY_INS (ins);
531                                 }
532                         }
533                 }
534         }
535
536         if (cfg->verbose_level >= 4) {
537                 for (i = 0; i < cfg->num_bblocks; ++i) {
538                         MonoBasicBlock *bb = cfg->bblocks [i];
539
540                         mono_print_bb (bb, "AFTER REMOVE SSA:");
541                 }
542         }
543
544         /*
545          * Removal of SSA form introduces many copies. To avoid this, we tyry to coalesce 
546          * the variables if possible. Since the newly introduced SSA variables don't
547          * have overlapping live ranges (because we don't do agressive optimization), we
548          * can coalesce them into the original variable.
549          */
550
551         for (bbindex = 0; bbindex < cfg->num_bblocks; ++bbindex) {
552                 MonoBasicBlock *bb = cfg->bblocks [bbindex];
553
554                 for (ins = bb->code; ins; ins = ins->next) {
555                         const char *spec = INS_INFO (ins->opcode);
556                         int num_sregs;
557                         int sregs [MONO_MAX_SRC_REGS];
558
559                         if (ins->opcode == OP_NOP)
560                                 continue;
561
562                         if (spec [MONO_INST_DEST] != ' ') {
563                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
564
565                                 if (var) {
566                                         MonoMethodVar *vmv = MONO_VARINFO (cfg, var->inst_c0);
567                                         
568                                         /* 
569                                          * The third condition avoids coalescing with variables eliminated
570                                          * during deadce.
571                                          */
572                                         if ((vmv->reg != -1) && (vmv->idx != vmv->reg) && (MONO_VARINFO (cfg, vmv->reg)->reg != -1)) {
573                                                 printf ("COALESCE: R%d -> R%d\n", ins->dreg, cfg->varinfo [vmv->reg]->dreg);
574                                                 ins->dreg = cfg->varinfo [vmv->reg]->dreg; 
575                                         }
576                                 }
577                         }
578
579                         num_sregs = mono_inst_get_src_registers (ins, sregs);
580                         for (i = 0; i < num_sregs; ++i) {
581                                 MonoInst *var = get_vreg_to_inst (cfg, sregs [i]);
582
583                                 if (var) {
584                                         MonoMethodVar *vmv = MONO_VARINFO (cfg, var->inst_c0);
585
586                                         if ((vmv->reg != -1) && (vmv->idx != vmv->reg) && (MONO_VARINFO (cfg, vmv->reg)->reg != -1)) {
587                                                 printf ("COALESCE: R%d -> R%d\n", sregs [i], cfg->varinfo [vmv->reg]->dreg);
588                                                 sregs [i] = cfg->varinfo [vmv->reg]->dreg;
589                                         }
590                                 }
591                         }
592                         mono_inst_set_src_registers (ins, sregs);
593                 }
594         }
595
596         for (i = 0; i < cfg->num_varinfo; ++i) {
597                 MONO_VARINFO (cfg, i)->reg = -1;
598         }
599
600         if (cfg->comp_done & MONO_COMP_REACHABILITY)
601                 unlink_unused_bblocks (cfg);
602
603         cfg->comp_done &= ~MONO_COMP_LIVENESS;
604
605         cfg->comp_done &= ~MONO_COMP_SSA;
606 }
607
608 static void
609 mono_ssa_create_def_use (MonoCompile *cfg) 
610 {
611         MonoBasicBlock *bb;
612         MonoInst *ins;
613         int i;
614
615         g_assert (!(cfg->comp_done & MONO_COMP_SSA_DEF_USE));
616
617         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
618                 for (ins = bb->code; ins; ins = ins->next) {
619                         const char *spec = INS_INFO (ins->opcode);
620                         MonoMethodVar *info;
621                         int num_sregs;
622                         int sregs [MONO_MAX_SRC_REGS];
623
624                         if (ins->opcode == OP_NOP)
625                                 continue;
626
627                         /* SREGs */
628                         num_sregs = mono_inst_get_src_registers (ins, sregs);
629                         for (i = 0; i < num_sregs; ++i) {
630                                 MonoInst *var = get_vreg_to_inst (cfg, sregs [i]);
631                                 if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
632                                         record_use (cfg, var, bb, ins);
633                         }
634
635                         if (MONO_IS_STORE_MEMBASE (ins)) {
636                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
637                                 if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
638                                         record_use (cfg, var, bb, ins);
639                         }
640
641                         if (MONO_IS_PHI (ins)) {
642                                 for (i = ins->inst_phi_args [0]; i > 0; i--) {
643                                         g_assert (ins->inst_phi_args [i] != -1);
644                                         record_use (cfg,  get_vreg_to_inst (cfg, ins->inst_phi_args [i]), bb, ins);
645                                 }
646                         }
647
648                         /* DREG */
649                         if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
650                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
651
652                                 if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
653                                         info = MONO_VARINFO (cfg, var->inst_c0);
654                                         info->def = ins;
655                                         info->def_bb = bb;
656                                 }
657                         }
658                 }
659         }
660
661         cfg->comp_done |= MONO_COMP_SSA_DEF_USE;
662 }
663
664 static void
665 mono_ssa_copyprop (MonoCompile *cfg)
666 {
667         int i, index;
668         GList *l;
669
670         g_assert ((cfg->comp_done & MONO_COMP_SSA_DEF_USE));
671
672         for (index = 0; index < cfg->num_varinfo; ++index) {
673                 MonoInst *var = cfg->varinfo [index];
674                 MonoMethodVar *info = MONO_VARINFO (cfg, index);
675
676                 if (info->def && (MONO_IS_MOVE (info->def))) {
677                         MonoInst *var2 = get_vreg_to_inst (cfg, info->def->sreg1);
678
679                         if (var2 && !(var2->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && MONO_VARINFO (cfg, var2->inst_c0)->def && (!MONO_IS_PHI (MONO_VARINFO (cfg, var2->inst_c0)->def))) {
680                                 /* Rewrite all uses of var to be uses of var2 */
681                                 int dreg = var->dreg;
682                                 int sreg1 = var2->dreg;
683
684                                 l = info->uses;
685                                 while (l) {
686                                         MonoVarUsageInfo *u = (MonoVarUsageInfo*)l->data;
687                                         MonoInst *ins = u->inst;
688                                         GList *next = l->next;
689                                         int num_sregs;
690                                         int sregs [MONO_MAX_SRC_REGS];
691
692                                         num_sregs = mono_inst_get_src_registers (ins, sregs);
693                                         for (i = 0; i < num_sregs; ++i) {
694                                                 if (sregs [i] == dreg)
695                                                         break;
696                                         }
697                                         if (i < num_sregs) {
698                                                 g_assert (sregs [i] == dreg);
699                                                 sregs [i] = sreg1;
700                                                 mono_inst_set_src_registers (ins, sregs);
701                                         } else if (MONO_IS_STORE_MEMBASE (ins) && ins->dreg == dreg) {
702                                                 ins->dreg = sreg1;
703                                         } else if (MONO_IS_PHI (ins)) {
704                                                 for (i = ins->inst_phi_args [0]; i > 0; i--) {
705                                                         int sreg = ins->inst_phi_args [i];
706                                                         if (sreg == var->dreg)
707                                                                 break;
708                                                 }
709                                                 g_assert (i > 0);
710                                                 ins->inst_phi_args [i] = sreg1;
711                                         }
712                                         else
713                                                 g_assert_not_reached ();
714
715                                         record_use (cfg, var2, u->bb, ins);
716
717                                         l = next;
718                                 }
719
720                                 info->uses = NULL;
721                         }
722                 }
723         }
724
725         if (cfg->verbose_level >= 4) {
726                 MonoBasicBlock *bb;
727
728                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
729                         mono_print_bb (bb, "AFTER SSA COPYPROP");
730         }
731 }
732
733 static int
734 evaluate_ins (MonoCompile *cfg, MonoInst *ins, MonoInst **res, MonoInst **carray)
735 {
736         MonoInst *args [MONO_MAX_SRC_REGS];
737         int rs [MONO_MAX_SRC_REGS];
738         MonoInst *c0;
739         gboolean const_args = TRUE;
740         const char *spec = INS_INFO (ins->opcode);
741         int num_sregs, i;
742         int sregs [MONO_MAX_SRC_REGS];
743
744         /* Short-circuit this */
745         if (ins->opcode == OP_ICONST) {
746                 *res = ins;
747                 return 1;
748         }
749
750         if (ins->opcode == OP_NOP)
751                 return 2;
752
753         num_sregs = mono_inst_get_src_registers (ins, sregs);
754         for (i = 0; i < MONO_MAX_SRC_REGS; ++i)
755                 args [i] = NULL;
756         for (i = 0; i < num_sregs; ++i) {
757                 MonoInst *var = get_vreg_to_inst (cfg, sregs [i]);
758
759                 rs [i] = 2;
760                 args [i] = carray [sregs [i]];
761                 if (args [i])
762                         rs [i] = 1;
763                 else if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
764                         rs [i] = MONO_VARINFO (cfg, var->inst_c0)->cpstate;
765                 if (rs [i] != 1)
766                         const_args = FALSE;
767         }
768
769         c0 = NULL;
770
771         if (num_sregs > 0 && const_args) {
772                 g_assert (num_sregs <= 2);
773                 if ((spec [MONO_INST_DEST] != ' ') && carray [ins->dreg]) {
774                         // Cached value
775                         *res = carray [ins->dreg];
776                         return 1;
777                 }
778                 c0 = mono_constant_fold_ins (cfg, ins, args [0], args [1], FALSE);
779                 if (c0) {
780                         if (G_UNLIKELY (cfg->verbose_level > 1)) {
781                                 printf ("\t cfold -> ");
782                                 mono_print_ins (c0);
783                         }
784                         *res = c0;
785                         return 1;
786                 }
787                 else
788                         /* Can't cfold this ins */
789                         return 2;
790         }
791
792         if (num_sregs == 0)
793                 return 2;
794         for (i = 0; i < num_sregs; ++i) {
795                 if (rs [i] == 2)
796                         return 2;
797         }
798         return 0;
799 }
800
801 static inline void
802 change_varstate (MonoCompile *cfg, GList **cvars, MonoMethodVar *info, int state, MonoInst *c0, MonoInst **carray)
803 {
804         if (info->cpstate >= state)
805                 return;
806
807         info->cpstate = state;
808
809         if (G_UNLIKELY (cfg->verbose_level > 1))
810                 printf ("\tState of R%d set to %d\n", cfg->varinfo [info->idx]->dreg, info->cpstate);
811
812         if (state == 1)
813                 g_assert (c0);
814
815         carray [cfg->varinfo [info->idx]->dreg] = c0;
816
817         if (!g_list_find (*cvars, info)) {
818                 *cvars = g_list_prepend (*cvars, info);
819         }
820 }
821
822 static inline void
823 add_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, GList **bblist)
824 {
825         if (G_UNLIKELY (cfg->verbose_level > 1))
826                 printf ("\tAdd BB%d to worklist\n", bb->block_num);
827
828     if (!(bb->flags &  BB_REACHABLE)) {
829             bb->flags |= BB_REACHABLE;
830                 *bblist = g_list_prepend (*bblist, bb);
831         }
832 }
833
834 static void
835 visit_inst (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, GList **cvars, GList **bblist, MonoInst **carray)
836 {
837         const char *spec = INS_INFO (ins->opcode);
838
839         if (ins->opcode == OP_NOP)
840                 return;
841
842         if (cfg->verbose_level > 1)
843                 mono_print_ins (ins);
844
845         /* FIXME: Support longs/floats */
846         /* FIXME: Work on vregs as well */
847
848         if (MONO_IS_PHI (ins)) {
849                 MonoMethodVar *info = MONO_VARINFO (cfg, get_vreg_to_inst (cfg, ins->dreg)->inst_c0);
850                 MonoInst *c0 = NULL;
851                 int j;
852
853                 for (j = 1; j <= ins->inst_phi_args [0]; j++) {
854                         MonoInst *var = get_vreg_to_inst (cfg, ins->inst_phi_args [j]);
855                         MonoMethodVar *mv = MONO_VARINFO (cfg, var->inst_c0);
856                         MonoInst *src = mv->def;
857
858                         if (mv->def_bb && !(mv->def_bb->flags & BB_REACHABLE))
859                                 continue;
860
861                         if (!mv->def || !src || mv->cpstate == 2) {
862                                 change_varstate (cfg, cvars, info, 2, NULL, carray);
863                                 break;
864                         }
865                                         
866                         if (mv->cpstate == 0)
867                                 continue;
868
869                         g_assert (carray [var->dreg]);
870
871                         if (!c0)
872                                 c0 = carray [var->dreg];
873                 
874                         /* FIXME: */
875                         if (c0->opcode != OP_ICONST) {
876                                 change_varstate (cfg, cvars, info, 2, NULL, carray);
877                                 break;
878                         }
879
880                         if (carray [var->dreg]->inst_c0 != c0->inst_c0) {
881                                 change_varstate (cfg, cvars, info, 2, NULL, carray);
882                                 break;
883                         }
884                 }
885                                 
886                 if (c0 && info->cpstate < 1) {
887                         change_varstate (cfg, cvars, info, 1, c0, carray);
888
889                         g_assert (c0->opcode == OP_ICONST);
890                 }
891         }
892         else if (!MONO_IS_STORE_MEMBASE (ins) && ((spec [MONO_INST_SRC1] != ' ') || (spec [MONO_INST_SRC2] != ' ') || (spec [MONO_INST_DEST] != ' '))) {
893                 MonoInst *var, *c0;
894                 int state;
895
896                 if (spec [MONO_INST_DEST] !=  ' ')
897                         var = get_vreg_to_inst (cfg, ins->dreg);
898                 else
899                         var = NULL;
900
901                 c0 = NULL;
902                 state = evaluate_ins (cfg, ins, &c0, carray);
903
904                 if (var && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
905                         MonoMethodVar *info = MONO_VARINFO (cfg, var->inst_c0);
906
907                         if (info->cpstate < 2) {
908                                 if (state == 1)
909                                         change_varstate (cfg, cvars, info, 1, c0, carray);
910                                 else if (state == 2)
911                                         change_varstate (cfg, cvars, info, 2, NULL, carray);
912                         }
913                 }
914                 else if (!var && (ins->dreg != -1)) {
915                         /*
916                          * We don't record def-use information for local vregs since it would be 
917                          * expensive. Instead, we depend on the fact that all uses of the vreg are in
918                          * the same bblock, so they will be examined after the definition.
919                          * FIXME: This isn't true if the ins is visited through an SSA edge.
920                          */
921                         if (c0) {
922                                 carray [ins->dreg] = c0;
923                         } else {
924                                 if (carray [ins->dreg]) {
925                                         /* 
926                                          * The state of the vreg changed from constant to non-constant
927                                          * -> need to rescan the whole bblock.
928                                          */
929                                         carray [ins->dreg] = NULL;
930                                         /* FIXME: Speed this up */
931
932                                         if (!g_list_find (*bblist, bb))
933                                                 *bblist = g_list_prepend (*bblist, bb);
934                                 }
935                         }
936                 }
937
938                 if (MONO_IS_JUMP_TABLE (ins)) {
939                         int i;
940                         MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)MONO_JUMP_TABLE_FROM_INS (ins);
941
942                         if (!ins->next || ins->next->opcode != OP_PADD) {
943                                 /* The PADD was optimized away */
944                                 /* FIXME: handle this as well */
945                                 for (i = 0; i < table->table_size; i++)
946                                         if (table->table [i])
947                                                 add_cprop_bb (cfg, table->table [i], bblist);
948                                 return;
949                         }
950
951                         g_assert (ins->next->opcode == OP_PADD);
952                         g_assert (ins->next->sreg1 == ins->dreg);
953
954                         if (carray [ins->next->sreg2]) {
955 #if SIZEOF_REGISTER == 8
956                                 int idx = carray [ins->next->sreg2]->inst_c0 >> 3;
957 #else
958                                 int idx = carray [ins->next->sreg2]->inst_c0 >> 2;
959 #endif
960                                 if ((idx < 0) || (idx >= table->table_size))
961                                         /* Out-of-range, no branch is executed */
962                                         return;
963                                 else
964                                         if (table->table [idx])
965                                                 add_cprop_bb (cfg, table->table [idx], bblist);
966                         }
967                         else {
968                                 for (i = 0; i < table->table_size; i++)
969                                         if (table->table [i])
970                                                 add_cprop_bb (cfg, table->table [i], bblist);
971                         }
972                 }
973
974                 if (ins->opcode == OP_SWITCH) {
975                         int i;
976                         MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)ins->inst_p0;
977
978                         for (i = 0; i < table->table_size; i++)
979                                 if (table->table [i])
980                                         add_cprop_bb (cfg, table->table [i], bblist);
981                 }
982
983                 /* Handle COMPARE+BRCOND pairs */
984                 if (ins->next && MONO_IS_COND_BRANCH_OP (ins->next)) {
985                         if (c0) {
986                                 g_assert (c0->opcode == OP_ICONST);
987
988                                 if (c0->inst_c0)
989                                         ins->next->flags |= MONO_INST_CFOLD_TAKEN;
990                                 else
991                                         ins->next->flags |= MONO_INST_CFOLD_NOT_TAKEN;
992                         }
993                         else {
994                                 ins->next->flags &= ~(MONO_INST_CFOLD_TAKEN | MONO_INST_CFOLD_NOT_TAKEN);
995                         }
996
997                         visit_inst (cfg, bb, ins->next, cvars, bblist, carray);
998                 }
999         } else if (ins->opcode == OP_BR) {
1000                 add_cprop_bb (cfg, ins->inst_target_bb, bblist);
1001         } else if (MONO_IS_COND_BRANCH_OP (ins)) {
1002                 if (ins->flags & MONO_INST_CFOLD_TAKEN) {
1003                         add_cprop_bb (cfg, ins->inst_true_bb, bblist);
1004                 } else if (ins->flags & MONO_INST_CFOLD_NOT_TAKEN) {
1005                         if (ins->inst_false_bb)
1006                                 add_cprop_bb (cfg, ins->inst_false_bb, bblist);
1007         } else {
1008                         add_cprop_bb (cfg, ins->inst_true_bb, bblist);
1009                         if (ins->inst_false_bb)
1010                                 add_cprop_bb (cfg, ins->inst_false_bb, bblist);
1011                 }
1012         }
1013 }
1014
1015 /**
1016  * fold_ins:
1017  *
1018  *   Replace INS with its constant value, if it exists
1019  */
1020 static void
1021 fold_ins (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, MonoInst **carray)
1022 {
1023         const char *spec = INS_INFO (ins->opcode);
1024         int opcode2;
1025         int num_sregs = mono_inst_get_num_src_registers (ins);
1026
1027         if ((ins->opcode != OP_NOP) && (ins->dreg != -1) && !MONO_IS_STORE_MEMBASE (ins)) {
1028                 if (carray [ins->dreg] && (spec [MONO_INST_DEST] == 'i') && (ins->dreg >= MONO_MAX_IREGS)) {
1029                         /* Perform constant folding */
1030                         /* FIXME: */
1031                         g_assert (carray [ins->dreg]->opcode == OP_ICONST);
1032                         ins->opcode = OP_ICONST;
1033                         ins->inst_c0 = carray [ins->dreg]->inst_c0;
1034                         MONO_INST_NULLIFY_SREGS (ins);
1035                 } else if (num_sregs == 2 && carray [ins->sreg2]) {
1036                         /* Perform op->op_imm conversion */
1037                         opcode2 = mono_op_to_op_imm (ins->opcode);
1038                         if (opcode2 != -1) {
1039                                 ins->opcode = opcode2;
1040                                 ins->inst_imm = carray [ins->sreg2]->inst_c0;
1041                                 ins->sreg2 = -1;
1042
1043                                 if ((opcode2 == OP_VOIDCALL) || (opcode2 == OP_CALL) || (opcode2 == OP_LCALL) || (opcode2 == OP_FCALL))
1044                                         ((MonoCallInst*)ins)->fptr = (gpointer)ins->inst_imm;
1045                         }
1046                 } else {
1047                         /* FIXME: Handle 3 op insns */
1048                 }
1049
1050                 if (MONO_IS_JUMP_TABLE (ins)) {
1051                         int i;
1052                         MonoJumpInfoBBTable *table = (MonoJumpInfoBBTable *)MONO_JUMP_TABLE_FROM_INS (ins);
1053
1054                         if (!ins->next || ins->next->opcode != OP_PADD) {
1055                                 /* The PADD was optimized away */
1056                                 /* FIXME: handle this as well */
1057                                 return;
1058                         }
1059
1060                         g_assert (ins->next->opcode == OP_PADD);
1061                         g_assert (ins->next->sreg1 == ins->dreg);
1062                         g_assert (ins->next->next->opcode == OP_LOAD_MEMBASE);
1063
1064                         if (carray [ins->next->sreg2]) {
1065                                 /* Convert to a simple branch */
1066 #if SIZEOF_REGISTER == 8
1067                                 int idx = carray [ins->next->sreg2]->inst_c0 >> 3;
1068 #else
1069                                 int idx = carray [ins->next->sreg2]->inst_c0 >> 2;
1070 #endif
1071
1072                                 if (!((idx >= 0) && (idx < table->table_size))) {
1073                                         /* Out of range, eliminate the whole switch */
1074                                         for (i = 0; i < table->table_size; ++i) {
1075                                                 remove_bb_from_phis (cfg, bb, table->table [i]);
1076                                                 mono_unlink_bblock (cfg, bb, table->table [i]);
1077                                         }
1078
1079                                         NULLIFY_INS (ins);
1080                                         NULLIFY_INS (ins->next);
1081                                         NULLIFY_INS (ins->next->next);
1082                                         if (ins->next->next->next)
1083                                                 NULLIFY_INS (ins->next->next->next);
1084
1085                                         return;
1086                                 }
1087
1088                                 if (!ins->next->next->next || ins->next->next->next->opcode != OP_BR_REG) {
1089                                         /* A one-way switch which got optimized away */
1090                                         if (G_UNLIKELY (cfg->verbose_level > 1)) {
1091                                                 printf ("\tNo cfold on ");
1092                                                 mono_print_ins (ins);
1093                                         }
1094                                         return;
1095                                 }
1096
1097                                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
1098                                         printf ("\tcfold on ");
1099                                         mono_print_ins (ins);
1100                                 }
1101
1102                                 /* Unlink target bblocks */
1103                                 for (i = 0; i < table->table_size; ++i) {
1104                                         if (table->table [i] != table->table [idx]) {
1105                                                 remove_bb_from_phis (cfg, bb, table->table [i]);
1106                                                 mono_unlink_bblock (cfg, bb, table->table [i]);
1107                                         }
1108                                 }
1109
1110                                 /* Change the OP_BR_REG to a simple branch */
1111                                 ins->next->next->next->opcode = OP_BR;
1112                                 ins->next->next->next->inst_target_bb = table->table [idx];
1113                                 ins->next->next->next->sreg1 = -1;
1114
1115                                 /* Nullify the other instructions */
1116                                 NULLIFY_INS (ins);
1117                                 NULLIFY_INS (ins->next);
1118                                 NULLIFY_INS (ins->next->next);
1119                         }
1120                 }
1121         } 
1122         else if (MONO_IS_COND_BRANCH_OP (ins)) {
1123                 if (ins->flags & MONO_INST_CFOLD_TAKEN) {
1124                         remove_bb_from_phis (cfg, bb, ins->inst_false_bb);
1125                         mono_unlink_bblock (cfg, bb, ins->inst_false_bb);
1126                         ins->opcode = OP_BR;
1127                         ins->inst_target_bb = ins->inst_true_bb;
1128                 } else if (ins->flags & MONO_INST_CFOLD_NOT_TAKEN) {
1129                         remove_bb_from_phis (cfg, bb, ins->inst_true_bb);
1130                         mono_unlink_bblock (cfg, bb, ins->inst_true_bb);
1131                         ins->opcode = OP_BR;
1132                         ins->inst_target_bb = ins->inst_false_bb;
1133                 }
1134         }
1135 }
1136
1137 void
1138 mono_ssa_cprop (MonoCompile *cfg) 
1139 {
1140         MonoInst **carray;
1141         MonoBasicBlock *bb;
1142         GList *bblock_list, *cvars;
1143         GList *tmp;
1144         int i;
1145         //printf ("SIMPLE OPTS BB%d %s\n", bb->block_num, mono_method_full_name (cfg->method, TRUE));
1146
1147         carray = g_new0 (MonoInst*, cfg->next_vreg);
1148
1149         if (!(cfg->comp_done & MONO_COMP_SSA_DEF_USE))
1150                 mono_ssa_create_def_use (cfg);
1151
1152         bblock_list = g_list_prepend (NULL, cfg->bb_entry);
1153         cfg->bb_entry->flags |= BB_REACHABLE;
1154
1155         memset (carray, 0, sizeof (MonoInst *) * cfg->num_varinfo);
1156
1157         for (i = 0; i < cfg->num_varinfo; i++) {
1158                 MonoMethodVar *info = MONO_VARINFO (cfg, i);
1159                 if (!info->def)
1160                         info->cpstate = 2;
1161         }
1162
1163         for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
1164                 /*
1165                  * FIXME: This should be bb->flags & BB_FLAG_EXCEPTION_HANDLER, but
1166                  * that would still allow unreachable try's to be removed.
1167                  */
1168                 if (bb->region)
1169                         add_cprop_bb (cfg, bb, &bblock_list);
1170         }
1171
1172         cvars = NULL;
1173
1174         while (bblock_list) {
1175                 MonoInst *inst;
1176
1177                 bb = (MonoBasicBlock *)bblock_list->data;
1178
1179                 bblock_list = g_list_delete_link (bblock_list, bblock_list);
1180
1181                 g_assert (bb->flags &  BB_REACHABLE);
1182
1183                 /* 
1184                  * Some bblocks are linked to 2 others even through they fall through to the
1185                  * next bblock.
1186                  */
1187                 if (!(bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins))) {
1188                         for (i = 0; i < bb->out_count; ++i)
1189                                 add_cprop_bb (cfg, bb->out_bb [i], &bblock_list);
1190                 }
1191
1192                 if (cfg->verbose_level > 1)
1193                         printf ("\nSSA CONSPROP BB%d:\n", bb->block_num);
1194
1195                 for (inst = bb->code; inst; inst = inst->next) {
1196                         visit_inst (cfg, bb, inst, &cvars, &bblock_list, carray);
1197                 }
1198
1199                 while (cvars) {
1200                         MonoMethodVar *info = (MonoMethodVar *)cvars->data;                     
1201                         cvars = g_list_delete_link (cvars, cvars);
1202
1203                         for (tmp = info->uses; tmp; tmp = tmp->next) {
1204                                 MonoVarUsageInfo *ui = (MonoVarUsageInfo *)tmp->data;
1205                                 if (!(ui->bb->flags & BB_REACHABLE))
1206                                         continue;
1207                                 visit_inst (cfg, ui->bb, ui->inst, &cvars, &bblock_list, carray);
1208                         }
1209                 }
1210         }
1211
1212         for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
1213                 MonoInst *inst;
1214                 for (inst = bb->code; inst; inst = inst->next) {
1215                         fold_ins (cfg, bb, inst, carray);
1216                 }
1217         }
1218
1219         g_free (carray);
1220
1221         cfg->comp_done |= MONO_COMP_REACHABILITY;
1222
1223         /* fixme: we should update usage infos during cprop, instead of computing it again */
1224         cfg->comp_done &=  ~MONO_COMP_SSA_DEF_USE;
1225         for (i = 0; i < cfg->num_varinfo; i++) {
1226                 MonoMethodVar *info = MONO_VARINFO (cfg, i);
1227                 info->def = NULL;
1228                 info->uses = NULL;
1229         }
1230 }
1231
1232 static inline void
1233 add_to_dce_worklist (MonoCompile *cfg, MonoMethodVar *var, MonoMethodVar *use, GList **wl)
1234 {
1235         GList *tmp;
1236
1237         *wl = g_list_prepend_mempool (cfg->mempool, *wl, use);
1238
1239         for (tmp = use->uses; tmp; tmp = tmp->next) {
1240                 MonoVarUsageInfo *ui = (MonoVarUsageInfo *)tmp->data;
1241                 if (ui->inst == var->def) {
1242                         /* from the mempool */
1243                         use->uses = g_list_remove_link (use->uses, tmp);
1244                         break;
1245                 }
1246         }       
1247 }
1248
1249 void
1250 mono_ssa_deadce (MonoCompile *cfg) 
1251 {
1252         int i;
1253         GList *work_list;
1254
1255         g_assert (cfg->comp_done & MONO_COMP_SSA);
1256
1257         //printf ("DEADCE %s\n", mono_method_full_name (cfg->method, TRUE));
1258
1259         if (!(cfg->comp_done & MONO_COMP_SSA_DEF_USE))
1260                 mono_ssa_create_def_use (cfg);
1261
1262         mono_ssa_copyprop (cfg);
1263
1264         work_list = NULL;
1265         for (i = 0; i < cfg->num_varinfo; i++) {
1266                 MonoMethodVar *info = MONO_VARINFO (cfg, i);
1267                 work_list = g_list_prepend_mempool (cfg->mempool, work_list, info);
1268         }
1269
1270         while (work_list) {
1271                 MonoMethodVar *info = (MonoMethodVar *)work_list->data;
1272                 work_list = g_list_remove_link (work_list, work_list);
1273
1274                 /* 
1275                  * The second part of the condition happens often when PHI nodes have their dreg
1276                  * as one of their arguments due to the fact that we use the original vars.
1277                  */
1278                 if (info->def && (!info->uses || ((info->uses->next == NULL) && (((MonoVarUsageInfo*)info->uses->data)->inst == info->def)))) {
1279                         MonoInst *def = info->def;
1280
1281                         /* Eliminating FMOVE could screw up the fp stack */
1282                         if (MONO_IS_MOVE (def) && (!MONO_ARCH_USE_FPSTACK || (def->opcode != OP_FMOVE))) {
1283                                 MonoInst *src_var = get_vreg_to_inst (cfg, def->sreg1);
1284                                 if (src_var && !(src_var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
1285                                         add_to_dce_worklist (cfg, info, MONO_VARINFO (cfg, src_var->inst_c0), &work_list);
1286                                 NULLIFY_INS (def);
1287                                 info->reg = -1;
1288                         } else if ((def->opcode == OP_ICONST) || (def->opcode == OP_I8CONST) || MONO_IS_ZERO (def)) {
1289                                 NULLIFY_INS (def);
1290                                 info->reg = -1;
1291                         } else if (MONO_IS_PHI (def)) {
1292                                 int j;
1293                                 for (j = def->inst_phi_args [0]; j > 0; j--) {
1294                                         MonoMethodVar *u = MONO_VARINFO (cfg, get_vreg_to_inst (cfg, def->inst_phi_args [j])->inst_c0);
1295                                         add_to_dce_worklist (cfg, info, u, &work_list);
1296                                 }
1297                                 NULLIFY_INS (def);
1298                                 info->reg = -1;
1299                         }
1300                         else if (def->opcode == OP_NOP) {
1301                         }
1302                         //else
1303                         //mono_print_ins (def);
1304                 }
1305
1306         }
1307 }
1308
1309 #if 0
1310 void
1311 mono_ssa_strength_reduction (MonoCompile *cfg)
1312 {
1313         MonoBasicBlock *bb;
1314         int i;
1315
1316         g_assert (cfg->comp_done & MONO_COMP_SSA);
1317         g_assert (cfg->comp_done & MONO_COMP_LOOPS);
1318         g_assert (cfg->comp_done & MONO_COMP_SSA_DEF_USE);
1319
1320         for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
1321                 GList *lp = bb->loop_blocks;
1322
1323                 if (lp) {
1324                         MonoBasicBlock *h = (MonoBasicBlock *)lp->data;
1325
1326                         /* we only consider loops with 2 in bblocks */
1327                         if (!h->in_count == 2)
1328                                 continue;
1329
1330                         for (i = 0; i < cfg->num_varinfo; i++) {
1331                                 MonoMethodVar *info = MONO_VARINFO (cfg, i);
1332                         
1333                                 if (info->def && info->def->ssa_op == MONO_SSA_STORE &&
1334                                     info->def->inst_i0->opcode == OP_LOCAL && g_list_find (lp, info->def_bb)) {
1335                                         MonoInst *v = info->def->inst_i1;
1336
1337
1338                                         printf ("FOUND %d in %s\n", info->idx, mono_method_full_name (cfg->method, TRUE));
1339                                 }
1340                         }
1341                 }
1342         }
1343 }
1344 #endif
1345
1346 void
1347 mono_ssa_loop_invariant_code_motion (MonoCompile *cfg)
1348 {
1349         MonoBasicBlock *bb, *h, *idom;
1350         MonoInst *ins, *n, *tins;
1351         int i;
1352
1353         g_assert (cfg->comp_done & MONO_COMP_SSA);
1354         if (!(cfg->comp_done & MONO_COMP_LOOPS) || !(cfg->comp_done & MONO_COMP_SSA_DEF_USE))
1355                 return;
1356
1357         for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
1358                 GList *lp = bb->loop_blocks;
1359
1360                 if (!lp)
1361                         continue;
1362                 h = (MonoBasicBlock *)lp->data;
1363                 if (bb != h)
1364                         continue;
1365                 MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) {
1366                         /*
1367                          * Try to move instructions out of loop headers into the preceeding bblock.
1368                          */
1369                         if (ins->opcode == OP_LDLEN || ins->opcode == OP_STRLEN || ins->opcode == OP_CHECK_THIS || ins->opcode == OP_AOTCONST || ins->opcode == OP_GENERIC_CLASS_INIT) {
1370                                 gboolean skip;
1371                                 int sreg;
1372
1373                                 idom = h->idom;
1374                                 /*
1375                                  * h->nesting is needed to work around:
1376                                  * http://llvm.org/bugs/show_bug.cgi?id=17868
1377                                  */
1378                                 if (!(idom && idom->last_ins && idom->last_ins->opcode == OP_BR && idom->last_ins->inst_target_bb == h && h->nesting == 1)) {
1379                                         continue;
1380                                 }
1381
1382                                 /*
1383                                  * Make sure there are no instructions with side effects before ins.
1384                                  */
1385                                 skip = FALSE;
1386                                 MONO_BB_FOR_EACH_INS (bb, tins) {
1387                                         if (tins == ins)
1388                                                 break;
1389                                         if (!MONO_INS_HAS_NO_SIDE_EFFECT (tins)) {
1390                                                 skip = TRUE;
1391                                                 break;
1392                                         }
1393                                 }
1394                                 if (skip) {
1395                                         /*
1396                                           printf ("%s\n", mono_method_full_name (cfg->method, TRUE));
1397                                           mono_print_ins (tins);
1398                                         */
1399                                         continue;
1400                                 }
1401
1402                                 /* Make sure we don't move the instruction before the def of its sreg */
1403                                 if (ins->opcode == OP_LDLEN || ins->opcode == OP_STRLEN || ins->opcode == OP_CHECK_THIS)
1404                                         sreg = ins->sreg1;
1405                                 else
1406                                         sreg = -1;
1407                                 if (sreg != -1) {
1408                                         MonoInst *tins, *var;
1409
1410                                         skip = FALSE;
1411                                         for (tins = ins->prev; tins; tins = tins->prev) {
1412                                                 const char *spec = INS_INFO (tins->opcode);
1413
1414                                                 if (tins->opcode == OP_MOVE && tins->dreg == sreg) {
1415                                                         sreg = tins->sreg1;
1416                                                 } if (spec [MONO_INST_DEST] != ' ' && tins->dreg == sreg) {
1417                                                         skip = TRUE;
1418                                                         break;
1419                                                 }
1420                                         }
1421                                         if (skip)
1422                                                 continue;
1423                                         var = get_vreg_to_inst (cfg, sreg);
1424                                         if (var && (var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)))
1425                                                 continue;
1426                                         ins->sreg1 = sreg;
1427                                 }
1428
1429                                 if (cfg->verbose_level > 1) {
1430                                         printf ("licm in BB%d on ", bb->block_num);
1431                                         mono_print_ins (ins);
1432                                 }
1433                                 //{ static int count = 0; count ++; printf ("%d\n", count); }
1434                                 MONO_REMOVE_INS (bb, ins);
1435                                 mono_bblock_insert_before_ins (idom, idom->last_ins, ins);
1436                                 if (ins->opcode == OP_LDLEN || ins->opcode == OP_STRLEN)
1437                                         idom->has_array_access = TRUE;
1438                         }
1439                 }
1440         }
1441
1442         cfg->comp_done &=  ~MONO_COMP_SSA_DEF_USE;
1443         for (i = 0; i < cfg->num_varinfo; i++) {
1444                 MonoMethodVar *info = MONO_VARINFO (cfg, i);
1445                 info->def = NULL;
1446                 info->uses = NULL;
1447         }
1448 }
1449
1450 #endif /* DISABLE_JIT */