Merge branch 'sgen-disable-gc'
[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 rem, max;
450                 guint32 abs_pos = (bb->dfn << 16);
451                 MonoMethodVar *vars = cfg->vars;
452
453                 if (!bb->live_out_set)
454                         continue;
455
456                 rem = max_vars % BITS_PER_CHUNK;
457                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
458                 for (j = 0; j < max; ++j) {
459                         gsize bits_in;
460                         gsize bits_out;
461                         int k;
462
463                         bits_in = mono_bitset_get_fast (bb->live_in_set, j);
464                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
465
466                         k = (j * BITS_PER_CHUNK);
467                         while ((bits_in || bits_out)) {
468                                 if (bits_in & 1)
469                                         update_live_range (&vars [k], abs_pos + 0);
470                                 if (bits_out & 1)
471                                         update_live_range (&vars [k], abs_pos + 0xffff);
472                                 bits_in >>= 1;
473                                 bits_out >>= 1;
474                                 k ++;
475                         }
476                 }
477         }
478
479         /*
480          * Arguments need to have their live ranges extended to the beginning of
481          * the method to account for the arg reg/memory -> global register copies
482          * in the prolog (bug #74992).
483          */
484
485         for (i = 0; i < max_vars; i ++) {
486                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
487                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG) {
488                         if (vi->range.last_use.abs_pos == 0 && !(cfg->varinfo [vi->idx]->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
489                                 /* 
490                                  * Can't eliminate the this variable in gshared code, since
491                                  * it is needed during exception handling to identify the
492                                  * method.
493                                  * It is better to check for this here instead of marking the variable
494                                  * VOLATILE, since that would prevent it from being allocated to
495                                  * registers.
496                                  */
497                                  if (!cfg->disable_deadce_vars && !(cfg->generic_sharing_context && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
498                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
499                         }
500                         vi->range.first_use.abs_pos = 0;
501                 }
502         }
503
504 #ifdef DEBUG_LIVENESS
505         if (cfg->verbose_level > 1) {
506                 for (i = cfg->num_bblocks - 1; i >= 0; i--) {
507                         MonoBasicBlock *bb = cfg->bblocks [i];
508                 
509                         printf ("LIVE IN  BB%d: ", bb->block_num); 
510                         mono_bitset_print (bb->live_in_set); 
511                         printf ("LIVE OUT BB%d: ", bb->block_num); 
512                         mono_bitset_print (bb->live_out_set); 
513                 }
514
515                 for (i = 0; i < max_vars; i ++) {
516                         MonoMethodVar *vi = MONO_VARINFO (cfg, i);
517
518                         printf ("V%d: [0x%x - 0x%x]\n", i, vi->range.first_use.abs_pos, vi->range.last_use.abs_pos);
519                 }
520         }
521 #endif
522
523         if (!cfg->disable_initlocals_opt)
524                 optimize_initlocals (cfg);
525
526 #ifdef ENABLE_LIVENESS2
527         /* This improves code size by about 5% but slows down compilation too much */
528         if (cfg->compile_aot)
529                 mono_analyze_liveness2 (cfg);
530 #endif
531 }
532
533 /**
534  * optimize_initlocals:
535  *
536  * Try to optimize away some of the redundant initialization code inserted because of
537  * 'locals init' using the liveness information.
538  */
539 static void
540 optimize_initlocals (MonoCompile *cfg)
541 {
542         MonoBitSet *used;
543         MonoInst *ins;
544         MonoBasicBlock *initlocals_bb;
545
546         used = mono_bitset_new (cfg->next_vreg + 1, 0);
547
548         mono_bitset_clear_all (used);
549         initlocals_bb = cfg->bb_entry->next_bb;
550         for (ins = initlocals_bb->code; ins; ins = ins->next) {
551                 int num_sregs, i;
552                 int sregs [MONO_MAX_SRC_REGS];
553
554                 num_sregs = mono_inst_get_src_registers (ins, sregs);
555                 for (i = 0; i < num_sregs; ++i)
556                         mono_bitset_set_fast (used, sregs [i]);
557
558                 if (MONO_IS_STORE_MEMBASE (ins))
559                         mono_bitset_set_fast (used, ins->dreg);
560         }
561
562         for (ins = initlocals_bb->code; ins; ins = ins->next) {
563                 const char *spec = INS_INFO (ins->opcode);
564
565                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
566                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
567                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
568
569                         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))) {
570                                 //printf ("DEAD: "); mono_print_ins (ins);
571                                 if (cfg->disable_initlocals_opt_refs && var->type == STACK_OBJ)
572                                         continue;
573                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) {
574                                         NULLIFY_INS (ins);
575                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
576                                         /* 
577                                          * We should shorten the liveness interval of these vars as well, but
578                                          * don't have enough info to do that.
579                                          */
580                                 }
581                         }
582                 }
583         }
584
585         g_free (used);
586 }
587
588 void
589 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
590 {
591         MonoLiveRange2 *prev_range, *next_range, *new_range;
592
593         g_assert (to >= from);
594
595         /* Optimize for extending the first interval backwards */
596         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
597                 interval->range->from = from;
598                 return;
599         }
600
601         /* Find a place in the list for the new range */
602         prev_range = NULL;
603         next_range = interval->range;
604         while ((next_range != NULL) && (next_range->from <= from)) {
605                 prev_range = next_range;
606                 next_range = next_range->next;
607         }
608
609         if (prev_range && prev_range->to == from) {
610                 /* Merge with previous */
611                 prev_range->to = to;
612         } else if (next_range && next_range->from == to) {
613                 /* Merge with previous */
614                 next_range->from = from;
615         } else {
616                 /* Insert it */
617                 new_range = mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
618                 new_range->from = from;
619                 new_range->to = to;
620                 new_range->next = NULL;
621
622                 if (prev_range)
623                         prev_range->next = new_range;
624                 else
625                         interval->range = new_range;
626                 if (next_range)
627                         new_range->next = next_range;
628                 else
629                         interval->last_range = new_range;
630         }
631
632         /* FIXME: Merge intersecting ranges */
633 }
634
635 void
636 mono_linterval_print (MonoLiveInterval *interval)
637 {
638         MonoLiveRange2 *range;
639
640         for (range = interval->range; range != NULL; range = range->next)
641                 printf ("[%x-%x] ", range->from, range->to);
642 }
643
644 void
645 mono_linterval_print_nl (MonoLiveInterval *interval)
646 {
647         mono_linterval_print (interval);
648         printf ("\n");
649 }
650
651 /**
652  * mono_linterval_convers:
653  *
654  *   Return whenever INTERVAL covers the position POS.
655  */
656 gboolean
657 mono_linterval_covers (MonoLiveInterval *interval, int pos)
658 {
659         MonoLiveRange2 *range;
660
661         for (range = interval->range; range != NULL; range = range->next) {
662                 if (pos >= range->from && pos <= range->to)
663                         return TRUE;
664                 if (range->from > pos)
665                         return FALSE;
666         }
667
668         return FALSE;
669 }
670
671 /**
672  * mono_linterval_get_intersect_pos:
673  *
674  *   Determine whenever I1 and I2 intersect, and if they do, return the first
675  * point of intersection. Otherwise, return -1.
676  */
677 gint32
678 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
679 {
680         MonoLiveRange2 *r1, *r2;
681
682         /* FIXME: Optimize this */
683         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
684                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
685                         if (r2->to > r1->from && r2->from < r1->to) {
686                                 if (r2->from <= r1->from)
687                                         return r1->from;
688                                 else
689                                         return r2->from;
690                         }
691                 }
692         }
693
694         return -1;
695 }
696  
697 /**
698  * mono_linterval_split
699  *
700  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
701  * part of L2.
702  */
703 void
704 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
705 {
706         MonoLiveRange2 *r;
707
708         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
709
710         *i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
711         *i2 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
712
713         for (r = interval->range; r; r = r->next) {
714                 if (pos > r->to) {
715                         /* Add it to the first child */
716                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
717                 } else if (pos > r->from && pos <= r->to) {
718                         /* Split at pos */
719                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
720                         mono_linterval_add_range (cfg, *i2, pos, r->to);
721                 } else {
722                         /* Add it to the second child */
723                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
724                 }
725         }
726 }
727
728 #if 1
729 #define LIVENESS_DEBUG(a) do { if (cfg->verbose_level > 1) do { a; } while (0); } while (0)
730 #define ENABLE_LIVENESS_DEBUG 1
731 #else
732 #define LIVENESS_DEBUG(a)
733 #endif
734
735 #ifdef ENABLE_LIVENESS2
736
737 static inline void
738 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
739 {
740         const char *spec = INS_INFO (ins->opcode);
741         int sreg;
742         int num_sregs, i;
743         int sregs [MONO_MAX_SRC_REGS];
744
745         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
746
747         if (ins->opcode == OP_NOP)
748                 return;
749
750         /* DREG */
751         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
752                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
753                 int idx = var->inst_c0;
754                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
755
756                 if (MONO_IS_STORE_MEMBASE (ins)) {
757                         if (last_use [idx] == 0) {
758                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
759                                 last_use [idx] = inst_num;
760                         }
761                 } else {
762                         if (last_use [idx] > 0) {
763                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
764                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
765                                 last_use [idx] = 0;
766                         }
767                         else {
768                                 /* Try dead code elimination */
769                                 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)) {
770                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
771                                         ins->opcode = OP_NOP;
772                                         ins->dreg = -1;
773                                         MONO_INST_NULLIFY_SREGS (ins);
774                                         return;
775                                 }
776
777                                 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));
778                                 mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + 1);
779                         }
780                 }
781         }
782
783         /* SREGs */
784         num_sregs = mono_inst_get_src_registers (ins, sregs);
785         for (i = 0; i < num_sregs; ++i) {
786                 sreg = sregs [i];
787                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
788                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
789                         int idx = var->inst_c0;
790
791                         if (last_use [idx] == 0) {
792                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
793                                 last_use [idx] = inst_num;
794                         }
795                 }
796         }
797 }
798
799 static void
800 mono_analyze_liveness2 (MonoCompile *cfg)
801 {
802         int bnum, idx, i, j, nins, rem, max, max_vars, block_from, block_to, pos, reverse_len;
803         gint32 *last_use;
804         static guint32 disabled = -1;
805         MonoInst **reverse;
806
807         if (disabled == -1)
808                 disabled = getenv ("DISABLED") != NULL;
809
810         if (disabled)
811                 return;
812
813         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
814
815         /*
816         if (strstr (cfg->method->name, "test_") != cfg->method->name)
817                 return;
818         */
819
820         max_vars = cfg->num_varinfo;
821         last_use = g_new0 (gint32, max_vars);
822
823         reverse_len = 1024;
824         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
825
826         for (idx = 0; idx < max_vars; ++idx) {
827                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
828
829                 vi->interval = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
830         }
831
832         /*
833          * Process bblocks in reverse order, so the addition of new live ranges
834          * to the intervals is faster.
835          */
836         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
837                 MonoBasicBlock *bb = cfg->bblocks [bnum];
838                 MonoInst *ins;
839
840                 block_from = (bb->dfn << 16) + 1; /* so pos > 0 */
841                 if (bnum < cfg->num_bblocks - 1)
842                         /* Beginning of the next bblock */
843                         block_to = (cfg->bblocks [bnum + 1]->dfn << 16) + 1;
844                 else
845                         block_to = (bb->dfn << 16) + 0xffff;
846
847                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
848
849                 memset (last_use, 0, max_vars * sizeof (gint32));
850                 
851                 /* For variables in bb->live_out, set last_use to block_to */
852
853                 rem = max_vars % BITS_PER_CHUNK;
854                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
855                 for (j = 0; j < max; ++j) {
856                         gsize bits_out;
857                         int k;
858
859                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
860                         k = (j * BITS_PER_CHUNK);       
861                         while (bits_out) {
862                                 if (bits_out & 1) {
863                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
864                                         last_use [k] = block_to;
865                                 }
866                                 bits_out >>= 1;
867                                 k ++;
868                         }
869                 }
870
871                 if (cfg->ret)
872                         last_use [cfg->ret->inst_c0] = block_to;
873
874                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
875                         if (nins >= reverse_len) {
876                                 int new_reverse_len = reverse_len * 2;
877                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
878                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
879                                 reverse = new_reverse;
880                                 reverse_len = new_reverse_len;
881                         }
882
883                         reverse [nins] = ins;
884                 }
885
886                 /* Process instructions backwards */
887                 for (i = nins - 1; i >= 0; --i) {
888                         MonoInst *ins = (MonoInst*)reverse [i];
889
890                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
891
892                         pos --;
893                 }
894
895                 for (idx = 0; idx < max_vars; ++idx) {
896                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
897
898                         if (last_use [idx] != 0) {
899                                 /* Live at exit, not written -> live on enter */
900                                 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]));
901                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
902                         }
903                 }
904         }
905
906         /*
907          * Arguments need to have their live ranges extended to the beginning of
908          * the method to account for the arg reg/memory -> global register copies
909          * in the prolog (bug #74992).
910          */
911         for (i = 0; i < max_vars; i ++) {
912                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
913                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
914                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
915         }
916
917 #if 0
918         for (idx = 0; idx < max_vars; ++idx) {
919                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
920                 
921                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
922                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
923                 LIVENESS_DEBUG (printf ("\n"));
924         }
925 #endif
926
927         g_free (last_use);
928 }
929
930 #endif
931
932 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
933
934 static inline void
935 update_liveness_gc (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, gint32 *last_use, MonoMethodVar **vreg_to_varinfo, GSList **callsites)
936 {
937         if (ins->opcode == OP_GC_LIVENESS_DEF || ins->opcode == OP_GC_LIVENESS_USE) {
938                 int vreg = ins->inst_c1;
939                 MonoMethodVar *vi = vreg_to_varinfo [vreg];
940                 int idx = vi->idx;
941                 int pc_offset = ins->backend.pc_offset;
942
943                 LIVENESS_DEBUG (printf ("\t%x: ", pc_offset); mono_print_ins (ins));
944
945                 if (ins->opcode == OP_GC_LIVENESS_DEF) {
946                         if (last_use [idx] > 0) {
947                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", vreg, pc_offset, last_use [idx]));
948                                 last_use [idx] = 0;
949                         }
950                 } else {
951                         if (last_use [idx] == 0) {
952                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", vreg, pc_offset));
953                                 last_use [idx] = pc_offset;
954                         }
955                 }
956         } else if (ins->opcode == OP_GC_PARAM_SLOT_LIVENESS_DEF) {
957                 GCCallSite *last;
958
959                 /* Add it to the last callsite */
960                 g_assert (*callsites);
961                 last = (*callsites)->data;
962                 last->param_slots = g_slist_prepend_mempool (cfg->mempool, last->param_slots, ins);
963         } else if (ins->flags & MONO_INST_GC_CALLSITE) {
964                 GCCallSite *callsite = mono_mempool_alloc0 (cfg->mempool, sizeof (GCCallSite));
965                 int i;
966
967                 LIVENESS_DEBUG (printf ("\t%x: ", ins->backend.pc_offset); mono_print_ins (ins));
968                 LIVENESS_DEBUG (printf ("\t\tlive: "));
969
970                 callsite->bb = bb;
971                 callsite->liveness = mono_mempool_alloc0 (cfg->mempool, ALIGN_TO (cfg->num_varinfo, 8) / 8);
972                 callsite->pc_offset = ins->backend.pc_offset;
973                 for (i = 0; i < cfg->num_varinfo; ++i) {
974                         if (last_use [i] != 0) {
975                                 LIVENESS_DEBUG (printf ("R%d", MONO_VARINFO (cfg, i)->vreg));
976                                 callsite->liveness [i / 8] |= (1 << (i % 8));
977                         }
978                 }
979                 LIVENESS_DEBUG (printf ("\n"));
980                 *callsites = g_slist_prepend_mempool (cfg->mempool, *callsites, callsite);
981         }
982 }
983
984 static inline int
985 get_vreg_from_var (MonoCompile *cfg, MonoInst *var)
986 {
987         if (var->opcode == OP_REGVAR)
988                 /* dreg contains a hreg, but inst_c0 still contains the var index */
989                 return MONO_VARINFO (cfg, var->inst_c0)->vreg;
990         else
991                 /* dreg still contains the vreg */
992                 return var->dreg;
993 }
994
995 /*
996  * mono_analyze_liveness_gc:
997  *
998  *   Compute liveness bitmaps for each call site.
999  * This function is a modified version of mono_analyze_liveness2 ().
1000  */
1001 void
1002 mono_analyze_liveness_gc (MonoCompile *cfg)
1003 {
1004         int idx, i, j, nins, rem, max, max_vars, block_from, block_to, pos, reverse_len;
1005         gint32 *last_use;
1006         MonoInst **reverse;
1007         MonoMethodVar **vreg_to_varinfo = NULL;
1008         MonoBasicBlock *bb;
1009         GSList *callsites;
1010
1011         LIVENESS_DEBUG (printf ("\n------------ GC LIVENESS: ----------\n"));
1012
1013         max_vars = cfg->num_varinfo;
1014         last_use = g_new0 (gint32, max_vars);
1015
1016         /*
1017          * var->inst_c0 no longer contains the variable index, so compute a mapping now.
1018          */
1019         vreg_to_varinfo = g_new0 (MonoMethodVar*, cfg->next_vreg);
1020         for (idx = 0; idx < max_vars; ++idx) {
1021                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
1022
1023                 vreg_to_varinfo [vi->vreg] = vi;
1024         }
1025
1026         reverse_len = 1024;
1027         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
1028
1029         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1030                 MonoInst *ins;
1031
1032                 block_from = bb->real_native_offset;
1033                 block_to = bb->native_offset + bb->native_length;
1034
1035                 LIVENESS_DEBUG (printf ("GC LIVENESS BB%d:\n", bb->block_num));
1036
1037                 if (!bb->code)
1038                         continue;
1039
1040                 memset (last_use, 0, max_vars * sizeof (gint32));
1041                 
1042                 /* For variables in bb->live_out, set last_use to block_to */
1043
1044                 rem = max_vars % BITS_PER_CHUNK;
1045                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
1046                 for (j = 0; j < max; ++j) {
1047                         gsize bits_out;
1048                         int k;
1049
1050                         if (!bb->live_out_set)
1051                                 /* The variables used in this bblock are volatile anyway */
1052                                 continue;
1053
1054                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
1055                         k = (j * BITS_PER_CHUNK);       
1056                         while (bits_out) {
1057                                 if ((bits_out & 1) && cfg->varinfo [k]->flags & MONO_INST_GC_TRACK) {
1058                                         int vreg = get_vreg_from_var (cfg, cfg->varinfo [k]);
1059                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, last_use set to %x.\n", vreg, block_to));
1060                                         last_use [k] = block_to;
1061                                 }
1062                                 bits_out >>= 1;
1063                                 k ++;
1064                         }
1065                 }
1066
1067                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
1068                         if (nins >= reverse_len) {
1069                                 int new_reverse_len = reverse_len * 2;
1070                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
1071                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
1072                                 reverse = new_reverse;
1073                                 reverse_len = new_reverse_len;
1074                         }
1075
1076                         reverse [nins] = ins;
1077                 }
1078
1079                 /* Process instructions backwards */
1080                 callsites = NULL;
1081                 for (i = nins - 1; i >= 0; --i) {
1082                         MonoInst *ins = (MonoInst*)reverse [i];
1083
1084                         update_liveness_gc (cfg, bb, ins, last_use, vreg_to_varinfo, &callsites);
1085                 }
1086                 /* The callsites should already be sorted by pc offset because we added them backwards */
1087                 bb->gc_callsites = callsites;
1088         }
1089
1090         g_free (last_use);
1091         g_free (vreg_to_varinfo);
1092 }
1093