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