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