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