dfddb021d2a7e78609ef209d9b6d0eed7ddc7a32
[libfirm] / ir / opt / ldstopt.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/opt/ldstopt.c
4  * Purpose:     load store optimizations
5  * Author:
6  * Created:
7  * CVS-ID:      $Id$
8  * Copyright:   (c) 1998-2004 Universit\81ät Karlsruhe
9  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
10  */
11 # include "irnode_t.h"
12 # include "irgraph_t.h"
13 # include "irmode_t.h"
14 # include "iropt_t.h"
15 # include "ircons_t.h"
16 # include "irgmod.h"
17 # include "irgwalk.h"
18 # include "irvrfy.h"
19 # include "tv_t.h"
20 # include "dbginfo_t.h"
21 # include "iropt_dbg.h"
22 # include "irflag_t.h"
23 # include "array.h"
24 # include "firmstat.h"
25
26 #undef IMAX
27 #define IMAX(a,b)       ((a) > (b) ? (a) : (b))
28
29 #define MAX_PROJ        IMAX(pn_Load_max, pn_Store_max)
30
31 /**
32  * walker environment
33  */
34 typedef struct _walk_env_t {
35   struct obstack obst;          /**< list of all stores */
36   int changes;
37 } walk_env_t;
38
39 /**
40  * a Load/Store info
41  */
42 typedef struct _ldst_info_t {
43   ir_node *projs[MAX_PROJ];     /**< list of Proj's of this node */
44   ir_node *exc_block;           /**< the exception block if available */
45   int     exc_idx;              /**< predecessor index in the exception block */
46 } ldst_info_t;
47
48 /**
49  * flags for control flow
50  */
51 enum block_flags_t {
52   BLOCK_HAS_COND = 1,      /**< Block has conditional control flow */
53   BLOCK_HAS_EXC  = 2       /**< Block has exceptionl control flow */
54 };
55
56 /**
57  * a Block info
58  */
59 typedef struct _block_info_t {
60   unsigned flags;               /**< flags for the block */
61 } block_info_t;
62
63 /**
64  * walker, clears all links first
65  */
66 static void init_links(ir_node *n, void *env)
67 {
68   set_irn_link(n, NULL);
69 }
70
71 /**
72  * get the Load/Store info of a node
73  */
74 static ldst_info_t *get_ldst_info(ir_node *node, walk_env_t *env)
75 {
76   ldst_info_t *info = get_irn_link(node);
77
78   if (! info) {
79     info = obstack_alloc(&env->obst, sizeof(*info));
80
81     memset(info, 0, sizeof(*info));
82
83     set_irn_link(node, info);
84   }
85   return info;
86 }
87
88 /**
89  * get the Block info of a node
90  */
91 static block_info_t *get_block_info(ir_node *node, walk_env_t *env)
92 {
93   block_info_t *info = get_irn_link(node);
94
95   if (! info) {
96     info = obstack_alloc(&env->obst, sizeof(*info));
97
98     memset(info, 0, sizeof(*info));
99
100     set_irn_link(node, info);
101   }
102   return info;
103 }
104
105 /**
106  * update the projection info for a Load/Store
107  */
108 static int update_projs(ldst_info_t *info, ir_node *proj)
109 {
110   long nr = get_Proj_proj(proj);
111
112   assert(0 <= nr && nr <= MAX_PROJ && "Wrong proj from LoadStore");
113
114   if (info->projs[nr]) {
115     /* there is already one, do CSE */
116     exchange(proj, info->projs[nr]);
117     return 1;
118   }
119   else {
120     info->projs[nr] = proj;
121     return 0;
122   }
123 }
124
125 /**
126  * update the exception block info for a Load/Store
127  */
128 static int update_exc(ldst_info_t *info, ir_node *block, int pos)
129 {
130   assert(info->exc_block == NULL && "more than one exception block found");
131
132   info->exc_block = block;
133   info->exc_idx   = pos;
134   return 0;
135 }
136
137 /**
138  * walker, collects all Load/Store/Proj nodes
139  *
140  * walks form Start -> End
141  */
142 static void collect_nodes(ir_node *node, void *env)
143 {
144   ir_node     *pred;
145   ldst_info_t *ldst_info;
146   walk_env_t  *wenv = env;
147
148   if (get_irn_op(node) == op_Proj) {
149     pred = get_Proj_pred(node);
150
151     if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
152       ldst_info = get_ldst_info(pred, wenv);
153
154       wenv->changes |= update_projs(ldst_info, node);
155     }
156   }
157   else if (get_irn_op(node) == op_Block) { /* check, if it's an exception block */
158     int i, n;
159
160     for (i = 0, n = get_Block_n_cfgpreds(node); i < n; ++i) {
161       ir_node      *pred_block;
162       block_info_t *bl_info;
163
164       pred = skip_Proj(get_Block_cfgpred(node, i));
165
166       /* ignore Bad predecessors, they will be removed later */
167       if (is_Bad(pred))
168         continue;
169
170       pred_block = get_nodes_block(pred);
171       bl_info    = get_block_info(pred_block, wenv);
172
173       if (is_fragile_op(pred))
174         bl_info->flags |= BLOCK_HAS_EXC;
175       else if (is_forking_op(pred))
176         bl_info->flags |= BLOCK_HAS_COND;
177
178       if (get_irn_op(pred) == op_Load || get_irn_op(pred) == op_Store) {
179         ldst_info = get_ldst_info(pred, wenv);
180
181         wenv->changes |= update_exc(ldst_info, node, i);
182       }
183     }
184   }
185 }
186
187 /**
188  * optimize a Load
189  */
190 static int optimize_load(ir_node *load)
191 {
192   ldst_info_t *info = get_irn_link(load);
193   ir_mode *load_mode = get_Load_mode(load);
194   ir_node *pred, *mem, *ptr;
195   int res = 0;
196
197   /* do NOT touch volatile loads for now */
198   if (get_Load_volatility(load) == volatility_is_volatile)
199     return 0;
200
201   if (! info->projs[pn_Load_res] && ! info->projs[pn_Load_X_except]) {
202     /* a Load which value is neither used nor exception checked, remove it */
203     mem  = get_Load_mem(load);
204     exchange(info->projs[pn_Load_M], mem);
205
206     return 1;
207   }
208
209   /* the address of the load to be optimized */
210   ptr = get_Load_ptr(load);
211
212   /* the mem of the load. Must still be returned after optimization */
213   mem  = get_Load_mem(load);
214
215   /* follow the memory chain as long as there are only Loads */
216   for (pred = load; res == 0;) {
217
218     /* follow only load chains */
219     if (get_irn_op(pred) != op_Load)
220       break;
221
222     /*
223      * BEWARE: one might think that checking the modes is useless, because
224      * if the pointers are identical, they refer to the same object.
225      * This is only true in strong typed languages, not is C were the following
226      * is possible a = *(type1 *)p; b = *(type2 *)p ...
227      */
228
229     pred = skip_Proj(get_Load_mem(pred));
230
231     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
232              get_irn_mode(get_Store_value(pred)) == load_mode) {
233       /*
234        * a load immediately after a store -- a read after write.
235        * We may remove the Load, if it does not have an exception handler
236        * OR they are in the same block. In the latter case the Load cannot
237        * throw an exception when the previous Store was quiet.
238        */
239       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
240         DBG_OPT_RAW(pred, load);
241         exchange( info->projs[pn_Load_res], get_Store_value(pred) );
242
243         if (info->projs[pn_Load_M])
244           exchange(info->projs[pn_Load_M], mem);
245
246         /* no exception */
247         if (info->projs[pn_Load_X_except])
248           exchange( info->projs[pn_Load_X_except], new_Bad());
249         res = 1;
250       }
251     }
252     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
253              get_Load_mode(pred) == load_mode) {
254       /*
255        * a load after a load -- a read after read.
256        * We may remove the second Load, if it does not have an exception handler
257        * OR they are in the same block. In the later case the Load cannot
258        * throw an exception when the previous Load was quiet.
259        */
260       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
261         ldst_info_t *pred_info = get_irn_link(pred);
262
263         DBG_OPT_RAR(pred, load);
264
265         if (pred_info->projs[pn_Load_res]) {
266           /* we need a data proj from the previous load for this optimization */
267           exchange( info->projs[pn_Load_res], pred_info->projs[pn_Load_res] );
268           if (info->projs[pn_Load_M])
269             exchange(info->projs[pn_Load_M], mem);
270         }
271         else {
272           if (info->projs[pn_Load_res]) {
273             set_Proj_pred(info->projs[pn_Load_res], pred);
274             set_nodes_block(info->projs[pn_Load_res], get_nodes_block(pred));
275           }
276           if (info->projs[pn_Load_M]) {
277             /* Actually, this if should not be necessary.  Construct the Loads
278                properly!!! */
279             exchange(info->projs[pn_Load_M], mem);
280           }
281         }
282
283         /* no exception */
284         if (info->projs[pn_Load_X_except])
285           exchange(info->projs[pn_Load_X_except], new_Bad());
286
287         res = 1;
288       }
289     }
290   }
291   return res;
292 }
293
294 /**
295  * optimize a Store
296  */
297 static int optimize_store(ir_node *store)
298 {
299   ldst_info_t *info = get_irn_link(store);
300   ir_node *pred, *mem, *ptr, *value, *block;
301   ir_mode *mode;
302   ldst_info_t *pred_info;
303   int res = 0;
304
305   if (get_Store_volatility(store) == volatility_is_volatile)
306     return 0;
307
308   /*
309    * BEWARE: one might think that checking the modes is useless, because
310    * if the pointers are identical, they refer to the same object.
311    * This is only true in strong typed languages, not is C were the following
312    * is possible *(type1 *)p = a; *(type2 *)p = b ...
313    */
314
315   block = get_nodes_block(store);
316   ptr   = get_Store_ptr(store);
317   mem   = get_Store_mem(store);
318   value = get_Store_value(store);
319   pred  = skip_Proj(mem);
320   mode  = get_irn_mode(value);
321
322   pred_info = get_irn_link(pred);
323
324   if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
325       get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
326     /*
327      * a store immediately after a store in the same block -- a write after write.
328      * We may remove the first Store, if it does not have an exception handler.
329      *
330      * TODO: What, if both have the same exception handler ???
331      */
332     if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
333       DBG_OPT_WAW(pred, store);
334       exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
335       res = 1;
336     }
337   }
338   else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
339            value == pred_info->projs[pn_Load_res]) {
340     /*
341      * a store a value immediately after a load -- a write after read.
342      * We may remove the second Store, if it does not have an exception handler.
343      */
344     if (! info->projs[pn_Store_X_except]) {
345       DBG_OPT_WAR(pred, store);
346       exchange( info->projs[pn_Store_M], mem );
347       res = 1;
348     }
349   }
350   return res;
351 }
352
353 /**
354  * walker, optimizes Phi after Stores:
355  * Does the following optimization:
356  *
357  *   val1   val2   val3          val1  val2  val3
358  *    |      |      |               \    |    /
359  *   Str    Str    Str               \   |   /
360  *      \    |    /                     Phi
361  *       \   |   /                       |
362  *        \  |  /                       Str
363  *          Phi
364  *
365  * This removes the number of stores and allows for predicated execution.
366  * Moves Stores back to the end of a function which may be bad
367  *
368  * Is only allowed if the predecessor blocks have only one successor.
369  */
370 static int optimize_phi(ir_node *phi, void *env)
371 {
372   walk_env_t *wenv = env;
373   int i, n;
374   ir_node *store, *ptr, *block, *phiM, *phiD, *exc, *projM;
375   ir_mode *mode;
376   ir_node **inM, **inD;
377   int *idx;
378   dbg_info *db = NULL;
379   ldst_info_t *info;
380   block_info_t *bl_info;
381
382   /* Must be a memory Phi */
383   if (get_irn_mode(phi) != mode_M)
384     return 0;
385
386   n = get_Phi_n_preds(phi);
387   if (n <= 0)
388     return 0;
389
390   store = skip_Proj(get_Phi_pred(phi, 0));
391   if (get_irn_op(store) != op_Store)
392     return 0;
393
394   /* abort on bad blocks */
395   if (is_Bad(get_nodes_block(store)))
396     return 0;
397
398   /* check if the block has only one output */
399   bl_info = get_irn_link(get_nodes_block(store));
400   if (bl_info->flags)
401     return 0;
402
403   /* this is the address of the store */
404   ptr  = get_Store_ptr(store);
405   mode = get_irn_mode(get_Store_value(store));
406   info = get_irn_link(store);
407   exc  = info->exc_block;
408
409   for (i = 1; i < n; ++i) {
410     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
411
412     if (get_irn_op(pred) != op_Store)
413       return 0;
414
415     if (mode != get_irn_mode(get_Store_value(pred)) || ptr != get_Store_ptr(pred))
416       return 0;
417
418     info = get_irn_link(pred);
419
420     /* check, if all stores have the same exception flow */
421     if (exc != info->exc_block)
422       return 0;
423
424     /* abort on bad blocks */
425     if (is_Bad(get_nodes_block(store)))
426       return 0;
427
428     /* check if the block has only one output */
429     bl_info = get_irn_link(get_nodes_block(store));
430     if (bl_info->flags)
431       return 0;
432   }
433
434   /*
435    * ok, when we are here, we found all predecessors of a Phi that
436    * are Stores to the same address. That means whatever we do before
437    * we enter the block of the Phi, we do a Store.
438    * So, we can move the store to the current block:
439    *
440    *   val1    val2    val3          val1  val2  val3
441    *    |       |       |               \    |    /
442    * | Str | | Str | | Str |             \   |   /
443    *      \     |     /                     Phi
444    *       \    |    /                       |
445    *        \   |   /                       Str
446    *           Phi
447    *
448    * Is only allowed if the predecessor blocks have only one successor.
449    */
450
451   /* first step: collect all inputs */
452   NEW_ARR_A(ir_node *, inM, n);
453   NEW_ARR_A(ir_node *, inD, n);
454   NEW_ARR_A(int, idx, n);
455
456   for (i = 0; i < n; ++i) {
457     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
458     info = get_irn_link(pred);
459
460     inM[i] = get_Store_mem(pred);
461     inD[i] = get_Store_value(pred);
462     idx[i] = info->exc_idx;
463   }
464   block = get_nodes_block(phi);
465
466   /* second step: create a new memory Phi */
467   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
468
469   /* third step: create a new data Phi */
470   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
471
472   /* fourth step: create the Store */
473   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
474   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
475
476   info = get_ldst_info(store, wenv);
477   info->projs[pn_Store_M] = projM;
478
479   /* fifths step: repair exception flow */
480   if (exc) {
481     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
482
483     info->projs[pn_Store_X_except] = projX;
484     info->exc_block                = exc;
485     info->exc_idx                  = idx[0];
486
487     for (i = 0; i < n; ++i) {
488       set_Block_cfgpred(exc, idx[i], projX);
489     }
490
491     if (n > 1) {
492       /* the exception block should be optimized as some inputs are identical now */
493     }
494   }
495
496   /* sixt step: replace old Phi */
497   exchange(phi, projM);
498
499   return 1;
500 }
501
502 /**
503  * walker, collects all Load/Store/Proj nodes
504  */
505 static void do_load_store_optimize(ir_node *n, void *env)
506 {
507   walk_env_t *wenv = env;
508
509   switch (get_irn_opcode(n)) {
510
511   case iro_Load:
512     wenv->changes |= optimize_load(n);
513     break;
514
515   case iro_Store:
516     wenv->changes |= optimize_store(n);
517     break;
518
519   case iro_Phi:
520     wenv->changes |= optimize_phi(n, env);
521
522   default:
523     ;
524   }
525 }
526
527 /*
528  * do the load store optimization
529  */
530 void optimize_load_store(ir_graph *irg)
531 {
532   walk_env_t env;
533
534   assert(get_irg_phase_state(irg) != phase_building);
535
536   if (!get_opt_redundant_LoadStore())
537     return;
538
539   obstack_init(&env.obst);
540   env.changes = 0;
541
542   /* init the links, then collect Loads/Stores/Proj's in lists */
543   irg_walk_graph(irg, init_links, collect_nodes, &env);
544
545   /* now we have collected enough information, optimize */
546   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
547
548   obstack_free(&env.obst, NULL);
549
550   /* Handle graph state */
551   if (env.changes) {
552     if (get_irg_outs_state(current_ir_graph) == outs_consistent)
553       set_irg_outs_inconsistent(current_ir_graph);
554
555     /* is this really needed: Yes, as exception block may get bad but this might be tested */
556     if (get_irg_dom_state(current_ir_graph) == dom_consistent)
557       set_irg_dom_inconsistent(current_ir_graph);
558   }
559 }