cfdc728c0d019e49bf5b19d187be5919eb0d0465
[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                         mono_print_ins_index (1, ins);
235                 }
236 #endif
237
238                 if (ins->opcode == OP_NOP)
239                         continue;
240
241                 if (ins->opcode == OP_LDADDR) {
242                         MonoInst *var = (MonoInst *)ins->inst_p0;
243                         int idx = var->inst_c0;
244                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
245
246 #ifdef DEBUG_LIVENESS
247                         if (cfg->verbose_level > 1)
248                                 printf ("\tGEN: R%d(%d)\n", var->dreg, idx);
249 #endif
250                         update_live_range (&vars [idx], abs_pos + inst_num); 
251                         if (!mono_bitset_test_fast (bb->kill_set, idx))
252                                 mono_bitset_set_fast (bb->gen_set, idx);
253                         vi->spill_costs += SPILL_COST_INCREMENT;
254                 }                               
255
256                 /* SREGs must come first, so MOVE r <- r is handled correctly */
257                 num_sregs = mono_inst_get_src_registers (ins, sregs);
258                 for (i = 0; i < num_sregs; ++i) {
259                         sreg = sregs [i];
260                         if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
261                                 MonoInst *var = get_vreg_to_inst (cfg, sreg);
262                                 int idx = var->inst_c0;
263                                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
264
265 #ifdef DEBUG_LIVENESS
266                                 if (cfg->verbose_level > 1)
267                                         printf ("\tGEN: R%d(%d)\n", sreg, idx);
268 #endif
269                                 update_live_range (&vars [idx], abs_pos + inst_num); 
270                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
271                                         mono_bitset_set_fast (bb->gen_set, idx);
272                                 vi->spill_costs += SPILL_COST_INCREMENT;
273                         }
274                 }
275
276                 /* DREG */
277                 if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
278                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
279                         int idx = var->inst_c0;
280                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
281
282                         if (MONO_IS_STORE_MEMBASE (ins)) {
283                                 update_live_range (&vars [idx], abs_pos + inst_num); 
284                                 if (!mono_bitset_test_fast (bb->kill_set, idx))
285                                         mono_bitset_set_fast (bb->gen_set, idx);
286                                 vi->spill_costs += SPILL_COST_INCREMENT;
287                         } else {
288 #ifdef DEBUG_LIVENESS
289                                 if (cfg->verbose_level > 1)
290                                         printf ("\tKILL: R%d(%d)\n", ins->dreg, idx);
291 #endif
292                                 update_live_range (&vars [idx], abs_pos + inst_num + 1); 
293                                 mono_bitset_set_fast (bb->kill_set, idx);
294                                 vi->spill_costs += SPILL_COST_INCREMENT;
295                         }
296                 }
297         }
298 }
299
300 /* generic liveness analysis code. CFG specific parts are 
301  * in update_gen_kill_set()
302  */
303 void
304 mono_analyze_liveness (MonoCompile *cfg)
305 {
306         MonoBitSet *old_live_out_set;
307         int i, j, max_vars = cfg->num_varinfo;
308         int out_iter;
309         gboolean *in_worklist;
310         MonoBasicBlock **worklist;
311         guint32 l_end;
312         int bitsize;
313
314 #ifdef DEBUG_LIVENESS
315         if (cfg->verbose_level > 1)
316                 printf ("\nLIVENESS:\n");
317 #endif
318
319         g_assert (!(cfg->comp_done & MONO_COMP_LIVENESS));
320
321         cfg->comp_done |= MONO_COMP_LIVENESS;
322         
323         if (max_vars == 0)
324                 return;
325
326         bitsize = mono_bitset_alloc_size (max_vars, 0);
327
328         for (i = 0; i < max_vars; i ++) {
329                 MONO_VARINFO (cfg, i)->range.first_use.abs_pos = ~ 0;
330                 MONO_VARINFO (cfg, i)->range.last_use .abs_pos =   0;
331                 MONO_VARINFO (cfg, i)->spill_costs = 0;
332         }
333
334         for (i = 0; i < cfg->num_bblocks; ++i) {
335                 MonoBasicBlock *bb = cfg->bblocks [i];
336
337                 bb->gen_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
338                 bb->kill_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
339
340 #ifdef DEBUG_LIVENESS
341                 if (cfg->verbose_level > 1) {
342                         printf ("BLOCK BB%d (", bb->block_num);
343                         for (j = 0; j < bb->out_count; j++) 
344                                 printf ("BB%d, ", bb->out_bb [j]->block_num);
345                 
346                         printf ("):\n");
347                 }
348 #endif
349
350                 analyze_liveness_bb (cfg, bb);
351
352 #ifdef DEBUG_LIVENESS
353                 if (cfg->verbose_level > 1) {
354                         printf ("GEN  BB%d: ", bb->block_num); mono_bitset_print (bb->gen_set);
355                         printf ("KILL BB%d: ", bb->block_num); mono_bitset_print (bb->kill_set);
356                 }
357 #endif
358         }
359
360         old_live_out_set = mono_bitset_new (max_vars, 0);
361         in_worklist = g_new0 (gboolean, cfg->num_bblocks + 1);
362
363         worklist = g_new (MonoBasicBlock *, cfg->num_bblocks + 1);
364         l_end = 0;
365
366         /*
367          * This is a backward dataflow analysis problem, so we process blocks in
368          * decreasing dfn order, this speeds up the iteration.
369          */
370         for (i = 0; i < cfg->num_bblocks; i ++) {
371                 MonoBasicBlock *bb = cfg->bblocks [i];
372
373                 worklist [l_end ++] = bb;
374                 in_worklist [bb->dfn] = TRUE;
375
376                 /* Initialized later */
377                 bb->live_in_set = NULL;
378                 bb->live_out_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
379         }
380
381         out_iter = 0;
382
383         if (cfg->verbose_level > 1)
384                 printf ("\nITERATION:\n");
385
386         while (l_end != 0) {
387                 MonoBasicBlock *bb = worklist [--l_end];
388                 MonoBasicBlock *out_bb;
389                 gboolean changed;
390
391                 in_worklist [bb->dfn] = FALSE;
392
393 #ifdef DEBUG_LIVENESS
394                 if (cfg->verbose_level > 1) {
395                         printf ("P: BB%d(%d): IN: ", bb->block_num, bb->dfn);
396                         for (j = 0; j < bb->in_count; ++j) 
397                                 printf ("BB%d ", bb->in_bb [j]->block_num);
398                         printf ("OUT:");
399                         for (j = 0; j < bb->out_count; ++j) 
400                                 printf ("BB%d ", bb->out_bb [j]->block_num);
401                         printf ("\n");
402                 }
403 #endif
404
405
406                 if (bb->out_count == 0)
407                         continue;
408
409                 out_iter ++;
410
411                 if (!bb->live_in_set) {
412                         /* First pass over this bblock */
413                         changed = TRUE;
414                 }
415                 else {
416                         changed = FALSE;
417                         mono_bitset_copyto_fast (bb->live_out_set, old_live_out_set);
418                 }
419  
420                 for (j = 0; j < bb->out_count; j++) {
421                         out_bb = bb->out_bb [j];
422
423                         if (!out_bb->live_in_set) {
424                                 out_bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
425
426                                 mono_bitset_copyto_fast (out_bb->live_out_set, out_bb->live_in_set);
427                                 mono_bitset_sub_fast (out_bb->live_in_set, out_bb->kill_set);
428                                 mono_bitset_union_fast (out_bb->live_in_set, out_bb->gen_set);
429                         }
430
431                         // FIXME: Do this somewhere else
432                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
433                         } else {
434                                 mono_bitset_union_fast (bb->live_out_set, out_bb->live_in_set);
435                         }
436                 }
437                                 
438                 if (changed || !mono_bitset_equal (old_live_out_set, bb->live_out_set)) {
439                         if (!bb->live_in_set)
440                                 bb->live_in_set = mono_bitset_mp_new_noinit (cfg->mempool, bitsize, max_vars);
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                         for (j = 0; j < bb->in_count; j++) {
446                                 MonoBasicBlock *in_bb = bb->in_bb [j];
447                                 /* 
448                                  * Some basic blocks do not seem to be in the 
449                                  * cfg->bblocks array...
450                                  */
451                                 if (in_bb->gen_set && !in_worklist [in_bb->dfn]) {
452 #ifdef DEBUG_LIVENESS
453                                         if (cfg->verbose_level > 1)
454                                                 printf ("\tADD: %d\n", in_bb->block_num);
455 #endif
456                                         /*
457                                          * Put the block at the top of the stack, so it
458                                          * will be processed right away.
459                                          */
460                                         worklist [l_end ++] = in_bb;
461                                         in_worklist [in_bb->dfn] = TRUE;
462                                 }
463                         }
464                 }
465
466                 if (G_UNLIKELY (cfg->verbose_level > 1)) {
467                         printf ("\tLIVE IN  BB%d: ", bb->block_num); 
468                         mono_bitset_print (bb->live_in_set); 
469                 }                       
470         }
471
472 #ifdef DEBUG_LIVENESS
473         if (cfg->verbose_level > 1)
474                 printf ("IT: %d %d.\n", cfg->num_bblocks, out_iter);
475 #endif
476
477         mono_bitset_free (old_live_out_set);
478
479         g_free (worklist);
480         g_free (in_worklist);
481
482         /* Compute live_in_set for bblocks skipped earlier */
483         for (i = 0; i < cfg->num_bblocks; ++i) {
484                 MonoBasicBlock *bb = cfg->bblocks [i];
485
486                 if (!bb->live_in_set) {
487                         bb->live_in_set = mono_bitset_mp_new (cfg->mempool, bitsize, max_vars);
488
489                         mono_bitset_copyto_fast (bb->live_out_set, bb->live_in_set);
490                         mono_bitset_sub_fast (bb->live_in_set, bb->kill_set);
491                         mono_bitset_union_fast (bb->live_in_set, bb->gen_set);
492                 }
493         }
494
495         for (i = 0; i < cfg->num_bblocks; ++i) {
496                 MonoBasicBlock *bb = cfg->bblocks [i];
497                 guint32 max;
498                 guint32 abs_pos = (bb->dfn << BB_ID_SHIFT);
499                 MonoMethodVar *vars = cfg->vars;
500
501                 if (!bb->live_out_set)
502                         continue;
503
504                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
505                 for (j = 0; j < max; ++j) {
506                         gsize bits_in;
507                         gsize bits_out;
508                         int k;
509
510                         bits_in = mono_bitset_get_fast (bb->live_in_set, j);
511                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
512
513                         k = (j * BITS_PER_CHUNK);
514                         while ((bits_in || bits_out)) {
515                                 if (bits_in & 1)
516                                         update_live_range (&vars [k], abs_pos + 0);
517                                 if (bits_out & 1)
518                                         update_live_range (&vars [k], abs_pos + ((1 << BB_ID_SHIFT) - 1));
519                                 bits_in >>= 1;
520                                 bits_out >>= 1;
521                                 k ++;
522                         }
523                 }
524         }
525
526         /*
527          * Arguments need to have their live ranges extended to the beginning of
528          * the method to account for the arg reg/memory -> global register copies
529          * in the prolog (bug #74992).
530          */
531
532         for (i = 0; i < max_vars; i ++) {
533                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
534                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG) {
535                         if (vi->range.last_use.abs_pos == 0 && !(cfg->varinfo [vi->idx]->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
536                                 /* 
537                                  * Can't eliminate the this variable in gshared code, since
538                                  * it is needed during exception handling to identify the
539                                  * method.
540                                  * It is better to check for this here instead of marking the variable
541                                  * VOLATILE, since that would prevent it from being allocated to
542                                  * registers.
543                                  */
544                                  if (!cfg->disable_deadce_vars && !(cfg->gshared && mono_method_signature (cfg->method)->hasthis && cfg->varinfo [vi->idx] == cfg->args [0]))
545                                          cfg->varinfo [vi->idx]->flags |= MONO_INST_IS_DEAD;
546                         }
547                         vi->range.first_use.abs_pos = 0;
548                 }
549         }
550
551 #ifdef DEBUG_LIVENESS
552         if (cfg->verbose_level > 1) {
553                 for (i = cfg->num_bblocks - 1; i >= 0; i--) {
554                         MonoBasicBlock *bb = cfg->bblocks [i];
555                 
556                         printf ("LIVE IN  BB%d: ", bb->block_num); 
557                         mono_bitset_print (bb->live_in_set); 
558                         printf ("LIVE OUT BB%d: ", bb->block_num); 
559                         mono_bitset_print (bb->live_out_set); 
560                 }
561
562                 for (i = 0; i < max_vars; i ++) {
563                         MonoMethodVar *vi = MONO_VARINFO (cfg, i);
564
565                         printf ("V%d: [0x%x - 0x%x]\n", i, vi->range.first_use.abs_pos, vi->range.last_use.abs_pos);
566                 }
567         }
568 #endif
569
570         if (!cfg->disable_initlocals_opt)
571                 optimize_initlocals (cfg);
572
573 #ifdef ENABLE_LIVENESS2
574         /* This improves code size by about 5% but slows down compilation too much */
575         if (cfg->compile_aot)
576                 mono_analyze_liveness2 (cfg);
577 #endif
578 }
579
580 /**
581  * optimize_initlocals:
582  *
583  * Try to optimize away some of the redundant initialization code inserted because of
584  * 'locals init' using the liveness information.
585  */
586 static void
587 optimize_initlocals (MonoCompile *cfg)
588 {
589         MonoBitSet *used;
590         MonoInst *ins;
591         MonoBasicBlock *initlocals_bb;
592
593         used = mono_bitset_new (cfg->next_vreg + 1, 0);
594
595         mono_bitset_clear_all (used);
596         initlocals_bb = cfg->bb_entry->next_bb;
597         for (ins = initlocals_bb->code; ins; ins = ins->next) {
598                 int num_sregs, i;
599                 int sregs [MONO_MAX_SRC_REGS];
600
601                 num_sregs = mono_inst_get_src_registers (ins, sregs);
602                 for (i = 0; i < num_sregs; ++i)
603                         mono_bitset_set_fast (used, sregs [i]);
604
605                 if (MONO_IS_STORE_MEMBASE (ins))
606                         mono_bitset_set_fast (used, ins->dreg);
607         }
608
609         for (ins = initlocals_bb->code; ins; ins = ins->next) {
610                 const char *spec = INS_INFO (ins->opcode);
611
612                 /* Look for statements whose dest is not used in this bblock and not live on exit. */
613                 if ((spec [MONO_INST_DEST] != ' ') && !MONO_IS_STORE_MEMBASE (ins)) {
614                         MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
615
616                         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))) {
617                                 //printf ("DEAD: "); mono_print_ins (ins);
618                                 if (cfg->disable_initlocals_opt_refs && var->type == STACK_OBJ)
619                                         continue;
620                                 if ((ins->opcode == OP_ICONST) || (ins->opcode == OP_I8CONST) || (ins->opcode == OP_R8CONST) || (ins->opcode == OP_R4CONST)) {
621                                         NULLIFY_INS (ins);
622                                         MONO_VARINFO (cfg, var->inst_c0)->spill_costs -= 1;
623                                         /* 
624                                          * We should shorten the liveness interval of these vars as well, but
625                                          * don't have enough info to do that.
626                                          */
627                                 }
628                         }
629                 }
630         }
631
632         g_free (used);
633 }
634
635 void
636 mono_linterval_add_range (MonoCompile *cfg, MonoLiveInterval *interval, int from, int to)
637 {
638         MonoLiveRange2 *prev_range, *next_range, *new_range;
639
640         g_assert (to >= from);
641
642         /* Optimize for extending the first interval backwards */
643         if (G_LIKELY (interval->range && (interval->range->from > from) && (interval->range->from == to))) {
644                 interval->range->from = from;
645                 return;
646         }
647
648         /* Find a place in the list for the new range */
649         prev_range = NULL;
650         next_range = interval->range;
651         while ((next_range != NULL) && (next_range->from <= from)) {
652                 prev_range = next_range;
653                 next_range = next_range->next;
654         }
655
656         if (prev_range && prev_range->to == from) {
657                 /* Merge with previous */
658                 prev_range->to = to;
659         } else if (next_range && next_range->from == to) {
660                 /* Merge with previous */
661                 next_range->from = from;
662         } else {
663                 /* Insert it */
664                 new_range = (MonoLiveRange2 *)mono_mempool_alloc (cfg->mempool, sizeof (MonoLiveRange2));
665                 new_range->from = from;
666                 new_range->to = to;
667                 new_range->next = NULL;
668
669                 if (prev_range)
670                         prev_range->next = new_range;
671                 else
672                         interval->range = new_range;
673                 if (next_range)
674                         new_range->next = next_range;
675                 else
676                         interval->last_range = new_range;
677         }
678
679         /* FIXME: Merge intersecting ranges */
680 }
681
682 void
683 mono_linterval_print (MonoLiveInterval *interval)
684 {
685         MonoLiveRange2 *range;
686
687         for (range = interval->range; range != NULL; range = range->next)
688                 printf ("[%x-%x] ", range->from, range->to);
689 }
690
691 void
692 mono_linterval_print_nl (MonoLiveInterval *interval)
693 {
694         mono_linterval_print (interval);
695         printf ("\n");
696 }
697
698 /**
699  * mono_linterval_convers:
700  *
701  *   Return whenever INTERVAL covers the position POS.
702  */
703 gboolean
704 mono_linterval_covers (MonoLiveInterval *interval, int pos)
705 {
706         MonoLiveRange2 *range;
707
708         for (range = interval->range; range != NULL; range = range->next) {
709                 if (pos >= range->from && pos <= range->to)
710                         return TRUE;
711                 if (range->from > pos)
712                         return FALSE;
713         }
714
715         return FALSE;
716 }
717
718 /**
719  * mono_linterval_get_intersect_pos:
720  *
721  *   Determine whenever I1 and I2 intersect, and if they do, return the first
722  * point of intersection. Otherwise, return -1.
723  */
724 gint32
725 mono_linterval_get_intersect_pos (MonoLiveInterval *i1, MonoLiveInterval *i2)
726 {
727         MonoLiveRange2 *r1, *r2;
728
729         /* FIXME: Optimize this */
730         for (r1 = i1->range; r1 != NULL; r1 = r1->next) {
731                 for (r2 = i2->range; r2 != NULL; r2 = r2->next) {
732                         if (r2->to > r1->from && r2->from < r1->to) {
733                                 if (r2->from <= r1->from)
734                                         return r1->from;
735                                 else
736                                         return r2->from;
737                         }
738                 }
739         }
740
741         return -1;
742 }
743  
744 /**
745  * mono_linterval_split
746  *
747  *   Split L at POS and store the newly created intervals into L1 and L2. POS becomes
748  * part of L2.
749  */
750 void
751 mono_linterval_split (MonoCompile *cfg, MonoLiveInterval *interval, MonoLiveInterval **i1, MonoLiveInterval **i2, int pos)
752 {
753         MonoLiveRange2 *r;
754
755         g_assert (pos > interval->range->from && pos <= interval->last_range->to);
756
757         *i1 = (MonoLiveInterval *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
758         *i2 = (MonoLiveInterval *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
759
760         for (r = interval->range; r; r = r->next) {
761                 if (pos > r->to) {
762                         /* Add it to the first child */
763                         mono_linterval_add_range (cfg, *i1, r->from, r->to);
764                 } else if (pos > r->from && pos <= r->to) {
765                         /* Split at pos */
766                         mono_linterval_add_range (cfg, *i1, r->from, pos - 1);
767                         mono_linterval_add_range (cfg, *i2, pos, r->to);
768                 } else {
769                         /* Add it to the second child */
770                         mono_linterval_add_range (cfg, *i2, r->from, r->to);
771                 }
772         }
773 }
774
775 #if 1
776 #define LIVENESS_DEBUG(a) do { if (cfg->verbose_level > 1) do { a; } while (0); } while (0)
777 #define ENABLE_LIVENESS_DEBUG 1
778 #else
779 #define LIVENESS_DEBUG(a)
780 #endif
781
782 #ifdef ENABLE_LIVENESS2
783
784 static inline void
785 update_liveness2 (MonoCompile *cfg, MonoInst *ins, gboolean set_volatile, int inst_num, gint32 *last_use)
786 {
787         const char *spec = INS_INFO (ins->opcode);
788         int sreg;
789         int num_sregs, i;
790         int sregs [MONO_MAX_SRC_REGS];
791
792         LIVENESS_DEBUG (printf ("\t%x: ", inst_num); mono_print_ins (ins));
793
794         if (ins->opcode == OP_NOP || ins->opcode == OP_IL_SEQ_POINT)
795                 return;
796
797         /* DREG */
798         if ((spec [MONO_INST_DEST] != ' ') && get_vreg_to_inst (cfg, ins->dreg)) {
799                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
800                 int idx = var->inst_c0;
801                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
802
803                 if (MONO_IS_STORE_MEMBASE (ins)) {
804                         if (last_use [idx] == 0) {
805                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", ins->dreg, inst_num));
806                                 last_use [idx] = inst_num;
807                         }
808                 } else {
809                         if (last_use [idx] > 0) {
810                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", ins->dreg, inst_num, last_use [idx]));
811                                 mono_linterval_add_range (cfg, vi->interval, inst_num, last_use [idx]);
812                                 last_use [idx] = 0;
813                         }
814                         else {
815                                 /* Try dead code elimination */
816                                 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)) {
817                                         LIVENESS_DEBUG (printf ("\tdead def of R%d, eliminated\n", ins->dreg));
818                                         NULLIFY_INS (ins);
819                                         return;
820                                 } else {
821                                         int inst_num_add = 1;
822                                         MonoInst *next = ins->next;
823                                         while (next && next->opcode == OP_IL_SEQ_POINT) {
824                                                 inst_num_add++;
825                                                 next = next->next;
826                                         }
827
828                                         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));
829                                         mono_linterval_add_range (cfg, vi->interval, inst_num, inst_num + inst_num_add);
830                                 }
831                         }
832                 }
833         }
834
835         /* SREGs */
836         num_sregs = mono_inst_get_src_registers (ins, sregs);
837         for (i = 0; i < num_sregs; ++i) {
838                 sreg = sregs [i];
839                 if ((spec [MONO_INST_SRC1 + i] != ' ') && get_vreg_to_inst (cfg, sreg)) {
840                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
841                         int idx = var->inst_c0;
842
843                         if (last_use [idx] == 0) {
844                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", sreg, inst_num));
845                                 last_use [idx] = inst_num;
846                         }
847                 }
848         }
849 }
850
851 static void
852 mono_analyze_liveness2 (MonoCompile *cfg)
853 {
854         int bnum, idx, i, j, nins, max, max_vars, block_from, block_to, pos;
855         gint32 *last_use;
856         static guint32 disabled = -1;
857
858         if (disabled == -1)
859                 disabled = g_getenv ("DISABLED") != NULL;
860
861         if (disabled)
862                 return;
863
864         if (cfg->num_bblocks >= (1 << (32 - BB_ID_SHIFT - 1)))
865                 /* Ranges would overflow */
866                 return;
867
868         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
869                 MonoBasicBlock *bb = cfg->bblocks [bnum];
870                 MonoInst *ins;
871
872                 nins = 0;
873                 for (nins = 0, ins = bb->code; ins; ins = ins->next, ++nins)
874                         nins ++;
875
876                 if (nins >= ((1 << BB_ID_SHIFT) - 1))
877                         /* Ranges would overflow */
878                         return;
879         }
880
881         LIVENESS_DEBUG (printf ("LIVENESS 2 %s\n", mono_method_full_name (cfg->method, TRUE)));
882
883         /*
884         if (strstr (cfg->method->name, "test_") != cfg->method->name)
885                 return;
886         */
887
888         max_vars = cfg->num_varinfo;
889         last_use = g_new0 (gint32, max_vars);
890
891         for (idx = 0; idx < max_vars; ++idx) {
892                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
893
894                 vi->interval = (MonoLiveInterval *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoLiveInterval));
895         }
896
897         /*
898          * Process bblocks in reverse order, so the addition of new live ranges
899          * to the intervals is faster.
900          */
901         for (bnum = cfg->num_bblocks - 1; bnum >= 0; --bnum) {
902                 MonoBasicBlock *bb = cfg->bblocks [bnum];
903                 MonoInst *ins;
904
905                 block_from = (bb->dfn << BB_ID_SHIFT) + 1; /* so pos > 0 */
906                 if (bnum < cfg->num_bblocks - 1)
907                         /* Beginning of the next bblock */
908                         block_to = (cfg->bblocks [bnum + 1]->dfn << BB_ID_SHIFT) + 1;
909                 else
910                         block_to = (bb->dfn << BB_ID_SHIFT) + ((1 << BB_ID_SHIFT) - 1);
911
912                 LIVENESS_DEBUG (printf ("LIVENESS BLOCK BB%d:\n", bb->block_num));
913
914                 memset (last_use, 0, max_vars * sizeof (gint32));
915                 
916                 /* For variables in bb->live_out, set last_use to block_to */
917
918                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
919                 for (j = 0; j < max; ++j) {
920                         gsize bits_out;
921                         int k;
922
923                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
924                         k = (j * BITS_PER_CHUNK);       
925                         while (bits_out) {
926                                 if (bits_out & 1) {
927                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, set last_use to %x\n", cfg->varinfo [k]->dreg, block_to));
928                                         last_use [k] = block_to;
929                                 }
930                                 bits_out >>= 1;
931                                 k ++;
932                         }
933                 }
934
935                 if (cfg->ret)
936                         last_use [cfg->ret->inst_c0] = block_to;
937
938                 pos = block_from + 1;
939                 MONO_BB_FOR_EACH_INS (bb, ins) pos++;
940
941                 /* Process instructions backwards */
942                 MONO_BB_FOR_EACH_INS_REVERSE (bb, ins) {
943                         update_liveness2 (cfg, ins, FALSE, pos, last_use);
944                         pos--;
945                 }
946
947                 for (idx = 0; idx < max_vars; ++idx) {
948                         MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
949
950                         if (last_use [idx] != 0) {
951                                 /* Live at exit, not written -> live on enter */
952                                 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]));
953                                 mono_linterval_add_range (cfg, vi->interval, block_from, last_use [idx]);
954                         }
955                 }
956         }
957
958         /*
959          * Arguments need to have their live ranges extended to the beginning of
960          * the method to account for the arg reg/memory -> global register copies
961          * in the prolog (bug #74992).
962          */
963         for (i = 0; i < max_vars; i ++) {
964                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
965                 if (cfg->varinfo [vi->idx]->opcode == OP_ARG)
966                         mono_linterval_add_range (cfg, vi->interval, 0, 1);
967         }
968
969 #if 0
970         for (idx = 0; idx < max_vars; ++idx) {
971                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
972                 
973                 LIVENESS_DEBUG (printf ("LIVENESS R%d: ", cfg->varinfo [idx]->dreg));
974                 LIVENESS_DEBUG (mono_linterval_print (vi->interval));
975                 LIVENESS_DEBUG (printf ("\n"));
976         }
977 #endif
978
979         g_free (last_use);
980 }
981
982 #endif
983
984 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
985
986 static inline void
987 update_liveness_gc (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, gint32 *last_use, MonoMethodVar **vreg_to_varinfo, GSList **callsites)
988 {
989         if (ins->opcode == OP_GC_LIVENESS_DEF || ins->opcode == OP_GC_LIVENESS_USE) {
990                 int vreg = ins->inst_c1;
991                 MonoMethodVar *vi = vreg_to_varinfo [vreg];
992                 int idx = vi->idx;
993                 int pc_offset = ins->backend.pc_offset;
994
995                 LIVENESS_DEBUG (printf ("\t%x: ", pc_offset); mono_print_ins (ins));
996
997                 if (ins->opcode == OP_GC_LIVENESS_DEF) {
998                         if (last_use [idx] > 0) {
999                                 LIVENESS_DEBUG (printf ("\tadd range to R%d: [%x, %x)\n", vreg, pc_offset, last_use [idx]));
1000                                 last_use [idx] = 0;
1001                         }
1002                 } else {
1003                         if (last_use [idx] == 0) {
1004                                 LIVENESS_DEBUG (printf ("\tlast use of R%d set to %x\n", vreg, pc_offset));
1005                                 last_use [idx] = pc_offset;
1006                         }
1007                 }
1008         } else if (ins->opcode == OP_GC_PARAM_SLOT_LIVENESS_DEF) {
1009                 GCCallSite *last;
1010
1011                 /* Add it to the last callsite */
1012                 g_assert (*callsites);
1013                 last = (GCCallSite *)(*callsites)->data;
1014                 last->param_slots = g_slist_prepend_mempool (cfg->mempool, last->param_slots, ins);
1015         } else if (ins->flags & MONO_INST_GC_CALLSITE) {
1016                 GCCallSite *callsite = (GCCallSite *)mono_mempool_alloc0 (cfg->mempool, sizeof (GCCallSite));
1017                 int i;
1018
1019                 LIVENESS_DEBUG (printf ("\t%x: ", ins->backend.pc_offset); mono_print_ins (ins));
1020                 LIVENESS_DEBUG (printf ("\t\tlive: "));
1021
1022                 callsite->bb = bb;
1023                 callsite->liveness = (guint8 *)mono_mempool_alloc0 (cfg->mempool, ALIGN_TO (cfg->num_varinfo, 8) / 8);
1024                 callsite->pc_offset = ins->backend.pc_offset;
1025                 for (i = 0; i < cfg->num_varinfo; ++i) {
1026                         if (last_use [i] != 0) {
1027                                 LIVENESS_DEBUG (printf ("R%d", MONO_VARINFO (cfg, i)->vreg));
1028                                 callsite->liveness [i / 8] |= (1 << (i % 8));
1029                         }
1030                 }
1031                 LIVENESS_DEBUG (printf ("\n"));
1032                 *callsites = g_slist_prepend_mempool (cfg->mempool, *callsites, callsite);
1033         }
1034 }
1035
1036 static inline int
1037 get_vreg_from_var (MonoCompile *cfg, MonoInst *var)
1038 {
1039         if (var->opcode == OP_REGVAR)
1040                 /* dreg contains a hreg, but inst_c0 still contains the var index */
1041                 return MONO_VARINFO (cfg, var->inst_c0)->vreg;
1042         else
1043                 /* dreg still contains the vreg */
1044                 return var->dreg;
1045 }
1046
1047 /*
1048  * mono_analyze_liveness_gc:
1049  *
1050  *   Compute liveness bitmaps for each call site.
1051  * This function is a modified version of mono_analyze_liveness2 ().
1052  */
1053 void
1054 mono_analyze_liveness_gc (MonoCompile *cfg)
1055 {
1056         int idx, i, j, nins, max, max_vars, block_from, block_to, pos, reverse_len;
1057         gint32 *last_use;
1058         MonoInst **reverse;
1059         MonoMethodVar **vreg_to_varinfo = NULL;
1060         MonoBasicBlock *bb;
1061         GSList *callsites;
1062
1063         LIVENESS_DEBUG (printf ("\n------------ GC LIVENESS: ----------\n"));
1064
1065         max_vars = cfg->num_varinfo;
1066         last_use = g_new0 (gint32, max_vars);
1067
1068         /*
1069          * var->inst_c0 no longer contains the variable index, so compute a mapping now.
1070          */
1071         vreg_to_varinfo = g_new0 (MonoMethodVar*, cfg->next_vreg);
1072         for (idx = 0; idx < max_vars; ++idx) {
1073                 MonoMethodVar *vi = MONO_VARINFO (cfg, idx);
1074
1075                 vreg_to_varinfo [vi->vreg] = vi;
1076         }
1077
1078         reverse_len = 1024;
1079         reverse = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * reverse_len);
1080
1081         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1082                 MonoInst *ins;
1083
1084                 block_from = bb->real_native_offset;
1085                 block_to = bb->native_offset + bb->native_length;
1086
1087                 LIVENESS_DEBUG (printf ("GC LIVENESS BB%d:\n", bb->block_num));
1088
1089                 if (!bb->code)
1090                         continue;
1091
1092                 memset (last_use, 0, max_vars * sizeof (gint32));
1093                 
1094                 /* For variables in bb->live_out, set last_use to block_to */
1095
1096                 max = ((max_vars + (BITS_PER_CHUNK -1)) / BITS_PER_CHUNK);
1097                 for (j = 0; j < max; ++j) {
1098                         gsize bits_out;
1099                         int k;
1100
1101                         if (!bb->live_out_set)
1102                                 /* The variables used in this bblock are volatile anyway */
1103                                 continue;
1104
1105                         bits_out = mono_bitset_get_fast (bb->live_out_set, j);
1106                         k = (j * BITS_PER_CHUNK);       
1107                         while (bits_out) {
1108                                 if ((bits_out & 1) && cfg->varinfo [k]->flags & MONO_INST_GC_TRACK) {
1109                                         int vreg = get_vreg_from_var (cfg, cfg->varinfo [k]);
1110                                         LIVENESS_DEBUG (printf ("Var R%d live at exit, last_use set to %x.\n", vreg, block_to));
1111                                         last_use [k] = block_to;
1112                                 }
1113                                 bits_out >>= 1;
1114                                 k ++;
1115                         }
1116                 }
1117
1118                 for (nins = 0, pos = block_from, ins = bb->code; ins; ins = ins->next, ++nins, ++pos) {
1119                         if (nins >= reverse_len) {
1120                                 int new_reverse_len = reverse_len * 2;
1121                                 MonoInst **new_reverse = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * new_reverse_len);
1122                                 memcpy (new_reverse, reverse, sizeof (MonoInst*) * reverse_len);
1123                                 reverse = new_reverse;
1124                                 reverse_len = new_reverse_len;
1125                         }
1126
1127                         reverse [nins] = ins;
1128                 }
1129
1130                 /* Process instructions backwards */
1131                 callsites = NULL;
1132                 for (i = nins - 1; i >= 0; --i) {
1133                         MonoInst *ins = (MonoInst*)reverse [i];
1134
1135                         update_liveness_gc (cfg, bb, ins, last_use, vreg_to_varinfo, &callsites);
1136                 }
1137                 /* The callsites should already be sorted by pc offset because we added them backwards */
1138                 bb->gc_callsites = callsites;
1139         }
1140
1141         g_free (last_use);
1142         g_free (vreg_to_varinfo);
1143 }
1144
1145 #else /* !DISABLE_JIT */
1146
1147 MONO_EMPTY_SOURCE_FILE (liveness);
1148
1149 #endif /* !DISABLE_JIT */