merge kaps
[libfirm] / ir / opt / code_placement.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    Code Placement.  Pins all floating nodes to a block where they
23  *           will be executed only if needed.
24  * @author   Christian Schaefer, Goetz Lindenmaier, Sebastian Felis,
25  *           Michael Beck
26  * @version  $Id$
27  */
28 #include "config.h"
29
30 #include "iroptimize.h"
31 #include "adt/pdeq.h"
32 #include "irnode_t.h"
33 #include "irouts.h"
34 #include "irgopt.h"
35 #include "irpass.h"
36
37 /**
38  * Returns non-zero, is a block is not reachable from Start.
39  *
40  * @param block  the block to test
41  */
42 static int is_Block_unreachable(ir_node *block)
43 {
44         return is_Block_dead(block) || get_Block_dom_depth(block) < 0;
45 }
46
47 /**
48  * Find the earliest correct block for node n.  --- Place n into the
49  * same Block as its dominance-deepest Input.
50  *
51  * We have to avoid calls to get_nodes_block() here
52  * because the graph is floating.
53  *
54  * move_out_of_loops() expects that place_floats_early() have placed
55  * all "living" nodes into a living block. That's why we must
56  * move nodes in dead block with "live" successors into a valid
57  * block.
58  * We move them just into the same block as its successor (or
59  * in case of a Phi into the effective use block). For Phi successors,
60  * this may still be a dead block, but then there is no real use, as
61  * the control flow will be dead later.
62  *
63  * @param n         the node to be placed
64  * @param worklist  a worklist, predecessors of non-floating nodes are placed here
65  */
66 static void place_floats_early(ir_node *n, waitq *worklist)
67 {
68         int i, irn_arity;
69
70         /* we must not run into an infinite loop */
71         assert(!irn_visited(n));
72         mark_irn_visited(n);
73
74         /* Place floating nodes. */
75         if (get_irn_pinned(n) == op_pin_state_floats) {
76                 ir_node *curr_block = get_nodes_block(n);
77                 int in_dead_block   = is_Block_unreachable(curr_block);
78                 int depth           = 0;
79                 ir_node *b          = NULL;   /* The block to place this node in */
80                 ir_graph *irg       = get_irn_irg(n);
81
82                 assert(!is_Block(n));
83
84                 if (is_irn_start_block_placed(n)) {
85                         /* These nodes will not be placed by the loop below. */
86                         b = get_irg_start_block(irg);
87                         depth = 1;
88                 }
89
90                 /* find the block for this node. */
91                 irn_arity = get_irn_arity(n);
92                 for (i = 0; i < irn_arity; i++) {
93                         ir_node *pred = get_irn_n(n, i);
94                         ir_node *pred_block;
95
96                         if (!irn_visited(pred)
97                             && (get_irn_pinned(pred) == op_pin_state_floats)) {
98
99                                 /*
100                                  * If the current node is NOT in a dead block, but one of its
101                                  * predecessors is, we must move the predecessor to a live
102                                  * block.
103                                  * Such thing can happen, if global CSE chose a node from a
104                                  * dead block. We move it simply to our block.
105                                  * Note that neither Phi nor End nodes are floating, so we don't
106                                  * need to handle them here.
107                                  */
108                                 if (! in_dead_block) {
109                                         if (get_irn_pinned(pred) == op_pin_state_floats &&
110                                                 is_Block_unreachable(get_nodes_block(pred)))
111                                                 set_nodes_block(pred, curr_block);
112                                 }
113                                 place_floats_early(pred, worklist);
114                         }
115
116                         /*
117                          * A node in the Bad block must stay in the bad block,
118                          * so don't compute a new block for it.
119                          */
120                         if (in_dead_block)
121                                 continue;
122
123                         /* Because all loops contain at least one op_pin_state_pinned node,
124                            now all our inputs are either op_pin_state_pinned or
125                            place_early() has already been finished on them.
126                            We do not have any unfinished inputs! */
127                         pred_block = get_nodes_block(pred);
128                         if ((!is_Block_dead(pred_block)) &&
129                                 (get_Block_dom_depth(pred_block) > depth)) {
130                                 b = pred_block;
131                                 depth = get_Block_dom_depth(pred_block);
132                         }
133                         /* Avoid that the node is placed in the Start block if we are not
134                            in the backend phase. */
135                         if (depth == 1 &&
136                                         get_Block_dom_depth(get_nodes_block(n)) > 1 &&
137                                         get_irg_phase_state(irg) != phase_backend) {
138                                 b = get_Block_cfg_out(get_irg_start_block(irg), 0);
139                                 assert(b != get_irg_start_block(irg));
140                                 depth = 2;
141                         }
142                 }
143                 if (b)
144                         set_nodes_block(n, b);
145         }
146
147         /*
148          * Add predecessors of non floating nodes and non-floating predecessors
149          * of floating nodes to worklist and fix their blocks if the are in dead
150          * block.
151          */
152         irn_arity = get_irn_arity(n);
153
154         if (is_End(n)) {
155                 /*
156                  * Simplest case: End node. Predecessors are keep-alives,
157                  * no need to move out of dead block.
158                  */
159                 for (i = -1; i < irn_arity; ++i) {
160                         ir_node *pred = get_irn_n(n, i);
161                         if (!irn_visited(pred))
162                                 waitq_put(worklist, pred);
163                 }
164         } else if (is_Block(n)) {
165                 /*
166                  * Blocks: Predecessors are control flow, no need to move
167                  * them out of dead block.
168                  */
169                 for (i = irn_arity - 1; i >= 0; --i) {
170                         ir_node *pred = get_irn_n(n, i);
171                         if (!irn_visited(pred))
172                                 waitq_put(worklist, pred);
173                 }
174         } else if (is_Phi(n)) {
175                 ir_node *pred;
176                 ir_node *curr_block = get_nodes_block(n);
177                 int in_dead_block   = is_Block_unreachable(curr_block);
178
179                 /*
180                  * Phi nodes: move nodes from dead blocks into the effective use
181                  * of the Phi-input if the Phi is not in a bad block.
182                  */
183                 pred = get_nodes_block(n);
184                 if (!irn_visited(pred))
185                         waitq_put(worklist, pred);
186
187                 for (i = irn_arity - 1; i >= 0; --i) {
188                         ir_node *pred = get_irn_n(n, i);
189
190                         if (!irn_visited(pred)) {
191                                 if (! in_dead_block &&
192                                         get_irn_pinned(pred) == op_pin_state_floats &&
193                                         is_Block_unreachable(get_nodes_block(pred))) {
194                                         set_nodes_block(pred, get_Block_cfgpred_block(curr_block, i));
195                                 }
196                                 waitq_put(worklist, pred);
197                         }
198                 }
199         } else {
200                 ir_node *pred;
201                 ir_node *curr_block = get_nodes_block(n);
202                 int in_dead_block   = is_Block_unreachable(curr_block);
203
204                 /*
205                  * All other nodes: move nodes from dead blocks into the same block.
206                  */
207                 pred = get_nodes_block(n);
208                 if (!irn_visited(pred))
209                         waitq_put(worklist, pred);
210
211                 for (i = irn_arity - 1; i >= 0; --i) {
212                         ir_node *pred = get_irn_n(n, i);
213
214                         if (!irn_visited(pred)) {
215                                 if (! in_dead_block &&
216                                         get_irn_pinned(pred) == op_pin_state_floats &&
217                                         is_Block_unreachable(get_nodes_block(pred))) {
218                                         set_nodes_block(pred, curr_block);
219                                 }
220                                 waitq_put(worklist, pred);
221                         }
222                 }
223         }
224 }
225
226 /**
227  * Floating nodes form subgraphs that begin at nodes as Const, Load,
228  * Start, Call and that end at op_pin_state_pinned nodes as Store, Call.
229  * Place_early places all floating nodes reachable from its argument through
230  * floating nodes and adds all beginnings at op_pin_state_pinned nodes to the
231  * worklist.
232  *
233  * @param worklist   a worklist, used for the algorithm, empty on in/output
234  */
235 static void place_early(ir_graph *irg, waitq *worklist)
236 {
237         assert(worklist);
238         inc_irg_visited(irg);
239
240         /* this inits the worklist */
241         place_floats_early(get_irg_end(irg), worklist);
242
243         /* Work the content of the worklist. */
244         while (!waitq_empty(worklist)) {
245                 ir_node *n = (ir_node*)waitq_get(worklist);
246                 if (!irn_visited(n))
247                         place_floats_early(n, worklist);
248         }
249         set_irg_pinned(irg, op_pin_state_pinned);
250 }
251
252 /**
253  * Compute the deepest common dominator tree ancestor of block and dca.
254  *
255  * @param dca    the deepest common dominator tree ancestor so far,
256  *               might be NULL
257  * @param block  a block
258  *
259  * @return  the deepest common dominator tree ancestor of block and dca
260  */
261 static ir_node *calc_dom_dca(ir_node *dca, ir_node *block)
262 {
263         assert(block != NULL);
264
265         /* we do not want to place nodes in dead blocks */
266         if (is_Block_dead(block))
267                 return dca;
268
269         /* We found a first legal placement. */
270         if (!dca) return block;
271
272         /* Find a placement that is dominates both, dca and block. */
273         while (get_Block_dom_depth(block) > get_Block_dom_depth(dca))
274                 block = get_Block_idom(block);
275
276         while (get_Block_dom_depth(dca) > get_Block_dom_depth(block)) {
277                 dca = get_Block_idom(dca);
278         }
279
280         while (block != dca) {
281                 block = get_Block_idom(block); dca = get_Block_idom(dca);
282         }
283         return dca;
284 }
285
286 /**
287  * Deepest common dominance ancestor of DCA and CONSUMER of PRODUCER.
288  * I.e., DCA is the block where we might place PRODUCER.
289  * A data flow edge points from producer to consumer.
290  */
291 static ir_node *consumer_dom_dca(ir_node *dca, ir_node *consumer, ir_node *producer)
292 {
293         /* Compute the last block into which we can place a node so that it is
294            before consumer. */
295         if (is_Phi(consumer)) {
296                 /* our consumer is a Phi-node, the effective use is in all those
297                    blocks through which the Phi-node reaches producer */
298                 ir_node *phi_block = get_nodes_block(consumer);
299                 int      arity     = get_irn_arity(consumer);
300                 int      i;
301
302                 for (i = 0;  i < arity; i++) {
303                         if (get_Phi_pred(consumer, i) == producer) {
304                                 ir_node *new_block = get_Block_cfgpred_block(phi_block, i);
305
306                                 if (!is_Block_unreachable(new_block))
307                                         dca = calc_dom_dca(dca, new_block);
308                         }
309                 }
310         } else {
311                 dca = calc_dom_dca(dca, get_nodes_block(consumer));
312         }
313         return dca;
314 }
315
316 static inline int get_block_loop_depth(ir_node *block)
317 {
318         return get_loop_depth(get_irn_loop(block));
319 }
320
321 /**
322  * Move n to a block with less loop depth than its current block. The
323  * new block must be dominated by early.
324  *
325  * @param n      the node that should be moved
326  * @param early  the earliest block we can n move to
327  */
328 static void move_out_of_loops(ir_node *n, ir_node *early)
329 {
330         ir_node *best, *dca;
331         assert(n && early);
332
333
334         /* Find the region deepest in the dominator tree dominating
335            dca with the least loop nesting depth, but still dominated
336            by our early placement. */
337         dca = get_nodes_block(n);
338
339         best = dca;
340         while (dca != early) {
341                 dca = get_Block_idom(dca);
342                 if (!dca || is_Bad(dca)) break; /* may be Bad if not reachable from Start */
343                 if (get_block_loop_depth(dca) < get_block_loop_depth(best)) {
344                         best = dca;
345                 }
346         }
347         if (best != get_nodes_block(n))
348                 set_nodes_block(n, best);
349 }
350
351 /**
352  * Calculate the deepest common ancestor in the dominator tree of all nodes'
353  * blocks depending on node; our final placement has to dominate DCA.
354  *
355  * @param node  the definition node
356  * @param dca   the deepest common ancestor block so far, initially
357  *              NULL
358  *
359  * @return the deepest common dominator ancestor of all blocks of node's users
360  */
361 static ir_node *get_deepest_common_dom_ancestor(ir_node *node, ir_node *dca)
362 {
363         int i;
364
365         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
366                 ir_node *succ = get_irn_out(node, i);
367
368                 if (is_End(succ)) {
369                         /*
370                          * This consumer is the End node, a keep alive edge.
371                          * This is not a real consumer, so we ignore it
372                          */
373                         continue;
374                 }
375
376                 if (is_Proj(succ)) {
377                         /* Proj nodes are in the same block as node, so
378                          * the users of Proj are our users. */
379                         dca = get_deepest_common_dom_ancestor(succ, dca);
380                 } else {
381                         /* ignore if succ is in dead code */
382                         ir_node *succ_blk = get_nodes_block(succ);
383                         if (is_Block_unreachable(succ_blk))
384                                 continue;
385                         dca = consumer_dom_dca(dca, succ, node);
386                 }
387         }
388         return dca;
389 }
390
391 /**
392  * Put all the Proj nodes of a node into a given block.
393  *
394  * @param node   the mode_T node
395  * @param block  the block to put the Proj nodes to
396  */
397 static void set_projs_block(ir_node *node, ir_node *block)
398 {
399         int i;
400
401         for (i = get_irn_n_outs(node) - 1; i >= 0; --i) {
402                 ir_node *succ = get_irn_out(node, i);
403
404                 assert(is_Proj(succ));
405
406                 if (get_irn_mode(succ) == mode_T) {
407                         set_projs_block(succ, block);
408                 }
409                 set_nodes_block(succ, block);
410         }
411 }
412
413 /**
414  * Find the latest legal block for N and place N into the
415  * `optimal' Block between the latest and earliest legal block.
416  * The `optimal' block is the dominance-deepest block of those
417  * with the least loop-nesting-depth.  This places N out of as many
418  * loops as possible and then makes it as control dependent as
419  * possible.
420  *
421  * @param n         the node to be placed
422  * @param worklist  a worklist, all successors of non-floating nodes are
423  *                  placed here
424  */
425 static void place_floats_late(ir_node *n, pdeq *worklist)
426 {
427         int i, n_outs;
428         ir_node *early_blk;
429
430         assert(!irn_visited(n)); /* no multiple placement */
431
432         mark_irn_visited(n);
433
434         /* no need to place block nodes, control nodes are already placed. */
435         if (!is_Block(n) &&
436             (!is_cfop(n)) &&
437             (get_irn_mode(n) != mode_X)) {
438                 /* Remember the early_blk placement of this block to move it
439                    out of loop no further than the early_blk placement. */
440                 early_blk = get_nodes_block(n);
441
442                 /*
443                  * BEWARE: Here we also get code, that is live, but
444                  * was in a dead block.  If the node is life, but because
445                  * of CSE in a dead block, we still might need it.
446                  */
447
448                 /* Assure that our users are all placed, except the Phi-nodes.
449                 --- Each data flow cycle contains at least one Phi-node.  We
450                     have to break the `user has to be placed before the
451                     producer' dependence cycle and the Phi-nodes are the
452                     place to do so, because we need to base our placement on the
453                     final region of our users, which is OK with Phi-nodes, as they
454                     are op_pin_state_pinned, and they never have to be placed after a
455                     producer of one of their inputs in the same block anyway. */
456                 for (i = get_irn_n_outs(n) - 1; i >= 0; --i) {
457                         ir_node *succ = get_irn_out(n, i);
458                         if (!irn_visited(succ) && !is_Phi(succ))
459                                 place_floats_late(succ, worklist);
460                 }
461
462                 if (! is_Block_dead(early_blk)) {
463                         /* do only move things that where not dead */
464                         ir_op *op = get_irn_op(n);
465
466                         /* We have to determine the final block of this node... except for
467                            constants and Projs */
468                         if ((get_irn_pinned(n) == op_pin_state_floats) &&
469                             (op != op_Const)    &&
470                             (op != op_SymConst) &&
471                             (op != op_Proj))
472                         {
473                                 /* deepest common ancestor in the dominator tree of all nodes'
474                                    blocks depending on us; our final placement has to dominate
475                                    DCA. */
476                                 ir_node *dca = get_deepest_common_dom_ancestor(n, NULL);
477                                 if (dca != NULL) {
478                                         set_nodes_block(n, dca);
479                                         move_out_of_loops(n, early_blk);
480                                         if (get_irn_mode(n) == mode_T) {
481                                                 set_projs_block(n, get_nodes_block(n));
482                                         }
483                                 }
484                         }
485                 }
486         }
487
488         /* Add successors of all non-floating nodes on list. (Those of floating
489            nodes are placed already and therefore are marked.)  */
490         n_outs = get_irn_n_outs(n);
491         for (i = 0; i < n_outs; i++) {
492                 ir_node *succ = get_irn_out(n, i);
493                 if (!irn_visited(succ)) {
494                         pdeq_putr(worklist, succ);
495                 }
496         }
497 }
498
499 /**
500  * Place floating nodes on the given worklist as late as possible using
501  * the dominance tree.
502  *
503  * @param worklist   the worklist containing the nodes to place
504  */
505 static void place_late(ir_graph *irg, waitq *worklist)
506 {
507         assert(worklist);
508         inc_irg_visited(irg);
509
510         /* This fills the worklist initially. */
511         place_floats_late(get_irg_start_block(irg), worklist);
512
513         /* And now empty the worklist again... */
514         while (!waitq_empty(worklist)) {
515                 ir_node *n = (ir_node*)waitq_get(worklist);
516                 if (!irn_visited(n))
517                         place_floats_late(n, worklist);
518         }
519 }
520
521 /* Code Placement. */
522 void place_code(ir_graph *irg)
523 {
524         waitq *worklist;
525
526         remove_critical_cf_edges(irg);
527
528         /* Handle graph state */
529         assert(get_irg_phase_state(irg) != phase_building);
530         assure_irg_outs(irg);
531         assure_doms(irg);
532         assure_cf_loop(irg);
533
534         /* Place all floating nodes as early as possible. This guarantees
535          a legal code placement. */
536         worklist = new_waitq();
537         place_early(irg, worklist);
538
539         /* Note: place_early changes only blocks, no data edges. So, the
540          * data out edges are still valid, no need to recalculate them here. */
541
542         /* Now move the nodes down in the dominator tree. This reduces the
543            unnecessary executions of the node. */
544         place_late(irg, worklist);
545
546         set_irg_outs_inconsistent(irg);
547         set_irg_loopinfo_inconsistent(irg);
548         del_waitq(worklist);
549 }
550
551 /**
552  * Wrapper for place_code() inside the place_code pass.
553  */
554 static void place_code_wrapper(ir_graph *irg)
555 {
556         set_opt_global_cse(1);
557         optimize_graph_df(irg);
558         place_code(irg);
559         set_opt_global_cse(0);
560 }
561
562 ir_graph_pass_t *place_code_pass(const char *name)
563 {
564         return def_graph_pass(name ? name : "place", place_code_wrapper);
565 }