Bugfix:
[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 *header, 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 == NULL) {
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 == header && is_rc(op2, op1_header)) {
335                         result = reduce(orig, op1, op2, env);
336                 }
337                 else if (op2_header == header && 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         }
345         return result;
346 }
347
348 /**
349  * The Reduce operation.
350  *
351  * @param orig   the node that represent the original operation and determines
352  *               the opcode, debug-info and mode of a newly created one
353  * @param iv     the induction variable
354  * @param rc     the region constant
355  * @param env    the environment
356  *
357  * @return the reduced node
358  */
359 static ir_node *reduce(ir_node *orig, ir_node *iv, ir_node *rc, iv_env *env) {
360         ir_opcode code = get_irn_opcode(orig);
361         ir_node *result = search(code, iv, rc, env);
362
363         if (result == NULL) {
364                 node_entry *e, *iv_e;
365                 int i, n;
366                 ir_mode *mode = get_irn_mode(orig);
367
368                 result = exact_copy(iv);
369
370                 /* Beware: we must always create a new induction variable with the same mode
371                    as the node we are replacing. Especially this means the mode might be changed
372                    from P to I and back. This is always possible, because we have only Phi, Add
373                    and Sub nodes. */
374                 set_irn_mode(result, mode);
375                 add(code, iv, rc, result, env);
376                 DB((dbg, LEVEL_3, "   Created new %+F for %+F (%s %+F)\n", result, iv,
377                         get_irn_opname(orig), rc));
378
379                 iv_e = get_irn_ne(iv, env);
380                 e    = get_irn_ne(result, env);
381                 e->header = iv_e->header;
382
383                 /* create the LFTR edge */
384                 LFTR_add(iv, result, code, rc, env);
385
386                 n = get_irn_arity(result);
387                 for (i = 0; i < n; ++i) {
388                         ir_node *o = get_irn_n(result, i);
389
390                         e = get_irn_ne(o, env);
391                         if (e->header == iv_e->header)
392                                 o = reduce(orig, o, rc, env);
393                         else if (is_Phi(result) || code == iro_Mul)
394                                 o = apply(iv_e->header, orig, o, rc, env);
395                         set_irn_n(result, i, o);
396                 }
397         }
398         else {
399                 DB((dbg, LEVEL_3, "   Already Created %+F for %+F (%s %+F)\n", result, iv,
400                         get_irn_opname(orig), rc));
401         }
402         return result;
403 }
404
405 /**
406  * Update the scc for a newly created IV.
407  */
408 static void update_scc(ir_node *iv, node_entry *e, iv_env *env) {
409         scc     *pscc   = e->pscc;
410         ir_node *header = e->header;
411         waitq    *wq = new_waitq();
412
413         DB((dbg, LEVEL_2, "  Creating SCC for new an induction variable:\n  "));
414         pscc->head = NULL;
415         waitq_put(wq, iv);
416         do {
417                 ir_node    *irn = waitq_get(wq);
418                 node_entry *ne  = get_irn_ne(irn, env);
419                 int        i;
420
421                 ne->pscc   = pscc;
422                 ne->next   = pscc->head;
423                 pscc->head = irn;
424                 DB((dbg, LEVEL_2, " %+F,", irn));
425
426                 for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
427                         ir_node    *pred = get_irn_n(irn, i);
428                         node_entry *pe   = get_irn_ne(pred, env);
429
430                         if (pe->header == header && pe->pscc == NULL) {
431                                 /* set the pscc here to ensure that the node is NOT enqueued another time */
432                                 pe->pscc = pscc;
433                                 waitq_put(wq, pred);
434                         }
435                 }
436         } while (! waitq_empty(wq));
437         del_waitq(wq);
438         DB((dbg, LEVEL_2, "\n"));
439 }
440
441 /**
442  * The Replace operation.
443  *
444  * @param irn   the node that will be replaced
445  * @param iv    the induction variable
446  * @param rc    the region constant
447  * @param env   the environment
448  */
449 static int replace(ir_node *irn, ir_node *iv, ir_node *rc, iv_env *env) {
450         ir_node *result;
451
452         DB((dbg, LEVEL_2, "  Replacing %+F\n", irn));
453
454         result = reduce(irn, iv, rc, env);
455         if (result != irn) {
456                 node_entry *e;
457
458                 hook_strength_red(current_ir_graph, irn);
459                 exchange(irn, result);
460                 e = get_irn_ne(result, env);
461                 if (e->pscc == NULL) {
462                         e->pscc = obstack_alloc(&env->obst, sizeof(*e->pscc));
463                         memset(e->pscc, 0, sizeof(*e->pscc));
464                         update_scc(result, e, env);
465                 }
466                 ++env->replaced;
467                 return 1;
468         }
469         return 0;
470 }
471
472 /**
473  * check if a given node is a mul with 2, 4, 8
474  */
475 static int is_x86_shift_const(ir_node *mul) {
476         ir_node *rc;
477
478         if (! is_Mul(mul))
479                 return 0;
480
481         /* normalization put constants on the right side */
482         rc = get_Mul_right(mul);
483         if (is_Const(rc)) {
484                 tarval *tv = get_Const_tarval(rc);
485
486                 if (tarval_is_long(tv)) {
487                         long value = get_tarval_long(tv);
488
489                         if (value == 2 || value == 4 || value == 8) {
490                                 /* do not reduce multiplications by 2, 4, 8 */
491                                 return 1;
492                         }
493                 }
494         }
495         return 0;
496 }
497
498 /**
499  * Check if an IV represents a counter with constant limits.
500  */
501 static int is_counter_iv(ir_node *iv, iv_env *env) {
502         node_entry *e         = get_irn_ne(iv, env);
503         scc        *pscc      = e->pscc;
504         ir_node    *have_init = NULL;
505         ir_node    *have_incr = NULL;
506         ir_opcode  code       = iro_Bad;
507         ir_node    *irn;
508
509         if (pscc->code != 0) {
510                 /* already analysed */
511                 return pscc->code != iro_Bad;
512         }
513
514         pscc->code = iro_Bad;
515         for (irn = pscc->head; irn != NULL; irn = e->next) {
516                 if (is_Add(irn)) {
517                         if (have_incr != NULL)
518                                 return 0;
519
520                         have_incr = get_Add_right(irn);
521                         if (! is_Const(have_incr)) {
522                                 have_incr = get_Add_left(irn);
523                                 if (! is_Const(have_incr))
524                                         return 0;
525                         }
526                         code = iro_Add;
527                 } else if (is_Sub(irn)) {
528                         if (have_incr != NULL)
529                                 return 0;
530
531                         have_incr = get_Sub_right(irn);
532                         if (! is_Const(have_incr))
533                                 return 0;
534                         code = iro_Sub;
535                 } else if (is_Phi(irn)) {
536                         int i;
537
538                         for (i = get_Phi_n_preds(irn) - 1; i >= 0; --i) {
539                                 ir_node    *pred = get_Phi_pred(irn, i);
540                                 node_entry *ne   = get_irn_ne(pred, env);
541
542                                 if (ne->header == e->header)
543                                         continue;
544                                 if (have_init != NULL)
545                                         return 0;
546                                 have_init = pred;
547                                 if (! is_Const(pred))
548                                         return 0;
549                         }
550                 } else
551                         return 0;
552                 e = get_irn_ne(irn, env);
553         }
554         pscc->init = get_Const_tarval(have_init);
555         pscc->incr = get_Const_tarval(have_incr);
556         pscc->code = code;
557         return code != iro_Bad;
558 }
559
560 /**
561  * Check the users of an induction variable for register pressure.
562  */
563 static int check_users_for_reg_pressure(ir_node *iv, iv_env *env) {
564         ir_node    *irn, *header;
565         ir_node    *have_user = NULL;
566         ir_node    *have_cmp  = NULL;
567         node_entry *e         = get_irn_ne(iv, env);
568         scc        *pscc      = e->pscc;
569
570         header = e->header;
571         for (irn = pscc->head; irn != NULL; irn = e->next) {
572                 const ir_edge_t *edge;
573
574                 foreach_out_edge(irn, edge) {
575                         ir_node    *user = get_edge_src_irn(edge);
576                         node_entry *ne = get_irn_ne(user, env);
577
578                         if (e->header == ne->header) {
579                                 /* found user from the same IV */
580                                 continue;
581                         }
582                         if (is_Cmp(user)) {
583                                 if (have_cmp != NULL) {
584                                         /* more than one cmp, for now end here */
585                                         return 0;
586                                 }
587                                 have_cmp = user;
588                         } else {
589                                 /* user is a real user of the IV */
590                                 if (have_user != NULL) {
591                                         /* found the second user */
592                                         return 0;
593                                 }
594                                 have_user = user;
595                         }
596                 }
597                 e = get_irn_ne(irn, env);
598         }
599
600         if (have_user == NULL) {
601                 /* no user, ignore */
602                 return 1;
603         }
604
605         if (have_cmp == NULL) {
606                 /* fine, only one user, try to reduce */
607                 return 1;
608         }
609         /*
610          * We found one user AND at least one cmp.
611          * We should check here if we can transform the Cmp.
612          *
613          * For now our capabilities for doing linear function test
614          * are limited, so check if the iv has the right form: Only ONE
615          * phi, only one Add/Sub with a Const
616          */
617         if (! is_counter_iv(iv, env))
618                 return 0;
619
620         /*
621          * Ok, we have only one increment AND it is a Const, we might be able
622          * to do a linear function test replacement, so go on.
623          */
624         return 1;
625 }
626
627 /**
628  * Check if a node can be replaced (+, -, *).
629  *
630  * @param irn   the node to check
631  * @param env   the environment
632  *
633  * @return non-zero if irn should be Replace'd
634  */
635 static int check_replace(ir_node *irn, iv_env *env) {
636         ir_node   *left, *right, *iv, *rc;
637         ir_op     *op  = get_irn_op(irn);
638         ir_opcode code = get_op_code(op);
639         ir_node   *liv, *riv;
640
641         switch (code) {
642         case iro_Mul:
643         case iro_Add:
644         case iro_Sub:
645                 iv = rc = NULL;
646
647                 left  = get_binop_left(irn);
648                 right = get_binop_right(irn);
649
650                 liv = is_iv(left, env);
651                 riv = is_iv(right, env);
652                 if (liv && is_rc(right, liv)) {
653                         iv = left; rc = right;
654                 }
655                 else if (riv && is_op_commutative(op) &&
656                                     is_rc(left, riv)) {
657                         iv = right; rc = left;
658                 }
659
660                 if (iv) {
661                         if (env->flags & osr_flag_keep_reg_pressure) {
662                                 if (! check_users_for_reg_pressure(iv, env))
663                                         return 0;
664                         }
665                         /* check for x86 constants */
666                         if (env->flags & osr_flag_ignore_x86_shift)
667                                 if (is_x86_shift_const(irn))
668                                         return 0;
669
670                         return replace(irn, iv, rc, env);
671                 }
672                 break;
673         default:
674                 break;
675         }
676         return 0;
677 }
678
679 /**
680  * Check which SCC's are induction variables.
681  *
682  * @param pscc  a SCC
683  * @param env   the environment
684  */
685 static void classify_iv(scc *pscc, iv_env *env) {
686         ir_node *irn, *next, *header = NULL;
687         node_entry *b, *h = NULL;
688         int j, only_phi, num_outside;
689         ir_node *out_rc;
690
691         /* find the header block for this scc */
692         for (irn = pscc->head; irn; irn = next) {
693                 node_entry *e = get_irn_link(irn);
694                 ir_node *block = get_nodes_block(irn);
695
696                 next = e->next;
697                 b = get_irn_ne(block, env);
698
699                 if (header) {
700                         if (h->POnum < b->POnum) {
701                                 header = block;
702                                 h      = b;
703                         }
704                 }
705                 else {
706                         header = block;
707                         h      = b;
708                 }
709         }
710
711         /* check if this scc contains only Phi, Add or Sub nodes */
712         only_phi    = 1;
713         num_outside = 0;
714         out_rc      = NULL;
715         for (irn = pscc->head; irn; irn = next) {
716                 node_entry *e = get_irn_ne(irn, env);
717
718                 next = e->next;
719                 switch (get_irn_opcode(irn)) {
720                 case iro_Add:
721                 case iro_Sub:
722                         only_phi = 0;
723                         /* fall through */
724                 case iro_Phi:
725                         for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
726                                 ir_node *pred  = get_irn_n(irn, j);
727                                 node_entry *pe = get_irn_ne(pred, env);
728
729                                 if (pe->pscc != e->pscc) {
730                                         /* not in the same SCC, must be a region const */
731                                         if (! is_rc(pred, header)) {
732                                                 /* not an induction variable */
733                                                 goto fail;
734                                         }
735                                         if (! out_rc) {
736                                                 out_rc = pred;
737                                                 ++num_outside;
738                                         } else if (out_rc != pred) {
739                                                 ++num_outside;
740                                         }
741                                 }
742                         }
743                         break;
744                 default:
745                         /* not an induction variable */
746                         goto fail;
747                 }
748         }
749         /* found an induction variable */
750         DB((dbg, LEVEL_2, "  Found an induction variable:\n  "));
751         if (only_phi && num_outside == 1) {
752                 /* a phi cycle with only one real predecessor can be collapsed */
753                 DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
754
755                 for (irn = pscc->head; irn; irn = next) {
756                         node_entry *e = get_irn_ne(irn, env);
757                         next = e->next;
758                         e->header = NULL;
759                         exchange(irn, out_rc);
760                 }
761                 ++env->replaced;
762                 return;
763         }
764
765         /* set the header for every node in this scc */
766         for (irn = pscc->head; irn; irn = next) {
767                 node_entry *e = get_irn_ne(irn, env);
768                 e->header = header;
769                 next = e->next;
770                 DB((dbg, LEVEL_2, " %+F,", irn));
771         }
772         DB((dbg, LEVEL_2, "\n"));
773         return;
774
775 fail:
776         for (irn = pscc->head; irn; irn = next) {
777                 node_entry *e = get_irn_ne(irn, env);
778
779                 next = e->next;
780                 e->header = NULL;
781         }
782 }
783
784 /**
785  * Process a SCC for the operator strength reduction.
786  *
787  * @param pscc  the SCC
788  * @param env   the environment
789  */
790 static void process_scc(scc *pscc, iv_env *env) {
791         ir_node *head = pscc->head;
792         node_entry *e = get_irn_link(head);
793
794 #ifdef DEBUG_libfirm
795         {
796                 ir_node *irn, *next;
797
798                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
799                 for (irn = pscc->head; irn; irn = next) {
800                         node_entry *e = get_irn_link(irn);
801
802                         next = e->next;
803
804                         DB((dbg, LEVEL_4, " %+F,", irn));
805                 }
806                 DB((dbg, LEVEL_4, "\n"));
807         }
808 #endif
809
810         if (e->next == NULL) {
811                 /* this SCC has only a single member */
812                 check_replace(head, env);
813         } else {
814                 classify_iv(pscc, env);
815         }
816 }
817
818 /**
819  * If an SCC is a Phi only cycle, remove it.
820  */
821 static void remove_phi_cycle(scc *pscc, iv_env *env) {
822         ir_node *irn, *next;
823         int j;
824         ir_node *out_rc;
825
826         /* check if this scc contains only Phi, Add or Sub nodes */
827         out_rc      = NULL;
828         for (irn = pscc->head; irn; irn = next) {
829                 node_entry *e = get_irn_ne(irn, env);
830
831                 next = e->next;
832                 if (! is_Phi(irn))
833                         return;
834
835                 for (j = get_irn_arity(irn) - 1; j >= 0; --j) {
836                         ir_node *pred  = get_irn_n(irn, j);
837                         node_entry *pe = get_irn_ne(pred, env);
838
839                         if (pe->pscc != e->pscc) {
840                                 /* not in the same SCC, must be the only input */
841                                 if (! out_rc) {
842                                         out_rc = pred;
843                                 } else if (out_rc != pred) {
844                                         return;
845                                 }
846                         }
847                 }
848         }
849         /* found a Phi cycle */
850         DB((dbg, LEVEL_2, "  Found an USELESS Phi cycle:\n  "));
851
852         for (irn = pscc->head; irn; irn = next) {
853                 node_entry *e = get_irn_ne(irn, env);
854                 next = e->next;
855                 e->header = NULL;
856                 exchange(irn, out_rc);
857         }
858         ++env->replaced;
859 }
860
861 /**
862  * Process a SCC for the Phi cycle removement.
863  *
864  * @param pscc  the SCC
865  * @param env   the environment
866  */
867 static void process_phi_only_scc(scc *pscc, iv_env *env) {
868         ir_node *head = pscc->head;
869         node_entry *e = get_irn_link(head);
870
871 #ifdef DEBUG_libfirm
872         {
873                 ir_node *irn, *next;
874
875                 DB((dbg, LEVEL_4, " SCC at %p:\n ", pscc));
876                 for (irn = pscc->head; irn; irn = next) {
877                         node_entry *e = get_irn_link(irn);
878
879                         next = e->next;
880
881                         DB((dbg, LEVEL_4, " %+F,", irn));
882                 }
883                 DB((dbg, LEVEL_4, "\n"));
884         }
885 #endif
886
887         if (e->next != NULL)
888                 remove_phi_cycle(pscc, env);
889 }
890
891
892 /**
893  * Push a node onto the stack.
894  *
895  * @param env   the environment
896  * @param n     the node to push
897  */
898 static void push(iv_env *env, ir_node *n) {
899         node_entry *e;
900
901         if (env->tos == ARR_LEN(env->stack)) {
902                 int nlen = ARR_LEN(env->stack) * 2;
903                 ARR_RESIZE(ir_node *, env->stack, nlen);
904         }
905         env->stack[env->tos++] = n;
906         e = get_irn_ne(n, env);
907         e->in_stack = 1;
908 }
909
910 /**
911  * pop a node from the stack
912  *
913  * @param env   the environment
914  *
915  * @return  The topmost node
916  */
917 static ir_node *pop(iv_env *env)
918 {
919         ir_node *n = env->stack[--env->tos];
920         node_entry *e = get_irn_ne(n, env);
921
922         e->in_stack = 0;
923         return n;
924 }
925
926 /**
927  * Do Tarjan's SCC algorithm and drive OSR.
928  *
929  * @param irn  start at this node
930  * @param env  the environment
931  */
932 static void dfs(ir_node *irn, iv_env *env)
933 {
934         int i, n;
935         node_entry *node = get_irn_ne(irn, env);
936
937         mark_irn_visited(irn);
938
939         /* do not put blocks into the scc */
940         if (is_Block(irn)) {
941                 n = get_irn_arity(irn);
942                 for (i = 0; i < n; ++i) {
943                         ir_node *pred = get_irn_n(irn, i);
944
945                         if (irn_not_visited(pred))
946                                 dfs(pred, env);
947                 }
948         }
949         else {
950                 ir_node *block = get_nodes_block(irn);
951
952                 node->DFSnum = env->nextDFSnum++;
953                 node->low    = node->DFSnum;
954                 push(env, irn);
955
956                 /* handle the block */
957                 if (irn_not_visited(block))
958                         dfs(block, env);
959
960                 n = get_irn_arity(irn);
961                 for (i = 0; i < n; ++i) {
962                         ir_node *pred = get_irn_n(irn, i);
963                         node_entry *o = get_irn_ne(pred, env);
964
965                         if (irn_not_visited(pred)) {
966                                 dfs(pred, env);
967                                 node->low = MIN(node->low, o->low);
968                         }
969                         if (o->DFSnum < node->DFSnum && o->in_stack)
970                                 node->low = MIN(o->DFSnum, node->low);
971                 }
972                 if (node->low == node->DFSnum) {
973                         scc *pscc = obstack_alloc(&env->obst, sizeof(*pscc));
974                         ir_node *x;
975
976                         memset(pscc, 0, sizeof(*pscc));
977                         do {
978                                 node_entry *e;
979
980                                 x = pop(env);
981                                 e = get_irn_ne(x, env);
982                                 e->pscc    = pscc;
983                                 e->next    = pscc->head;
984                                 pscc->head = x;
985                         } while (x != irn);
986
987                         env->process_scc(pscc, env);
988                 }
989         }
990 }
991
992 /**
993  * Do the DFS by starting at the End node of a graph.
994  *
995  * @param irg  the graph to process
996  * @param env  the environment
997  */
998 static void do_dfs(ir_graph *irg, iv_env *env) {
999         ir_graph *rem = current_ir_graph;
1000         ir_node *end = get_irg_end(irg);
1001         int i, n;
1002
1003         set_using_irn_visited(irg);
1004
1005         current_ir_graph = irg;
1006         inc_irg_visited(irg);
1007
1008         /* visit all visible nodes */
1009         dfs(end, env);
1010
1011         /* visit the keep-alives */
1012         n = get_End_n_keepalives(end);
1013         for (i = 0; i < n; ++i) {
1014                 ir_node *ka = get_End_keepalive(end, i);
1015
1016                 if (irn_not_visited(ka))
1017                         dfs(ka, env);
1018         }
1019
1020         clear_using_irn_visited(irg);
1021
1022         current_ir_graph = rem;
1023 }
1024
1025 /**
1026  * Post-block-walker: assign the post-order number.
1027  */
1028 static void assign_po(ir_node *block, void *ctx) {
1029         iv_env *env = ctx;
1030         node_entry *e = get_irn_ne(block, env);
1031
1032         e->POnum = env->POnum++;
1033 }
1034
1035 /**
1036  * Follows the LFTR edges and return the last node in the chain.
1037  *
1038  * @param irn  the node that should be followed
1039  * @param env  the IV environment
1040  *
1041  * @note
1042  * In the current implementation only the last edge is stored, so
1043  * only one chain exists. That's why we might miss some opportunities.
1044  */
1045 static ir_node *followEdges(ir_node *irn, iv_env *env) {
1046         for (;;) {
1047                 LFTR_edge *e = LFTR_find(irn, env);
1048                 if (e)
1049                         irn = e->dst;
1050                 else
1051                         return irn;
1052         }
1053 }
1054
1055 /**
1056  * Apply one LFTR edge operation.
1057  * Return NULL if the transformation cannot be done safely without
1058  * an Overflow.
1059  *
1060  * @param iv   the induction variable
1061  * @param rc   the constant that should be translated
1062  * @param e    the LFTR edge
1063  * @param env  the IV environment
1064  *
1065  * @return the translated region constant or NULL
1066  *         if the translation was not possible
1067  *
1068  * @note
1069  * In the current implementation only the last edge is stored, so
1070  * only one chain exists. That's why we might miss some opportunities.
1071  */
1072 static ir_node *applyOneEdge(ir_node *iv, ir_node *rc, LFTR_edge *e, iv_env *env) {
1073         if (env->flags & osr_flag_lftr_with_ov_check) {
1074                 tarval *tv_l, *tv_r, *tv, *tv_init, *tv_incr;
1075                 tarval_int_overflow_mode_t ovmode;
1076                 scc *pscc;
1077
1078                 if (! is_counter_iv(iv, env)) {
1079                         DB((dbg, LEVEL_4, " not counter IV"));
1080                         return NULL;
1081                 }
1082
1083                 /* overflow can only be decided for Consts */
1084                 if (! is_Const(e->rc)) {
1085                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)", e->rc));
1086                         return NULL;
1087                 }
1088
1089                 tv_l = get_Const_tarval(rc);
1090                 tv_r = get_Const_tarval(e->rc);
1091
1092                 ovmode = tarval_get_integer_overflow_mode();
1093                 tarval_set_integer_overflow_mode(TV_OVERFLOW_BAD);
1094
1095                 pscc    = get_iv_scc(iv, env);
1096                 tv_incr = pscc->incr;
1097                 tv_init = pscc->init;
1098
1099                 /*
1100                  * Check that no overflow occurs:
1101                  * init must be transformed without overflow
1102                  * the new rc must be transformed without overflow
1103                  * rc +/- incr must be possible without overflow
1104                  */
1105                 switch (e->code) {
1106                 case iro_Mul:
1107                         tv      = tarval_mul(tv_l, tv_r);
1108                         tv_init = tarval_mul(tv_init, tv_r);
1109                         tv_incr = tarval_mul(tv_incr, tv_r);
1110                         DB((dbg, LEVEL_4, " * %+F", tv_r));
1111                         break;
1112                 case iro_Add:
1113                         tv      = tarval_add(tv_l, tv_r);
1114                         tv_init = tarval_add(tv_init, tv_r);
1115                         DB((dbg, LEVEL_4, " + %+F", tv_r));
1116                         break;
1117                 case iro_Sub:
1118                         tv      = tarval_sub(tv_l, tv_r);
1119                         tv_init = tarval_sub(tv_init, tv_r);
1120                         DB((dbg, LEVEL_4, " - %+F", tv_r));
1121                         break;
1122                 default:
1123                         assert(0);
1124                         tv = tarval_bad;
1125                 }
1126
1127                 if (pscc->code == iro_Add) {
1128                         tv = tarval_add(tv, tv_incr);
1129                 } else {
1130                         assert(pscc->code == iro_Sub);
1131                         tv = tarval_sub(tv, tv_incr);
1132                 }
1133
1134                 tarval_set_integer_overflow_mode(ovmode);
1135
1136                 if (tv == tarval_bad || tv_init == tarval_bad) {
1137                         DB((dbg, LEVEL_4, " = OVERFLOW"));
1138                         return NULL;
1139                 }
1140                 return new_r_Const(current_ir_graph, get_irn_n(rc, -1), get_tarval_mode(tv), tv);
1141         }
1142         return do_apply(e->code, NULL, rc, e->rc, get_irn_mode(rc));
1143 }
1144
1145 /**
1146  * Applies the operations represented by the LFTR edges to a
1147  * region constant and returns the value.
1148  * Return NULL if the transformation cannot be done safely without
1149  * an Overflow.
1150  *
1151  * @param iv   the IV node that starts the LFTR edge chain
1152  * @param rc   the region constant that should be translated
1153  * @param env  the IV environment
1154  *
1155  * @return the translated region constant or NULL
1156  *         if the translation was not possible
1157  */
1158 static ir_node *applyEdges(ir_node *iv, ir_node *rc, iv_env *env) {
1159         if (env->flags & osr_flag_lftr_with_ov_check) {
1160                 /* overflow can only be decided for Consts */
1161                 if (! is_counter_iv(iv, env)) {
1162                         DB((dbg, LEVEL_4, "not counter IV\n", rc));
1163                         return NULL;
1164                 }
1165                 if (! is_Const(rc)) {
1166                         DB((dbg, LEVEL_4, " = UNKNOWN (%+F)\n", rc));
1167                         return NULL;
1168                 }
1169                 DB((dbg, LEVEL_4, "%+F", get_Const_tarval(rc)));
1170         }
1171
1172         for (; rc;) {
1173                 LFTR_edge *e = LFTR_find(iv, env);
1174                 if (e) {
1175                         rc = applyOneEdge(iv, rc, e, env);
1176                         iv = e->dst;
1177                 }
1178                 else
1179                         break;
1180         }
1181         DB((dbg, LEVEL_3, "\n"));
1182         return rc;
1183 }
1184
1185 /**
1186  * Walker, finds Cmp(iv, rc) or Cmp(rc, iv)
1187  * and tries to optimize them.
1188  */
1189 static void do_lftr(ir_node *cmp, void *ctx) {
1190         iv_env *env = ctx;
1191         ir_node *left, *right, *liv, *riv;
1192         ir_node *iv, *rc;
1193         ir_node *nleft = NULL, *nright = NULL;
1194
1195         if (get_irn_op(cmp) != op_Cmp)
1196                 return;
1197
1198         left  = get_Cmp_left(cmp);
1199         right = get_Cmp_right(cmp);
1200
1201         liv = is_iv(left, env);
1202         riv = is_iv(right, env);
1203         if (liv && is_rc(right, liv)) {
1204                 iv = left; rc = right;
1205
1206                 nright = applyEdges(iv, rc, env);
1207                 if (nright && nright != rc) {
1208                         nleft = followEdges(iv, env);
1209                 }
1210         }
1211         else if (riv && is_rc(left, riv)) {
1212                 iv = right; rc = left;
1213
1214                 nleft = applyEdges(iv, rc, env);
1215                 if (nleft && nleft != rc) {
1216                         nright = followEdges(iv, env);
1217                 }
1218         }
1219
1220         if (nleft && nright) {
1221                 DB((dbg, LEVEL_2, "  LFTR for %+F\n", cmp));
1222                 set_Cmp_left(cmp, nleft);
1223                 set_Cmp_right(cmp, nright);
1224                 ++env->lftr_replaced;
1225         }
1226 }
1227
1228 /**
1229  * do linear function test replacement.
1230  *
1231  * @param irg   the graph that should be optimized
1232  * @param env   the IV environment
1233  */
1234 static void lftr(ir_graph *irg, iv_env *env) {
1235         irg_walk_graph(irg, NULL, do_lftr, env);
1236 }
1237
1238 /**
1239  * Pre-walker: set all node links to NULL and fix the
1240  * block of Proj nodes.
1241  */
1242 static void clear_and_fix(ir_node *irn, void *env)
1243 {
1244         (void) env;
1245         set_irn_link(irn, NULL);
1246
1247         if (is_Proj(irn)) {
1248                 ir_node *pred = get_Proj_pred(irn);
1249                 set_nodes_block(irn, get_nodes_block(pred));
1250         }
1251 }
1252
1253 /* Performs Operator Strength Reduction for the passed graph. */
1254 void opt_osr(ir_graph *irg, unsigned flags) {
1255         iv_env   env;
1256         ir_graph *rem;
1257         int      edges;
1258
1259         if (! get_opt_strength_red()) {
1260                 /* only kill Phi cycles  */
1261                 remove_phi_cycles(irg);
1262                 return;
1263         }
1264
1265         rem = current_ir_graph;
1266         current_ir_graph = irg;
1267
1268         FIRM_DBG_REGISTER(dbg, "firm.opt.osr");
1269
1270         DB((dbg, LEVEL_1, "Doing Operator Strength Reduction for %+F\n", irg));
1271
1272         obstack_init(&env.obst);
1273         env.stack         = NEW_ARR_F(ir_node *, 128);
1274         env.tos           = 0;
1275         env.nextDFSnum    = 0;
1276         env.POnum         = 0;
1277         env.quad_map      = new_set(quad_cmp, 64);
1278         env.lftr_edges    = new_set(LFTR_cmp, 64);
1279         env.replaced      = 0;
1280         env.lftr_replaced = 0;
1281         env.flags         = flags;
1282         env.process_scc   = process_scc;
1283
1284         /* Clear all links and move Proj nodes into the
1285            the same block as it's predecessors.
1286            This can improve the placement of new nodes.
1287          */
1288         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1289
1290         /* we need dominance */
1291         assure_doms(irg);
1292
1293         edges = edges_assure(irg);
1294
1295         /* calculate the post order number for blocks. */
1296         irg_block_edges_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1297
1298         /* calculate the SCC's and drive OSR. */
1299         do_dfs(irg, &env);
1300
1301         if (env.replaced) {
1302                 /* try linear function test replacements */
1303                 lftr(irg, &env);
1304
1305                 set_irg_outs_inconsistent(irg);
1306                 DB((dbg, LEVEL_1, "Replacements: %u + %u (lftr)\n\n", env.replaced, env.lftr_replaced));
1307         }
1308
1309         del_set(env.lftr_edges);
1310         del_set(env.quad_map);
1311         DEL_ARR_F(env.stack);
1312         obstack_free(&env.obst, NULL);
1313
1314         if (! edges)
1315                 edges_deactivate(irg);
1316
1317         current_ir_graph = rem;
1318 }
1319
1320 /* Remove any Phi cycles with only one real input. */
1321 void remove_phi_cycles(ir_graph *irg) {
1322         iv_env   env;
1323         ir_graph *rem;
1324
1325         rem = current_ir_graph;
1326         current_ir_graph = irg;
1327
1328         FIRM_DBG_REGISTER(dbg, "firm.opt.remove_phi");
1329
1330         DB((dbg, LEVEL_1, "Doing Phi cycle removement for %+F\n", irg));
1331
1332         obstack_init(&env.obst);
1333         env.stack         = NEW_ARR_F(ir_node *, 128);
1334         env.tos           = 0;
1335         env.nextDFSnum    = 0;
1336         env.POnum         = 0;
1337         env.quad_map      = NULL;
1338         env.lftr_edges    = NULL;
1339         env.replaced      = 0;
1340         env.lftr_replaced = 0;
1341         env.flags         = 0;
1342         env.process_scc   = process_phi_only_scc;
1343
1344         /* Clear all links and move Proj nodes into the
1345            the same block as it's predecessors.
1346            This can improve the placement of new nodes.
1347          */
1348         irg_walk_graph(irg, NULL, clear_and_fix, NULL);
1349
1350         /* we need outs for calculating the post order */
1351         assure_irg_outs(irg);
1352
1353         /* calculate the post order number for blocks. */
1354         irg_out_block_walk(get_irg_start_block(irg), NULL, assign_po, &env);
1355
1356         /* calculate the SCC's and drive OSR. */
1357         do_dfs(irg, &env);
1358
1359         if (env.replaced) {
1360                 set_irg_outs_inconsistent(irg);
1361                 DB((dbg, LEVEL_1, "remove_phi_cycles: %u Cycles removed\n\n", env.replaced));
1362         }
1363
1364         DEL_ARR_F(env.stack);
1365         obstack_free(&env.obst, NULL);
1366
1367         current_ir_graph = rem;
1368 }