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