29345085e253febb12f865849d43817fa20e0bbb
[libfirm] / ir / be / belower.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Performs lowering of perm nodes. Inserts copies to assure register constraints.
23  * @author      Christian Wuerdig
24  * @date        14.12.2005
25  * @version     $Id$
26  */
27 #include "config.h"
28
29 #include <stdlib.h>
30
31 #include "ircons.h"
32 #include "debug.h"
33 #include "irhooks.h"
34 #include "xmalloc.h"
35 #include "irnodeset.h"
36 #include "irgmod.h"
37 #include "iredges_t.h"
38 #include "irgwalk.h"
39 #include "array_t.h"
40
41 #include "bearch_t.h"
42 #include "belower.h"
43 #include "benode_t.h"
44 #include "besched_t.h"
45 #include "bestat.h"
46 #include "bessaconstr.h"
47 #include "beintlive_t.h"
48
49 #undef KEEP_ALIVE_COPYKEEP_HACK
50
51 /** Associates an op with it's copy and CopyKeep. */
52 typedef struct {
53         ir_node *op;         /**< an irn which must be different */
54         ir_nodeset_t copies; /**< all non-spillable copies of this irn */
55         const arch_register_class_t *cls;
56 } op_copy_assoc_t;
57
58 /** Environment for constraints. */
59 typedef struct {
60         be_irg_t       *birg;
61         pset           *op_set;
62         struct obstack obst;
63         DEBUG_ONLY(firm_dbg_module_t *dbg;)
64 } constraint_env_t;
65
66 /** Lowering walker environment. */
67 typedef struct _lower_env_t {
68         be_irg_t         *birg;
69         unsigned          do_copy : 1;
70         DEBUG_ONLY(firm_dbg_module_t *dbg_module;)
71 } lower_env_t;
72
73 /** Holds a Perm register pair. */
74 typedef struct _reg_pair_t {
75         const arch_register_t *in_reg;    /**< a perm IN register */
76         ir_node               *in_node;   /**< the in node to which the register belongs */
77
78         const arch_register_t *out_reg;   /**< a perm OUT register */
79         ir_node               *out_node;  /**< the out node to which the register belongs */
80
81         int                    checked;   /**< indicates whether the pair was check for cycle or not */
82 } reg_pair_t;
83
84 typedef enum _perm_type_t {
85         PERM_CYCLE,
86         PERM_CHAIN,
87         PERM_SWAP,
88         PERM_COPY
89 } perm_type_t;
90
91 /** Structure to represent cycles or chains in a Perm. */
92 typedef struct _perm_cycle_t {
93         const arch_register_t **elems;       /**< the registers in the cycle */
94         int                     n_elems;     /**< number of elements in the cycle */
95         perm_type_t             type;        /**< type (CHAIN or CYCLE) */
96 } perm_cycle_t;
97
98 /** Compare the two operands. */
99 static int cmp_op_copy_assoc(const void *a, const void *b) {
100         const op_copy_assoc_t *op1 = a;
101         const op_copy_assoc_t *op2 = b;
102
103         return op1->op != op2->op;
104 }
105
106 /** Compare the in registers of two register pairs. */
107 static int compare_reg_pair(const void *a, const void *b) {
108         const reg_pair_t *pair_a = a;
109         const reg_pair_t *pair_b = b;
110
111         if (pair_a->in_reg->index > pair_b->in_reg->index)
112                 return 1;
113         else
114                 return -1;
115 }
116
117 /** returns the number register pairs marked as checked. */
118 static int get_n_checked_pairs(reg_pair_t *pairs, int n) {
119         int i, n_checked = 0;
120
121         for (i = 0; i < n; i++) {
122                 if (pairs[i].checked)
123                         n_checked++;
124         }
125
126         return n_checked;
127 }
128
129 /**
130  * Gets the node corresponding to a register from an array of register pairs.
131  * NOTE: The given registers pairs and the register to look for must belong
132  *       to the same register class.
133  *
134  * @param pairs  The array of register pairs
135  * @param n      The number of pairs
136  * @param reg    The register to look for
137  * @param in_out 0 == look for IN register, 1 == look for OUT register
138  * @return The corresponding node or NULL if not found
139  */
140 static ir_node *get_node_for_register(reg_pair_t *pairs, int n, const arch_register_t *reg, int in_out) {
141         int i;
142
143         if (in_out) {
144                 for (i = 0; i < n; i++) {
145                         /* out register matches */
146                         if (pairs[i].out_reg->index == reg->index)
147                                 return pairs[i].out_node;
148                 }
149         }
150         else {
151                 for (i = 0; i < n; i++) {
152                         /* in register matches */
153                         if (pairs[i].in_reg->index == reg->index)
154                                 return pairs[i].in_node;
155                 }
156         }
157
158         return NULL;
159 }
160
161 /**
162  * Gets the index in the register pair array where the in/out register
163  * corresponds to reg_idx.
164  *
165  * @param pairs  The array of register pairs
166  * @param n      The number of pairs
167  * @param reg    The register index to look for
168  * @param in_out 0 == look for IN register, 1 == look for OUT register
169  * @return The corresponding index in pairs or -1 if not found
170  */
171 static int get_pairidx_for_regidx(reg_pair_t *pairs, int n, int reg_idx, int in_out) {
172         int i;
173
174         if (in_out) {
175                 for (i = 0; i < n; i++) {
176                         /* out register matches */
177                         if ((int) pairs[i].out_reg->index == reg_idx)
178                                 return i;
179                 }
180         }
181         else {
182                 for (i = 0; i < n; i++) {
183                         /* in register matches */
184                         if ((int) pairs[i].in_reg->index == reg_idx)
185                                 return i;
186                 }
187         }
188
189         return -1;
190 }
191
192 /**
193  * Gets an array of register pairs and tries to identify a cycle or chain starting
194  * at position start.
195  *
196  * @param cycle Variable to hold the cycle
197  * @param pairs Array of register pairs
198  * @param start Index to start
199  * @return The cycle or chain
200  */
201 static perm_cycle_t *get_perm_cycle(perm_cycle_t *cycle, reg_pair_t *pairs, int n, int start) {
202         int head         = pairs[start].in_reg->index;
203         int cur_idx      = pairs[start].out_reg->index;
204         int cur_pair_idx = start;
205         int n_pairs_done = get_n_checked_pairs(pairs, n);
206         int idx;
207         perm_type_t cycle_tp = PERM_CYCLE;
208
209         /* We could be right in the middle of a chain, so we need to find the start */
210         while (head != cur_idx) {
211                 /* goto previous register in cycle or chain */
212                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, head, 1);
213
214                 if (cur_pair_idx < 0) {
215                         cycle_tp = PERM_CHAIN;
216                         break;
217                 }
218                 else {
219                         head  = pairs[cur_pair_idx].in_reg->index;
220                         start = cur_pair_idx;
221                 }
222         }
223
224         /* assume worst case: all remaining pairs build a cycle or chain */
225         cycle->elems    = XMALLOCNZ(const arch_register_t*, (n - n_pairs_done) * 2);
226         cycle->n_elems  = 2;  /* initial number of elements is 2 */
227         cycle->elems[0] = pairs[start].in_reg;
228         cycle->elems[1] = pairs[start].out_reg;
229         cycle->type     = cycle_tp;
230         cur_idx         = pairs[start].out_reg->index;
231
232         idx = 2;
233         /* check for cycle or end of a chain */
234         while (cur_idx != head) {
235                 /* goto next register in cycle or chain */
236                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cur_idx, 0);
237
238                 if (cur_pair_idx < 0)
239                         break;
240
241                 cur_idx = pairs[cur_pair_idx].out_reg->index;
242
243                 /* it's not the first element: insert it */
244                 if (cur_idx != head) {
245                         cycle->elems[idx++] = pairs[cur_pair_idx].out_reg;
246                         cycle->n_elems++;
247                 }
248                 else {
249                         /* we are there where we started -> CYCLE */
250                         cycle->type = PERM_CYCLE;
251                 }
252         }
253
254         /* mark all pairs having one in/out register with cycle in common as checked */
255         for (idx = 0; idx < cycle->n_elems; idx++) {
256                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 0);
257
258                 if (cur_pair_idx >= 0)
259                         pairs[cur_pair_idx].checked = 1;
260
261                 cur_pair_idx = get_pairidx_for_regidx(pairs, n, cycle->elems[idx]->index, 1);
262
263                 if (cur_pair_idx >= 0)
264                         pairs[cur_pair_idx].checked = 1;
265         }
266
267         return cycle;
268 }
269
270 /**
271  * Lowers a perm node.  Resolves cycles and creates a bunch of
272  * copy and swap operations to permute registers.
273  * Note: The caller of this function has to make sure, that irn
274  *       is a Perm node.
275  *
276  * @param irn      The perm node
277  * @param block    The block the perm node belongs to
278  * @param walk_env The environment
279  */
280 static void lower_perm_node(ir_node *irn, void *walk_env) {
281         ir_graph        *irg = get_irn_irg(irn);
282         const arch_register_class_t *reg_class;
283         lower_env_t     *env         = walk_env;
284         int             real_size    = 0;
285         int             keep_perm    = 0;
286         int             n, i, pn, do_copy, j, n_ops;
287         reg_pair_t      *pairs;
288         const ir_edge_t *edge;
289         ir_node         *sched_point, *block, *in[2];
290         ir_node         *arg1, *arg2, *res1, *res2;
291         ir_node         *cpyxchg = NULL;
292         DEBUG_ONLY(firm_dbg_module_t *mod;)
293
294         do_copy  = env->do_copy;
295         DEBUG_ONLY(mod = env->dbg_module;)
296         block    = get_nodes_block(irn);
297
298         /*
299                 Get the schedule predecessor node to the perm
300                 NOTE: This works with auto-magic. If we insert the
301                         new copy/exchange nodes after this node, everything
302                         should be ok.
303         */
304         sched_point = sched_prev(irn);
305         DBG((mod, LEVEL_1, "perm: %+F\n", irn));
306         DBG((mod, LEVEL_1, "sched point is %+F\n", sched_point));
307         assert(sched_point && "Perm is not scheduled or has no predecessor");
308
309         n = get_irn_arity(irn);
310         assert(n == get_irn_n_edges(irn) && "perm's in and out numbers different");
311
312         reg_class = arch_get_irn_register(get_irn_n(irn, 0))->reg_class;
313         pairs     = alloca(n * sizeof(pairs[0]));
314
315         /* build the list of register pairs (in, out) */
316         i = 0;
317         foreach_out_edge(irn, edge) {
318                 pairs[i].out_node = get_edge_src_irn(edge);
319                 pn                = get_Proj_proj(pairs[i].out_node);
320                 pairs[i].in_node  = get_irn_n(irn, pn);
321
322                 pairs[i].in_reg  = arch_get_irn_register(pairs[i].in_node);
323                 pairs[i].out_reg = arch_get_irn_register(pairs[i].out_node);
324
325                 pairs[i].checked = 0;
326                 i++;
327         }
328
329         /* sort the register pairs by the indices of the in registers */
330         qsort(pairs, n, sizeof(pairs[0]), compare_reg_pair);
331
332         /* Mark all equal pairs as checked, and exchange the OUT proj with
333                 the IN node. */
334         for (i = 0; i < n; i++) {
335                 if (pairs[i].in_reg->index == pairs[i].out_reg->index) {
336                         DBG((mod, LEVEL_1, "%+F removing equal perm register pair (%+F, %+F, %s)\n",
337                                 irn, pairs[i].in_node, pairs[i].out_node, pairs[i].out_reg->name));
338
339                         /* We have to check for a special case:
340                                 The in-node could be a Proj from a Perm. In this case,
341                                 we need to correct the projnum */
342                         if (be_is_Perm(pairs[i].in_node) && is_Proj(pairs[i].in_node)) {
343                                 set_Proj_proj(pairs[i].out_node, get_Proj_proj(pairs[i].in_node));
344                         }
345
346                         /* reroute the edges from the proj to the argument */
347                         exchange(pairs[i].out_node, pairs[i].in_node);
348                         //edges_reroute(pairs[i].out_node, pairs[i].in_node, env->birg->irg);
349                         //set_irn_n(pairs[i].out_node, 0, new_Bad());
350
351                         pairs[i].checked = 1;
352                 }
353         }
354
355         /* Set do_copy to 0 if it's on but we have no free register */
356         if (do_copy) {
357                 do_copy = 0;
358         }
359
360         real_size = n - get_n_checked_pairs(pairs, n);
361
362         /* check for cycles and chains */
363         while (get_n_checked_pairs(pairs, n) < n) {
364                 perm_cycle_t *cycle;
365
366                 i = n_ops = 0;
367
368                 /* go to the first not-checked pair */
369                 while (pairs[i].checked) i++;
370                 cycle = XMALLOCZ(perm_cycle_t);
371                 cycle = get_perm_cycle(cycle, pairs, n, i);
372
373                 DB((mod, LEVEL_1, "%+F: following %s created:\n  ", irn, cycle->type == PERM_CHAIN ? "chain" : "cycle"));
374                 for (j = 0; j < cycle->n_elems; j++) {
375                         DB((mod, LEVEL_1, " %s", cycle->elems[j]->name));
376                 }
377                 DB((mod, LEVEL_1, "\n"));
378
379                 /*
380                         We don't need to do anything if we have a Perm with two
381                         elements which represents a cycle, because those nodes
382                         already represent exchange nodes
383                 */
384                 if (n == 2 && cycle->type == PERM_CYCLE) {
385                         free(cycle);
386                         keep_perm = 1;
387                         continue;
388                 }
389
390 //TODO: - iff PERM_CYCLE && do_copy -> determine free temp reg and insert copy to/from it before/after
391 //        the copy cascade (this reduces the cycle into a chain)
392
393                 /* build copy/swap nodes from back to front */
394                 for (i = cycle->n_elems - 2; i >= 0; i--) {
395                         arg1 = get_node_for_register(pairs, n, cycle->elems[i], 0);
396                         arg2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 0);
397
398                         res1 = get_node_for_register(pairs, n, cycle->elems[i], 1);
399                         res2 = get_node_for_register(pairs, n, cycle->elems[i + 1], 1);
400                         /*
401                                 If we have a cycle and don't copy: we need to create exchange nodes
402                                 NOTE: An exchange node is a perm node with 2 INs and 2 OUTs
403                                 IN_1  = in node with register i
404                                 IN_2  = in node with register i + 1
405                                 OUT_1 = out node with register i + 1
406                                 OUT_2 = out node with register i
407                         */
408                         if (cycle->type == PERM_CYCLE && !do_copy) {
409                                 in[0] = arg1;
410                                 in[1] = arg2;
411
412                                 /* At this point we have to handle the following problem:     */
413                                 /*                                                            */
414                                 /* If we have a cycle with more than two elements, then       */
415                                 /* this could correspond to the following Perm node:          */
416                                 /*                                                            */
417                                 /*   +----+   +----+   +----+                                 */
418                                 /*   | r1 |   | r2 |   | r3 |                                 */
419                                 /*   +-+--+   +-+--+   +--+-+                                 */
420                                 /*     |        |         |                                   */
421                                 /*     |        |         |                                   */
422                                 /*   +-+--------+---------+-+                                 */
423                                 /*   |         Perm         |                                 */
424                                 /*   +-+--------+---------+-+                                 */
425                                 /*     |        |         |                                   */
426                                 /*     |        |         |                                   */
427                                 /*   +-+--+   +-+--+   +--+-+                                 */
428                                 /*   |Proj|   |Proj|   |Proj|                                 */
429                                 /*   | r2 |   | r3 |   | r1 |                                 */
430                                 /*   +----+   +----+   +----+                                 */
431                                 /*                                                            */
432                                 /* This node is about to be split up into two 2x Perm's       */
433                                 /* for which we need 4 Proj's and the one additional Proj     */
434                                 /* of the first Perm has to be one IN of the second. So in    */
435                                 /* general we need to create one additional Proj for each     */
436                                 /* "middle" Perm and set this to one in node of the successor */
437                                 /* Perm.                                                      */
438
439                                 DBG((mod, LEVEL_1, "%+F creating exchange node (%+F, %s) and (%+F, %s) with\n",
440                                         irn, arg1, cycle->elems[i]->name, arg2, cycle->elems[i + 1]->name));
441                                 DBG((mod, LEVEL_1, "%+F                        (%+F, %s) and (%+F, %s)\n",
442                                         irn, res1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
443
444                                 cpyxchg = be_new_Perm(reg_class, irg, block, 2, in);
445                                 n_ops++;
446
447                                 if (i > 0) {
448                                         /* cycle is not done yet */
449                                         int pidx = get_pairidx_for_regidx(pairs, n, cycle->elems[i]->index, 0);
450
451                                         /* create intermediate proj */
452                                         res1 = new_r_Proj(irg, block, cpyxchg, get_irn_mode(res1), 0);
453
454                                         /* set as in for next Perm */
455                                         pairs[pidx].in_node = res1;
456                                 }
457
458                                 set_Proj_pred(res2, cpyxchg);
459                                 set_Proj_proj(res2, 0);
460                                 set_Proj_pred(res1, cpyxchg);
461                                 set_Proj_proj(res1, 1);
462
463                                 arch_set_irn_register(res2, cycle->elems[i + 1]);
464                                 arch_set_irn_register(res1, cycle->elems[i]);
465
466                                 /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
467                                 sched_add_after(sched_point, cpyxchg);
468
469                                 DBG((mod, LEVEL_1, "replacing %+F with %+F, placed new node after %+F\n", irn, cpyxchg, sched_point));
470
471                                 /* set the new scheduling point */
472                                 sched_point = res1;
473                         }
474                         else {
475                                 DBG((mod, LEVEL_1, "%+F creating copy node (%+F, %s) -> (%+F, %s)\n",
476                                         irn, arg1, cycle->elems[i]->name, res2, cycle->elems[i + 1]->name));
477
478                                 cpyxchg = be_new_Copy(reg_class, irg, block, arg1);
479                                 arch_set_irn_register(cpyxchg, cycle->elems[i + 1]);
480                                 n_ops++;
481
482                                 /* exchange copy node and proj */
483                                 exchange(res2, cpyxchg);
484
485                                 /* insert the copy/exchange node in schedule after the magic schedule node (see above) */
486                                 sched_add_after(sched_point, cpyxchg);
487
488                                 /* set the new scheduling point */
489                                 sched_point = cpyxchg;
490                         }
491                 }
492
493                 free((void *) cycle->elems);
494                 free(cycle);
495         }
496
497         /* remove the perm from schedule */
498         if (! keep_perm) {
499                 sched_remove(irn);
500                 kill_node(irn);
501         }
502 }
503
504
505
506 static int has_irn_users(const ir_node *irn) {
507         return get_irn_out_edge_first_kind(irn, EDGE_KIND_NORMAL) != 0;
508 }
509
510 /**
511  * Skip all Proj nodes.
512  */
513 static INLINE ir_node *belower_skip_proj(ir_node *irn) {
514         while(is_Proj(irn))
515                 irn = get_Proj_pred(irn);
516         return irn;
517 }
518
519 static ir_node *find_copy(ir_node *irn, ir_node *op)
520 {
521         ir_node *block    = get_nodes_block(irn);
522         ir_node *cur_node;
523
524         for (cur_node = sched_prev(irn);
525                 ! is_Block(cur_node) && be_is_Copy(cur_node) && get_nodes_block(cur_node) == block;
526                 cur_node = sched_prev(cur_node))
527         {
528                 if (be_get_Copy_op(cur_node) == op && arch_irn_is(cur_node, dont_spill))
529                         return cur_node;
530         }
531
532         return NULL;
533 }
534
535 static void gen_assure_different_pattern(ir_node *irn, ir_node *other_different, constraint_env_t *env) {
536         be_irg_t                    *birg     = env->birg;
537         ir_graph                    *irg      = be_get_birg_irg(birg);
538         pset                        *op_set   = env->op_set;
539         ir_node                     *block    = get_nodes_block(irn);
540         const arch_register_class_t *cls      = arch_get_irn_reg_class(other_different, -1);
541         ir_node                     *in[2], *keep, *cpy;
542         op_copy_assoc_t             key, *entry;
543         DEBUG_ONLY(firm_dbg_module_t *mod     = env->dbg;)
544
545         if (arch_irn_is(other_different, ignore) ||
546                         !mode_is_datab(get_irn_mode(other_different))) {
547                 DBG((mod, LEVEL_1, "ignore constraint for %+F because other_irn is ignore or not a datab node\n", irn));
548                 return;
549         }
550
551         /* Make a not spillable copy of the different node   */
552         /* this is needed because the different irn could be */
553         /* in block far far away                             */
554         /* The copy is optimized later if not needed         */
555
556         /* check if already exists such a copy in the schedule immediately before */
557         cpy = find_copy(belower_skip_proj(irn), other_different);
558         if (! cpy) {
559                 cpy = be_new_Copy(cls, irg, block, other_different);
560                 be_node_set_flags(cpy, BE_OUT_POS(0), arch_irn_flags_dont_spill);
561                 DBG((mod, LEVEL_1, "created non-spillable %+F for value %+F\n", cpy, other_different));
562         }
563         else {
564                 DBG((mod, LEVEL_1, "using already existing %+F for value %+F\n", cpy, other_different));
565         }
566
567         in[0] = irn;
568         in[1] = cpy;
569
570         /* Add the Keep resp. CopyKeep and reroute the users */
571         /* of the other_different irn in case of CopyKeep.   */
572         if (has_irn_users(other_different)) {
573                 keep = be_new_CopyKeep_single(cls, irg, block, cpy, irn, get_irn_mode(other_different));
574                 be_node_set_reg_class(keep, 1, cls);
575         }
576         else {
577                 keep = be_new_Keep(cls, irg, block, 2, in);
578         }
579
580         DBG((mod, LEVEL_1, "created %+F(%+F, %+F)\n\n", keep, irn, cpy));
581
582         /* insert copy and keep into schedule */
583         assert(sched_is_scheduled(irn) && "need schedule to assure constraints");
584         if (! sched_is_scheduled(cpy))
585                 sched_add_before(belower_skip_proj(irn), cpy);
586         sched_add_after(irn, keep);
587
588         /* insert the other different and it's copies into the set */
589         key.op = other_different;
590         entry  = pset_find(op_set, &key, hash_irn(other_different));
591
592         if (! entry) {
593                 entry         = obstack_alloc(&env->obst, sizeof(*entry));
594                 ir_nodeset_init(&entry->copies);
595                 entry->op     = other_different;
596                 entry->cls    = cls;
597         }
598
599         /* insert copy */
600         ir_nodeset_insert(&entry->copies, cpy);
601
602         /* insert keep in case of CopyKeep */
603         if (be_is_CopyKeep(keep)) {
604                 ir_nodeset_insert(&entry->copies, keep);
605         }
606
607         pset_insert(op_set, entry, hash_irn(other_different));
608 }
609
610 /**
611  * Checks if node has a must_be_different constraint in output and adds a Keep
612  * then to assure the constraint.
613  */
614 static void assure_different_constraints(ir_node *irn, constraint_env_t *env) {
615         ir_node                   *skipped_irn = belower_skip_proj(irn);
616         const arch_register_req_t *req         = arch_get_register_req(irn, -1);
617
618         if (arch_register_req_is(req, must_be_different)) {
619                 const unsigned other = req->other_different;
620                 int i;
621
622                 if (arch_register_req_is(req, should_be_same)) {
623                         const unsigned same = req->other_same;
624
625                         if (is_po2(other) && is_po2(same)) {
626                                 int idx_other = ntz(other);
627                                 int idx_same  = ntz(same);
628
629                                 /*
630                                  * We can safely ignore a should_be_same x must_be_different y
631                                  * IFF both inputs are equal!
632                                  */
633                                 if (get_irn_n(skipped_irn, idx_other) == get_irn_n(skipped_irn, idx_same)) {
634                                         return;
635                                 }
636                         }
637                 }
638                 for (i = 0; 1U << i <= other; ++i) {
639                         if (other & (1U << i)) {
640                                 ir_node *different_from = get_irn_n(skipped_irn, i);
641                                 gen_assure_different_pattern(irn, different_from, env);
642                         }
643                 }
644         }
645 }
646
647 /**
648  * Calls the functions to assure register constraints.
649  *
650  * @param irn      The node to be checked for lowering
651  * @param walk_env The walker environment
652  */
653 static void assure_constraints_walker(ir_node *irn, void *walk_env) {
654         if (is_Block(irn))
655                 return;
656
657         if (sched_is_scheduled(irn) && mode_is_datab(get_irn_mode(irn)))
658                 assure_different_constraints(irn, walk_env);
659 }
660
661 /**
662  * Melt all copykeeps pointing to the same node
663  * (or Projs of the same node), copying the same operand.
664  */
665 static void melt_copykeeps(constraint_env_t *cenv) {
666         be_irg_t *birg = cenv->birg;
667         ir_graph *irg  = be_get_birg_irg(birg);
668         op_copy_assoc_t *entry;
669
670         /* for all */
671         foreach_pset(cenv->op_set, entry) {
672                 int     idx, num_ck;
673                 ir_node *cp;
674                 struct obstack obst;
675                 ir_nodeset_iterator_t iter;
676                 ir_node **ck_arr, **melt_arr;
677
678                 obstack_init(&obst);
679
680                 /* collect all copykeeps */
681                 num_ck = idx = 0;
682                 foreach_ir_nodeset(&entry->copies, cp, iter) {
683                         if (be_is_CopyKeep(cp)) {
684                                 obstack_grow(&obst, &cp, sizeof(cp));
685                                 ++num_ck;
686                         }
687 #ifdef KEEP_ALIVE_COPYKEEP_HACK
688                         else {
689                                 set_irn_mode(cp, mode_ANY);
690                                 keep_alive(cp);
691                         }
692 #endif /* KEEP_ALIVE_COPYKEEP_HACK */
693                 }
694
695                 /* compare each copykeep with all other copykeeps */
696                 ck_arr = (ir_node **)obstack_finish(&obst);
697                 for (idx = 0; idx < num_ck; ++idx) {
698                         ir_node *ref, *ref_mode_T;
699
700                         if (ck_arr[idx]) {
701                                 int j, n_melt;
702                                 ir_node **new_ck_in;
703                                 ir_node *new_ck;
704                                 ir_node *sched_pt = NULL;
705
706                                 n_melt     = 1;
707                                 ref        = ck_arr[idx];
708                                 ref_mode_T = skip_Proj(get_irn_n(ref, 1));
709                                 obstack_grow(&obst, &ref, sizeof(ref));
710
711                                 DBG((cenv->dbg, LEVEL_1, "Trying to melt %+F:\n", ref));
712
713                                 /* check for copykeeps pointing to the same mode_T node as the reference copykeep */
714                                 for (j = 0; j < num_ck; ++j) {
715                                         ir_node *cur_ck = ck_arr[j];
716
717                                         if (j != idx && cur_ck && skip_Proj(get_irn_n(cur_ck, 1)) == ref_mode_T) {
718                                                 obstack_grow(&obst, &cur_ck, sizeof(cur_ck));
719                                                 ir_nodeset_remove(&entry->copies, cur_ck);
720                                                 DBG((cenv->dbg, LEVEL_1, "\t%+F\n", cur_ck));
721                                                 ck_arr[j] = NULL;
722                                                 ++n_melt;
723                                                 sched_remove(cur_ck);
724                                         }
725                                 }
726                                 ck_arr[idx] = NULL;
727
728                                 /* check, if we found some candidates for melting */
729                                 if (n_melt == 1) {
730                                         DBG((cenv->dbg, LEVEL_1, "\tno candidate found\n"));
731                                         continue;
732                                 }
733
734                                 ir_nodeset_remove(&entry->copies, ref);
735                                 sched_remove(ref);
736
737                                 melt_arr = (ir_node **)obstack_finish(&obst);
738                                 /* melt all found copykeeps */
739                                 NEW_ARR_A(ir_node *, new_ck_in, n_melt);
740                                 for (j = 0; j < n_melt; ++j) {
741                                         new_ck_in[j] = get_irn_n(melt_arr[j], 1);
742
743                                         /* now, we can kill the melted keep, except the */
744                                         /* ref one, we still need some information      */
745                                         if (melt_arr[j] != ref)
746                                                 kill_node(melt_arr[j]);
747                                 }
748
749 #ifdef KEEP_ALIVE_COPYKEEP_HACK
750                                 new_ck = be_new_CopyKeep(entry->cls, irg, get_nodes_block(ref), be_get_CopyKeep_op(ref), n_melt, new_ck_in, mode_ANY);
751                                 keep_alive(new_ck);
752 #else
753                                 new_ck = be_new_CopyKeep(entry->cls, irg, get_nodes_block(ref), be_get_CopyKeep_op(ref), n_melt, new_ck_in, get_irn_mode(ref));
754 #endif /* KEEP_ALIVE_COPYKEEP_HACK */
755
756                                 /* set register class for all kept inputs */
757                                 for (j = 1; j <= n_melt; ++j)
758                                         be_node_set_reg_class(new_ck, j, entry->cls);
759
760                                 ir_nodeset_insert(&entry->copies, new_ck);
761
762                                 /* find scheduling point */
763                                 sched_pt = ref_mode_T;
764                                 do {
765                                         /* just walk along the schedule until a non-Keep/CopyKeep node is found */
766                                         sched_pt = sched_next(sched_pt);
767                                 } while (be_is_Keep(sched_pt) || be_is_CopyKeep(sched_pt));
768
769                                 sched_add_before(sched_pt, new_ck);
770                                 DBG((cenv->dbg, LEVEL_1, "created %+F, scheduled before %+F\n", new_ck, sched_pt));
771
772                                 /* finally: kill the reference copykeep */
773                                 kill_node(ref);
774                         }
775                 }
776
777                 obstack_free(&obst, NULL);
778         }
779 }
780
781 /**
782  * Walks over all nodes to assure register constraints.
783  *
784  * @param birg  The birg structure containing the irg
785  */
786 void assure_constraints(be_irg_t *birg) {
787         ir_graph         *irg      = be_get_birg_irg(birg);
788         constraint_env_t cenv;
789         op_copy_assoc_t  *entry;
790         ir_node          **nodes;
791         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, "firm.be.lower.constr");
792
793         DEBUG_ONLY(cenv.dbg = mod;)
794         cenv.birg   = birg;
795         cenv.op_set = new_pset(cmp_op_copy_assoc, 16);
796         obstack_init(&cenv.obst);
797
798         irg_walk_blkwise_graph(irg, NULL, assure_constraints_walker, &cenv);
799
800         /* melt copykeeps, pointing to projs of */
801         /* the same mode_T node and keeping the */
802         /* same operand                         */
803         melt_copykeeps(&cenv);
804
805         /* for all */
806         foreach_pset(cenv.op_set, entry) {
807                 int     n;
808                 ir_node *cp;
809                 ir_nodeset_iterator_t iter;
810                 be_ssa_construction_env_t senv;
811
812                 n     = ir_nodeset_size(&entry->copies);
813                 nodes = alloca(n * sizeof(nodes[0]));
814
815                 /* put the node in an array */
816                 DBG((mod, LEVEL_1, "introduce copies for %+F ", entry->op));
817
818                 /* collect all copies */
819                 n = 0;
820                 foreach_ir_nodeset(&entry->copies, cp, iter) {
821                         nodes[n++] = cp;
822                         DB((mod, LEVEL_1, ", %+F ", cp));
823                 }
824
825                 DB((mod, LEVEL_1, "\n"));
826
827                 /* introduce the copies for the operand and it's copies */
828                 be_ssa_construction_init(&senv, birg);
829                 be_ssa_construction_add_copy(&senv, entry->op);
830                 be_ssa_construction_add_copies(&senv, nodes, n);
831                 be_ssa_construction_fix_users(&senv, entry->op);
832                 be_ssa_construction_destroy(&senv);
833
834                 /* Could be that not all CopyKeeps are really needed, */
835                 /* so we transform unnecessary ones into Keeps.       */
836                 foreach_ir_nodeset(&entry->copies, cp, iter) {
837                         if (be_is_CopyKeep(cp) && get_irn_n_edges(cp) < 1) {
838                                 ir_node *keep;
839                                 int     n = get_irn_arity(cp);
840
841                                 keep = be_new_Keep(arch_get_irn_reg_class(cp, -1),
842                                         irg, get_nodes_block(cp), n, get_irn_in(cp) + 1);
843                                 sched_add_before(cp, keep);
844
845                                 /* Set all ins (including the block) of the CopyKeep BAD to keep the verifier happy. */
846                                 sched_remove(cp);
847                                 kill_node(cp);
848                         }
849                 }
850
851                 ir_nodeset_destroy(&entry->copies);
852         }
853
854         del_pset(cenv.op_set);
855         obstack_free(&cenv.obst, NULL);
856         be_liveness_invalidate(be_get_birg_liveness(birg));
857 }
858
859
860 /**
861  * Push nodes that do not need to be permed through the Perm.
862  * This is commonly a reload cascade at block ends.
863  * @note This routine needs interference.
864  * @note Probably, we can implement it a little more efficient.
865  *       Especially searching the frontier lazily might be better.
866  * @param perm The perm.
867  * @param data The walker data (lower_env_t).
868  * @return     1, if there is something left to perm over.
869  *             0, if removed the complete perm.
870  */
871 static int push_through_perm(ir_node *perm, void *data)
872 {
873         lower_env_t *env = data;
874
875         ir_graph *irg     = get_irn_irg(perm);
876         ir_node *bl       = get_nodes_block(perm);
877         ir_node *node;
878         int  arity        = get_irn_arity(perm);
879         int *map;
880         int *proj_map;
881         bitset_t *moved   = bitset_alloca(arity);
882         int n_moved;
883         int new_size;
884         ir_node *frontier = bl;
885         FIRM_DBG_REGISTER(firm_dbg_module_t *mod, "firm.be.lower.permmove");
886
887         int i, n;
888         const ir_edge_t *edge;
889         ir_node *one_proj = NULL, *irn;
890         const arch_register_class_t *cls = NULL;
891
892         DBG((mod, LEVEL_1, "perm move %+F irg %+F\n", perm, irg));
893
894         /* get some Proj and find out the register class of that Proj. */
895         edge     = get_irn_out_edge_first_kind(perm, EDGE_KIND_NORMAL);
896         one_proj = get_edge_src_irn(edge);
897         assert(is_Proj(one_proj));
898         cls      = arch_get_irn_reg_class(one_proj, -1);
899
900         /* Find the point in the schedule after which the
901          * potentially movable nodes must be defined.
902          * A Perm will only be pushed up to first instruction
903          * which lets an operand of itself die.
904          * If we would allow to move the Perm above this instruction,
905          * the former dead operand would be live now at the point of
906          * the Perm, increasing the register pressure by one.
907          */
908         sched_foreach_reverse_from (sched_prev(perm), irn) {
909                 for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
910                         ir_node *op = get_irn_n(irn, i);
911                         if (arch_irn_consider_in_reg_alloc(cls, op) &&
912                             !values_interfere(env->birg, op, one_proj)) {
913                                 frontier = irn;
914                                 goto found_front;
915                         }
916                 }
917         }
918 found_front:
919
920         DBG((mod, LEVEL_2, "\tfrontier: %+F\n", frontier));
921
922         node = sched_prev(perm);
923         n_moved = 0;
924         while(!sched_is_begin(node)) {
925                 const arch_register_req_t *req;
926                 int                        input = -1;
927                 ir_node                   *proj;
928
929                 /* search if node is a INPUT of Perm */
930                 foreach_out_edge(perm, edge) {
931                         ir_node *out = get_edge_src_irn(edge);
932                         int      pn  = get_Proj_proj(out);
933                         ir_node *in  = get_irn_n(perm, pn);
934                         if (node == in) {
935                                 proj  = out;
936                                 input = pn;
937                                 break;
938                         }
939                 }
940                 /* it wasn't an input to the perm, we can't do anything more */
941                 if(input < 0)
942                         break;
943                 if(!sched_comes_after(frontier, node))
944                         break;
945                 if (arch_irn_is(node, modify_flags))
946                         break;
947                 if(is_Proj(node)) {
948                         req = arch_get_register_req(get_Proj_pred(node),
949                                                     -1 - get_Proj_proj(node));
950                 } else {
951                         req = arch_get_register_req(node, -1);
952                 }
953                 if(req->type != arch_register_req_type_normal)
954                         break;
955                 for(i = get_irn_arity(node) - 1; i >= 0; --i) {
956                         ir_node *opop = get_irn_n(node, i);
957                         if (arch_irn_consider_in_reg_alloc(cls, opop)) {
958                                 break;
959                         }
960                 }
961                 if(i >= 0)
962                         break;
963
964                 DBG((mod, LEVEL_2, "\tmoving %+F after %+F, killing %+F\n", node, perm, proj));
965
966                 /* move the movable node in front of the Perm */
967                 sched_remove(node);
968                 sched_add_after(perm, node);
969
970                 /* give it the proj's register */
971                 arch_set_irn_register(node, arch_get_irn_register(proj));
972
973                 /* reroute all users of the proj to the moved node. */
974                 edges_reroute(proj, node, irg);
975
976                 /* and kill it */
977                 set_Proj_pred(proj, new_Bad());
978                 kill_node(proj);
979
980                 bitset_set(moved, input);
981                 n_moved++;
982
983                 node = sched_prev(node);
984         }
985
986         /* well, we could not push anything through the perm */
987         if(n_moved == 0)
988                 return 1;
989
990         new_size = arity - n_moved;
991         if(new_size == 0) {
992                 return 0;
993         }
994
995         map      = alloca(new_size * sizeof(map[0]));
996         proj_map = alloca(arity * sizeof(proj_map[0]));
997         memset(proj_map, -1, sizeof(proj_map[0]));
998         n   = 0;
999         for(i = 0; i < arity; ++i) {
1000                 if(bitset_is_set(moved, i))
1001                         continue;
1002                 map[n]      = i;
1003                 proj_map[i] = n;
1004                 n++;
1005         }
1006         assert(n == new_size);
1007         foreach_out_edge(perm, edge) {
1008                 ir_node *proj = get_edge_src_irn(edge);
1009                 int      pn   = get_Proj_proj(proj);
1010                 pn = proj_map[pn];
1011                 assert(pn >= 0);
1012                 set_Proj_proj(proj, pn);
1013         }
1014
1015         be_Perm_reduce(perm, new_size, map);
1016         return 1;
1017 }
1018
1019 /**
1020  * Calls the corresponding lowering function for the node.
1021  *
1022  * @param irn      The node to be checked for lowering
1023  * @param walk_env The walker environment
1024  */
1025 static void lower_nodes_after_ra_walker(ir_node *irn, void *walk_env) {
1026         int perm_stayed;
1027
1028         if (is_Block(irn) || is_Proj(irn))
1029                 return;
1030         if (!be_is_Perm(irn))
1031                 return;
1032
1033         perm_stayed = push_through_perm(irn, walk_env);
1034         if (!perm_stayed)
1035                 return;
1036
1037         lower_perm_node(irn, walk_env);
1038 }
1039
1040 /**
1041  * Walks over all blocks in an irg and performs lowering need to be
1042  * done after register allocation (e.g. perm lowering).
1043  *
1044  * @param birg      The birg object
1045  * @param do_copy   1 == resolve cycles with a free reg if available
1046  */
1047 void lower_nodes_after_ra(be_irg_t *birg, int do_copy) {
1048         lower_env_t env;
1049         ir_graph    *irg = be_get_birg_irg(birg);
1050
1051         env.birg    = birg;
1052         env.do_copy = do_copy;
1053         FIRM_DBG_REGISTER(env.dbg_module, "firm.be.lower");
1054
1055         /* we will need interference */
1056         be_liveness_assure_chk(be_get_birg_liveness(birg));
1057
1058         irg_walk_blkwise_graph(irg, NULL, lower_nodes_after_ra_walker, &env);
1059 }