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