made code C89 compliant (changed unnamed union in attributes)
[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 #include "debug.h"
18
19 #include "bearch.h"
20 #include "belower.h"
21 #include "benode_t.h"
22 #include "bechordal_t.h"
23 #include "besched_t.h"
24
25 #include "irgmod.h"
26 #include "iredges_t.h"
27 #include "irgwalk.h"
28
29 #ifdef HAVE_MALLOC_H
30  #include <malloc.h>
31 #endif
32 #ifdef HAVE_ALLOCA_H
33  #include <alloca.h>
34 #endif
35
36 #undef is_Perm
37 #define is_Perm(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_perm)
38
39 #undef is_Call
40 #define is_Call(arch_env, irn) (arch_irn_classify(arch_env, irn) == arch_irn_class_call)
41
42 /* lowering walker environment */
43 typedef struct _lower_env_t {
44         be_chordal_env_t  *chord_env;
45         int                do_copy;
46         firm_dbg_module_t *dbg_module;
47 } lower_env_t;
48
49 /* holds a perm register pair */
50 typedef struct _reg_pair_t {
51         const arch_register_t *in_reg;    /**< a perm IN register */
52         ir_node               *in_node;   /**< the in node to which the register belongs */
53
54         const arch_register_t *out_reg;   /**< a perm OUT register */
55         ir_node               *out_node;  /**< the out node to which the register belongs */
56
57         int                    checked;   /**< indicates whether the pair was check for cycle or not */
58 } reg_pair_t;
59
60 typedef enum _perm_type_t {
61         PERM_CYCLE,
62         PERM_CHAIN,
63         PERM_SWAP,
64         PERM_COPY
65 } perm_type_t;
66
67 /* structure to represent cycles or chains in a perm */
68 typedef struct _perm_cycle_t {
69         const arch_register_t **elems;       /**< the registers in the cycle */
70         int                     n_elems;     /**< number of elements in the cycle */
71         perm_type_t             type;        /**< type (CHAIN or CYCLE) */
72 } perm_cycle_t;
73
74 /* Compare the in registers of two register pairs */
75 static int compare_reg_pair(const void *a, const void *b) {
76         const reg_pair_t *pair_a = a;
77         const reg_pair_t *pair_b = b;
78
79         if (pair_a->in_reg->index > pair_b->in_reg->index)
80                 return 1;
81         else
82                 return -1;
83 }
84
85 /* returns the number register pairs marked as checked */
86 static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
87         int i, n_checked = 0;
88
89         for (i = 0; i < n; i++) {
90                 if (pairs[i].checked)
91                         n_checked++;
92         }
93
94         return n_checked;
95 }
96
97 /**
98  * Gets the node corresponding to a register from an array of register pairs.
99  * NOTE: The given registers pairs and the register to look for must belong
100  *       to the same register class.
101  *
102  * @param pairs  The array of register pairs
103  * @param n      The number of pairs
104  * @param reg    The register to look for
105  * @param in_out 0 == look for IN register, 1 == look for OUT register
106  * @return The corresponding node or NULL if not found
107  */
108 static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_register_t *reg, int in_out) {
109         int i;
110
111         if (in_out) {
112                 for (i = 0; i < n; i++) {
113                         /* out register matches */
114                         if (pairs[i].out_reg->index == reg->index)
115                                 return pairs[i].out_node;
116                 }
117         }
118         else {
119                 for (i = 0; i < n; i++) {
120                         /* in register matches */
121                         if (pairs[i].in_reg->index == reg->index)
122                                 return pairs[i].in_node;
123                 }
124         }
125
126         return NULL;
127 }
128
129 /**
130  * Gets the index in the register pair array where the in/out register
131  * corresponds to reg_idx.
132  *
133  * @param pairs  The array of register pairs
134  * @param n      The number of pairs
135  * @param reg    The register index to look for
136  * @param in_out 0 == look for IN register, 1 == look for OUT register
137  * @return The corresponding index in pairs or -1 if not found
138  */
139 static int get_pairidx_for_regidx(reg_pair_t *pairs, int n, int reg_idx, int in_out) {
140         int i;
141
142         if (in_out) {
143                 for (i = 0; i < n; i++) {
144                         /* out register matches */
145                         if (pairs[i].out_reg->index == reg_idx)
146                                 return i;
147                 }
148         }
149         else {
150                 for (i = 0; i < n; i++) {
151                         /* in register matches */
152                         if (pairs[i].in_reg->index == reg_idx)
153                                 return i;
154                 }
155         }
156
157         return -1;
158 }
159
160 /**
161  * Gets an array of register pairs and tries to identify a cycle or chain starting
162  * at position start.
163  *
164  * @param cycle Variable to hold the cycle
165  * @param pairs Array of register pairs
166  * @param start Index to start
167  * @return The cycle or chain
168  */
169 static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int n, int start) {
170         int head         = pairs[start].in_reg->index;
171         int cur_idx      = pairs[start].out_reg->index;
172         int cur_pair_idx = start;
173         int n_pairs_done = get_n_checked_pairs(pairs, n);
174         int idx;
175         perm_type_t cycle_tp = PERM_CYCLE;
176
177         /* We could be right in the middle of a chain, so we need to find the start */
178         while (head != cur_idx) {
179                 /* goto previous register in cycle or chain */
180                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, head, 1);
181
182                 if (cur_pair_idx < 0) {
183                         cycle_tp = PERM_CHAIN;
184                         break;
185                 }
186                 else {
187                         head  = pairs[cur_pair_idx].in_reg->index;
188                         start = cur_pair_idx;
189                 }
190         }
191
192         /* assume worst case: all remaining pairs build a cycle or chain */
193         cycle->elems    = xcalloc((n - n_pairs_done) * 2, sizeof(cycle->elems[0]));
194         cycle->n_elems  = 2;  /* initial number of elements is 2 */
195         cycle->elems[0] = pairs[start].in_reg;
196         cycle->elems[1] = pairs[start].out_reg;
197         cycle->type     = cycle_tp;
198         cur_idx         = pairs[start].out_reg->index;
199
200         idx = 2;
201         /* check for cycle or end of a chain */
202         while (cur_idx != head) {
203                 /* goto next register in cycle or chain */
204                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cur_idx, 0);
205
206                 if (cur_pair_idx < 0)
207                         break;
208
209                 cur_idx = pairs[cur_pair_idx].out_reg->index;
210
211                 /* it's not the first element: insert it */
212                 if (cur_idx != head) {
213                         cycle->elems[idx++] = pairs[cur_pair_idx].out_reg;
214                         cycle->n_elems++;
215                 }
216                 else {
217                         /* we are there where we started -> CYCLE */
218                         cycle->type = PERM_CYCLE;
219                 }
220         }
221
222         /* mark all pairs having one in/out register with cycle in common as checked */
223         for (idx = 0; idx < cycle->n_elems; idx++) {
224                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 0);
225
226                 if (cur_pair_idx >= 0)
227                         pairs[cur_pair_idx].checked = 1;
228
229                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 1);
230
231                 if (cur_pair_idx >= 0)
232                         pairs[cur_pair_idx].checked = 1;
233         }
234
235         return cycle;
236 }
237
238 /**
239  * Lowers a perm node.  Resolves cycles and creates a bunch of
240  * copy and swap operations to permute registers.
241  * Note: The caller of this function has to make sure, that irn
242  *       is a Perm node.
243  *
244  * @param irn      The perm node
245  * @param block    The block the perm node belongs to
246  * @param walk_env The environment
247  */
248 static void lower_perm_node(ir_node *irn, void *walk_env) {
249         const arch_register_class_t *reg_class;
250         const arch_env_t            *arch_env;
251         firm_dbg_module_t           *mod;
252         lower_env_t     *env = walk_env;
253         reg_pair_t      *pairs;
254         const ir_edge_t *edge;
255         perm_cycle_t    *cycle;
256         int              n, i, pn, do_copy, j;
257         ir_node         *sched_point, *block, *in[2];
258         ir_node         *arg1, *arg2, *res1, *res2;
259         ir_node         *cpyxchg = NULL;
260
261         arch_env = env->chord_env->birg->main_env->arch_env;
262         do_copy  = env->do_copy;
263         mod      = env->dbg_module;
264         block    = get_nodes_block(irn);
265
266         /*
267                 Get the schedule predecessor node to the perm
268                 NOTE: This works with auto-magic. If we insert the
269                         new copy/exchange nodes after this node, everything
270                         should be ok.
271         */
272         sched_point = sched_prev(irn);
273         DBG((mod, LEVEL_1, "sched point is %+F\n", sched_point));
274         assert(sched_point && "Perm is not scheduled or has no predecessor");
275
276         n = get_irn_arity(irn);
277         assert(n == get_irn_n_edges(irn) && "perm's in and out numbers different");
278
279         reg_class = arch_get_irn_register(arch_env, get_irn_n(irn, 0))->reg_class;
280         pairs     = alloca(n * sizeof(pairs[0]));
281
282         /* build the list of register pairs (in, out) */
283         i = 0;
284         foreach_out_edge(irn, edge) {
285                 pairs[i].out_node = get_edge_src_irn(edge);
286                 pn                = get_Proj_proj(pairs[i].out_node);
287                 pairs[i].in_node  = get_irn_n(irn, pn);
288
289                 pairs[i].in_reg  = arch_get_irn_register(arch_env, pairs[i].in_node);
290                 pairs[i].out_reg = arch_get_irn_register(arch_env, pairs[i].out_node);
291
292                 pairs[i].checked = 0;
293                 i++;
294         }
295
296         /* sort the register pairs by the indices of the in registers */
297         qsort(pairs, n, sizeof(pairs[0]), compare_reg_pair);
298
299         /* Mark all equal pairs as checked, and exchange the OUT proj with
300                 the IN node. */
301         for (i = 0; i < n; i++) {
302                 if (pairs[i].in_reg->index == pairs[i].out_reg->index) {
303                         DBG((mod, LEVEL_1, "%+F removing equal perm register pair (%+F, %+F, %s)\n",
304                                 irn, pairs[i].in_node, pairs[i].out_node, pairs[i].out_reg->name));
305
306                         /* We have to check for a special case:
307                                 The in-node could be a Proj from a Perm. In this case,
308                                 we need to correct the projnum */
309                         if (is_Perm(arch_env, pairs[i].in_node) && is_Proj(pairs[i].in_node)) {
310                                 set_Proj_proj(pairs[i].out_node, get_Proj_proj(pairs[i].in_node));
311                         }
312
313                         /* remove the proj from the schedule */
314                         sched_remove(pairs[i].out_node);
315
316                         /* reroute the edges from the proj to the argument */
317                         edges_reroute(pairs[i].out_node, pairs[i].in_node, env->chord_env->irg);
318
319                         pairs[i].checked = 1;
320                 }
321         }
322
323         /* Set do_copy to 0 if it's on but we have no free register */
324         if (do_copy) {
325                 do_copy = 0;
326         }
327
328         /* check for cycles and chains */
329         while (get_n_checked_pairs(pairs, n) < n) {
330                 i = 0;
331
332                 /* go to the first not-checked pair */
333                 while (pairs[i].checked) i++;
334                 cycle = xcalloc(1, sizeof(*cycle));
335                 cycle = get_perm_cycle(cycle, pairs, n, i);
336
337                 DB((mod, LEVEL_1, "%+F: following %s created:\n  ", irn, cycle->type == PERM_CHAIN ? "chain" : "cycle"));
338                 for (j = 0; j < cycle->n_elems; j++) {
339                         DB((mod, LEVEL_1, " %s", cycle->elems[j]->name));
340                 }
341                 DB((mod, LEVEL_1, "\n"));
342
343                 /* We don't need to do anything if we have a Perm with two
344                         elements which represents a cycle, because those nodes
345                         already represent exchange nodes */
346                 if (n == 2 && cycle->type == PERM_CYCLE) {
347                         free(cycle);
348                         continue;
349                 }
350
351 //TODO: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
352 //        the copy cascade (this reduces the cycle into a chain)
353
354                 /* build copy/swap nodes from back to front */
355                 for (i = cycle->n_elems - 2; i >= 0; i--) {
356                         arg1 = get_node_for_register(pairs, n, cycle->elems[i], 0);
357                         arg2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
358
359                         res1 = get_node_for_register(pairs, n, cycle->elems[i], 1);
360                         res2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
361
362                         /*
363                                 If we have a cycle and don't copy: we need to create exchange nodes
364                                 NOTE: An exchange node is a perm node with 2 INs and 2 OUTs
365                                 IN_1  = in node with register i
366                                 IN_2  = in node with register i + 1
367                                 OUT_1 = out node with register i + 1
368                                 OUT_2 = out node with register i
369                         */
370                         if (cycle->type == PERM_CYCLE && !do_copy) {
371                                 in[0] = arg1;
372                                 in[1] = arg2;
373
374                                 /* At this point we have to handle the following problem:     */
375                                 /*                                                            */
376                                 /* If we have a cycle with more than two elements, then       */
377                                 /* this could correspond to the following Perm node:          */
378                                 /*                                                            */
379                                 /*   +----+   +----+   +----+                                 */
380                                 /*   | r1 |   | r2 |   | r3 |                                 */
381                                 /*   +-+--+   +-+--+   +--+-+                                 */
382                                 /*     |        |         |                                   */
383                                 /*     |        |         |                                   */
384                                 /*   +-+--------+---------+-+                                 */
385                                 /*   |         Perm         |                                 */
386                                 /*   +-+--------+---------+-+                                 */
387                                 /*     |        |         |                                   */
388                                 /*     |        |         |                                   */
389                                 /*   +-+--+   +-+--+   +--+-+                                 */
390                                 /*   |Proj|   |Proj|   |Proj|                                 */
391                                 /*   | r2 |   | r3 |   | r1 |                                 */
392                                 /*   +----+   +----+   +----+                                 */
393                                 /*                                                            */
394                                 /* This node is about to be split up into two 2x Perm's       */
395                                 /* for which we need 4 Proj's and the one additional Proj     */
396                                 /* of the first Perm has to be one IN of the second. So in    */
397                                 /* general we need to create one additional Proj for each     */
398                                 /* "middle" Perm and set this to one in node of the successor */
399                                 /* Perm.                                                      */
400
401                                 DBG((mod, LEVEL_1, "%+F creating exchange node (%+F, %s) and (%+F, %s) with\n",
402                                         irn, arg1, cycle->elems[i]->name, arg2, cycle->elems[i + 1]->name));
403                                 DBG((mod, LEVEL_1, "%+F                        (%+F, %s) and (%+F, %s)\n",
404                                         irn, res1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
405
406                                 cpyxchg = be_new_Perm(reg_class, env->chord_env->irg, block, 2, in);
407
408                                 if (i > 0) {
409                                         /* cycle is not done yet */
410                                         int pidx = get_pairidx_for_regidx(pairs, n, cycle->elems[i]->index, 0);
411
412                                         /* create intermediate proj */
413                                         res1 = new_r_Proj(get_irn_irg(irn), block, cpyxchg, get_irn_mode(res1), 0);
414
415                                         /* set as in for next Perm */
416                                         pairs[pidx].in_node = res1;
417                                 }
418                                 else {
419                                         sched_remove(res1);
420                                 }
421
422                                 sched_remove(res2);
423
424                                 set_Proj_pred(res2, cpyxchg);
425                                 set_Proj_proj(res2, 0);
426                                 set_Proj_pred(res1, cpyxchg);
427                                 set_Proj_proj(res1, 1);
428
429                                 sched_add_after(sched_point, res1);
430                                 sched_add_after(sched_point, res2);
431
432                                 arch_set_irn_register(arch_env, res2, cycle->elems[i + 1]);
433                                 arch_set_irn_register(arch_env, res1, cycle->elems[i]);
434
435                                 /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
436                                 sched_add_after(sched_point, cpyxchg);
437
438                                 DBG((mod, LEVEL_1, "replacing %+F with %+F, placed new node after %+F\n", irn, cpyxchg, sched_point));
439
440                                 /* set the new scheduling point */
441                                 sched_point = res1;
442                         }
443                         else {
444                                 DBG((mod, LEVEL_1, "%+F creating copy node (%+F, %s) -> (%+F, %s)\n",
445                                         irn, arg1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
446
447                                 cpyxchg = be_new_Copy(reg_class, env->chord_env->irg, block, arg1);
448                                 arch_set_irn_register(arch_env, cpyxchg, cycle->elems[i + 1]);
449
450                                 /* remove the proj from the schedule */
451                                 sched_remove(res2);
452
453                                 /* exchange copy node and proj */
454                                 exchange(res2, cpyxchg);
455
456                                 /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
457                                 sched_add_after(sched_point, cpyxchg);
458
459                                 /* set the new scheduling point */
460                                 sched_point = cpyxchg;
461                         }
462                 }
463
464                 free((void *) cycle->elems);
465                 free(cycle);
466         }
467
468         /* remove the perm from schedule */
469         sched_remove(irn);
470 }
471
472
473
474 static int get_n_out_edges(const ir_node *irn) {
475         const ir_edge_t *edge;
476         int cnt = 0;
477
478         foreach_out_edge(irn, edge) {
479                 cnt++;
480         }
481
482         return cnt;
483 }
484
485 static ir_node *belower_skip_proj(ir_node *irn) {
486         while(is_Proj(irn))
487                 irn = get_Proj_pred(irn);
488         return irn;
489 }
490
491 static void fix_in(ir_node *irn, ir_node *old, ir_node *nw) {
492         int i, n;
493
494         irn = belower_skip_proj(irn);
495         n   = get_irn_arity(irn);
496
497         for (i = 0; i < n; i++) {
498                 if (get_irn_n(irn, i) == old) {
499                         set_irn_n(irn, i, nw);
500                         break;
501                 }
502         }
503 }
504
505 static void gen_assure_different_pattern(ir_node *irn, be_irg_t *birg, ir_node *other_different) {
506         const arch_env_t          *arch_env = birg->main_env->arch_env;
507         ir_node                   *in[2], *keep, *cpy, *temp;
508         ir_node                   *block = get_nodes_block(irn);
509         const arch_register_class_t *cls = arch_get_irn_reg_class(arch_env, other_different, -1);
510         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, "firm.be.lower");
511
512         if (arch_irn_is(arch_env, other_different, ignore) || ! mode_is_datab(get_irn_mode(other_different))) {
513                 DBG((mod, LEVEL_1, "ignore constraint for %+F because other_irn is ignore or not a datab node\n", irn));
514                 return;
515         }
516
517         /* Make a not spillable copy of the different node   */
518         /* this is needed because the different irn could be */
519         /* in block far far away                             */
520         /* The copy is optimized later if not needed         */
521
522         temp = new_rd_Unknown(birg->irg, get_irn_mode(other_different));
523         cpy = be_new_Copy(cls, birg->irg, block, temp);
524         be_node_set_flags(cpy, BE_OUT_POS(0), arch_irn_flags_dont_spill);
525
526         in[0] = irn;
527         in[1] = cpy;
528
529         /* Let the irn use the copy instead of the old other_different */
530         fix_in(irn, other_different, cpy);
531
532         /* Add the Keep resp. CopyKeep and reroute the users */
533         /* of the other_different irn in case of CopyKeep.   */
534         if (get_n_out_edges(other_different) == 0) {
535                 keep = be_new_Keep(cls, birg->irg, block, 2, in);
536         }
537         else {
538                 keep = be_new_CopyKeep_single(cls, birg->irg, block, cpy, irn, get_irn_mode(other_different));
539                 be_node_set_reg_class(keep, 1, cls);
540                 edges_reroute(other_different, keep, birg->irg);
541         }
542
543         /* after rerouting: let the copy point to the other_different irn */
544         set_irn_n(cpy, 0, other_different);
545
546         DBG((mod, LEVEL_1, "created %+F for %+F to assure should_be_different\n", keep, irn));
547 }
548
549 /**
550  * Checks if node has a should_be_different constraint in output
551  * and adds a Keep then to assure the constraint.
552  */
553 static void assure_different_constraints(ir_node *irn, be_irg_t *birg) {
554         const arch_env_t          *arch_env = birg->main_env->arch_env;
555         const arch_register_req_t *req;
556         arch_register_req_t        req_temp;
557         int i, n;
558
559         req = arch_get_register_req(arch_env, &req_temp, irn, -1);
560
561         if (req) {
562                 if (arch_register_req_is(req, should_be_different)) {
563                         gen_assure_different_pattern(irn, birg, req->other_different);
564                 }
565                 else if (arch_register_req_is(req, should_be_different_from_all)) {
566                         n = get_irn_arity(belower_skip_proj(irn));
567                         for (i = 0; i < n; i++) {
568                                 gen_assure_different_pattern(irn, birg, get_irn_n(belower_skip_proj(irn), i));
569                         }
570                 }
571         }
572 }
573
574
575
576 /**
577  * Calls the functions to assure register constraints.
578  *
579  * @param irn      The node to be checked for lowering
580  * @param walk_env The walker environment
581  */
582 static void assure_constraints_walker(ir_node *irn, void *walk_env) {
583         if (is_Block(irn))
584                 return;
585
586         if (mode_is_datab(get_irn_mode(irn)))
587                 assure_different_constraints(irn, walk_env);
588
589         return;
590 }
591
592
593
594 /**
595  * Walks over all nodes to assure register constraints.
596  *
597  * @param birg  The birg structure containing the irg
598  */
599 void assure_constraints(be_irg_t *birg) {
600         irg_walk_blkwise_graph(birg->irg, NULL, assure_constraints_walker, birg);
601 }
602
603
604
605 /**
606  * Calls the corresponding lowering function for the node.
607  *
608  * @param irn      The node to be checked for lowering
609  * @param walk_env The walker environment
610  */
611 static void lower_nodes_after_ra_walker(ir_node *irn, void *walk_env) {
612         lower_env_t      *env      = walk_env;
613         const arch_env_t *arch_env = env->chord_env->birg->main_env->arch_env;
614
615         if (!is_Block(irn) && !is_Proj(irn)) {
616                 if (is_Perm(arch_env, irn)) {
617                         lower_perm_node(irn, walk_env);
618                 }
619         }
620
621         return;
622 }
623
624
625
626 /**
627  * Walks over all blocks in an irg and performs lowering need to be
628  * done after register allocation (e.g. perm lowering).
629  *
630  * @param chord_env The chordal environment containing the irg
631  * @param do_copy   1 == resolve cycles with a free reg if available
632  */
633 void lower_nodes_after_ra(be_chordal_env_t *chord_env, int do_copy) {
634         lower_env_t env;
635
636         env.chord_env  = chord_env;
637         env.do_copy    = do_copy;
638         FIRM_DBG_REGISTER(env.dbg_module, "firm.be.lower");
639
640         irg_walk_blkwise_graph(chord_env->irg, NULL, lower_nodes_after_ra_walker, &env);
641 }
642
643 #undef is_Perm
644 #undef is_Call