Merge pull request #1222 from LogosBible/uri-trycreate
[mono.git] / mono / mini / liveness.c
1 /*
2  * liveness.c: liveness analysis
3  *
4  * Author:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *
7  * (C) 2002 Ximian, Inc.
8  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9  */
10
11 #include <config.h>
12
13 #ifndef DISABLE_JIT
14
15 #include "mini.h"
16
17 #define SPILL_COST_INCREMENT (1 << (bb->nesting << 1))
18
19 #define DEBUG_LIVENESS
20
21 #define BITS_PER_CHUNK MONO_BITSET_BITS_PER_CHUNK
22
23 #define BB_ID_SHIFT 18
24
25 /* 
26  * The liveness2 pass can't handle long vars on 32 bit platforms because the component
27  * vars have the same 'idx'.
28  */
29 #if SIZEOF_REGISTER == 8
30 #define ENABLE_LIVENESS2
31 #endif
32
33 #ifdef ENABLE_LIVENESS2
34 static void mono_analyze_liveness2 (MonoCompile *cfg);
35 #endif
36
37 static void
38 optimize_initlocals (MonoCompile *cfg);
39
40 /* mono_bitset_mp_new:
41  * 
42  * allocates a MonoBitSet inside a memory pool
43  */
44 static inline MonoBitSet* 
45 mono_bitset_mp_new (MonoMemPool *mp, guint32 size, guint32 max_size)
46 {
47         guint8 *mem = mono_mempool_alloc0 (mp, size);
48         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
49 }
50
51 static inline MonoBitSet* 
52 mono_bitset_mp_new_noinit (MonoMemPool *mp, guint32 size, guint32 max_size)
53 {
54         guint8 *mem = mono_mempool_alloc (mp, size);
55         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
56 }
57
58 G_GNUC_UNUSED static void
59 mono_bitset_print (MonoBitSet *set)
60 {
61         int i;
62         gboolean first = TRUE;
63
64         printf ("{");
65         for (i = 0; i < mono_bitset_size (set); i++) {
66
67                 if (mono_bitset_test (set, i)) {
68                         if (!first)
69                                 printf (", ");
70                         printf ("%d", i);
71                         first = FALSE;
72                 }
73         }
74         printf ("}\n");
75 }
76
77 static void
78 visit_bb (MonoCompile *cfg, MonoBasicBlock *bb, GSList **visited)
79 {
80         int i;
81         MonoInst *ins;
82
83         if (g_slist_find (*visited, bb))
84                 return;
85
86         for (ins = bb->code; ins; ins = ins->next) {
87                 const char *spec = INS_INFO (ins->opcode);
88                 int regtype, srcindex, sreg, num_sregs;
89                 int sregs [MONO_MAX_SRC_REGS];
90
91                 if (ins->opcode == OP_NOP)
92                         continue;
93
94                 /* DREG */
95                 regtype = spec [MONO_INST_DEST];
96                 g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
97                                 
98                 if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
99                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
100                         int idx = var->inst_c0;
101                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
102
103                         cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
104                         if (SIZEOF_REGISTER == 4 && (var->type == STACK_I8 || (var->type == STACK_R8 && COMPILE_SOFT_FLOAT (cfg)))) {
105                                 /* Make the component vregs volatile as well (#612206) */
106                                 get_vreg_to_inst (cfg, var->dreg + 1)->flags |= MONO_INST_VOLATILE;
107                                 get_vreg_to_inst (cfg, var->dreg + 2)->flags |= MONO_INST_VOLATILE;
108                         }
109                 }
110                         
111                 /* SREGS */
112                 num_sregs = mono_inst_get_src_registers (ins, sregs);
113                 for (srcindex = 0; srcindex < num_sregs; ++srcindex) {
114                         sreg = sregs [srcindex];
115
116                         g_assert (sreg != -1);
117                         if (get_vreg_to_inst (cfg, sreg)) {
118                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
119                                 int idx = var->inst_c0;
120                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
121
122                                 cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
123                                 if (SIZEOF_REGISTER == 4 && (var->type == STACK_I8 || (var->type == STACK_R8 && COMPILE_SOFT_FLOAT (cfg)))) {
124                                         /* Make the component vregs volatile as well (#612206) */
125                                         get_vreg_to_inst (cfg, var->dreg + 1)->flags |= MONO_INST_VOLATILE;
126                                         get_vreg_to_inst (cfg, var->dreg + 2)->flags |= MONO_INST_VOLATILE;
127                                 }
128                         }
129                 }
130         }
131
132         *visited = g_slist_append (*visited, bb);
133
134         /* 
135          * Need to visit all bblocks reachable from this one since they can be
136          * reached during exception handling.
137          */
138         for (i = 0; i < bb->out_count; ++i) {
139                 visit_bb (cfg, bb->out_bb [i], visited);
140         }
141 }
142
143 void
144 mono_liveness_handle_exception_clauses (MonoCompile *cfg)
145 {
146         MonoBasicBlock *bb;
147         GSList *visited = NULL;
148         MonoMethodHeader *header = cfg->header;
149         MonoExceptionClause *clause, *clause2;
150         int i, j;
151         gboolean *outer_try;
152
153         /* 
154          * Determine which clauses are outer try clauses, i.e. they are not contained in any
155          * other non-try clause.
156          */
157         outer_try = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * header->num_clauses);
158         for (i = 0; i < header->num_clauses; ++i)
159                 outer_try [i] = TRUE;
160         /* Iterate over the clauses backward, so outer clauses come first */
161         /* This avoids doing an O(2) search, since we can determine when inner clauses end */
162         for (i = header->num_clauses - 1; i >= 0; --i) {
163                 clause = &header->clauses [i];
164
165                 if (clause->flags != 0) {
166                         outer_try [i] = TRUE;
167                         /* Iterate over inner clauses */
168                         for (j = i - 1; j >= 0; --j) {
169                                 clause2 = &header->clauses [j];
170
171                                 if (clause2->flags == 0 && MONO_OFFSET_IN_HANDLER (clause, clause2->try_offset)) {
172                                         outer_try [j] = FALSE;
173                                         break;
174                                 }
175                                 if (clause2->try_offset < clause->try_offset)
176                                         /* End of inner clauses */
177                                         break;
178                         }
179                 }
180         }
181
182         /*
183          * Variables in exception handler register cannot be allocated to registers
184          * so make them volatile. See bug #42136. This will not be neccessary when
185          * the back ends could guarantee that the variables will be in the
186          * correct registers when a handler is called.
187          * This includes try blocks too, since a variable in a try block might be
188          * accessed after an exception handler has been run.
189          */
190         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
191
192                 if (bb->region == -1)
193                         continue;
194
195                 if (MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY) && outer_try [MONO_REGION_CLAUSE_INDEX (bb->region)])
196                         continue;
197
198                 if (cfg->verbose_level > 2)
199                         printf ("pessimize variables in bb %d.\n", bb->block_num);
200
201                 visit_bb (cfg, bb, &visited);
202         }
203         g_slist_free (visited);
204 }
205
206 static inline void
207 update_live_range (MonoMethodVar *var, int abs_pos)
208 {
209         if (var->range.first_use.abs_pos > abs_pos)
210                 var->range.first_use.abs_pos = abs_pos;
211
212         if (var->range.last_use.abs_pos < abs_pos)
213                 var->range.last_use.abs_pos = abs_pos;
214 }
215
216 static void
217 analyze_liveness_bb (MonoCompile *cfg, MonoBasicBlock *bb)
218 {
219         MonoInst *ins;
220         int sreg, inst_num;
221         MonoMethodVar *vars = cfg->vars;
222         guint32 abs_pos = (bb->dfn << BB_ID_SHIFT);
223         
224         /* Start inst_num from > 0, so last_use.abs_pos is only 0 for dead variables */
225         for (inst_num = 2, ins = bb->code; ins; ins = ins->next, inst_num += 2) {
226                 const char *spec = INS_INFO (ins->opcode);
227                 int num_sregs, i;
228                 int sregs [MONO_MAX_SRC_REGS];
229
230 #ifdef DEBUG_LIVENESS
231                 if (cfg->verbose_level > 1) {
232                         printf ("\t");
233                         mono_print_ins (ins);
234                 }
235 #endif
236
237                 if (ins->opcode == OP_NOP)
238                         continue;
239
240                 if (ins->opcode == OP_LDADDR) {
241                         MonoInst *var = ins->inst_p0;
242                         int idx = var->inst_c0;
243                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
244
245 #ifdef DEBUG_LIVENESS
246                         if (cfg->verbose_level > 1)
247                                 printf ("\tGEN: R%d(%d)\n", var->dreg, idx);
248 #endif
249                         update_live_range (&vars [idx], abs_pos + inst_num); 
250                         if (!mono_bitset_test_fast (bb->kill_set, idx))
251                                 mono_bitset_set_fast (bb->gen_set, idx);
252                         vi->spill_costs += SPILL_COST_INCREMENT;
253                 }                               
254
255                 /* SREGs must come first, so MOVE r <- r is handled correctly */
256                 num_sregs = mono_inst_get_src_registers (ins, sregs);
257                 for (i = 0; i < num_sregs; ++i) {
258                         sreg = sregs [i];
259                         if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
260                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
261                                 int idx = var->inst_c0;
262                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
263
264 #ifdef DEBUG_LIVENESS
265                                 if (cfg->verbose_level > 1)
266                                         printf ("\tGEN: R%d(%d)\n", sreg, idx);
267 #endif
268                                 update_live_range (&vars [idx], abs_pos + inst_num); 
269                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
270                                         mono_bitset_set_fast (bb->gen_set, idx);
271                                 vi->spill_costs += SPILL_COST_INCREMENT;
272                         }
273                 }
274
275                 /* DREG */
276                 if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
277                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
278                         int idx = var->inst_c0;
279                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
280
281                         if (MONO_IS_STORE_MEMBASE (ins)) {
282                                 update_live_range (&vars [idx], abs_pos + inst_num); 
283                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
284                                         mono_bitset_set_fast (bb->gen_set, idx);
285                                 vi->spill_costs += SPILL_COST_INCREMENT;
286                         } else {
287 #ifdef DEBUG_LIVENESS
288                                 if (cfg->verbose_level > 1)
289                                         printf ("\tKILL: R%d(%d)\n", ins->dreg, idx);
290 #endif
291                                 update_live_range (&vars [idx], abs_pos + inst_num + 1); 
292                                 mono_bitset_set_fast (bb->kill_set, idx);
293                                 vi->spill_costs += SPILL_COST_INCREMENT;
294                         }
295                 }
296         }
297 }
298
299 /* generic liveness analysis code. CFG specific parts are 
300  * in update_gen_kill_set()
301  */
302 void
303 mono_analyze_liveness (MonoCompile *cfg)
304 {
305         MonoBitSet *old_live_out_set;
306         int i, j, max_vars = cfg->num_varinfo;
307         int out_iter;
308         gboolean *in_worklist;
309         MonoBasicBlock **worklist;
310         guint32 l_end;
311         int bitsize;
312
313 #ifdef DEBUG_LIVENESS
314         if (cfg->verbose_level > 1)
315                 printf ("\nLIVENESS:\n");
316 #endif
317
318         g_assert (!(cfg->comp_done & MONO_COMP_LIVENESS));
319
320         cfg->comp_done |= MONO_COMP_LIVENESS;
321         
322         if (max_vars == 0)
323                 return;
324
325         bitsize = mono_bitset_alloc_size (max_vars, 0);
326
327         for (i = 0; i < max_vars; i ++) {
328                 MONO_VARINFO (cfg, i)->range.first_use.abs_pos = ~ 0;
329                 MONO_VARINFO (cfg, i)->range.last_use .abs_pos =   0;
330                 MONO_VARINFO (cfg, i)->spill_costs = 0;
331         }
332
333         for (i = 0; i < cfg->num_bblocks; ++i) {
334                 MonoBasicBlock *bb = cfg->bblocks [i];
335
336                 bb->gen_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
337                 bb->kill_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
338
339 #ifdef DEBUG_LIVENESS
340                 if (cfg->verbose_level > 1) {
341                         printf ("BLOCK BB%d (", bb->block_num);
342                         for (j = 0; j < bb->out_count; j++) 
343                                 printf ("BB%d, ", bb->out_bb [j]->block_num);
344                 
345                         printf ("):\n");
346                 }
347 #endif
348
349                 analyze_liveness_bb (cfg, bb);
350
351 #ifdef DEBUG_LIVENESS
352                 if (cfg->verbose_level > 1) {
353                         printf ("GEN  BB%d: ", bb->block_num); mono_bitset_print (bb->gen_set);
354                         printf ("KILL BB%d: ", bb->block_num); mono_bitset_print (bb->kill_set);
355                 }
356 #endif
357         }
358
359         old_live_out_set = mono_bitset_new (max_vars, 0);
360         in_worklist = g_new0 (gboolean, cfg->num_bblocks + 1);
361
362         worklist = g_new (MonoBasicBlock *, cfg->num_bblocks + 1);
363         l_end = 0;
364
365         /*
366          * This is a backward dataflow analysis problem, so we process blocks in
367          * decreasing dfn order, this speeds up the iteration.
368          */
369         for (i = 0; i < cfg->num_bblocks; i ++) {
370                 MonoBasicBlock *bb = cfg->bblocks [i];
371
372                 worklist [l_end ++] = bb;
373                 in_worklist [bb->dfn] = TRUE;
374
375                 /* Initialized later */
376                 bb->live_in_set = NULL;
377                 bb->live_out_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
378         }
379
380         out_iter = 0;
381
382         if (cfg->verbose_level > 1)
383                 printf ("\nITERATION:\n");
384
385         while (l_end != 0) {
386                 MonoBasicBlock *bb = worklist [--l_end];
387                 MonoBasicBlock *out_bb;
388                 gboolean changed;
389
390                 in_worklist [bb->dfn] = FALSE;
391
392 #ifdef DEBUG_LIVENESS
393                 if (cfg->verbose_level > 1) {
394                         printf ("P: BB%d(%d): IN: ", bb->block_num, bb->dfn);
395                         for (j = 0; j < bb->in_count; ++j) 
396                                 printf ("BB%d ", bb->in_bb [j]->block_num);
397                         printf ("OUT:");
398                         for (j = 0; j < bb->out_count; ++j) 
399                                 printf ("BB%d ", bb->out_bb [j]->block_num);
400                         printf ("\n");
401                 }
402 #endif
403
404
405                 if (bb->out_count == 0)
406                         continue;
407
408                 out_iter ++;
409
410                 if (!bb->live_in_set) {
411                         /* First pass over this bblock */
412                         changed = TRUE;
413                 }
414                 else {
415                         changed = FALSE;
416                         mono_bitset_copyto_fast (bb->live_out_set, old_live_out_set);
417                 }
418  
419                 for (j = 0; j < bb->out_count; j++) {
420                         out_bb = bb->out_bb [j];
421
422                         if (!out_bb->live_in_set) {
423                                 out_bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
424
425                                 mono_bitset_copyto_fast (out_bb->live_out_set, out_bb->live_in_set);
426                                 mono_bitset_sub_fast (out_bb->live_in_set, out_bb->kill_set);
427                                 mono_bitset_union_fast (out_bb->live_in_set, out_bb->gen_set);
428                         }
429
430                         // FIXME: Do this somewhere else
431                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
432                         } else {
433                                 mono_bitset_union_fast (bb->live_out_set, out_bb->live_in_set);
434                         }
435                 }
436                                 
437                 if (changed || !mono_bitset_equal (old_live_out_set, bb->live_out_set)) {
438                         if (!bb->live_in_set)
439                                 bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
440                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
441                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
442                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
443
444                         for (j = 0; j < bb->in_count; j++) {
445                                 MonoBasicBlock *in_bb = bb->in_bb [j];
446                                 /* 
447                                  * Some basic blocks do not seem to be in the 
448                                  * cfg->bblocks array...
449                                  */
450                                 if (in_bb->gen_set && !in_worklist [in_bb->dfn]) {
451 #ifdef DEBUG_LIVENESS
452                                         if (cfg->verbose_level > 1)
453                                                 printf ("\tADD: %d\n", in_bb->block_num);
454 #endif
455                                         /*
456                                          * Put the block at the top of the stack, so it
457                                          * will be processed right away.
458                                          */
459                                         worklist [l_end ++] = in_bb;
460                                         in_worklist [in_bb->dfn] = TRUE;
461                                 }
462                         }
463                 }
464
465                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
466                         printf ("\tLIVE IN  BB%d: ", bb->block_num); 
467                         mono_bitset_print (bb->live_in_set); 
468                 }                       
469         }
470
471 #ifdef DEBUG_LIVENESS
472         if (cfg->verbose_level > 1)
473                 printf ("IT: %d %d.\n", cfg->num_bblocks, out_iter);
474 #endif
475
476         mono_bitset_free (old_live_out_set);
477
478         g_free (worklist);
479         g_free (in_worklist);
480
481         /* Compute live_in_set for bblocks skipped earlier */
482         for (i = 0; i < cfg->num_bblocks; ++i) {
483                 MonoBasicBlock *bb = cfg->bblocks [i];
484
485                 if (!bb->live_in_set) {
486                         bb->live_in_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
487
488                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
489                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
490                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
491                 }
492         }
493
494         for (i = 0; i < cfg->num_bblocks; ++i) {
495                 MonoBasicBlock *bb = cfg->bblocks [i];
496                 guint32 max;
497                 guint32 abs_pos = (bb->dfn << BB_ID_SHIFT);
498                 MonoMethodVar *vars = cfg->vars;
499
500                 if (!bb->live_out_set)
501                         continue;
502
503                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
504                 for (j = 0; j < max; ++j) {
505                         gsize bits_in;
506                         gsize bits_out;
507                         int k;
508
509                         bits_in = mono_bitset_get_fast (bb->live_in_set, j);
510                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
511
512                         k = (j * BITS_PER_CHUNK);
513                         while ((bits_in || bits_out)) {
514                                 if (bits_in & 1)
515                                         update_live_range (&vars [k], abs_pos + 0);
516                                 if (bits_out & 1)
517                                         update_live_range (&vars [k], abs_pos + ((1 << BB_ID_SHIFT) - 1));
518                                 bits_in >>= 1;
519                                 bits_out >>= 1;
520                                 k ++;
521                         }
522                 }
523         }
524
525         /*
526          * Arguments need to have their live ranges extended to the beginning of
527          * the method to account for the arg reg/memory -> global register copies
528          * in the prolog (bug #74992).
529          */
530
531         for (i = 0; i < max_vars; i ++) {
532                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
533                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG) {
534                         if (vi->range.last_use.abs_pos == 0 && !(cfg->varinfo [vi->idx]->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
535                                 /* 
536                                  * Can't eliminate the this variable in gshared code, since
537                                  * it is needed during exception handling to identify the
538                                  * method.
539                                  * It is better to check for this here instead of marking the variable
540                                  * VOLATILE, since that would prevent it from being allocated to
541                                  * registers.
542                                  */
543                                  if (!cfg->disable_deadce_vars && !(cfg->generic_sharing_context && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
544                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
545                         }
546                         vi->range.first_use.abs_pos = 0;
547                 }
548         }
549
550 #ifdef DEBUG_LIVENESS
551         if (cfg->verbose_level > 1) {
552                 for (i = cfg->num_bblocks - 1; i >= 0; i--) {
553                         MonoBasicBlock *bb = cfg->bblocks [i];
554                 
555                         printf ("LIVE IN  BB%d: ", bb->block_num); 
556                         mono_bitset_print (bb->live_in_set); 
557                         printf ("LIVE OUT BB%d: ", bb->block_num); 
558                         mono_bitset_print (bb->live_out_set); 
559                 }
560
561                 for (i = 0; i < max_vars; i ++) {
562                         MonoMethodVar *vi = MONO_VARINFO (cfg, i);
563
564                         printf ("V%d: [0x%x - 0x%x]\n", i, vi->range.first_use.abs_pos, vi->range.last_use.abs_pos);
565                 }
566         }
567 #endif
568
569         if (!cfg->disable_initlocals_opt)
570                 optimize_initlocals (cfg);
571
572 #ifdef ENABLE_LIVENESS2
573         /* This improves code size by about 5% but slows down compilation too much */
574         if (cfg->compile_aot)
575                 mono_analyze_liveness2 (cfg);
576 #endif
577 }
578
579 /**
580  * optimize_initlocals:
581  *
582  * Try to optimize away some of the redundant initialization code inserted because of
583  * 'locals init' using the liveness information.
584  */
585 static void
586 optimize_initlocals (MonoCompile *cfg)
587 {
588         MonoBitSet *used;
589         MonoInst *ins;
590         MonoBasicBlock *initlocals_bb;
591
592         used = mono_bitset_new (cfg->next_vreg + 1, 0);
593
594         mono_bitset_clear_all (used);
595         initlocals_bb = cfg->bb_entry->next_bb;
596         for (ins = initlocals_bb->code; ins; ins = ins->next) {
597                 int num_sregs, i;
598                 int sregs [MONO_MAX_SRC_REGS];
599
600                 num_sregs = mono_inst_get_src_registers (ins, sregs);
601                 for (i = 0; i < num_sregs; ++i)
602                         mono_bitset_set_fast (used, sregs [i]);
603
604                 if (MONO_IS_STORE_MEMBASE (ins))
605                         mono_bitset_set_fast (used, ins->dreg);
606         }
607
608         for (ins = initlocals_bb->code; ins; ins = ins->next) {
609                 const char *spec = INS_INFO (ins->opcode);
610
611                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
612                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
613                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
614
615                         if (var && !mono_bitset_test_fast (used, ins->dreg) && !mono_bitset_test_fast (initlocals_bb->live_out_set, var->inst_c0) && (var != cfg->ret) && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
616                                 //printf ("DEAD: "); mono_print_ins (ins);
617                                 if (cfg->disable_initlocals_opt_refs && var->type == STACK_OBJ)
618                                         continue;
619                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST) || (ins->opcode == OP_R4CONST)) {
620                                         NULLIFY_INS (ins);
621                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
622                                         /* 
623                                          * We should shorten the liveness interval of these vars as well, but
624                                          * don't have enough info to do that.
625                                          */
626                                 }
627                         }
628                 }
629         }
630
631         g_free (used);
632 }
633
634 void
635 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
636 {
637         MonoLiveRange2 *prev_range, *next_range, *new_range;
638
639         g_assert (to >= from);
640
641         /* Optimize for extending the first interval backwards */
642         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
643                 interval->range->from = from;
644                 return;
645         }
646
647         /* Find a place in the list for the new range */
648         prev_range = NULL;
649         next_range = interval->range;
650         while ((next_range != NULL) && (next_range->from <= from)) {
651                 prev_range = next_range;
652                 next_range = next_range->next;
653         }
654
655         if (prev_range && prev_range->to == from) {
656                 /* Merge with previous */
657                 prev_range->to = to;
658         } else if (next_range && next_range->from == to) {
659                 /* Merge with previous */
660                 next_range->from = from;
661         } else {
662                 /* Insert it */
663                 new_range = mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
664                 new_range->from = from;
665                 new_range->to = to;
666                 new_range->next = NULL;
667
668                 if (prev_range)
669                         prev_range->next = new_range;
670                 else
671                         interval->range = new_range;
672                 if (next_range)
673                         new_range->next = next_range;
674                 else
675                         interval->last_range = new_range;
676         }
677
678         /* FIXME: Merge intersecting ranges */
679 }
680
681 void
682 mono_linterval_print (MonoLiveInterval *interval)
683 {
684         MonoLiveRange2 *range;
685
686         for (range = interval->range; range != NULL; range = range->next)
687                 printf ("[%x-%x] ", range->from, range->to);
688 }
689
690 void
691 mono_linterval_print_nl (MonoLiveInterval *interval)
692 {
693         mono_linterval_print (interval);
694         printf ("\n");
695 }
696
697 /**
698  * mono_linterval_convers:
699  *
700  *   Return whenever INTERVAL covers the position POS.
701  */
702 gboolean
703 mono_linterval_covers (MonoLiveInterval *interval, int pos)
704 {
705         MonoLiveRange2 *range;
706
707         for (range = interval->range; range != NULL; range = range->next) {
708                 if (pos >= range->from && pos <= range->to)
709                         return TRUE;
710                 if (range->from > pos)
711                         return FALSE;
712         }
713
714         return FALSE;
715 }
716
717 /**
718  * mono_linterval_get_intersect_pos:
719  *
720  *   Determine whenever I1 and I2 intersect, and if they do, return the first
721  * point of intersection. Otherwise, return -1.
722  */
723 gint32
724 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
725 {
726         MonoLiveRange2 *r1, *r2;
727
728         /* FIXME: Optimize this */
729         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
730                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
731                         if (r2->to > r1->from && r2->from < r1->to) {
732                                 if (r2->from <= r1->from)
733                                         return r1->from;
734                                 else
735                                         return r2->from;
736                         }
737                 }
738         }
739
740         return -1;
741 }
742  
743 /**
744  * mono_linterval_split
745  *
746  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
747  * part of L2.
748  */
749 void
750 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
751 {
752         MonoLiveRange2 *r;
753
754         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
755
756         *i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
757         *i2 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
758
759         for (r = interval->range; r; r = r->next) {
760                 if (pos > r->to) {
761                         /* Add it to the first child */
762                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
763                 } else if (pos > r->from && pos <= r->to) {
764                         /* Split at pos */
765                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
766                         mono_linterval_add_range (cfg, *i2, pos, r->to);
767                 } else {
768                         /* Add it to the second child */
769                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
770                 }
771         }
772 }
773
774 #if 1
775 #define LIVENESS_DEBUG(a) do { if (cfg->verbose_level > 1) do { a; } while (0); } while (0)
776 #define ENABLE_LIVENESS_DEBUG 1
777 #else
778 #define LIVENESS_DEBUG(a)
779 #endif
780
781 #ifdef ENABLE_LIVENESS2
782
783 static inline void
784 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
785 {
786         const char *spec = INS_INFO (ins->opcode);
787         int sreg;
788         int num_sregs, i;
789         int sregs [MONO_MAX_SRC_REGS];
790
791         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
792
793         if (ins->opcode == OP_NOP || ins->opcode == OP_IL_SEQ_POINT)
794                 return;
795
796         /* DREG */
797         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
798                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
799                 int idx = var->inst_c0;
800                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
801
802                 if (MONO_IS_STORE_MEMBASE (ins)) {
803                         if (last_use [idx] == 0) {
804                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
805                                 last_use [idx] = inst_num;
806                         }
807                 } else {
808                         if (last_use [idx] > 0) {
809                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
810                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
811                                 last_use [idx] = 0;
812                         }
813                         else {
814                                 /* Try dead code elimination */
815                                 if (!cfg->disable_deadce_vars && (var != cfg->ret) && !(var->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT)) && ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) && !(var->flags & MONO_INST_VOLATILE)) {
816                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
817                                         NULLIFY_INS (ins);
818                                         return;
819                                 } else {
820                                         int inst_num_add = 1;
821                                         MonoInst *next = ins->next;
822                                         while (next && next->opcode == OP_IL_SEQ_POINT) {
823                                                 inst_num_add++;
824                                                 next = next->next;
825                                         }
826
827                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, add range to R%d: [%x, %x]\n", ins->dreg, ins->dreg, inst_num, inst_num + inst_num_add));
828                                         mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + inst_num_add);
829                                 }
830                         }
831                 }
832         }
833
834         /* SREGs */
835         num_sregs = mono_inst_get_src_registers (ins, sregs);
836         for (i = 0; i < num_sregs; ++i) {
837                 sreg = sregs [i];
838                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
839                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
840                         int idx = var->inst_c0;
841
842                         if (last_use [idx] == 0) {
843                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
844                                 last_use [idx] = inst_num;
845                         }
846                 }
847         }
848 }
849
850 static void
851 mono_analyze_liveness2 (MonoCompile *cfg)
852 {
853         int bnum, idx, i, j, nins, max, max_vars, block_from, block_to, pos, reverse_len;
854         gint32 *last_use;
855         static guint32 disabled = -1;
856         MonoInst **reverse;
857
858         if (disabled == -1)
859                 disabled = g_getenv ("DISABLED") != NULL;
860
861         if (disabled)
862                 return;
863
864         if (cfg->num_bblocks >= (1 << (32 - BB_ID_SHIFT - 1)))
865                 /* Ranges would overflow */
866                 return;
867
868         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
869                 MonoBasicBlock *bb = cfg->bblocks [bnum];
870                 MonoInst *ins;
871
872                 nins = 0;
873                 for (nins = 0, ins = bb->code; ins; ins = ins->next, ++nins)
874                         nins ++;
875
876                 if (nins >= ((1 << BB_ID_SHIFT) - 1))
877                         /* Ranges would overflow */
878                         return;
879         }
880
881         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
882
883         /*
884         if (strstr (cfg->method->name, "test_") != cfg->method->name)
885                 return;
886         */
887
888         max_vars = cfg->num_varinfo;
889         last_use = g_new0 (gint32, max_vars);
890
891         reverse_len = 1024;
892         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
893
894         for (idx = 0; idx < max_vars; ++idx) {
895                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
896
897                 vi->interval = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
898         }
899
900         /*
901          * Process bblocks in reverse order, so the addition of new live ranges
902          * to the intervals is faster.
903          */
904         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
905                 MonoBasicBlock *bb = cfg->bblocks [bnum];
906                 MonoInst *ins;
907
908                 block_from = (bb->dfn << BB_ID_SHIFT) + 1; /* so pos > 0 */
909                 if (bnum < cfg->num_bblocks - 1)
910                         /* Beginning of the next bblock */
911                         block_to = (cfg->bblocks [bnum + 1]->dfn << BB_ID_SHIFT) + 1;
912                 else
913                         block_to = (bb->dfn << BB_ID_SHIFT) + ((1 << BB_ID_SHIFT) - 1);
914
915                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
916
917                 memset (last_use, 0, max_vars * sizeof (gint32));
918                 
919                 /* For variables in bb->live_out, set last_use to block_to */
920
921                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
922                 for (j = 0; j < max; ++j) {
923                         gsize bits_out;
924                         int k;
925
926                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
927                         k = (j * BITS_PER_CHUNK);       
928                         while (bits_out) {
929                                 if (bits_out & 1) {
930                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
931                                         last_use [k] = block_to;
932                                 }
933                                 bits_out >>= 1;
934                                 k ++;
935                         }
936                 }
937
938                 if (cfg->ret)
939                         last_use [cfg->ret->inst_c0] = block_to;
940
941                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
942                         if (nins >= reverse_len) {
943                                 int new_reverse_len = reverse_len * 2;
944                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
945                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
946                                 reverse = new_reverse;
947                                 reverse_len = new_reverse_len;
948                         }
949
950                         reverse [nins] = ins;
951                 }
952
953                 /* Process instructions backwards */
954                 for (i = nins - 1; i >= 0; --i) {
955                         MonoInst *ins = (MonoInst*)reverse [i];
956
957                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
958
959                         pos --;
960                 }
961
962                 for (idx = 0; idx < max_vars; ++idx) {
963                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
964
965                         if (last_use [idx] != 0) {
966                                 /* Live at exit, not written -> live on enter */
967                                 LIVENESS_DEBUG (printf ("Var R%d live at enter, add range to R%d: [%x, %x)\n", cfg->varinfo [idx]->dreg, cfg->varinfo [idx]->dreg, block_from, last_use [idx]));
968                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
969                         }
970                 }
971         }
972
973         /*
974          * Arguments need to have their live ranges extended to the beginning of
975          * the method to account for the arg reg/memory -> global register copies
976          * in the prolog (bug #74992).
977          */
978         for (i = 0; i < max_vars; i ++) {
979                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
980                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
981                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
982         }
983
984 #if 0
985         for (idx = 0; idx < max_vars; ++idx) {
986                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
987                 
988                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
989                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
990                 LIVENESS_DEBUG (printf ("\n"));
991         }
992 #endif
993
994         g_free (last_use);
995 }
996
997 #endif
998
999 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
1000
1001 static inline void
1002 update_liveness_gc (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, gint32 *last_use, MonoMethodVar **vreg_to_varinfo, GSList **callsites)
1003 {
1004         if (ins->opcode == OP_GC_LIVENESS_DEF || ins->opcode == OP_GC_LIVENESS_USE) {
1005                 int vreg = ins->inst_c1;
1006                 MonoMethodVar *vi = vreg_to_varinfo [vreg];
1007                 int idx = vi->idx;
1008                 int pc_offset = ins->backend.pc_offset;
1009
1010                 LIVENESS_DEBUG (printf ("\t%x: ", pc_offset); mono_print_ins (ins));
1011
1012                 if (ins->opcode == OP_GC_LIVENESS_DEF) {
1013                         if (last_use [idx] > 0) {
1014                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", vreg, pc_offset, last_use [idx]));
1015                                 last_use [idx] = 0;
1016                         }
1017                 } else {
1018                         if (last_use [idx] == 0) {
1019                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", vreg, pc_offset));
1020                                 last_use [idx] = pc_offset;
1021                         }
1022                 }
1023         } else if (ins->opcode == OP_GC_PARAM_SLOT_LIVENESS_DEF) {
1024                 GCCallSite *last;
1025
1026                 /* Add it to the last callsite */
1027                 g_assert (*callsites);
1028                 last = (*callsites)->data;
1029                 last->param_slots = g_slist_prepend_mempool (cfg->mempool, last->param_slots, ins);
1030         } else if (ins->flags & MONO_INST_GC_CALLSITE) {
1031                 GCCallSite *callsite = mono_mempool_alloc0 (cfg->mempool, sizeof (GCCallSite));
1032                 int i;
1033
1034                 LIVENESS_DEBUG (printf ("\t%x: ", ins->backend.pc_offset); mono_print_ins (ins));
1035                 LIVENESS_DEBUG (printf ("\t\tlive: "));
1036
1037                 callsite->bb = bb;
1038                 callsite->liveness = mono_mempool_alloc0 (cfg->mempool, ALIGN_TO (cfg->num_varinfo, 8) / 8);
1039                 callsite->pc_offset = ins->backend.pc_offset;
1040                 for (i = 0; i < cfg->num_varinfo; ++i) {
1041                         if (last_use [i] != 0) {
1042                                 LIVENESS_DEBUG (printf ("R%d", MONO_VARINFO (cfg, i)->vreg));
1043                                 callsite->liveness [i / 8] |= (1 << (i % 8));
1044                         }
1045                 }
1046                 LIVENESS_DEBUG (printf ("\n"));
1047                 *callsites = g_slist_prepend_mempool (cfg->mempool, *callsites, callsite);
1048         }
1049 }
1050
1051 static inline int
1052 get_vreg_from_var (MonoCompile *cfg, MonoInst *var)
1053 {
1054         if (var->opcode == OP_REGVAR)
1055                 /* dreg contains a hreg, but inst_c0 still contains the var index */
1056                 return MONO_VARINFO (cfg, var->inst_c0)->vreg;
1057         else
1058                 /* dreg still contains the vreg */
1059                 return var->dreg;
1060 }
1061
1062 /*
1063  * mono_analyze_liveness_gc:
1064  *
1065  *   Compute liveness bitmaps for each call site.
1066  * This function is a modified version of mono_analyze_liveness2 ().
1067  */
1068 void
1069 mono_analyze_liveness_gc (MonoCompile *cfg)
1070 {
1071         int idx, i, j, nins, max, max_vars, block_from, block_to, pos, reverse_len;
1072         gint32 *last_use;
1073         MonoInst **reverse;
1074         MonoMethodVar **vreg_to_varinfo = NULL;
1075         MonoBasicBlock *bb;
1076         GSList *callsites;
1077
1078         LIVENESS_DEBUG (printf ("\n------------ GC LIVENESS: ----------\n"));
1079
1080         max_vars = cfg->num_varinfo;
1081         last_use = g_new0 (gint32, max_vars);
1082
1083         /*
1084          * var->inst_c0 no longer contains the variable index, so compute a mapping now.
1085          */
1086         vreg_to_varinfo = g_new0 (MonoMethodVar*, cfg->next_vreg);
1087         for (idx = 0; idx < max_vars; ++idx) {
1088                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
1089
1090                 vreg_to_varinfo [vi->vreg] = vi;
1091         }
1092
1093         reverse_len = 1024;
1094         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
1095
1096         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1097                 MonoInst *ins;
1098
1099                 block_from = bb->real_native_offset;
1100                 block_to = bb->native_offset + bb->native_length;
1101
1102                 LIVENESS_DEBUG (printf ("GC LIVENESS BB%d:\n", bb->block_num));
1103
1104                 if (!bb->code)
1105                         continue;
1106
1107                 memset (last_use, 0, max_vars * sizeof (gint32));
1108                 
1109                 /* For variables in bb->live_out, set last_use to block_to */
1110
1111                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
1112                 for (j = 0; j < max; ++j) {
1113                         gsize bits_out;
1114                         int k;
1115
1116                         if (!bb->live_out_set)
1117                                 /* The variables used in this bblock are volatile anyway */
1118                                 continue;
1119
1120                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
1121                         k = (j * BITS_PER_CHUNK);       
1122                         while (bits_out) {
1123                                 if ((bits_out & 1) && cfg->varinfo [k]->flags & MONO_INST_GC_TRACK) {
1124                                         int vreg = get_vreg_from_var (cfg, cfg->varinfo [k]);
1125                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, last_use set to %x.\n", vreg, block_to));
1126                                         last_use [k] = block_to;
1127                                 }
1128                                 bits_out >>= 1;
1129                                 k ++;
1130                         }
1131                 }
1132
1133                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
1134                         if (nins >= reverse_len) {
1135                                 int new_reverse_len = reverse_len * 2;
1136                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
1137                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
1138                                 reverse = new_reverse;
1139                                 reverse_len = new_reverse_len;
1140                         }
1141
1142                         reverse [nins] = ins;
1143                 }
1144
1145                 /* Process instructions backwards */
1146                 callsites = NULL;
1147                 for (i = nins - 1; i >= 0; --i) {
1148                         MonoInst *ins = (MonoInst*)reverse [i];
1149
1150                         update_liveness_gc (cfg, bb, ins, last_use, vreg_to_varinfo, &callsites);
1151                 }
1152                 /* The callsites should already be sorted by pc offset because we added them backwards */
1153                 bb->gc_callsites = callsites;
1154         }
1155
1156         g_free (last_use);
1157         g_free (vreg_to_varinfo);
1158 }
1159
1160 #endif /* DISABLE_JIT */