f4bfd78c72bee9e78d7af4a865967f008861dbe3
[libfirm] / ir / be / belower.c
1 /**
2  * Author:      Christian Wuerdig
3  * Date:        2005/12/14
4  * Copyright:   (c) Universitaet Karlsruhe
5  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
6  * CVS-Id:      $Id$
7  *
8  * Performs lowering of perm nodes and spill/reload optimization.
9  */
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13
14 #include <stdlib.h>
15
16 #include "ircons.h"
17
18 #include "bearch.h"
19 #include "belower.h"
20 #include "benode_t.h"
21 #include "bechordal_t.h"
22 #include "besched_t.h"
23
24 #include "irgmod.h"
25 #include "iredges_t.h"
26 #include "irgwalk.h"
27
28 #undef is_Perm
29 #define is_Perm(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_perm)
30
31 #undef is_Call
32 #define is_Call(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_call)
33
34 /* lowering walker environment */
35 typedef struct _lower_env_t {
36         be_chordal_env_t  *chord_env;
37         int                do_copy;
38         firm_dbg_module_t *dbg_module;
39 } lower_env_t;
40
41 /* holds a perm register pair */
42 typedef struct _reg_pair_t {
43         const arch_register_t *in_reg;    /**< a perm IN register */
44         ir_node               *in_node;   /**< the in node to which the register belongs */
45
46         const arch_register_t *out_reg;   /**< a perm OUT register */
47         ir_node               *out_node;  /**< the out node to which the register belongs */
48
49         int                    checked;   /**< indicates whether the pair was check for cycle or not */
50 } reg_pair_t;
51
52 typedef enum _perm_type_t {
53         PERM_CYCLE,
54         PERM_CHAIN,
55         PERM_SWAP,
56         PERM_COPY
57 } perm_type_t;
58
59 /* structure to represent cycles or chains in a perm */
60 typedef struct _perm_cycle_t {
61         const arch_register_t **elems;       /**< the registers in the cycle */
62         int                     n_elems;     /**< number of elements in the cycle */
63         perm_type_t             type;        /**< type (CHAIN or CYCLE) */
64 } perm_cycle_t;
65
66 /* Compare the in registers of two register pairs */
67 static int compare_reg_pair(const void *a, const void *b) {
68         const reg_pair_t *pair_a = a;
69         const reg_pair_t *pair_b = b;
70
71         if (pair_a->in_reg->index > pair_b->in_reg->index)
72                 return 1;
73         else
74                 return -1;
75 }
76
77 /* returns the number register pairs marked as checked */
78 static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
79         int i, n_checked = 0;
80
81         for (i = 0; i < n; i++) {
82                 if (pairs[i].checked)
83                         n_checked++;
84         }
85
86         return n_checked;
87 }
88
89 /**
90  * Gets the node corresponding to a register from an array of register pairs.
91  * NOTE: The given registers pairs and the register to look for must belong
92  *       to the same register class.
93  *
94  * @param pairs  The array of register pairs
95  * @param n      The number of pairs
96  * @param reg    The register to look for
97  * @param in_out 0 == look for IN register, 1 == look for OUT register
98  * @return The corresponding node or NULL if not found
99  */
100 static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_register_t *reg, int in_out) {
101         int i;
102
103         if (in_out) {
104                 for (i = 0; i < n; i++) {
105                         /* out register matches */
106                         if (pairs[i].out_reg->index == reg->index)
107                                 return pairs[i].out_node;
108                 }
109         }
110         else {
111                 for (i = 0; i < n; i++) {
112                         /* in register matches */
113                         if (pairs[i].in_reg->index == reg->index)
114                                 return pairs[i].in_node;
115                 }
116         }
117
118         return NULL;
119 }
120
121 /**
122  * Gets the index in the register pair array where the in/out register
123  * corresponds to reg_idx.
124  *
125  * @param pairs  The array of register pairs
126  * @param n      The number of pairs
127  * @param reg    The register index to look for
128  * @param in_out 0 == look for IN register, 1 == look for OUT register
129  * @return The corresponding index in pairs or -1 if not found
130  */
131 static int get_pairidx_for_regidx(reg_pair_t *pairs, int n, int reg_idx, int in_out) {
132         int i;
133
134         if (in_out) {
135                 for (i = 0; i < n; i++) {
136                         /* out register matches */
137                         if (pairs[i].out_reg->index == reg_idx)
138                                 return i;
139                 }
140         }
141         else {
142                 for (i = 0; i < n; i++) {
143                         /* in register matches */
144                         if (pairs[i].in_reg->index == reg_idx)
145                                 return i;
146                 }
147         }
148
149         return -1;
150 }
151
152 /**
153  * Gets an array of register pairs and tries to identify a cycle or chain starting
154  * at position start.
155  *
156  * @param cycle Variable to hold the cycle
157  * @param pairs Array of register pairs
158  * @param start Index to start
159  * @return The cycle or chain
160  */
161 static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int n, int start) {
162         int head         = pairs[start].in_reg->index;
163         int cur_idx      = pairs[start].out_reg->index;
164         int cur_pair_idx = start;
165         int n_pairs_done = get_n_checked_pairs(pairs, n) + 1;
166         int idx;
167
168         /* assume worst case: all remaining pairs build a cycle or chain */
169         cycle->elems    = calloc(n - n_pairs_done, sizeof(cycle->elems[0]));
170         cycle->n_elems  = 2;  /* initial number of elements is 2 */
171         cycle->elems[0] = pairs[start].in_reg;
172         cycle->elems[1] = pairs[start].out_reg;
173         cycle->type     = PERM_CHAIN; /* default is CHAIN, only changed when we found a cycle */
174
175         /* mark the first pair as checked */
176         pairs[start].checked = 1;
177
178         idx = 2;
179         /* check for cycle or end of a chain */
180         while (cur_idx != head && n_pairs_done < n) {
181                 /* goto next register in cycle or chain */
182                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cur_idx, 0);
183
184                 if (cur_pair_idx < 0)
185                         break;
186
187                 cur_idx = pairs[cur_pair_idx].out_reg->index;
188
189                 /* it's not the first element: insert it */
190                 if (cur_idx != head) {
191                         cycle->elems[idx++] = pairs[cur_pair_idx].out_reg;
192                         cycle->n_elems++;
193
194                         n_pairs_done++;
195                 }
196                 else {
197                         /* we are there where we started -> CYCLE */
198                         cycle->type = PERM_CYCLE;
199                 }
200
201                 /* mark the pair as checked */
202                 pairs[cur_pair_idx].checked = 1;
203         }
204
205         return cycle;
206 }
207
208 /**
209  * Lowers a perm node.  Resolves cycles and creates a bunch of
210  * copy and swap operations to permute registers.
211  * Note: The caller of this function has to make sure, that irn
212  *       is a Perm node.
213  *
214  * @param irn      The perm node
215  * @param block    The block the perm node belongs to
216  * @param walk_env The environment
217  */
218 static void lower_perm_node(ir_node *irn, void *walk_env) {
219         const arch_register_class_t *reg_class;
220         const arch_env_t            *arch_env;
221         firm_dbg_module_t           *mod;
222         lower_env_t     *env = walk_env;
223         reg_pair_t      *pairs;
224         const ir_edge_t *edge;
225         perm_cycle_t    *cycle;
226         int              n, i, pn, do_copy;
227         ir_node         *sched_point, *block, *in[2];
228         ir_node         *arg1, *arg2, *res1, *res2;
229         ir_node         *cpyxchg = NULL;
230
231         arch_env = env->chord_env->main_env->arch_env;
232         do_copy  = env->do_copy;
233         mod      = env->dbg_module;
234         block    = get_nodes_block(irn);
235
236         /*
237                 Get the schedule predecessor node to the perm
238                 NOTE: This works with auto-magic. If we insert the
239                         new copy/exchange nodes after this node, everything
240                         should be ok.
241         */
242         sched_point = sched_prev(irn);
243         DBG((mod, LEVEL_1, "sched point is %+F\n", sched_point));
244         assert(sched_point && "Perm is not scheduled or has no predecessor");
245
246         n = get_irn_arity(irn);
247         assert(n == get_irn_n_edges(irn) && "perm's in and out numbers different");
248
249         reg_class = arch_get_irn_register(arch_env, get_irn_n(irn, 0))->reg_class;
250         pairs     = calloc(n, sizeof(pairs[0]));
251
252         /* build the list of register pairs (in, out) */
253         i = 0;
254         foreach_out_edge(irn, edge) {
255                 pairs[i].out_node = get_edge_src_irn(edge);
256                 pn                = get_Proj_proj(pairs[i].out_node);
257                 pairs[i].in_node  = get_irn_n(irn, pn);
258
259                 pairs[i].in_reg  = arch_get_irn_register(arch_env, pairs[i].in_node);
260                 pairs[i].out_reg = arch_get_irn_register(arch_env, pairs[i].out_node);
261
262                 pairs[i].checked = 0;
263                 i++;
264         }
265
266         /* sort the register pairs by the indices of the in registers */
267         qsort(pairs, n, sizeof(pairs[0]), compare_reg_pair);
268
269         /* Mark all equal pairs as checked, and exchange the OUT proj with
270                 the IN node. */
271         for (i = 0; i < n; i++) {
272                 if (pairs[i].in_reg->index == pairs[i].out_reg->index) {
273                         DBG((mod, LEVEL_1, "%+F removing equal perm register pair (%+F, %+F, %s)\n",
274                                 irn, pairs[i].in_node, pairs[i].out_node, pairs[i].out_reg->name));
275
276                         /* We have to check for a special case:
277                                 The in-node could be a Proj from a Perm. In this case,
278                                 we need to correct the projnum */
279                         if (is_Perm(arch_env, pairs[i].in_node) && is_Proj(pairs[i].in_node)) {
280                                 set_Proj_proj(pairs[i].out_node, get_Proj_proj(pairs[i].in_node));
281                         }
282
283                         /* remove the proj from the schedule */
284                         sched_remove(pairs[i].out_node);
285
286                         /* reroute the edges from the proj to the argument */
287                         edges_reroute(pairs[i].out_node, pairs[i].in_node, env->chord_env->irg);
288
289                         pairs[i].checked = 1;
290                 }
291         }
292
293         /* Set do_copy to 0 if it's on but we have no free register */
294         if (do_copy) {
295                 do_copy = 0;
296         }
297
298         /* check for cycles and chains */
299         while (get_n_checked_pairs(pairs, n) < n) {
300                 i = 0;
301
302                 /* go to the first not-checked pair */
303                 while (pairs[i].checked) i++;
304                 cycle = calloc(1, sizeof(*cycle));
305                 cycle = get_perm_cycle(cycle, pairs, n, i);
306
307                 /* We don't need to do anything if we have a Perm with two
308                         elements which represents a cycle, because those nodes
309                         already represent exchange nodes */
310                 if (n == 2 && cycle->type == PERM_CYCLE) {
311                         free(cycle);
312                         continue;
313                 }
314
315 //TODO: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
316 //        the copy cascade (this reduces the cycle into a chain)
317
318                 /* build copy/swap nodes from back to front */
319                 for (i = cycle->n_elems - 2; i >= 0; i--) {
320                         arg1 = get_node_for_register(pairs, n, cycle->elems[i], 0);
321                         arg2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
322
323                         res1 = get_node_for_register(pairs, n, cycle->elems[i], 1);
324                         res2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
325
326                         /*
327                                 If we have a cycle and don't copy: we need to create exchange nodes
328                                 NOTE: An exchange node is a perm node with 2 INs and 2 OUTs
329                                 IN_1  = in node with register i
330                                 IN_2  = in node with register i + 1
331                                 OUT_1 = out node with register i + 1
332                                 OUT_2 = out node with register i
333                         */
334                         if (cycle->type == PERM_CYCLE && !do_copy) {
335                                 in[0] = arg1;
336                                 in[1] = arg2;
337
338                                 DBG((mod, LEVEL_1, "%+F creating exchange node (%+F, %s) and (%+F, %s) with\n",
339                                         irn, arg1, cycle->elems[i]->name, arg2, cycle->elems[i + 1]->name));
340                                 DBG((mod, LEVEL_1, "%+F                        (%+F, %s) and (%+F, %s)\n",
341                                         irn, res1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
342
343                                 cpyxchg = be_new_Perm(reg_class, env->chord_env->irg, block, 2, in);
344
345                                 sched_remove(res1);
346                                 sched_remove(res2);
347
348                                 set_Proj_pred(res2, cpyxchg);
349                                 set_Proj_proj(res2, 0);
350                                 set_Proj_pred(res1, cpyxchg);
351                                 set_Proj_proj(res1, 1);
352
353                                 sched_add_after(sched_point, res1);
354                                 sched_add_after(sched_point, res2);
355
356                                 arch_set_irn_register(arch_env, res2, cycle->elems[i + 1]);
357                                 arch_set_irn_register(arch_env, res1, cycle->elems[i]);
358                         }
359                         else {
360                                 DBG((mod, LEVEL_1, "%+F creating copy node (%+F, %s) -> (%+F, %s)\n",
361                                         irn, arg1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
362
363                                 cpyxchg = be_new_Copy(reg_class, env->chord_env->irg, block, arg1);
364                                 arch_set_irn_register(arch_env, cpyxchg, cycle->elems[i + 1]);
365
366                                 /* remove the proj from the schedule */
367                                 sched_remove(res2);
368
369                                 /* exchange copy node and proj */
370                                 exchange(res2, cpyxchg);
371                         }
372
373                         /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
374                         sched_add_after(sched_point, cpyxchg);
375
376                         DBG((mod, LEVEL_1, "replacing %+F with %+F, placed new node after %+F\n", irn, cpyxchg, sched_point));
377                 }
378
379 //              free(cycle->elems);
380                 free(cycle);
381         }
382
383         /* remove the perm from schedule */
384         sched_remove(irn);
385 }
386
387
388
389 /**
390  * Adds Projs to keep nodes for each register class, which eats the
391  * caller saved registers.
392  * Note: The caller has to make sure, that call is a Call
393  *
394  * @param call     The Call node
395  * @param walk_env The walker environment
396  */
397 static void lower_call_node(ir_node *call, void *walk_env) {
398         lower_env_t                 *env      = walk_env;
399         const arch_env_t            *arch_env = env->chord_env->main_env->arch_env;
400         firm_dbg_module_t           *mod      = env->dbg_module;
401         const arch_register_class_t *reg_class;
402         int                          i, j, set_size = 0, pn, keep_arity;
403         arch_isa_t                  *isa      = arch_env_get_isa(arch_env);
404         const ir_node               *proj_T   = NULL;
405         ir_node                     **in_keep, *block = get_nodes_block(call);
406         ir_node                     *last_proj = NULL;
407         bitset_t                    *proj_set;
408         const ir_edge_t             *edge;
409         const arch_register_t       *reg;
410
411         /* Prepare the bitset where we store the projnums which are already in use*/
412         for (i = 0; i < arch_isa_get_n_reg_class(isa); i++) {
413                 reg_class  = arch_isa_get_reg_class(isa, i);
414                 set_size  += arch_register_class_n_regs(reg_class);
415         }
416
417         in_keep = malloc(set_size * sizeof(ir_node *));
418
419         proj_set = bitset_malloc(set_size);
420         bitset_clear_all(proj_set);
421
422         /* check if there is a ProjT node and which arguments are used */
423         foreach_out_edge(call, edge) {
424                 if (get_irn_mode(get_edge_src_irn(edge)) == mode_T)
425                         proj_T = get_edge_src_irn(edge);
426         }
427
428         /* set all used arguments */
429         if (proj_T) {
430
431
432                 foreach_out_edge(proj_T, edge) {
433                         ir_node *proj       = get_edge_src_irn(edge);
434
435                         assert(is_Proj(proj));
436                         bitset_set(proj_set, get_Proj_proj(get_edge_src_irn(edge)));
437
438                         /*
439                          * Filter out the last proj in the schedule.
440                          * After that one, we have to insert the Keep node.
441                          */
442                         if(!last_proj || sched_comes_after(last_proj, proj))
443                                 last_proj = proj;
444
445                 }
446         }
447         else {
448                 proj_T = new_r_Proj(current_ir_graph, block, call, mode_T, pn_Call_T_result);
449         }
450
451         /* Create for each caller save register a proj (keep node arguement) */
452         /* if this proj is not already present */
453         for (i = 0; i < arch_isa_get_n_reg_class(isa); i++) {
454
455                 /* reset the keep input, as we need one keep for each register class */
456                 memset(in_keep, 0, set_size * sizeof(ir_node *));
457                 keep_arity = 0;
458                 reg_class  = arch_isa_get_reg_class(isa, i);
459
460                 for (j = 0; j < arch_register_class_n_regs(reg_class); j++) {
461                         reg = arch_register_for_index(reg_class, j);
462
463                         /* only check caller save registers */
464                         if (arch_register_type_is(reg, caller_saved)) {
465                                 pn = isa->impl->get_projnum_for_register(isa, reg);
466                                 if (!bitset_is_set(proj_set, pn)) {
467                                         ir_node *proj = new_r_Proj(current_ir_graph, block, (ir_node *)proj_T, mode_Is, pn);
468
469                                         in_keep[keep_arity++] = proj;
470                                         sched_add_after(last_proj, proj);
471                                         last_proj = proj;
472                                 }
473                         }
474                 }
475
476                 /* ok, we found some caller save register which are not in use but must be saved */
477                 if (keep_arity) {
478                         ir_node *keep;
479
480                         keep = be_new_Keep(reg_class, current_ir_graph, block, keep_arity, in_keep);
481                         sched_add_after(last_proj, keep);
482                 }
483         }
484
485         bitset_free(proj_set);
486         return;
487 }
488
489
490
491 /**
492  * Calls the backend code generator functions to lower Spill and
493  * Reload nodes into Store and Load. The backend is fully responsible
494  * for creating the new nodes and setting their input correct.
495  * Note: The caller of this has to make sure that irn is a Spill
496  *       or Reload!
497  *
498  * @param irn      The Spill/Reload node
499  * @param walk_env The walker environment
500  */
501 static void lower_spill_reload(ir_node *irn, void *walk_env) {
502         lower_env_t           *env  = walk_env;
503         arch_code_generator_t *cg   = env->chord_env->main_env->cg;
504         const arch_env_t      *aenv = env->chord_env->main_env->arch_env;
505         ir_node               *res  = NULL;
506         ir_node               *sched_point;
507
508         if (be_is_Spill(irn) && cg->impl->lower_spill) {
509                 res = cg->impl->lower_spill(cg, irn);
510         }
511         else if (be_is_Reload(irn) && cg->impl->lower_reload) {
512                 res = cg->impl->lower_reload(cg, irn);
513                 if (res && res != irn) {
514                         /* copy the result register from the reload to the load */
515                         arch_set_irn_register(aenv, res, arch_get_irn_register(aenv, irn));
516                 }
517         }
518
519         if (res && res != irn) {
520                 sched_point = sched_prev(irn);
521                 sched_remove(irn);
522                 exchange(irn, res);
523                 sched_add_after(sched_point, res);
524         }
525         else {
526                 DBG((env->dbg_module, LEVEL_1, "node %+F not lowered\n", irn));
527         }
528
529         return;
530 }
531
532
533
534 /**
535  * Calls the corresponding lowering function for the node.
536  *
537  * @param irn      The node to be checked for lowering
538  * @param walk_env The walker environment
539  */
540 static void lower_nodes_walker(ir_node *irn, void *walk_env) {
541         lower_env_t      *env      = walk_env;
542         const arch_env_t *arch_env = env->chord_env->main_env->arch_env;
543
544         if (!is_Block(irn) && !is_Proj(irn)) {
545                 if (is_Perm(arch_env, irn)) {
546                         lower_perm_node(irn, walk_env);
547                 }
548                 else if (is_Call(arch_env, irn)) {
549                         lower_call_node(irn, walk_env);
550                 }
551                 else if (be_is_Spill(irn) || be_is_Reload(irn)) {
552                         lower_spill_reload(irn, walk_env);
553                 }
554         }
555
556         return;
557 }
558
559 /**
560  * Walks over all blocks in an irg and performs some lowering.
561  *
562  * @param chord_env The chordal environment containing the irg
563  * @param do_copy   1 == resolve cycles with a free reg if available
564  */
565 void lower_nodes(be_chordal_env_t *chord_env, int do_copy) {
566         lower_env_t env;
567
568         env.chord_env  = chord_env;
569         env.do_copy    = do_copy;
570         env.dbg_module = firm_dbg_register("ir.be.lower");
571
572         irg_walk_blkwise_graph(chord_env->irg, NULL, lower_nodes_walker, &env);
573 }
574
575 #undef is_Perm
576 #undef is_Call