a025732959fb694434ac208d0d68b6a253c4c445
[libfirm] / ir / be / bespill.c
1 /**
2  * Author:      Daniel Grund, Sebastian Hack
3  * Date:                29.09.2005
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  */
7 #ifdef HAVE_CONFIG_H
8 #include "config.h"
9 #endif
10
11 #include <stdlib.h>
12
13 #include "pset.h"
14 #include "irnode_t.h"
15 #include "ircons_t.h"
16 #include "iredges_t.h"
17 #include "ident_t.h"
18 #include "type_t.h"
19 #include "entity_t.h"
20 #include "debug.h"
21 #include "irgwalk.h"
22 #include "array.h"
23 #include "pdeq.h"
24
25 #include "belive_t.h"
26 #include "besched_t.h"
27 #include "bespill.h"
28 #include "benode_t.h"
29 #include "bechordal_t.h"
30
31 #define REMAT
32 /* This enables re-computation of values. Current state: Unfinished and buggy. */
33 #undef BUGGY_REMAT
34
35 typedef struct _reloader_t reloader_t;
36 typedef struct _spill_info_t spill_info_t;
37
38 struct _reloader_t {
39         reloader_t *next;
40         ir_node *reloader;
41 };
42
43 struct _spill_info_t {
44         ir_node *spilled_node;
45         reloader_t *reloaders;
46 };
47
48 typedef struct _spill_ctx_t {
49         ir_node *spilled;  /**< The spilled node. */
50         ir_node *user;     /**< The node this spill is for. */
51         ir_node *spill;    /**< The spill itself. */
52 } spill_ctx_t;
53
54 struct _spill_env_t {
55         const arch_register_class_t *cls;
56         const be_chordal_env_t *chordal_env;
57         struct obstack obst;
58         set *spill_ctxs;
59         set *spills;                            /**< all spill_info_t's, which must be placed */
60         pset *mem_phis;                         /**< set of all special spilled phis. allocated and freed separately */
61         ir_node **copies;                       /**< set of copies placed because of phi spills */
62         DEBUG_ONLY(firm_dbg_module_t *dbg;)
63 };
64
65 /* associated Phi -> Spill*/
66 typedef struct _phi_spill_assoc_t {
67         ir_node *phi;
68         ir_node *spill;
69 } phi_spill_assoc_t;
70
71 /**
72  * Compare two Phi->Spill associations.
73  */
74 static int cmp_phi_spill_assoc(const void *a, const void *b, size_t n) {
75         const phi_spill_assoc_t *p1 = a;
76         const phi_spill_assoc_t *p2 = b;
77         return p1->phi != p2->phi;
78 }
79
80 /**
81  * compare two spill contexts.
82  */
83 static int cmp_spillctx(const void *a, const void *b, size_t n) {
84         const spill_ctx_t *p = a;
85         const spill_ctx_t *q = b;
86         return p->user != q->user || p->spilled != q->spilled;
87 }
88
89 /**
90  * Compare two spill infos.
91  */
92 static int cmp_spillinfo(const void *x, const void *y, size_t size) {
93         const spill_info_t *xx = x;
94         const spill_info_t *yy = y;
95         return xx->spilled_node != yy->spilled_node;
96 }
97
98 DEBUG_ONLY(
99 /* Sets the debug module of a spill environment. */
100 void be_set_spill_env_dbg_module(spill_env_t *env, firm_dbg_module_t *dbg) {
101         env->dbg = dbg;
102 }
103 )
104
105 /* Creates a new spill environment. */
106 spill_env_t *be_new_spill_env(const be_chordal_env_t *chordal_env) {
107         spill_env_t *env        = xmalloc(sizeof(env[0]));
108         env->spill_ctxs         = new_set(cmp_spillctx, 1024);
109         env->spills                     = new_set(cmp_spillinfo, 1024);
110         env->cls                        = chordal_env->cls;
111         env->chordal_env        = chordal_env;
112         env->mem_phis           = pset_new_ptr_default();
113         env->copies                     = NEW_ARR_F(ir_node*, 0);
114         obstack_init(&env->obst);
115         return env;
116 }
117
118 /* Deletes a spill environment. */
119 void be_delete_spill_env(spill_env_t *env) {
120         del_set(env->spill_ctxs);
121         del_set(env->spills);
122         del_pset(env->mem_phis);
123         DEL_ARR_F(env->copies);
124         obstack_free(&env->obst, NULL);
125         free(env);
126 }
127
128 /**
129  * Returns a spill context. If the context did not exists, create one.
130  *
131  * @param sc        the set containing all spill contexts
132  * @param to_spill  the node that should be spilled
133  * @param ctx_irn   an user of the spilled node
134  *
135  * @return a spill context.
136  */
137 static spill_ctx_t *be_get_spill_ctx(set *sc, ir_node *to_spill, ir_node *ctx_irn) {
138         spill_ctx_t templ;
139
140         templ.spilled = to_spill;
141         templ.user    = ctx_irn;
142         templ.spill   = NULL;
143
144         return set_insert(sc, &templ, sizeof(templ), HASH_COMBINE(HASH_PTR(to_spill), HASH_PTR(ctx_irn)));
145 }
146
147 /**
148  * Creates a spill.
149  *
150  * @param senv      the spill environment
151  * @param irn       the node that should be spilled
152  * @param ctx_irn   an user of the spilled node
153  *
154  * @return a be_Spill node
155  */
156 static ir_node *be_spill_irn(spill_env_t *senv, ir_node *irn, ir_node *ctx_irn) {
157         spill_ctx_t *ctx;
158         const be_main_env_t *env = senv->chordal_env->birg->main_env;
159         DBG((senv->dbg, LEVEL_1, "%+F in ctx %+F\n", irn, ctx_irn));
160
161         // Has the value already been spilled?
162         ctx = be_get_spill_ctx(senv->spill_ctxs, irn, ctx_irn);
163         if(ctx->spill)
164                 return ctx->spill;
165
166         /* Trying to spill an already spilled value, no need for a new spill
167          * node then, we can simply connect to the same one for this reload
168          */
169         if(be_is_Reload(irn)) {
170                 return get_irn_n(irn, be_pos_Reload_mem);
171         }
172
173         ctx->spill = be_spill(env->arch_env, irn, ctx_irn);
174
175         return ctx->spill;
176 }
177
178 /**
179  * Removes all copies introduced for phi-spills
180  */
181 static void remove_copies(spill_env_t *env) {
182         int i;
183
184         for(i = 0; i < ARR_LEN(env->copies); ++i) {
185                 ir_node *node = env->copies[i];
186                 ir_node *src;
187                 const ir_edge_t *edge, *ne;
188
189                 assert(be_is_Copy(node));
190
191                 src = be_get_Copy_op(node);
192                 foreach_out_edge_safe(node, edge, ne) {
193                         ir_node *user = get_edge_src_irn(edge);
194                         int user_pos  = get_edge_src_pos(edge);
195
196                         set_irn_n(user, user_pos, src);
197                 }
198         }
199
200         ARR_SETLEN(ir_node*, env->copies, 0);
201 }
202
203 /**
204  * Inserts a copy (needed for spilled phi handling) of a value at the earliest
205  * possible location in a block. That is after the last use/def of the value or at
206  * the beginning of the block if there is no use/def.
207  */
208 static ir_node *insert_copy(spill_env_t *env, ir_node *block, ir_node *value) {
209         ir_node* node;
210         ir_graph *irg = get_irn_irg(block);
211         ir_node *copy = be_new_Copy(env->cls, irg, block, value);
212
213         ARR_APP1(ir_node*, env->copies, copy);
214
215         // walk schedule backwards until we find a use/def, or until we have reached the first phi
216         // TODO we could also do this by iterating over all uses and checking the
217         // sched_get_time_step value. Need benchmarks to decide this...
218         sched_foreach_reverse(block, node) {
219                 int i, arity;
220
221                 if(is_Phi(node)) {
222                         sched_add_after(node, copy);
223                         goto placed;
224                 }
225                 if(value == node) {
226                         sched_add_after(node, copy);
227                         goto placed;
228                 }
229                 for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
230                         ir_node *arg = get_irn_n(node, i);
231                         if(arg == value) {
232                                 sched_add_after(node, copy);
233                                 goto placed;
234                         }
235                 }
236         }
237         // we didn't find a use or a phi yet, so place the copy at the beginning of the block
238         sched_add_before(sched_first(block), copy);
239
240 placed:
241
242         return copy;
243 }
244
245 /**
246  * If the first usage of a Phi result would be out of memory
247  * there is no sense in allocating a register for it.
248  * Thus we spill it and all its operands to the same spill slot.
249  * Therefore the phi/dataB becomes a phi/Memory
250  *
251  * @param senv      the spill environment
252  * @param phi       the Phi node that should be spilled
253  * @param ctx_irn   an user of the spilled node
254  *
255  * @return a be_Spill node
256  */
257 static ir_node *spill_phi(spill_env_t *senv, ir_node *phi, ir_node *ctx_irn, set *already_visited_phis, bitset_t *bs) {
258         int         i;
259         int arity = get_irn_arity(phi);
260         ir_graph    *irg      = senv->chordal_env->irg;
261         ir_node     *bl       = get_nodes_block(phi);
262         ir_node     **ins, *phi_spill;
263         phi_spill_assoc_t key;
264         spill_ctx_t *ctx;
265
266         assert(is_Phi(phi));
267         DBG((senv->dbg, LEVEL_1, "%+F in ctx %+F\n", phi, ctx_irn));
268
269         /* build a new PhiM */
270         NEW_ARR_A(ir_node *, ins, arity);
271         for (i = 0; i < arity; ++i) {
272                 ins[i] = new_r_Bad(irg);
273         }
274         phi_spill = new_r_Phi(senv->chordal_env->irg, bl, arity, ins, mode_M);
275         key.phi   = phi;
276         key.spill = phi_spill;
277         set_insert(already_visited_phis, &key, sizeof(key), HASH_PTR(phi));
278         bitset_set(bs, get_irn_idx(phi));
279
280         /* search an existing spill for this context */
281         ctx = be_get_spill_ctx(senv->spill_ctxs, phi, ctx_irn);
282
283         /* if not found spill the phi */
284         if (! ctx->spill) {
285                 /* collect all arguments of the phi */
286                 for (i = 0; i < arity; ++i) {
287                         ir_node *arg = get_irn_n(phi, i);
288                         ir_node *sub_res;
289                         phi_spill_assoc_t *entry;
290
291                         if(is_Phi(arg) && pset_find_ptr(senv->mem_phis, arg)) {
292                                 // looping edge?
293                                 if(arg == phi) {
294                                         sub_res = phi_spill;
295                                 } else if (! bitset_is_set(bs, get_irn_idx(arg))) {
296                                         sub_res = spill_phi(senv, arg, ctx_irn, already_visited_phis, bs);
297                                 } else {
298                                         /* we already visited the argument phi: get it's spill */
299                                         key.phi   = arg;
300                                         key.spill = NULL;
301                                         entry     = set_find(already_visited_phis, &key, sizeof(key), HASH_PTR(arg));
302                                         assert(entry && "argument phi already visited, but no spill found?!?");
303                                         sub_res   = entry->spill;
304                                         assert(sub_res && "spill missing?!?");
305                                 }
306                         }
307                         else
308                                 sub_res = be_spill_irn(senv, arg, ctx_irn);
309
310                         set_irn_n(phi_spill, i, sub_res);
311                 }
312
313                 ctx->spill = phi_spill;
314         }
315         return ctx->spill;
316 }
317
318 /**
319  * Spill a node.
320  *
321  * @param senv      the spill environment
322  * @param to_spill  the node that should be spilled
323  *
324  * @return a be_Spill node
325  */
326 static ir_node *be_spill_node(spill_env_t *senv, ir_node *to_spill) {
327         ir_graph *irg = get_irn_irg(to_spill);
328         ir_node  *res;
329
330         if (pset_find_ptr(senv->mem_phis, to_spill)) {
331                 set *already_visited_phis = new_set(cmp_phi_spill_assoc, 10);
332                 bitset_t *bs = bitset_alloca(get_irg_last_idx(irg));
333                 res = spill_phi(senv, to_spill, to_spill, already_visited_phis, bs);
334                 del_set(already_visited_phis);
335         } else {
336                 res = be_spill_irn(senv, to_spill, to_spill);
337         }
338
339         return res;
340 }
341
342 #ifdef REMAT
343
344 #ifdef BUGGY_REMAT
345
346 /**
347  * Check if a spilled node could be rematerialized.
348  *
349  * @param senv      the spill environment
350  * @param spill     the Spill node
351  * @param spilled   the node that was spilled
352  * @param reloader  a irn that requires a reload
353  */
354 static int check_remat_conditions(spill_env_t *senv, ir_node *spill, ir_node *spilled, ir_node *reloader) {
355         int pos, max;
356
357         /* check for 'normal' spill and general remat condition */
358         if (!be_is_Spill(spill) || !arch_irn_is(senv->chordal_env->birg->main_env->arch_env, spilled, rematerializable))
359                 return 0;
360
361         /* check availability of original arguments */
362         if (is_Block(reloader)) {
363
364                 /* we want to remat at the end of a block.
365                  * thus all arguments must be alive at the end of the block
366                  */
367                 for (pos=0, max=get_irn_arity(spilled); pos<max; ++pos) {
368                         ir_node *arg = get_irn_n(spilled, pos);
369                         if (!is_live_end(reloader, arg))
370                                 return 0;
371                 }
372
373         } else {
374
375                 /* we want to remat before the insn reloader
376                  * thus an arguments is alive if
377                  *   - it interferes with the reloaders result
378                  * or
379                  *   - or it is (last-) used by reloader itself
380                  */
381                 for (pos=0, max=get_irn_arity(spilled); pos<max; ++pos) {
382                         ir_node *arg = get_irn_n(spilled, pos);
383                         int i, m;
384
385                         if (values_interfere(reloader, arg))
386                                 goto is_alive;
387
388                         for (i=0, m=get_irn_arity(reloader); i<m; ++i) {
389                                 ir_node *rel_arg = get_irn_n(reloader, i);
390                                 if (rel_arg == arg)
391                                         goto is_alive;
392                         }
393
394                         /* arg is not alive before reloader */
395                         return 0;
396
397 is_alive:       ;
398
399                 }
400
401         }
402
403         return 1;
404 }
405
406 #else /* BUGGY_REMAT */
407
408 /**
409  * A very simple rematerialization checker.
410  *
411  * @param senv      the spill environment
412  * @param spill     the Spill node
413  * @param spilled   the node that was spilled
414  * @param reloader  a irn that requires a reload
415  */
416 static int check_remat_conditions(spill_env_t *senv, ir_node *spill, ir_node *spilled, ir_node *reloader) {
417         const arch_env_t *aenv = senv->chordal_env->birg->main_env->arch_env;
418
419         return get_irn_arity(spilled) == 0 &&
420                    be_is_Spill(spill) &&
421                    arch_irn_is(aenv, spilled, rematerializable);
422 }
423
424 #endif /* BUGGY_REMAT */
425
426 #endif /* REMAT */
427
428 /**
429  * Re-materialize a node.
430  *
431  * @param senv      the spill environment
432  * @param spilled   the node that was spilled
433  * @param reloader  a irn that requires a reload
434  */
435 static ir_node *do_remat(spill_env_t *senv, ir_node *spilled, ir_node *reloader) {
436         ir_node *res;
437         ir_node *bl = (is_Block(reloader)) ? reloader : get_nodes_block(reloader);
438
439         /* recompute the value */
440         res = new_ir_node(get_irn_dbg_info(spilled), senv->chordal_env->irg, bl,
441                 get_irn_op(spilled),
442                 get_irn_mode(spilled),
443                 get_irn_arity(spilled),
444                 get_irn_in(spilled) + 1);
445         copy_node_attr(spilled, res);
446
447         DBG((senv->dbg, LEVEL_1, "Insert remat %+F before reloader %+F\n", res, reloader));
448
449         /* insert in schedule */
450         if (is_Block(reloader)) {
451                 ir_node *insert = sched_skip(reloader, 0, sched_skip_cf_predicator, (void *) senv->chordal_env->birg->main_env->arch_env);
452                 sched_add_after(insert, res);
453         } else {
454                 sched_add_before(reloader, res);
455         }
456
457         return res;
458 }
459
460 void be_spill_phi(spill_env_t *env, ir_node *node) {
461         assert(is_Phi(node));
462
463         pset_insert_ptr(env->mem_phis, node);
464 }
465
466 void be_insert_spills_reloads(spill_env_t *env) {
467         const arch_env_t *arch_env = env->chordal_env->birg->main_env->arch_env;
468         ir_node *node;
469         spill_info_t *si;
470
471         DBG((env->dbg, LEVEL_1, "Reloads for mem-phis:\n"));
472         foreach_pset(env->mem_phis, node) {
473                 const ir_edge_t *e;
474                 int i, arity;
475
476                 assert(is_Phi(node));
477
478                 /* We have to place copy nodes in the predecessor blocks to temporarily
479                  * produce new values that get separate spill slots
480                  */
481                 for(i = 0, arity = get_irn_arity(node); i < arity; ++i) {
482                         ir_node *pred_block, *arg, *copy;
483
484                         /* Don't do anything for looping edges (there's no need
485                          * and placing copies here breaks stuff as it suddenly
486                          * generates new living values through the whole loop)
487                          */
488                         arg = get_irn_n(node, i);
489                         if(arg == node)
490                                 continue;
491
492                         pred_block = get_Block_cfgpred_block(get_nodes_block(node), i);
493                         copy = insert_copy(env, pred_block, arg);
494
495                         set_irn_n(node, i, copy);
496                 }
497
498                 /* Add reloads for mem_phis */
499                 /* BETTER: These reloads (1) should only be inserted, if they are really needed */
500                 DBG((env->dbg, LEVEL_1, " Mem-phi %+F\n", node));
501                 foreach_out_edge(node, e) {
502                         ir_node *user = e->src;
503                         if (is_Phi(user) && !pset_find_ptr(env->mem_phis, user)) {
504                                 ir_node *use_bl = get_nodes_block(user);
505                                 DBG((env->dbg, LEVEL_1, " non-mem-phi user %+F\n", user));
506                                 be_add_reload_on_edge(env, node, use_bl, e->pos); /* (1) */
507                         }
508                 }
509         }
510
511         /* process each spilled node */
512         DBG((env->dbg, LEVEL_1, "Insert spills and reloads:\n"));
513         for(si = set_first(env->spills); si; si = set_next(env->spills)) {
514                 reloader_t *rld;
515                 ir_mode *mode = get_irn_mode(si->spilled_node);
516                 //ir_node *value;
517                 pset *values = pset_new_ptr(16);
518
519                 /* go through all reloads for this spill */
520                 for(rld = si->reloaders; rld; rld = rld->next) {
521                         ir_node *new_val;
522
523                         /* the spill for this reloader */
524                         ir_node *spill   = be_spill_node(env, si->spilled_node);
525
526 #ifdef REMAT
527                         if (check_remat_conditions(env, spill, si->spilled_node, rld->reloader)) {
528                                 new_val = do_remat(env, si->spilled_node, rld->reloader);
529                                 //pdeq_putl(possibly_dead, spill);
530                         }
531                         else
532 #endif
533                                 /* do a reload */
534                                 new_val = be_reload(arch_env, env->cls, rld->reloader, mode, spill);
535
536                         DBG((env->dbg, LEVEL_1, " %+F of %+F before %+F\n", new_val, si->spilled_node, rld->reloader));
537                         pset_insert_ptr(values, new_val);
538                 }
539
540                 /* introduce copies, rewire the uses */
541                 assert(pset_count(values) > 0 && "???");
542                 pset_insert_ptr(values, si->spilled_node);
543                 be_ssa_constr_set_ignore(env->chordal_env->dom_front, values, env->mem_phis);
544
545                 del_pset(values);
546         }
547
548         remove_copies(env);
549
550         // reloads are placed now, but we might reuse the spill environment for further spilling decisions
551         del_set(env->spills);
552         env->spills = new_set(cmp_spillinfo, 1024);
553 }
554
555 void be_add_reload(spill_env_t *env, ir_node *to_spill, ir_node *before) {
556         spill_info_t templ, *res;
557         reloader_t *rel;
558
559         assert(arch_irn_consider_in_reg_alloc(env->chordal_env->birg->main_env->arch_env, env->cls, to_spill));
560
561         if(is_Phi(to_spill)) {
562                 be_spill_phi(env, to_spill);
563         }
564
565         templ.spilled_node = to_spill;
566         templ.reloaders    = NULL;
567         res = set_insert(env->spills, &templ, sizeof(templ), HASH_PTR(to_spill));
568
569         rel           = obstack_alloc(&env->obst, sizeof(rel[0]));
570         rel->reloader = before;
571         rel->next     = res->reloaders;
572         res->reloaders = rel;
573 }
574
575 void be_add_reload_on_edge(spill_env_t *env, ir_node *to_spill, ir_node *bl, int pos) {
576         ir_node *insert_bl = get_irn_arity(bl) == 1 ? sched_first(bl) : get_Block_cfgpred_block(bl, pos);
577         be_add_reload(env, to_spill, insert_bl);
578 }
579
580
581
582 /****************************************
583
584         SPILL SLOT MANAGEMENT AND OPTS
585
586 ****************************************/
587
588 typedef struct _spill_slot_t {
589         unsigned size;
590         unsigned align;
591         pset *members;
592         ir_mode *largest_mode;  /* the mode of all members with largest size */
593 } spill_slot_t;
594
595 typedef struct _ss_env_t {
596         struct obstack ob;
597         be_chordal_env_t *cenv;
598         pmap *slots;            /* maps spill_contexts to spill_slots */
599         pmap *types;    /* maps modes to types */
600         DEBUG_ONLY(firm_dbg_module_t *dbg;)
601 } ss_env_t;
602
603
604 /**
605  * Walker: compute the spill slots
606  */
607 static void compute_spill_slots_walker(ir_node *spill, void *env) {
608         ss_env_t *ssenv = env;
609         ir_node *ctx;
610         pmap_entry *entry;
611         spill_slot_t *ss;
612
613         if (!be_is_Spill(spill))
614                 return;
615
616         /* check, if this spill is for a context already known */
617         ctx = be_get_Spill_context(spill);
618         entry = pmap_find(ssenv->slots, ctx);
619
620         if (!entry) {
621                 struct _arch_env_t *arch_env     = ssenv->cenv->birg->main_env->arch_env;
622                 const arch_register_class_t *cls = arch_get_irn_reg_class(arch_env, spill, be_pos_Spill_val);
623                 ir_mode *largest_mode            = arch_register_class_mode(cls);
624
625                 /* this is a new spill context */
626                 ss = obstack_alloc(&ssenv->ob, sizeof(*ss));
627                 ss->members      = pset_new_ptr(8);
628                 ss->largest_mode = largest_mode;
629                 ss->size         = get_mode_size_bytes(ss->largest_mode);
630                 ss->align        = arch_isa_get_reg_class_alignment(arch_env->isa, cls);
631                 pmap_insert(ssenv->slots, ctx, ss);
632         } else {
633                 /* values with the same spill_ctx must go into the same spill slot */
634                 ss = entry->value;
635
636 #ifndef NDEBUG
637                 /* ugly mega assert :-) */
638                 {
639                         ir_node *irn;
640                         struct _arch_env_t *arch_env     = ssenv->cenv->birg->main_env->arch_env;
641                         const arch_register_class_t *cls = arch_get_irn_reg_class(arch_env, spill, be_pos_Spill_val);
642                         int size = get_mode_size_bytes(arch_register_class_mode(cls));
643                         assert((int) ss->size == size && "Different sizes for the same spill slot are not allowed.");
644                         for (irn = pset_first(ss->members); irn; irn = pset_next(ss->members)) {
645                                 /* use values_interfere here, because it uses the dominance check,
646                                          which does work for values in memory */
647                                 assert(!values_interfere(spill, irn) && "Spills for the same spill slot must not interfere!");
648                         }
649                 }
650 #endif /* NDEBUG */
651         }
652
653         pset_insert_ptr(ss->members, spill);
654 }
655
656 /**
657  * qsort compare function, sort spill slots by size.
658  */
659 static int ss_sorter(const void *v1, const void *v2) {
660         const spill_slot_t **ss1 = (const spill_slot_t **)v1;
661         const spill_slot_t **ss2 = (const spill_slot_t **)v2;
662         return ((int) (*ss2)->size) - ((int) (*ss1)->size);
663 }
664
665
666 /**
667  * This function should optimize the spill slots.
668  *  - Coalescing of multiple slots
669  *  - Ordering the slots
670  *
671  * Input slots are in @p ssenv->slots
672  * @p size The count of initial spill slots in @p ssenv->slots
673  *         This also is the size of the preallocated array @p ass
674  *
675  * @return An array of spill slots @p ass in specific order
676  **/
677 static void optimize_slots(ss_env_t *ssenv, int size, spill_slot_t *ass[]) {
678         int i, o, used_slots;
679         pmap_entry *entr;
680
681         i=0;
682         pmap_foreach(ssenv->slots, entr)
683                 ass[i++] = entr->value;
684
685         /* Sort the array to minimize fragmentation and cache footprint.
686            Large slots come first */
687         qsort(ass, size, sizeof(ass[0]), ss_sorter);
688
689         /* For each spill slot:
690                 - assign a new offset to this slot
691             - xor find another slot to coalesce with */
692         used_slots = 0;
693         for (i=0; i<size; ++i) { /* for each spill slot */
694                 ir_node *n1;
695                 int tgt_slot = -1;
696
697                 DBG((ssenv->dbg, LEVEL_1, "Spill slot %d members:\n", i));
698                 for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
699                         DBG((ssenv->dbg, LEVEL_1, "  %+F\n", n1));
700
701
702                 for (o=0; o < used_slots && tgt_slot == -1; ++o) { /* for each offset-assigned spill slot */
703                         /* check inter-slot-pairs for interference */
704                         ir_node *n2;
705                         for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
706                                 for(n2 = pset_first(ass[o]->members); n2; n2 = pset_next(ass[o]->members))
707                                         if(values_interfere(n1, n2)) {
708                                                 pset_break(ass[i]->members);
709                                                 pset_break(ass[o]->members);
710                                                 DBG((ssenv->dbg, LEVEL_1, "    Interf %+F -- %+F\n", n1, n2));
711                                                 goto interf_detected;
712                                         }
713
714                         /* if we are here, there is no interference between ass[i] and ass[o] */
715                         tgt_slot = o;
716
717 interf_detected: /*nothing*/ ;
718                 }
719
720                 /* now the members of ass[i] join the members of ass[tgt_slot] */
721
722                 /* do we need a new slot? */
723                 if (tgt_slot == -1) {
724                         tgt_slot = used_slots;
725                         used_slots++;
726
727                         /* init slot */
728                         if (tgt_slot != i) {
729                                 ass[tgt_slot]->size = ass[i]->size;
730                                 del_pset(ass[tgt_slot]->members);
731                                 ass[tgt_slot]->members = pset_new_ptr(8);
732                         }
733                 }
734
735                 /* copy the members to the target pset */
736                 /* NOTE: If src and tgt pset are the same, inserting while iterating is not allowed */
737                 if (tgt_slot != i)
738                         for(n1 = pset_first(ass[i]->members); n1; n1 = pset_next(ass[i]->members))
739                                         pset_insert_ptr(ass[tgt_slot]->members, n1);
740         }
741 }
742
743 #define ALIGN_SPILL_AREA 16
744 #define pset_foreach(pset, elm)  for(elm=pset_first(pset); elm; elm=pset_next(pset))
745
746 /**
747  * Returns a spill type for a mode. Keep them in a map to reduce
748  * the number of types.
749  *
750  * @param types  a map containing all created types
751  * @param ss     the spill slot
752  *
753  * Note that type types should are identical for every mode.
754  * This rule might break if two different register classes return the same
755  * mode but different alignments.
756  */
757 static ir_type *get_spill_type(pmap *types, spill_slot_t *ss) {
758   pmap_entry *e = pmap_find(types, ss->largest_mode);
759   ir_type *res;
760
761   if (! e) {
762                 char buf[64];
763     snprintf(buf, sizeof(buf), "spill_slot_type_%s", get_mode_name(ss->largest_mode));
764     res = new_type_primitive(new_id_from_str(buf), ss->largest_mode);
765                 set_type_alignment_bytes(res, ss->align);
766     pmap_insert(types, ss->largest_mode, res);
767   }
768   else {
769     res = e->value;
770                 assert(get_type_alignment_bytes(res) == (int)ss->align);
771         }
772   return res;
773 }
774
775 /**
776  * Create spill slot entities on the frame type.
777  *
778  * @param ssenv   the spill environment
779  * @param n       number of spill slots
780  * @param ss      array of spill slots
781  */
782 static void assign_entities(ss_env_t *ssenv, int n_slots, spill_slot_t *ss[]) {
783         int i, offset, frame_align;
784         ir_type *frame = get_irg_frame_type(ssenv->cenv->irg);
785
786         /* aligning by increasing frame size */
787         offset = get_type_size_bits(frame) / 8;
788         offset = round_up2(offset, ALIGN_SPILL_AREA);
789         set_type_size_bytes(frame, -1);
790
791         /* create entities and assign offsets according to size and alignment*/
792         for (i = 0; i < n_slots; ++i) {
793                 char buf[64];
794                 ident *name;
795                 entity *spill_ent;
796                 ir_node *irn;
797
798                 /* build entity */
799                 snprintf(buf, sizeof(buf), "spill_slot_%d", i);
800                 name = new_id_from_str(buf);
801
802                 spill_ent = new_entity(frame, name, get_spill_type(ssenv->types, ss[i]));
803
804                 /* align */
805                 offset = round_up2(offset, ss[i]->align);
806                 /* set */
807                 set_entity_offset_bytes(spill_ent, offset);
808                 /* next possible offset */
809                 offset += round_up2(ss[i]->size, ss[i]->align);
810
811                 pset_foreach(ss[i]->members, irn)
812                         be_set_Spill_entity(irn, spill_ent);
813         }
814
815
816         /* set final size of stack frame */
817         frame_align = get_type_alignment_bytes(frame);
818         set_type_size_bytes(frame, round_up2(offset, frame_align));
819 }
820
821 void be_compute_spill_offsets(be_chordal_env_t *cenv) {
822         ss_env_t ssenv;
823         spill_slot_t **ss;
824         int ss_size;
825         pmap_entry *pme;
826
827         obstack_init(&ssenv.ob);
828         ssenv.cenv  = cenv;
829         ssenv.slots = pmap_create();
830         ssenv.types = pmap_create();
831         FIRM_DBG_REGISTER(ssenv.dbg, "ir.be.spillslots");
832
833         /* Get initial spill slots */
834         irg_walk_graph(cenv->irg, NULL, compute_spill_slots_walker, &ssenv);
835
836         /* Build an empty array for optimized spill slots */
837         ss_size = pmap_count(ssenv.slots);
838         ss = obstack_alloc(&ssenv.ob, ss_size * sizeof(*ss));
839         optimize_slots(&ssenv, ss_size, ss);
840
841         /* Integrate slots into the stack frame entity */
842         assign_entities(&ssenv, ss_size, ss);
843
844         /* Clean up */
845         pmap_foreach(ssenv.slots, pme)
846         del_pset(((spill_slot_t *)pme->value)->members);
847         pmap_destroy(ssenv.slots);
848         pmap_destroy(ssenv.types);
849         obstack_free(&ssenv.ob, NULL);
850
851         be_copy_entities_to_reloads(cenv->irg);
852 }