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