* HttpRuntime.cs: Avoid ANE on Windows when HttpRuntime is used
[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 #if SIZEOF_REGISTER == 8
17 #define BITS_PER_CHUNK 64
18 #else
19 #define BITS_PER_CHUNK 32
20 #endif
21
22 /* 
23  * The liveness2 pass can't handle long vars on 32 bit platforms because the component
24  * vars have the same 'idx'.
25  */
26 #if SIZEOF_REGISTER == 8
27 #define ENABLE_LIVENESS2
28 #endif
29
30 #ifdef ENABLE_LIVENESS2
31 static void mono_analyze_liveness2 (MonoCompile *cfg);
32 #endif
33
34 static void
35 optimize_initlocals (MonoCompile *cfg);
36
37 /* mono_bitset_mp_new:
38  * 
39  * allocates a MonoBitSet inside a memory pool
40  */
41 static inline MonoBitSet* 
42 mono_bitset_mp_new (MonoMemPool *mp, guint32 size, guint32 max_size)
43 {
44         guint8 *mem = mono_mempool_alloc0 (mp, size);
45         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
46 }
47
48 static inline MonoBitSet* 
49 mono_bitset_mp_new_noinit (MonoMemPool *mp, guint32 size, guint32 max_size)
50 {
51         guint8 *mem = mono_mempool_alloc (mp, size);
52         return mono_bitset_mem_new (mem, max_size, MONO_BITSET_DONT_FREE);
53 }
54
55 G_GNUC_UNUSED static void
56 mono_bitset_print (MonoBitSet *set)
57 {
58         int i;
59
60         printf ("{");
61         for (i = 0; i < mono_bitset_size (set); i++) {
62
63                 if (mono_bitset_test (set, i))
64                         printf ("%d, ", i);
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                 }
98                         
99                 /* SREGS */
100                 num_sregs = mono_inst_get_src_registers (ins, sregs);
101                 g_assert (num_sregs <= 2);
102                 for (srcindex = 0; srcindex < num_sregs; ++srcindex) {
103                         regtype = spec [(srcindex == 0) ? MONO_INST_SRC1 : MONO_INST_SRC2];
104                         sreg = sregs [srcindex];
105
106                         g_assert (sreg != -1);
107                         if (get_vreg_to_inst (cfg, sreg)) {
108                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
109                                 int idx = var->inst_c0;
110                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
111
112                                 cfg->varinfo [vi->idx]->flags |= MONO_INST_VOLATILE;
113                         }
114                 }
115         }
116
117         *visited = g_slist_append (*visited, bb);
118
119         /* 
120          * Need to visit all bblocks reachable from this one since they can be
121          * reached during exception handling.
122          */
123         for (i = 0; i < bb->out_count; ++i) {
124                 visit_bb (cfg, bb->out_bb [i], visited);
125         }
126 }
127
128 void
129 mono_liveness_handle_exception_clauses (MonoCompile *cfg)
130 {
131         MonoBasicBlock *bb;
132         GSList *visited = NULL;
133
134         /*
135          * Variables in exception handler register cannot be allocated to registers
136          * so make them volatile. See bug #42136. This will not be neccessary when
137          * the back ends could guarantee that the variables will be in the
138          * correct registers when a handler is called.
139          * This includes try blocks too, since a variable in a try block might be
140          * accessed after an exception handler has been run.
141          */
142         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
143
144                 if (bb->region == -1 || MONO_BBLOCK_IS_IN_REGION (bb, MONO_REGION_TRY))
145                         continue;
146
147                 visit_bb (cfg, bb, &visited);
148         }
149         g_slist_free (visited);
150 }
151
152 static inline void
153 update_live_range (MonoMethodVar *var, int abs_pos)
154 {
155         if (var->range.first_use.abs_pos > abs_pos)
156                 var->range.first_use.abs_pos = abs_pos;
157
158         if (var->range.last_use.abs_pos < abs_pos)
159                 var->range.last_use.abs_pos = abs_pos;
160 }
161
162 static void
163 analyze_liveness_bb (MonoCompile *cfg, MonoBasicBlock *bb)
164 {
165         MonoInst *ins;
166         int sreg, inst_num;
167         MonoMethodVar *vars = cfg->vars;
168         guint32 abs_pos = (bb->dfn << 16);
169         
170         for (inst_num = 0, ins = bb->code; ins; ins = ins->next, inst_num += 2) {
171                 const char *spec = INS_INFO (ins->opcode);
172                 int num_sregs, i;
173                 int sregs [MONO_MAX_SRC_REGS];
174
175 #ifdef DEBUG_LIVENESS
176                         printf ("\t"); mono_print_ins (ins);
177 #endif
178
179                 if (ins->opcode == OP_NOP)
180                         continue;
181
182                 if (ins->opcode == OP_LDADDR) {
183                         MonoInst *var = ins->inst_p0;
184                         int idx = var->inst_c0;
185                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
186
187 #ifdef DEBUG_LIVENESS
188                         printf ("\tGEN: R%d(%d)\n", var->dreg, idx);
189 #endif
190                         update_live_range (&vars [idx], abs_pos + inst_num); 
191                         if (!mono_bitset_test_fast (bb->kill_set, idx))
192                                 mono_bitset_set_fast (bb->gen_set, idx);
193                         vi->spill_costs += SPILL_COST_INCREMENT;
194                 }                               
195
196                 /* SREGs must come first, so MOVE r <- r is handled correctly */
197                 num_sregs = mono_inst_get_src_registers (ins, sregs);
198                 for (i = 0; i < num_sregs; ++i) {
199                         sreg = sregs [i];
200                         if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
201                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
202                                 int idx = var->inst_c0;
203                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
204
205 #ifdef DEBUG_LIVENESS
206                                 printf ("\tGEN: R%d(%d)\n", sreg, idx);
207 #endif
208                                 update_live_range (&vars [idx], abs_pos + inst_num); 
209                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
210                                         mono_bitset_set_fast (bb->gen_set, idx);
211                                 vi->spill_costs += SPILL_COST_INCREMENT;
212                         }
213                 }
214
215                 /* DREG */
216                 if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
217                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
218                         int idx = var->inst_c0;
219                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
220
221                         if (MONO_IS_STORE_MEMBASE (ins)) {
222                                 update_live_range (&vars [idx], abs_pos + inst_num); 
223                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
224                                         mono_bitset_set_fast (bb->gen_set, idx);
225                                 vi->spill_costs += SPILL_COST_INCREMENT;
226                         } else {
227 #ifdef DEBUG_LIVENESS
228                                 printf ("\tKILL: R%d(%d)\n", ins->dreg, idx);
229 #endif
230                                 update_live_range (&vars [idx], abs_pos + inst_num + 1); 
231                                 mono_bitset_set_fast (bb->kill_set, idx);
232                                 vi->spill_costs += SPILL_COST_INCREMENT;
233                         }
234                 }
235         }
236 }
237
238 /* generic liveness analysis code. CFG specific parts are 
239  * in update_gen_kill_set()
240  */
241 void
242 mono_analyze_liveness (MonoCompile *cfg)
243 {
244         MonoBitSet *old_live_out_set;
245         int i, j, max_vars = cfg->num_varinfo;
246         int out_iter;
247         gboolean *in_worklist;
248         MonoBasicBlock **worklist;
249         guint32 l_end;
250         int bitsize;
251
252 #ifdef DEBUG_LIVENESS
253         printf ("LIVENESS %s\n", mono_method_full_name (cfg->method, TRUE));
254 #endif
255
256         g_assert (!(cfg->comp_done & MONO_COMP_LIVENESS));
257
258         cfg->comp_done |= MONO_COMP_LIVENESS;
259         
260         if (max_vars == 0)
261                 return;
262
263         bitsize = mono_bitset_alloc_size (max_vars, 0);
264
265         for (i = 0; i < max_vars; i ++) {
266                 MONO_VARINFO (cfg, i)->range.first_use.abs_pos = ~ 0;
267                 MONO_VARINFO (cfg, i)->range.last_use .abs_pos =   0;
268                 MONO_VARINFO (cfg, i)->spill_costs = 0;
269         }
270
271         for (i = 0; i < cfg->num_bblocks; ++i) {
272                 MonoBasicBlock *bb = cfg->bblocks [i];
273
274                 bb->gen_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
275                 bb->kill_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
276
277                 analyze_liveness_bb (cfg, bb);
278
279 #ifdef DEBUG_LIVENESS
280                 printf ("BLOCK BB%d (", bb->block_num);
281                 for (j = 0; j < bb->out_count; j++) 
282                         printf ("BB%d, ", bb->out_bb [j]->block_num);
283                 
284                 printf (")\n");
285                 printf ("GEN  BB%d: ", bb->block_num); mono_bitset_print (bb->gen_set);
286                 printf ("KILL BB%d: ", bb->block_num); mono_bitset_print (bb->kill_set);
287 #endif
288         }
289
290         old_live_out_set = mono_bitset_new (max_vars, 0);
291         in_worklist = g_new0 (gboolean, cfg->num_bblocks + 1);
292
293         worklist = g_new (MonoBasicBlock *, cfg->num_bblocks + 1);
294         l_end = 0;
295
296         /*
297          * This is a backward dataflow analysis problem, so we process blocks in
298          * decreasing dfn order, this speeds up the iteration.
299          */
300         for (i = 0; i < cfg->num_bblocks; i ++) {
301                 MonoBasicBlock *bb = cfg->bblocks [i];
302
303                 worklist [l_end ++] = bb;
304                 in_worklist [bb->dfn] = TRUE;
305
306                 /* Initialized later */
307                 bb->live_in_set = NULL;
308                 bb->live_out_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
309         }
310
311         out_iter = 0;
312
313         while (l_end != 0) {
314                 MonoBasicBlock *bb = worklist [--l_end];
315                 MonoBasicBlock *out_bb;
316                 gboolean changed;
317
318                 in_worklist [bb->dfn] = FALSE;
319
320 #ifdef DEBUG_LIVENESS
321                 printf ("P: %d(%d): IN: ", bb->block_num, bb->dfn);
322                 for (j = 0; j < bb->in_count; ++j) 
323                         printf ("BB%d ", bb->in_bb [j]->block_num);
324                 printf ("OUT:");
325                 for (j = 0; j < bb->out_count; ++j) 
326                         printf ("BB%d ", bb->out_bb [j]->block_num);
327                 printf ("\n");
328 #endif
329
330
331                 if (bb->out_count == 0)
332                         continue;
333
334                 out_iter ++;
335
336                 if (!bb->live_in_set) {
337                         /* First pass over this bblock */
338                         changed = TRUE;
339                 }
340                 else {
341                         changed = FALSE;
342                         mono_bitset_copyto_fast (bb->live_out_set, old_live_out_set);
343                 }
344  
345                 for (j = 0; j < bb->out_count; j++) {
346                         out_bb = bb->out_bb [j];
347
348                         if (!out_bb->live_in_set) {
349                                 out_bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
350
351                                 mono_bitset_copyto_fast (out_bb->live_out_set, out_bb->live_in_set);
352                                 mono_bitset_sub_fast (out_bb->live_in_set, out_bb->kill_set);
353                                 mono_bitset_union_fast (out_bb->live_in_set, out_bb->gen_set);
354                         }
355
356                         mono_bitset_union_fast (bb->live_out_set, out_bb->live_in_set);
357                 }
358                                 
359                 if (changed || !mono_bitset_equal (old_live_out_set, bb->live_out_set)) {
360                         if (!bb->live_in_set)
361                                 bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
362                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
363                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
364                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
365
366                         for (j = 0; j < bb->in_count; j++) {
367                                 MonoBasicBlock *in_bb = bb->in_bb [j];
368                                 /* 
369                                  * Some basic blocks do not seem to be in the 
370                                  * cfg->bblocks array...
371                                  */
372                                 if (in_bb->gen_set && !in_worklist [in_bb->dfn]) {
373 #ifdef DEBUG_LIVENESS
374                                         printf ("\tADD: %d\n", in_bb->block_num);
375 #endif
376                                         /*
377                                          * Put the block at the top of the stack, so it
378                                          * will be processed right away.
379                                          */
380                                         worklist [l_end ++] = in_bb;
381                                         in_worklist [in_bb->dfn] = TRUE;
382                                 }
383                         }
384                 }
385         }
386
387 #ifdef DEBUG_LIVENESS
388                 printf ("IT: %d %d.\n", cfg->num_bblocks, out_iter);
389 #endif
390
391         mono_bitset_free (old_live_out_set);
392
393         g_free (worklist);
394         g_free (in_worklist);
395
396         /* Compute live_in_set for bblocks skipped earlier */
397         for (i = 0; i < cfg->num_bblocks; ++i) {
398                 MonoBasicBlock *bb = cfg->bblocks [i];
399
400                 if (!bb->live_in_set) {
401                         bb->live_in_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
402
403                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
404                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
405                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
406                 }
407         }
408
409         for (i = 0; i < cfg->num_bblocks; ++i) {
410                 MonoBasicBlock *bb = cfg->bblocks [i];
411                 guint32 rem, max;
412                 guint32 abs_pos = (bb->dfn << 16);
413                 MonoMethodVar *vars = cfg->vars;
414
415                 if (!bb->live_out_set)
416                         continue;
417
418                 rem = max_vars % BITS_PER_CHUNK;
419                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
420                 for (j = 0; j < max; ++j) {
421                         gsize bits_in;
422                         gsize bits_out;
423                         int k;
424
425                         bits_in = mono_bitset_get_fast (bb->live_in_set, j);
426                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
427
428                         k = (j * BITS_PER_CHUNK);
429                         while ((bits_in || bits_out)) {
430                                 if (bits_in & 1)
431                                         update_live_range (&vars [k], abs_pos + 0);
432                                 if (bits_out & 1)
433                                         update_live_range (&vars [k], abs_pos + 0xffff);
434                                 bits_in >>= 1;
435                                 bits_out >>= 1;
436                                 k ++;
437                         }
438                 }
439         }
440
441         /*
442          * Arguments need to have their live ranges extended to the beginning of
443          * the method to account for the arg reg/memory -> global register copies
444          * in the prolog (bug #74992).
445          */
446
447         for (i = 0; i < max_vars; i ++) {
448                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
449                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG) {
450                         if (vi->range.last_use.abs_pos == 0 && !(cfg->varinfo [vi->idx]->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
451                                 /* 
452                                  * Can't eliminate the this variable in gshared code, since
453                                  * it is needed during exception handling to identify the
454                                  * method.
455                                  * It is better to check for this here instead of marking the variable
456                                  * VOLATILE, since that would prevent it from being allocated to
457                                  * registers.
458                                  */
459                                  if (!cfg->disable_deadce_vars && !(cfg->generic_sharing_context && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
460                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
461                         }
462                         vi->range.first_use.abs_pos = 0;
463                 }
464         }
465
466 #ifdef DEBUG_LIVENESS
467         for (i = cfg->num_bblocks - 1; i >= 0; i--) {
468                 MonoBasicBlock *bb = cfg->bblocks [i];
469                 
470                 printf ("LIVE IN  BB%d: ", bb->block_num); 
471                 mono_bitset_print (bb->live_in_set); 
472                 printf ("LIVE OUT BB%d: ", bb->block_num); 
473                 mono_bitset_print (bb->live_out_set); 
474         }
475 #endif
476
477         if (!cfg->disable_initlocals_opt)
478                 optimize_initlocals (cfg);
479
480 #ifdef ENABLE_LIVENESS2
481         /* This improves code size by about 5% but slows down compilation too much */
482         if (cfg->compile_aot)
483                 mono_analyze_liveness2 (cfg);
484 #endif
485 }
486
487 /**
488  * optimize_initlocals:
489  *
490  * Try to optimize away some of the redundant initialization code inserted because of
491  * 'locals init' using the liveness information.
492  */
493 static void
494 optimize_initlocals (MonoCompile *cfg)
495 {
496         MonoBitSet *used;
497         MonoInst *ins;
498         MonoBasicBlock *initlocals_bb;
499
500         used = mono_bitset_new (cfg->next_vreg + 1, 0);
501
502         mono_bitset_clear_all (used);
503         initlocals_bb = cfg->bb_entry->next_bb;
504         for (ins = initlocals_bb->code; ins; ins = ins->next) {
505                 int num_sregs, i;
506                 int sregs [MONO_MAX_SRC_REGS];
507
508                 num_sregs = mono_inst_get_src_registers (ins, sregs);
509                 for (i = 0; i < num_sregs; ++i)
510                         mono_bitset_set_fast (used, sregs [i]);
511
512                 if (MONO_IS_STORE_MEMBASE (ins))
513                         mono_bitset_set_fast (used, ins->dreg);
514         }
515
516         for (ins = initlocals_bb->code; ins; ins = ins->next) {
517                 const char *spec = INS_INFO (ins->opcode);
518
519                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
520                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
521                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
522
523                         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))) {
524                                 //printf ("DEAD: "); mono_print_ins (ins);
525                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST)) {
526                                         NULLIFY_INS (ins);
527                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
528                                         /* 
529                                          * We should shorten the liveness interval of these vars as well, but
530                                          * don't have enough info to do that.
531                                          */
532                                 }
533                         }
534                 }
535         }
536
537         g_free (used);
538 }
539
540 void
541 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
542 {
543         MonoLiveRange2 *prev_range, *next_range, *new_range;
544
545         g_assert (to >= from);
546
547         /* Optimize for extending the first interval backwards */
548         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
549                 interval->range->from = from;
550                 return;
551         }
552
553         /* Find a place in the list for the new range */
554         prev_range = NULL;
555         next_range = interval->range;
556         while ((next_range != NULL) && (next_range->from <= from)) {
557                 prev_range = next_range;
558                 next_range = next_range->next;
559         }
560
561         if (prev_range && prev_range->to == from) {
562                 /* Merge with previous */
563                 prev_range->to = to;
564         } else if (next_range && next_range->from == to) {
565                 /* Merge with previous */
566                 next_range->from = from;
567         } else {
568                 /* Insert it */
569                 new_range = mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
570                 new_range->from = from;
571                 new_range->to = to;
572                 new_range->next = NULL;
573
574                 if (prev_range)
575                         prev_range->next = new_range;
576                 else
577                         interval->range = new_range;
578                 if (next_range)
579                         new_range->next = next_range;
580                 else
581                         interval->last_range = new_range;
582         }
583
584         /* FIXME: Merge intersecting ranges */
585 }
586
587 void
588 mono_linterval_print (MonoLiveInterval *interval)
589 {
590         MonoLiveRange2 *range;
591
592         for (range = interval->range; range != NULL; range = range->next)
593                 printf ("[%x-%x] ", range->from, range->to);
594 }
595
596 void
597 mono_linterval_print_nl (MonoLiveInterval *interval)
598 {
599         mono_linterval_print (interval);
600         printf ("\n");
601 }
602
603 /**
604  * mono_linterval_convers:
605  *
606  *   Return whenever INTERVAL covers the position POS.
607  */
608 gboolean
609 mono_linterval_covers (MonoLiveInterval *interval, int pos)
610 {
611         MonoLiveRange2 *range;
612
613         for (range = interval->range; range != NULL; range = range->next) {
614                 if (pos >= range->from && pos <= range->to)
615                         return TRUE;
616                 if (range->from > pos)
617                         return FALSE;
618         }
619
620         return FALSE;
621 }
622
623 /**
624  * mono_linterval_get_intersect_pos:
625  *
626  *   Determine whenever I1 and I2 intersect, and if they do, return the first
627  * point of intersection. Otherwise, return -1.
628  */
629 gint32
630 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
631 {
632         MonoLiveRange2 *r1, *r2;
633
634         /* FIXME: Optimize this */
635         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
636                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
637                         if (r2->to > r1->from && r2->from < r1->to) {
638                                 if (r2->from <= r1->from)
639                                         return r1->from;
640                                 else
641                                         return r2->from;
642                         }
643                 }
644         }
645
646         return -1;
647 }
648  
649 /**
650  * mono_linterval_split
651  *
652  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
653  * part of L2.
654  */
655 void
656 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
657 {
658         MonoLiveRange2 *r;
659
660         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
661
662         *i1 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
663         *i2 = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
664
665         for (r = interval->range; r; r = r->next) {
666                 if (pos > r->to) {
667                         /* Add it to the first child */
668                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
669                 } else if (pos > r->from && pos <= r->to) {
670                         /* Split at pos */
671                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
672                         mono_linterval_add_range (cfg, *i2, pos, r->to);
673                 } else {
674                         /* Add it to the second child */
675                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
676                 }
677         }
678 }
679
680 #ifdef ENABLE_LIVENESS2
681
682 #if 0
683 #define LIVENESS_DEBUG(a) do { a; } while (0)
684 #else
685 #define LIVENESS_DEBUG(a)
686 #endif
687
688 static inline void
689 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
690 {
691         const char *spec = INS_INFO (ins->opcode);
692         int sreg;
693         int num_sregs, i;
694         int sregs [MONO_MAX_SRC_REGS];
695
696         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
697
698         if (ins->opcode == OP_NOP)
699                 return;
700
701         /* DREG */
702         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
703                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
704                 int idx = var->inst_c0;
705                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
706
707                 if (MONO_IS_STORE_MEMBASE (ins)) {
708                         if (last_use [idx] == 0) {
709                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
710                                 last_use [idx] = inst_num;
711                         }
712                 } else {
713                         if (last_use [idx] > 0) {
714                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
715                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
716                                 last_use [idx] = 0;
717                         }
718                         else {
719                                 /* Try dead code elimination */
720                                 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)) {
721                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
722                                         ins->opcode = OP_NOP;
723                                         ins->dreg = -1;
724                                         MONO_INST_NULLIFY_SREGS (ins);
725                                         return;
726                                 }
727
728                                 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));
729                                 mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + 1);
730                         }
731                 }
732         }
733
734         /* SREGs */
735         num_sregs = mono_inst_get_src_registers (ins, sregs);
736         for (i = 0; i < num_sregs; ++i) {
737                 sreg = sregs [i];
738                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
739                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
740                         int idx = var->inst_c0;
741
742                         if (last_use [idx] == 0) {
743                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
744                                 last_use [idx] = inst_num;
745                         }
746                 }
747         }
748 }
749
750 static void
751 mono_analyze_liveness2 (MonoCompile *cfg)
752 {
753         int bnum, idx, i, j, nins, rem, max, max_vars, block_from, block_to, pos, reverse_len;
754         gint32 *last_use;
755         static guint32 disabled = -1;
756         MonoInst **reverse;
757
758         if (disabled == -1)
759                 disabled = getenv ("DISABLED") != NULL;
760
761         if (disabled)
762                 return;
763
764         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
765
766         /*
767         if (strstr (cfg->method->name, "test_") != cfg->method->name)
768                 return;
769         */
770
771         max_vars = cfg->num_varinfo;
772         last_use = g_new0 (gint32, max_vars);
773
774         reverse_len = 1024;
775         reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
776
777         for (idx = 0; idx < max_vars; ++idx) {
778                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
779
780                 vi->interval = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
781         }
782
783         /*
784          * Process bblocks in reverse order, so the addition of new live ranges
785          * to the intervals is faster.
786          */
787         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
788                 MonoBasicBlock *bb = cfg->bblocks [bnum];
789                 MonoInst *ins;
790
791                 block_from = (bb->dfn << 16) + 1; /* so pos > 0 */
792                 if (bnum < cfg->num_bblocks - 1)
793                         /* Beginning of the next bblock */
794                         block_to = (cfg->bblocks [bnum + 1]->dfn << 16) + 1;
795                 else
796                         block_to = (bb->dfn << 16) + 0xffff;
797
798                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
799
800                 memset (last_use, 0, max_vars * sizeof (gint32));
801                 
802                 /* For variables in bb->live_out, set last_use to block_to */
803
804                 rem = max_vars % BITS_PER_CHUNK;
805                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
806                 for (j = 0; j < max; ++j) {
807                         gsize bits_out;
808                         int k;
809
810                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
811                         k = (j * BITS_PER_CHUNK);       
812                         while (bits_out) {
813                                 if (bits_out & 1) {
814                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
815                                         last_use [k] = block_to;
816                                 }
817                                 bits_out >>= 1;
818                                 k ++;
819                         }
820                 }
821
822                 if (cfg->ret)
823                         last_use [cfg->ret->inst_c0] = block_to;
824
825                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
826                         if (nins >= reverse_len) {
827                                 int new_reverse_len = reverse_len * 2;
828                                 MonoInst **new_reverse = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
829                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
830                                 reverse = new_reverse;
831                                 reverse_len = new_reverse_len;
832                         }
833
834                         reverse [nins] = ins;
835                 }
836
837                 /* Process instructions backwards */
838                 for (i = nins - 1; i >= 0; --i) {
839                         MonoInst *ins = (MonoInst*)reverse [i];
840
841                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
842
843                         pos --;
844                 }
845
846                 for (idx = 0; idx < max_vars; ++idx) {
847                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
848
849                         if (last_use [idx] != 0) {
850                                 /* Live at exit, not written -> live on enter */
851                                 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]));
852                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
853                         }
854                 }
855         }
856
857         /*
858          * Arguments need to have their live ranges extended to the beginning of
859          * the method to account for the arg reg/memory -> global register copies
860          * in the prolog (bug #74992).
861          */
862         for (i = 0; i < max_vars; i ++) {
863                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
864                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
865                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
866         }
867
868 #if 0
869         for (idx = 0; idx < max_vars; ++idx) {
870                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
871                 
872                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
873                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
874                 LIVENESS_DEBUG (printf ("\n"));
875         }
876 #endif
877
878         g_free (last_use);
879 }
880
881 #endif