bugfix: update_scc() must mark already seen SCC nodes, else a node might be put more...
[libfirm] / ir / opt / opt_osr.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   Operator Strength Reduction.
23  * @date    12.5.2006
24  * @author  Michael Beck
25  * @version $Id$
26  * @summary
27  *  Implementation of the Operator Strength Reduction algorithm
28  *  by Keith D. Cooper, L. Taylor Simpson, Christopher A. Vick.
29  *  Extended version.
30  */
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #include "adt/pdeq.h"
36 #include "iroptimize.h"
37 #include "irgraph.h"
38 #include "ircons.h"
39 #include "irop_t.h"
40 #include "irdom.h"
41 #include "irgmod.h"
42 #include "irflag_t.h"
43 #include "irgwalk.h"
44 #include "irouts.h"
45 #include "iredges.h"
46 #include "debug.h"
47 #include "obst.h"
48 #include "set.h"
49 #include "tv.h"
50 #include "hashptr.h"
51 #include "irtools.h"
52 #include "irloop_t.h"
53 #include "array.h"
54 #include "firmstat.h"
55 #include "xmalloc.h"
56
57 /** The debug handle. */
58 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
59
60 /** A scc. */
61 typedef struct scc {
62         ir_node  *head;         /**< the head of the list */
63         tarval   *init;     /**< the init value iff only one exists. */
64         tarval   *incr;     /**< the induction variable increment if only a single const exists. */
65         unsigned code;      /**< == iro_Add if +incr, iro_Sub if -incr, 0 if not analysed, iro_Bad else */
66 } scc;
67
68 /** A node entry */
69 typedef struct node_entry {
70         unsigned DFSnum;    /**< the DFS number of this node */
71         unsigned low;       /**< the low number of this node */
72         ir_node  *header;   /**< the header of this node */
73         int      in_stack;  /**< flag, set if the node is on the stack */
74         ir_node  *next;     /**< link to the next node the the same scc */
75         scc      *pscc;     /**< the scc of this node */
76         unsigned POnum;     /**< the post order number for blocks */
77 } node_entry;
78
79 /** The environment. */
80 typedef struct iv_env {
81         struct obstack obst;    /**< an obstack for allocations */
82         ir_node  **stack;       /**< the node stack */
83         int      tos;           /**< tos index */
84         unsigned nextDFSnum;    /**< the current DFS number */
85         unsigned POnum;         /**< current post order number */
86         set      *quad_map;     /**< a map from (op, iv, rc) to node */
87         set      *lftr_edges;   /**< the set of lftr edges */
88         unsigned replaced;      /**< number of replaced ops */
89         unsigned lftr_replaced; /**< number of applied linear function test replacements */
90         unsigned flags;         /**< additional flags */
91         /** Function called to process a SCC. */
92         void (*process_scc)(scc *pscc, struct iv_env *env);
93 } iv_env;
94
95 /**
96  * An entry in the (op, node, node) -> node map.
97  */
98 typedef struct quadruple_t {
99         ir_opcode code;  /**< the opcode of the reduced operation */
100         ir_node   *op1;  /**< the first operand the reduced operation */
101         ir_node   *op2;  /**< the second operand of the reduced operation */
102
103         ir_node   *res; /**< the reduced operation */
104 } quadruple_t;
105
106 /**
107  * A LFTR edge.
108  */
109 typedef struct LFTR_edge {
110         ir_node   *src;   /**< the source node */
111         ir_node   *dst;   /**< the destination node */
112         ir_opcode code;   /**< the opcode that must be applied */
113         ir_node   *rc;    /**< the region const that must be applied */
114 } LFTR_edge;
115
116 /* forward */
117 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env);
118
119 /**
120  * Compare two LFTR edges.
121  */
122 static int LFTR_cmp(const void *e1, const void *e2, size_t size) {
123         const LFTR_edge *l1 = e1;
124         const LFTR_edge *l2 = e2;
125         (void) size;
126
127         return l1->src != l2->src;
128 }
129
130 /**
131  * Find a LFTR edge.
132  */
133 static LFTR_edge *LFTR_find(ir_node *src, iv_env *env) {
134         LFTR_edge key;
135
136         key.src  = src;
137
138         return set_find(env->lftr_edges, &key, sizeof(key), HASH_PTR(src));
139 }
140
141 /**
142  * Add a LFTR edge.
143  */
144 static void LFTR_add(ir_node *src, ir_node *dst, ir_opcode code, ir_node *rc, iv_env *env) {
145         LFTR_edge key;
146
147         key.src  = src;
148         key.dst  = dst;
149         key.code = code;
150         key.rc   = rc;
151
152         /*
153          * There might be more than one edge here. This is rather bad
154          * because we currently store only one.
155          */
156 //      assert(LFTR_find(src, env) == NULL);
157         set_insert(env->lftr_edges, &key, sizeof(key), HASH_PTR(src));
158 }
159
160 /**
161  * Gets the node_entry of a node
162  */
163 static node_entry *get_irn_ne(ir_node *irn, iv_env *env) {
164         node_entry *e = get_irn_link(irn);
165
166         if (! e) {
167                 e = obstack_alloc(&env->obst, sizeof(*e));
168                 memset(e, 0, sizeof(*e));
169                 set_irn_link(irn, e);
170         }
171         return e;
172 }
173
174 /**
175  * Gets the scc from an IV.
176  */
177 static scc *get_iv_scc(ir_node *iv, iv_env *env) {
178         node_entry *e = get_irn_ne(iv, env);
179         return e->pscc;
180 }
181
182 /**
183  * Check if irn is an IV.
184  *
185  * @param irn  the node to check
186  * @param env  the environment
187  *
188  * @returns the header if it is one, NULL else
189  */
190 static ir_node *is_iv(ir_node *irn, iv_env *env) {
191         return get_irn_ne(irn, env)->header;
192 }
193
194 /**
195  * Check if irn is a region constant.
196  * The block or irn must strictly dominate the header block.
197  *
198  * @param irn           the node to check
199  * @param header_block  the header block of the induction variable
200  */
201 static int is_rc(ir_node *irn, ir_node *header_block) {
202         ir_node *block = get_nodes_block(irn);
203
204         return (block != header_block) && block_dominates(block, header_block);
205 }
206
207 /**
208  * Set compare function for the quad set.
209  */
210 static int quad_cmp(const void *e1, const void *e2, size_t size) {
211         const quadruple_t *c1 = e1;
212         const quadruple_t *c2 = e2;
213         (void) size;
214
215         return c1->code != c2->code || c1->op1 != c2->op1 || c1->op2 != c2->op2;
216 }
217
218 /**
219  * Check if an reduced operation was already calculated.
220  *
221  * @param code  the opcode of the operation
222  * @param op1   the first operand of the operation
223  * @param op2   the second operand of the operation
224  * @param env   the environment
225  *
226  * @return the already reduced node or NULL if this operation is not yet reduced
227  */
228 static ir_node *search(ir_opcode code, ir_node *op1, ir_node *op2, iv_env *env) {
229         quadruple_t key, *entry;
230
231         key.code = code;
232         key.op1 = op1;
233         key.op2 = op2;
234
235         entry = set_find(env->quad_map, &key, sizeof(key),
236                          (code * 9) ^ HASH_PTR(op1) ^HASH_PTR(op2));
237         if (entry)
238                 return entry->res;
239         return NULL;
240 }
241
242 /**
243  * Add an reduced operation.
244  *
245  * @param code    the opcode of the operation
246  * @param op1     the first operand of the operation
247  * @param op2     the second operand of the operation
248  * @param result  the result of the reduced operation
249  * @param env     the environment
250  */
251 static void add(ir_opcode code, ir_node *op1, ir_node *op2, ir_node *result, iv_env *env) {
252         quadruple_t key;
253
254         key.code = code;
255         key.op1  = op1;
256         key.op2  = op2;
257         key.res  = result;
258
259         set_insert(env->quad_map, &key, sizeof(key),
260                    (code * 9) ^ HASH_PTR(op1) ^HASH_PTR(op2));
261 }
262
263 /**
264  * Find a location where to place a bin-op whose operands are in
265  * block1 and block2.
266  *
267  * @param block1  the block of the first operand
268  * @param block2  the block of the second operand
269  *
270  * Note that we know here that such a place must exists. Moreover, this means
271  * that either block1 dominates block2 or vice versa. So, just return
272  * the "smaller" one.
273  */
274 static ir_node *find_location(ir_node *block1, ir_node *block2) {
275         if (block_dominates(block1, block2))
276                 return block2;
277         assert(block_dominates(block2, block1));
278         return block1;
279 }
280
281 /**
282  * Create a node that executes an op1 code op1 operation.
283  *
284  * @param code   the opcode to execute
285  * @param db     debug info to add to the new node
286  * @param op1    the first operand
287  * @param op2    the second operand
288  * @param mode   the mode of the new operation
289  *
290  * @return the newly created node
291  */
292 static ir_node *do_apply(ir_opcode code, dbg_info *db, ir_node *op1, ir_node *op2, ir_mode *mode) {
293         ir_graph *irg = current_ir_graph;
294         ir_node *result;
295         ir_node *block = find_location(get_nodes_block(op1), get_nodes_block(op2));
296
297         switch (code) {
298         case iro_Mul:
299                 result = new_rd_Mul(db, irg, block, op1, op2, mode);
300                 break;
301         case iro_Add:
302                 result = new_rd_Add(db, irg, block, op1, op2, mode);
303                 break;
304         case iro_Sub:
305                 result = new_rd_Sub(db, irg, block, op1, op2, mode);
306                 break;
307         default:
308                 assert(0);
309                 result = NULL;
310         }
311         return result;
312 }
313
314 /**
315  * The Apply operation.
316  *
317  * @param orig   the node that represent the original operation and determines
318  *               the opcode, debug-info and mode of a newly created one
319  * @param op1    the first operand
320  * @param op2    the second operand
321  * @param env    the environment
322  *
323  * @return the newly created node
324  */
325 static ir_node *apply(ir_node *orig, ir_node *op1, ir_node *op2, iv_env *env) {
326         ir_opcode code = get_irn_opcode(orig);
327         ir_node *result = search(code, op1, op2, env);
328
329         if (! result) {
330                 dbg_info *db = get_irn_dbg_info(orig);
331                 ir_node *op1_header = get_irn_ne(op1, env)->header;
332                 ir_node *op2_header = get_irn_ne(op2, env)->header;
333
334                 if (op1_header != NULL && is_rc(op2, op1_header)) {
335                         result = reduce(orig, op1, op2, env);
336                 }
337                 else if (op2_header != NULL && is_rc(op1, op2_header)) {
338                         result = reduce(orig, op2, op1, env);
339                 }
340                 else {
341                         result = do_apply(code, db, op1, op2, get_irn_mode(orig));
342                         get_irn_ne(result, env)->header = NULL;         }
343         }
344         return result;
345 }
346
347 /**
348  * The Reduce operation.
349  *
350  * @param orig   the node that represent the original operation and determines
351  *               the opcode, debug-info and mode of a newly created one
352  * @param iv     the induction variable
353  * @param rc     the region constant
354  * @param env    the environment
355  *
356  * @return the reduced node
357  */
358 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env) {
359         ir_opcode code = get_irn_opcode(orig);
360         ir_node *result = search(code, iv, rc, env);
361
362         if (! result) {
363                 node_entry *e, *iv_e;
364                 int i, n;
365                 ir_mode *mode = get_irn_mode(orig);
366
367                 result = exact_copy(iv);
368
369                 /* Beware: we must always create a new induction variable with the same mode
370                    as the node we are replacing. Especially this means the mode might be changed
371                    from P to I and back. This is always possible, because we have only Phi, Add
372                    and Sub nodes. */
373                 set_irn_mode(result, mode);
374                 add(code, iv, rc, result, env);
375                 DB((dbg, LEVEL_3, "   Created new %+F for %+F (%s %+F)\n", result, iv,
376                         get_irn_opname(orig), rc));
377
378                 iv_e = get_irn_ne(iv, env);
379                 e    = get_irn_ne(result, env);
380                 e->header = iv_e->header;
381
382                 /* create the LFTR edge */
383                 LFTR_add(iv, result, code, rc, env);
384
385                 n = get_irn_arity(result);
386                 for (i = 0; i < n; ++i) {
387                         ir_node *o = get_irn_n(result, i);
388
389                         e = get_irn_ne(o, env);
390                         if (e->header == iv_e->header)
391                                 o = reduce(orig, o, rc, env);
392                         else if (is_Phi(result) || code == iro_Mul)
393                                 o = apply(orig, o, rc, env);
394                         set_irn_n(result, i, o);
395                 }
396         }
397         else {
398                 DB((dbg, LEVEL_3, "   Already Created %+F for %+F (%s %+F)\n", result, iv,
399                         get_irn_opname(orig), rc));
400         }
401         return result;
402 }
403
404 /**
405  * Update the scc for a newly created IV.
406  */
407 static void update_scc(ir_node *iv, node_entry *e, iv_env *env) {
408         scc     *pscc   = e->pscc;
409         ir_node *header = e->header;
410         waitq    *wq = new_waitq();
411
412         DB((dbg, LEVEL_2, "  Creating SCC for new an induction variable:\n  "));
413         pscc->head = NULL;
414         waitq_put(wq, iv);
415         do {
416                 ir_node    *irn = waitq_get(wq);
417                 node_entry *ne  = get_irn_ne(irn, env);
418                 int        i;
419
420                 ne->pscc   = pscc;
421                 ne->next   = pscc->head;
422                 pscc->head = irn;
423                 DB((dbg, LEVEL_2, " %+F,", irn));
424
425                 for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
426                         ir_node    *pred = get_irn_n(irn, i);
427                         node_entry *pe   = get_irn_ne(pred, env);
428
429                         if (pe->header == header && pe->pscc == NULL) {
430                                 /* set the psc here to ensure that the node is NOT enqueued another time */
431                                 pe->pscc = pscc;
432                                 waitq_put(wq, pred);
433                         }
434                 }
435         } while (! waitq_empty(wq));
436         del_waitq(wq);
437         DB((dbg, LEVEL_2, "\n"));
438 }
439
440 /**
441  * The Replace operation.
442  *
443  * @param irn   the node that will be replaced
444  * @param iv    the induction variable
445  * @param rc    the region constant
446  * @param env   the environment
447  */
448 static int replace(ir_node *irn, ir_node *iv, ir_node *rc, iv_env *env) {
449         ir_node *result;
450
451         DB((dbg, LEVEL_2, "  Replacing %+F\n", irn));
452
453         result = reduce(irn, iv, rc, env);
454         if (result != irn) {
455                 node_entry *e;
456
457                 hook_strength_red(current_ir_graph, irn);
458                 exchange(irn, result);
459                 e = get_irn_ne(result, env);
460                 if (e->pscc == NULL) {
461                         e->pscc = obstack_alloc(&env->obst, sizeof(*e->pscc));
462                         memset(e->pscc, 0, sizeof(*e->pscc));
463                         update_scc(result, e, env);
464                 }
465                 ++env->replaced;
466                 return 1;
467         }
468         return 0;
469 }
470
471 /**
472  * check if a given node is a mul with 2, 4, 8
473  */
474 static int is_x86_shift_const(ir_node *mul) {
475         ir_node *rc;
476
477         if (! is_Mul(mul))
478                 return 0;
479
480         /* normalization put constants on the right side */
481         rc = get_Mul_right(mul);
482         if (is_Const(rc)) {
483                 tarval *tv = get_Const_tarval(rc);
484
485                 if (tarval_is_long(tv)) {
486                         long value = get_tarval_long(tv);
487
488                         if (value == 2 || value == 4 || value == 8) {
489                                 /* do not reduce multiplications by 2, 4, 8 */
490                                 return 1;
491                         }
492                 }
493         }
494         return 0;
495 }
496
497 /**
498  * Check if an IV represents a counter with constant limits.
499  */
500 static int is_counter_iv(ir_node *iv, iv_env *env) {
501         node_entry *e         = get_irn_ne(iv, env);
502         scc        *pscc      = e->pscc;
503         ir_node    *have_init = NULL;
504         ir_node    *have_incr = NULL;
505         ir_opcode  code       = iro_Bad;
506         ir_node    *irn;
507
508         if (pscc->code != 0) {
509                 /* already analysed */
510                 return pscc->code != iro_Bad;
511         }
512
513         pscc->code = iro_Bad;
514         for (irn = pscc->head; irn != NULL; irn = e->next) {
515                 if (is_Add(irn)) {
516                         if (have_incr != NULL)
517                                 return 0;
518
519                         have_incr = get_Add_right(irn);
520                         if (! is_Const(have_incr)) {
521                                 have_incr = get_Add_left(irn);
522                                 if (! is_Const(have_incr))
523                                         return 0;
524                         }
525                         code = iro_Add;
526                 } else if (is_Sub(irn)) {
527                         if (have_incr != NULL)
528                                 return 0;
529
530                         have_incr = get_Sub_right(irn);
531                         if (! is_Const(have_incr))
532                                 return 0;
533                         code = iro_Sub;
534                 } else if (is_Phi(irn)) {
535                         int i;
536
537                         for (i = get_Phi_n_preds(irn) - 1; i >= 0; --i) {
538                                 ir_node    *pred = get_Phi_pred(irn, i);
539                                 node_entry *ne   = get_irn_ne(pred, env);
540
541                                 if (ne->header == e->header)
542                                         continue;
543                                 if (have_init != NULL)
544                                         return 0;
545                                 have_init = pred;
546                                 if (! is_Const(pred))
547                                         return 0;
548                         }
549                 } else
550                         return 0;
551                 e = get_irn_ne(irn, env);
552         }
553         pscc->init = get_Const_tarval(have_init);
554         pscc->incr = get_Const_tarval(have_incr);
555         pscc->code = code;
556         return code != iro_Bad;
557 }
558
559 /**
560  * Check the users of an induction variable for register pressure.
561  */
562 static int check_users_for_reg_pressure(ir_node *iv, iv_env *env) {
563         ir_node    *irn, *header;
564         ir_node    *have_user = NULL;
565         ir_node    *have_cmp  = NULL;
566         node_entry *e         = get_irn_ne(iv, env);
567         scc        *pscc      = e->pscc;
568
569         header = e->header;
570         for (irn = pscc->head; irn != NULL; irn = e->next) {
571                 const ir_edge_t *edge;
572
573                 foreach_out_edge(irn, edge) {
574                         ir_node    *user = get_edge_src_irn(edge);
575                         node_entry *ne = get_irn_ne(user, env);
576
577                         if (e->header == ne->header) {
578                                 /* found user from the same IV */
579                                 continue;
580                         }
581                         if (is_Cmp(user)) {
582                                 if (have_cmp != NULL) {
583                                         /* more than one cmp, for now end here */
584                                         return 0;
585                                 }
586                                 have_cmp = user;
587                         } else {
588                                 /* user is a real user of the IV */
589                                 if (have_user != NULL) {
590                                         /* found the second user */
591                                         return 0;
592                                 }
593                                 have_user = user;
594                         }
595                 }
596                 e = get_irn_ne(irn, env);
597         }
598
599         if (have_user == NULL) {
600                 /* no user, ignore */
601                 return 1;
602         }
603
604         if (have_cmp == NULL) {
605                 /* fine, only one user, try to reduce */
606                 return 1;
607         }
608         /*
609          * We found one user AND at least one cmp.
610          * We should check here if we can transform the Cmp.
611          *
612          * For now our capabilities for doing linear function test
613          * are limited, so check if the iv has the right form: Only ONE
614          * phi, only one Add/Sub with a Const
615          */
616         if (! is_counter_iv(iv, env))
617                 return 0;
618
619         /*
620          * Ok, we have only one increment AND it is a Const, we might be able
621          * to do a linear function test replacement, so go on.
622          */
623         return 1;
624 }
625
626 /**
627  * Check if a node can be replaced (+, -, *).
628  *
629  * @param irn   the node to check
630  * @param env   the environment
631  *
632  * @return non-zero if irn should be Replace'd
633  */
634 static int check_replace(ir_node *irn, iv_env *env) {
635         ir_node   *left, *right, *iv, *rc;
636         ir_op     *op  = get_irn_op(irn);
637         ir_opcode code = get_op_code(op);
638         ir_node   *liv, *riv;
639
640         switch (code) {
641         case iro_Mul:
642         case iro_Add:
643         case iro_Sub:
644                 iv = rc = NULL;
645
646                 left  = get_binop_left(irn);
647                 right = get_binop_right(irn);
648
649                 liv = is_iv(left, env);
650                 riv = is_iv(right, env);
651                 if (liv && is_rc(right, liv)) {
652                         iv = left; rc = right;
653                 }
654                 else if (riv && is_op_commutative(op) &&
655                                     is_rc(left, riv)) {
656                         iv = right; rc = left;
657                 }
658
659                 if (iv) {
660                         if (env->flags & osr_flag_keep_reg_pressure) {
661                                 if (! check_users_for_reg_pressure(iv, env))
662                                         return 0;
663                         }
664                         /* check for x86 constants */
665                         if (env->flags & osr_flag_ignore_x86_shift)
666                                 if (is_x86_shift_const(irn))
667                                         return 0;
668
669                         return replace(irn, iv, rc, env);
670                 }
671                 break;
672         default:
673                 break;
674         }
675         return 0;
676 }
677
678 /**
679  * Check which SCC's are induction variables.
680  *
681  * @param pscc  a SCC
682  * @param env   the environment
683  */
684 static void classify_iv(scc *pscc, iv_env *env) {
685         ir_node *irn, *next, *header = NULL;
686         node_entry *b, *h = NULL;
687         int j, only_phi, num_outside;
688         ir_node *out_rc;
689
690         /* find the header block for this scc */
691         for (irn = pscc->head; irn; irn = next) {
692                 node_entry *e = get_irn_link(irn);
693                 ir_node *block = get_nodes_block(irn);
694
695                 next = e->next;
696                 b = get_irn_ne(block, env);
697
698                 if (header) {
699                         if (h->POnum < b->POnum) {
700                                 header = block;
701                                 h      = b;
702                         }
703                 }
704                 else {
705                         header = block;
706                         h      = b;
707                 }
708         }
709
710         /* check if this scc contains only Phi, Add or Sub nodes */
711         only_phi    = 1;
712         num_outside = 0;
713         out_rc      = NULL;
714         for (irn = pscc->head; irn; irn = next) {
715                 node_entry *e = get_irn_ne(irn, env);
716
717                 next = e->next;
718                 switch (get_irn_opcode(irn)) {
719                 case iro_Add:
720                 case iro_Sub:
721                         only_phi = 0;
722                         /* fall through */
723                 case iro_Phi:
724                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
725                                 ir_node *pred  = get_irn_n(irn, j);
726                                 node_entry *pe = get_irn_ne(pred, env);
727
728                                 if (pe->pscc != e->pscc) {
729                                         /* not in the same SCC, must be a region const */
730                                         if (! is_rc(pred, header)) {
731                                                 /* not an induction variable */
732                                                 goto fail;
733                                         }
734                                         if (! out_rc) {
735                                                 out_rc = pred;
736                                                 ++num_outside;
737                                         } else if (out_rc != pred) {
738                                                 ++num_outside;
739                                         }
740                                 }
741                         }
742                         break;
743                 default:
744                         /* not an induction variable */
745                         goto fail;
746                 }
747         }
748         /* found an induction variable */
749         DB((dbg, LEVEL_2, "  Found an induction variable:\n  "));
750         if (only_phi && num_outside == 1) {
751                 /* a phi cycle with only one real predecessor can be collapsed */
752                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
753
754                 for (irn = pscc->head; irn; irn = next) {
755                         node_entry *e = get_irn_ne(irn, env);
756                         next = e->next;
757                         e->header = NULL;
758                         exchange(irn, out_rc);
759                 }
760                 ++env->replaced;
761                 return;
762         }
763
764         /* set the header for every node in this scc */
765         for (irn = pscc->head; irn; irn = next) {
766                 node_entry *e = get_irn_ne(irn, env);
767                 e->header = header;
768                 next = e->next;
769                 DB((dbg, LEVEL_2, " %+F,", irn));
770         }
771         DB((dbg, LEVEL_2, "\n"));
772         return;
773
774 fail:
775         for (irn = pscc->head; irn; irn = next) {
776                 node_entry *e = get_irn_ne(irn, env);
777
778                 next = e->next;
779                 e->header = NULL;
780         }
781 }
782
783 /**
784  * Process a SCC for the operator strength reduction.
785  *
786  * @param pscc  the SCC
787  * @param env   the environment
788  */
789 static void process_scc(scc *pscc, iv_env *env) {
790         ir_node *head = pscc->head;
791         node_entry *e = get_irn_link(head);
792
793 #ifdef DEBUG_libfirm
794         {
795                 ir_node *irn, *next;
796
797                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
798                 for (irn = pscc->head; irn; irn = next) {
799                         node_entry *e = get_irn_link(irn);
800
801                         next = e->next;
802
803                         DB((dbg, LEVEL_4, " %+F,", irn));
804                 }
805                 DB((dbg, LEVEL_4, "\n"));
806         }
807 #endif
808
809         if (e->next == NULL) {
810                 /* this SCC has only a single member */
811                 check_replace(head, env);
812         } else {
813                 classify_iv(pscc, env);
814         }
815 }
816
817 /**
818  * If an SCC is a Phi only cycle, remove it.
819  */
820 static void remove_phi_cycle(scc *pscc, iv_env *env) {
821         ir_node *irn, *next;
822         int j;
823         ir_node *out_rc;
824
825         /* check if this scc contains only Phi, Add or Sub nodes */
826         out_rc      = NULL;
827         for (irn = pscc->head; irn; irn = next) {
828                 node_entry *e = get_irn_ne(irn, env);
829
830                 next = e->next;
831                 if (! is_Phi(irn))
832                         return;
833
834                 for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
835                         ir_node *pred  = get_irn_n(irn, j);
836                         node_entry *pe = get_irn_ne(pred, env);
837
838                         if (pe->pscc != e->pscc) {
839                                 /* not in the same SCC, must be the only input */
840                                 if (! out_rc) {
841                                         out_rc = pred;
842                                 } else if (out_rc != pred) {
843                                         return;
844                                 }
845                         }
846                 }
847         }
848         /* found a Phi cycle */
849         DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
850
851         for (irn = pscc->head; irn; irn = next) {
852                 node_entry *e = get_irn_ne(irn, env);
853                 next = e->next;
854                 e->header = NULL;
855                 exchange(irn, out_rc);
856         }
857         ++env->replaced;
858 }
859
860 /**
861  * Process a SCC for the Phi cycle removement.
862  *
863  * @param pscc  the SCC
864  * @param env   the environment
865  */
866 static void process_phi_only_scc(scc *pscc, iv_env *env) {
867         ir_node *head = pscc->head;
868         node_entry *e = get_irn_link(head);
869
870 #ifdef DEBUG_libfirm
871         {
872                 ir_node *irn, *next;
873
874                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
875                 for (irn = pscc->head; irn; irn = next) {
876                         node_entry *e = get_irn_link(irn);
877
878                         next = e->next;
879
880                         DB((dbg, LEVEL_4, " %+F,", irn));
881                 }
882                 DB((dbg, LEVEL_4, "\n"));
883         }
884 #endif
885
886         if (e->next != NULL)
887                 remove_phi_cycle(pscc, env);
888 }
889
890
891 /**
892  * Push a node onto the stack.
893  *
894  * @param env   the environment
895  * @param n     the node to push
896  */
897 static void push(iv_env *env, ir_node *n) {
898         node_entry *e;
899
900         if (env->tos == ARR_LEN(env->stack)) {
901                 int nlen = ARR_LEN(env->stack) * 2;
902                 ARR_RESIZE(ir_node *, env->stack, nlen);
903         }
904         env->stack[env->tos++] = n;
905         e = get_irn_ne(n, env);
906         e->in_stack = 1;
907 }
908
909 /**
910  * pop a node from the stack
911  *
912  * @param env   the environment
913  *
914  * @return  The topmost node
915  */
916 static ir_node *pop(iv_env *env)
917 {
918         ir_node *n = env->stack[--env->tos];
919         node_entry *e = get_irn_ne(n, env);
920
921         e->in_stack = 0;
922         return n;
923 }
924
925 /**
926  * Do Tarjan's SCC algorithm and drive OSR.
927  *
928  * @param irn  start at this node
929  * @param env  the environment
930  */
931 static void dfs(ir_node *irn, iv_env *env)
932 {
933         int i, n;
934         node_entry *node = get_irn_ne(irn, env);
935
936         mark_irn_visited(irn);
937
938         /* do not put blocks into the scc */
939         if (is_Block(irn)) {
940                 n = get_irn_arity(irn);
941                 for (i = 0; i < n; ++i) {
942                         ir_node *pred = get_irn_n(irn, i);
943
944                         if (irn_not_visited(pred))
945                                 dfs(pred, env);
946                 }
947         }
948         else {
949                 ir_node *block = get_nodes_block(irn);
950
951                 node->DFSnum = env->nextDFSnum++;
952                 node->low    = node->DFSnum;
953                 push(env, irn);
954
955                 /* handle the block */
956                 if (irn_not_visited(block))
957                         dfs(block, env);
958
959                 n = get_irn_arity(irn);
960                 for (i = 0; i < n; ++i) {
961                         ir_node *pred = get_irn_n(irn, i);
962                         node_entry *o = get_irn_ne(pred, env);
963
964                         if (irn_not_visited(pred)) {
965                                 dfs(pred, env);
966                                 node->low = MIN(node->low, o->low);
967                         }
968                         if (o->DFSnum < node->DFSnum && o->in_stack)
969                                 node->low = MIN(o->DFSnum, node->low);
970                 }
971                 if (node->low == node->DFSnum) {
972                         scc *pscc = obstack_alloc(&env->obst, sizeof(*pscc));
973                         ir_node *x;
974
975                         memset(pscc, 0, sizeof(*pscc));
976                         do {
977                                 node_entry *e;
978
979                                 x = pop(env);
980                                 e = get_irn_ne(x, env);
981                                 e->pscc    = pscc;
982                                 e->next    = pscc->head;
983                                 pscc->head = x;
984                         } while (x != irn);
985
986                         env->process_scc(pscc, env);
987                 }
988         }
989 }
990
991 /**
992  * Do the DFS by starting at the End node of a graph.
993  *
994  * @param irg  the graph to process
995  * @param env  the environment
996  */
997 static void do_dfs(ir_graph *irg, iv_env *env) {
998         ir_graph *rem = current_ir_graph;
999         ir_node *end = get_irg_end(irg);
1000         int i, n;
1001
1002         set_using_irn_visited(irg);
1003
1004         current_ir_graph = irg;
1005         inc_irg_visited(irg);
1006
1007         /* visit all visible nodes */
1008         dfs(end, env);
1009
1010         /* visit the keep-alives */
1011         n = get_End_n_keepalives(end);
1012         for (i = 0; i < n; ++i) {
1013                 ir_node *ka = get_End_keepalive(end, i);
1014
1015                 if (irn_not_visited(ka))
1016                         dfs(ka, env);
1017         }
1018
1019         clear_using_irn_visited(irg);
1020
1021         current_ir_graph = rem;
1022 }
1023
1024 /**
1025  * Post-block-walker: assign the post-order number.
1026  */
1027 static void assign_po(ir_node *block, void *ctx) {
1028         iv_env *env = ctx;
1029         node_entry *e = get_irn_ne(block, env);
1030
1031         e->POnum = env->POnum++;
1032 }
1033
1034 /**
1035  * Follows the LFTR edges and return the last node in the chain.
1036  *
1037  * @param irn  the node that should be followed
1038  * @param env  the IV environment
1039  *
1040  * @note
1041  * In the current implementation only the last edge is stored, so
1042  * only one chain exists. That's why we might miss some opportunities.
1043  */
1044 static ir_node *followEdges(ir_node *irn, iv_env *env) {
1045         for (;;) {
1046                 LFTR_edge *e = LFTR_find(irn, env);
1047                 if (e)
1048                         irn = e->dst;
1049                 else
1050                         return irn;
1051         }
1052 }
1053
1054 /**
1055  * Apply one LFTR edge operation.
1056  * Return NULL if the transformation cannot be done safely without
1057  * an Overflow.
1058  *
1059  * @param iv   the induction variable
1060  * @param rc   the constant that should be translated
1061  * @param e    the LFTR edge
1062  * @param env  the IV environment
1063  *
1064  * @return the translated region constant or NULL
1065  *         if the translation was not possible
1066  *
1067  * @note
1068  * In the current implementation only the last edge is stored, so
1069  * only one chain exists. That's why we might miss some opportunities.
1070  */
1071 static ir_node *applyOneEdge(ir_node *iv, ir_node *rc, LFTR_edge *e, iv_env *env) {
1072         if (env->flags & osr_flag_lftr_with_ov_check) {
1073                 tarval *tv_l, *tv_r, *tv, *tv_init, *tv_incr;
1074                 tarval_int_overflow_mode_t ovmode;
1075                 scc *pscc;
1076
1077                 if (! is_counter_iv(iv, env)) {
1078                         DB((dbg, LEVEL_4, " not counter IV"));
1079                         return NULL;
1080                 }
1081
1082                 /* overflow can only be decided for Consts */
1083                 if (! is_Const(e->rc)) {
1084                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)", e->rc));
1085                         return NULL;
1086                 }
1087
1088                 tv_l = get_Const_tarval(rc);
1089                 tv_r = get_Const_tarval(e->rc);
1090
1091                 ovmode = tarval_get_integer_overflow_mode();
1092                 tarval_set_integer_overflow_mode(TV_OVERFLOW_BAD);
1093
1094                 pscc    = get_iv_scc(iv, env);
1095                 tv_incr = pscc->incr;
1096                 tv_init = pscc->init;
1097
1098                 /*
1099                  * Check that no overflow occurs:
1100                  * init must be transformed without overflow
1101                  * the new rc must be transformed without overflow
1102                  * rc +/- incr must be possible without overflow
1103                  */
1104                 switch (e->code) {
1105                 case iro_Mul:
1106                         tv      = tarval_mul(tv_l, tv_r);
1107                         tv_init = tarval_mul(tv_init, tv_r);
1108                         tv_incr = tarval_mul(tv_incr, tv_r);
1109                         DB((dbg, LEVEL_4, " * %+F", tv_r));
1110                         break;
1111                 case iro_Add:
1112                         tv      = tarval_add(tv_l, tv_r);
1113                         tv_init = tarval_add(tv_init, tv_r);
1114                         DB((dbg, LEVEL_4, " + %+F", tv_r));
1115                         break;
1116                 case iro_Sub:
1117                         tv      = tarval_sub(tv_l, tv_r);
1118                         tv_init = tarval_sub(tv_init, tv_r);
1119                         DB((dbg, LEVEL_4, " - %+F", tv_r));
1120                         break;
1121                 default:
1122                         assert(0);
1123                         tv = tarval_bad;
1124                 }
1125
1126                 if (pscc->code == iro_Add) {
1127                         tv = tarval_add(tv, tv_incr);
1128                 } else {
1129                         assert(pscc->code == iro_Sub);
1130                         tv = tarval_sub(tv, tv_incr);
1131                 }
1132
1133                 tarval_set_integer_overflow_mode(ovmode);
1134
1135                 if (tv == tarval_bad || tv_init == tarval_bad) {
1136                         DB((dbg, LEVEL_4, " = OVERFLOW"));
1137                         return NULL;
1138                 }
1139                 return new_r_Const(current_ir_graph, get_irn_n(rc, -1), get_tarval_mode(tv), tv);
1140         }
1141         return do_apply(e->code, NULL, rc, e->rc, get_irn_mode(rc));
1142 }
1143
1144 /**
1145  * Applies the operations represented by the LFTR edges to a
1146  * region constant and returns the value.
1147  * Return NULL if the transformation cannot be done safely without
1148  * an Overflow.
1149  *
1150  * @param iv   the IV node that starts the LFTR edge chain
1151  * @param rc   the region constant that should be translated
1152  * @param env  the IV environment
1153  *
1154  * @return the translated region constant or NULL
1155  *         if the translation was not possible
1156  */
1157 static ir_node *applyEdges(ir_node *iv, ir_node *rc, iv_env *env) {
1158         if (env->flags & osr_flag_lftr_with_ov_check) {
1159                 /* overflow can only be decided for Consts */
1160                 if (! is_counter_iv(iv, env)) {
1161                         DB((dbg, LEVEL_4, "not counter IV\n", rc));
1162                         return NULL;
1163                 }
1164                 if (! is_Const(rc)) {
1165                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)\n", rc));
1166                         return NULL;
1167                 }
1168                 DB((dbg, LEVEL_4, "%+F", get_Const_tarval(rc)));
1169         }
1170
1171         for (; rc;) {
1172                 LFTR_edge *e = LFTR_find(iv, env);
1173                 if (e) {
1174                         rc = applyOneEdge(iv, rc, e, env);
1175                         iv = e->dst;
1176                 }
1177                 else
1178                         break;
1179         }
1180         DB((dbg, LEVEL_3, "\n"));
1181         return rc;
1182 }
1183
1184 /**
1185  * Walker, finds Cmp(iv, rc) or Cmp(rc, iv)
1186  * and tries to optimize them.
1187  */
1188 static void do_lftr(ir_node *cmp, void *ctx) {
1189         iv_env *env = ctx;
1190         ir_node *left, *right, *liv, *riv;
1191         ir_node *iv, *rc;
1192         ir_node *nleft = NULL, *nright = NULL;
1193
1194         if (get_irn_op(cmp) != op_Cmp)
1195                 return;
1196
1197         left  = get_Cmp_left(cmp);
1198         right = get_Cmp_right(cmp);
1199
1200         liv = is_iv(left, env);
1201         riv = is_iv(right, env);
1202         if (liv && is_rc(right, liv)) {
1203                 iv = left; rc = right;
1204
1205                 nright = applyEdges(iv, rc, env);
1206                 if (nright && nright != rc) {
1207                         nleft = followEdges(iv, env);
1208                 }
1209         }
1210         else if (riv && is_rc(left, riv)) {
1211                 iv = right; rc = left;
1212
1213                 nleft = applyEdges(iv, rc, env);
1214                 if (nleft && nleft != rc) {
1215                         nright = followEdges(iv, env);
1216                 }
1217         }
1218
1219         if (nleft && nright) {
1220                 DB((dbg, LEVEL_2, "  LFTR for %+F\n", cmp));
1221                 set_Cmp_left(cmp, nleft);
1222                 set_Cmp_right(cmp, nright);
1223                 ++env->lftr_replaced;
1224         }
1225 }
1226
1227 /**
1228  * do linear function test replacement.
1229  *
1230  * @param irg   the graph that should be optimized
1231  * @param env   the IV environment
1232  */
1233 static void lftr(ir_graph *irg, iv_env *env) {
1234         irg_walk_graph(irg, NULL, do_lftr, env);
1235 }
1236
1237 /**
1238  * Pre-walker: set all node links to NULL and fix the
1239  * block of Proj nodes.
1240  */
1241 static void clear_and_fix(ir_node *irn, void *env)
1242 {
1243         (void) env;
1244         set_irn_link(irn, NULL);
1245
1246         if (is_Proj(irn)) {
1247                 ir_node *pred = get_Proj_pred(irn);
1248                 set_nodes_block(irn, get_nodes_block(pred));
1249         }
1250 }
1251
1252 /* Performs Operator Strength Reduction for the passed graph. */
1253 void opt_osr(ir_graph *irg, unsigned flags) {
1254         iv_env   env;
1255         ir_graph *rem;
1256         int      edges;
1257
1258         if (! get_opt_strength_red()) {
1259                 /* only kill Phi cycles  */
1260                 remove_phi_cycles(irg);
1261                 return;
1262         }
1263
1264         rem = current_ir_graph;
1265         current_ir_graph = irg;
1266
1267         FIRM_DBG_REGISTER(dbg, "firm.opt.osr");
1268
1269         DB((dbg, LEVEL_1, "Doing Operator Strength Reduction for %+F\n", irg));
1270
1271         obstack_init(&env.obst);
1272         env.stack         = NEW_ARR_F(ir_node *, 128);
1273         env.tos           = 0;
1274         env.nextDFSnum    = 0;
1275         env.POnum         = 0;
1276         env.quad_map      = new_set(quad_cmp, 64);
1277         env.lftr_edges    = new_set(LFTR_cmp, 64);
1278         env.replaced      = 0;
1279         env.lftr_replaced = 0;
1280         env.flags         = flags;
1281         env.process_scc   = process_scc;
1282
1283         /* Clear all links and move Proj nodes into the
1284            the same block as it's predecessors.
1285            This can improve the placement of new nodes.
1286          */
1287         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1288
1289         /* we need dominance */
1290         assure_doms(irg);
1291
1292         edges = edges_assure(irg);
1293
1294         /* calculate the post order number for blocks. */
1295         irg_block_edges_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1296
1297         /* calculate the SCC's and drive OSR. */
1298         do_dfs(irg, &env);
1299
1300         if (env.replaced) {
1301                 /* try linear function test replacements */
1302                 lftr(irg, &env);
1303
1304                 set_irg_outs_inconsistent(irg);
1305                 DB((dbg, LEVEL_1, "Replacements: %u + %u (lftr)\n\n", env.replaced, env.lftr_replaced));
1306         }
1307
1308         del_set(env.lftr_edges);
1309         del_set(env.quad_map);
1310         DEL_ARR_F(env.stack);
1311         obstack_free(&env.obst, NULL);
1312
1313         if (! edges)
1314                 edges_deactivate(irg);
1315
1316         current_ir_graph = rem;
1317 }
1318
1319 /* Remove any Phi cycles with only one real input. */
1320 void remove_phi_cycles(ir_graph *irg) {
1321         iv_env   env;
1322         ir_graph *rem;
1323
1324         rem = current_ir_graph;
1325         current_ir_graph = irg;
1326
1327         FIRM_DBG_REGISTER(dbg, "firm.opt.remove_phi");
1328
1329         DB((dbg, LEVEL_1, "Doing Phi cycle removement for %+F\n", irg));
1330
1331         obstack_init(&env.obst);
1332         env.stack         = NEW_ARR_F(ir_node *, 128);
1333         env.tos           = 0;
1334         env.nextDFSnum    = 0;
1335         env.POnum         = 0;
1336         env.quad_map      = NULL;
1337         env.lftr_edges    = NULL;
1338         env.replaced      = 0;
1339         env.lftr_replaced = 0;
1340         env.flags         = 0;
1341         env.process_scc   = process_phi_only_scc;
1342
1343         /* Clear all links and move Proj nodes into the
1344            the same block as it's predecessors.
1345            This can improve the placement of new nodes.
1346          */
1347         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1348
1349         /* we need outs for calculating the post order */
1350         assure_irg_outs(irg);
1351
1352         /* calculate the post order number for blocks. */
1353         irg_out_block_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1354
1355         /* calculate the SCC's and drive OSR. */
1356         do_dfs(irg, &env);
1357
1358         if (env.replaced) {
1359                 set_irg_outs_inconsistent(irg);
1360                 DB((dbg, LEVEL_1, "remove_phi_cycles: %u Cycles removed\n\n", env.replaced));
1361         }
1362
1363         DEL_ARR_F(env.stack);
1364         obstack_free(&env.obst, NULL);
1365
1366         current_ir_graph = rem;
1367 }