strdup fix
[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   if ((get_irn_opcode(ptr) == iro_SymConst) && (get_SymConst_kind(ptr) == symconst_addr_ent)) {
216     entity *ent = get_SymConst_entity(ptr);
217
218     assert(mode_is_reference(get_irn_mode(ptr)));
219
220     if ((allocation_static == get_entity_allocation(ent)) &&
221         (visibility_external_allocated != get_entity_visibility(ent))) {
222       /* a static allocation that is not external: there should be NO exception
223        * when loading. */
224
225       /* no exception, clear the info field as it might be checked later again */
226       if (info->projs[pn_Load_X_except]) {
227         exchange(info->projs[pn_Load_X_except], new_Bad());
228         info->projs[pn_Load_X_except] = NULL;
229       }
230
231       if (variability_constant == get_entity_variability(ent)) {
232         /* more simpler case: we load the content of a constant value:
233          * replace it by the constant itself
234          */
235
236         /* no memory */
237         if (info->projs[pn_Load_M])
238           exchange(info->projs[pn_Load_M], mem);
239
240         /* no result :-) */
241         if (info->projs[pn_Load_res])
242           exchange(info->projs[pn_Load_res], copy_const_value(get_atomic_ent_value(ent)));
243
244         return 1;
245       }
246
247       /* we changed the irg, but try further */
248       res = 1;
249     }
250   }
251
252   /* follow the memory chain as long as there are only Loads */
253   for (pred = skip_Proj(mem); ; pred = skip_Proj(get_Load_mem(pred))) {
254
255     /*
256      * BEWARE: one might think that checking the modes is useless, because
257      * if the pointers are identical, they refer to the same object.
258      * This is only true in strong typed languages, not is C were the following
259      * is possible a = *(type1 *)p; b = *(type2 *)p ...
260      */
261
262     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
263         get_irn_mode(get_Store_value(pred)) == load_mode) {
264       ldst_info_t *pred_info = get_irn_link(pred);
265
266       /*
267        * a load immediately after a store -- a read after write.
268        * We may remove the Load, if both load & Store does not have an exception handler
269        * OR they are in the same block. In the latter case the Load cannot
270        * throw an exception when the previous Store was quiet.
271        *
272        * Why we need to check for Store Exc? If the Store cannot be executed (ROM)
273        * the exception handler might simply jump into the load block :-(
274        * We could make it a little bit better if we would know that the exception
275        * handler of teh Store jumps directly to the end...
276        */
277       if ((!pred_info->projs[pn_Store_X_except] && !info->projs[pn_Load_X_except]) ||
278           get_nodes_block(load) == get_nodes_block(pred)) {
279         DBG_OPT_RAW(pred, load);
280         exchange( info->projs[pn_Load_res], get_Store_value(pred) );
281
282         if (info->projs[pn_Load_M])
283           exchange(info->projs[pn_Load_M], mem);
284
285         /* no exception */
286         if (info->projs[pn_Load_X_except])
287           exchange( info->projs[pn_Load_X_except], new_Bad());
288         return 1;
289       }
290     }
291     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
292              get_Load_mode(pred) == load_mode) {
293       /*
294        * a load after a load -- a read after read.
295        * We may remove the second Load, if it does not have an exception handler
296        * OR they are in the same block. In the later case the Load cannot
297        * throw an exception when the previous Load was quiet.
298        *
299        * Here, there is no need to check if the previos load has an exception hander because
300        * they would have exact the same exception...
301        */
302       if (! info->projs[pn_Load_X_except] || get_nodes_block(load) == get_nodes_block(pred)) {
303         ldst_info_t *pred_info = get_irn_link(pred);
304
305         DBG_OPT_RAR(pred, load);
306
307         if (pred_info->projs[pn_Load_res]) {
308           /* we need a data proj from the previous load for this optimization */
309           exchange( info->projs[pn_Load_res], pred_info->projs[pn_Load_res] );
310           if (info->projs[pn_Load_M])
311             exchange(info->projs[pn_Load_M], mem);
312         }
313         else {
314           if (info->projs[pn_Load_res]) {
315             set_Proj_pred(info->projs[pn_Load_res], pred);
316             set_nodes_block(info->projs[pn_Load_res], get_nodes_block(pred));
317           }
318           if (info->projs[pn_Load_M]) {
319             /* Actually, this if should not be necessary.  Construct the Loads
320                properly!!! */
321             exchange(info->projs[pn_Load_M], mem);
322           }
323         }
324
325         /* no exception */
326         if (info->projs[pn_Load_X_except])
327           exchange(info->projs[pn_Load_X_except], new_Bad());
328
329         return 1;
330       }
331     }
332
333     /* follow only load chains */
334     if (get_irn_op(pred) != op_Load)
335       break;
336    }
337   return res;
338 }
339
340 /**
341  * optimize a Store
342  */
343 static int optimize_store(ir_node *store)
344 {
345   ldst_info_t *info = get_irn_link(store);
346   ir_node *pred, *mem, *ptr, *value, *block;
347   ir_mode *mode;
348   int res = 0;
349
350   if (get_Store_volatility(store) == volatility_is_volatile)
351     return 0;
352
353   /*
354    * BEWARE: one might think that checking the modes is useless, because
355    * if the pointers are identical, they refer to the same object.
356    * This is only true in strong typed languages, not is C were the following
357    * is possible *(type1 *)p = a; *(type2 *)p = b ...
358    */
359
360   block = get_nodes_block(store);
361   ptr   = get_Store_ptr(store);
362   mem   = get_Store_mem(store);
363   value = get_Store_value(store);
364
365   mode  = get_irn_mode(value);
366
367   /* follow the memory chain as long as there are only Loads */
368   for (pred = skip_Proj(mem); ; pred = skip_Proj(get_Load_mem(pred))) {
369     ldst_info_t *pred_info = get_irn_link(pred);
370
371     if (get_irn_op(pred) == op_Store && get_Store_ptr(pred) == ptr &&
372         get_nodes_block(pred) == block && get_irn_mode(get_Store_value(pred)) == mode) {
373       /*
374        * a store after a store in the same block -- a write after write.
375        * We may remove the first Store, if it does not have an exception handler.
376        *
377        * TODO: What, if both have the same exception handler ???
378        */
379       if (get_Store_volatility(pred) != volatility_is_volatile && !pred_info->projs[pn_Store_X_except]) {
380         DBG_OPT_WAW(pred, store);
381         exchange( pred_info->projs[pn_Store_M], get_Store_mem(pred) );
382         return 1;
383       }
384     }
385     else if (get_irn_op(pred) == op_Load && get_Load_ptr(pred) == ptr &&
386              value == pred_info->projs[pn_Load_res]) {
387       /*
388        * a store of a value after a load -- a write after read.
389        * We may remove the second Store, if it does not have an exception handler.
390        */
391       if (! info->projs[pn_Store_X_except]) {
392         DBG_OPT_WAR(pred, store);
393         exchange( info->projs[pn_Store_M], mem );
394         return 1;
395       }
396     }
397
398     /* follow only load chains */
399     if (get_irn_op(pred) != op_Load)
400       break;
401   }
402   return res;
403 }
404
405 /**
406  * walker, optimizes Phi after Stores:
407  * Does the following optimization:
408  *
409  *   val1   val2   val3          val1  val2  val3
410  *    |      |      |               \    |    /
411  *   Str    Str    Str               \   |   /
412  *      \    |    /                     Phi
413  *       \   |   /                       |
414  *        \  |  /                       Str
415  *          Phi
416  *
417  * This removes the number of stores and allows for predicated execution.
418  * Moves Stores back to the end of a function which may be bad
419  *
420  * Is only allowed if the predecessor blocks have only one successor.
421  */
422 static int optimize_phi(ir_node *phi, void *env)
423 {
424   walk_env_t *wenv = env;
425   int i, n;
426   ir_node *store, *ptr, *block, *phiM, *phiD, *exc, *projM;
427   ir_mode *mode;
428   ir_node **inM, **inD;
429   int *idx;
430   dbg_info *db = NULL;
431   ldst_info_t *info;
432   block_info_t *bl_info;
433
434   /* Must be a memory Phi */
435   if (get_irn_mode(phi) != mode_M)
436     return 0;
437
438   n = get_Phi_n_preds(phi);
439   if (n <= 0)
440     return 0;
441
442   store = skip_Proj(get_Phi_pred(phi, 0));
443   if (get_irn_op(store) != op_Store)
444     return 0;
445
446   /* abort on bad blocks */
447   if (is_Bad(get_nodes_block(store)))
448     return 0;
449
450   /* check if the block has only one output */
451   bl_info = get_irn_link(get_nodes_block(store));
452   if (bl_info->flags)
453     return 0;
454
455   /* this is the address of the store */
456   ptr  = get_Store_ptr(store);
457   mode = get_irn_mode(get_Store_value(store));
458   info = get_irn_link(store);
459   exc  = info->exc_block;
460
461   for (i = 1; i < n; ++i) {
462     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
463
464     if (get_irn_op(pred) != op_Store)
465       return 0;
466
467     if (mode != get_irn_mode(get_Store_value(pred)) || ptr != get_Store_ptr(pred))
468       return 0;
469
470     info = get_irn_link(pred);
471
472     /* check, if all stores have the same exception flow */
473     if (exc != info->exc_block)
474       return 0;
475
476     /* abort on bad blocks */
477     if (is_Bad(get_nodes_block(store)))
478       return 0;
479
480     /* check if the block has only one output */
481     bl_info = get_irn_link(get_nodes_block(store));
482     if (bl_info->flags)
483       return 0;
484   }
485
486   /*
487    * ok, when we are here, we found all predecessors of a Phi that
488    * are Stores to the same address. That means whatever we do before
489    * we enter the block of the Phi, we do a Store.
490    * So, we can move the store to the current block:
491    *
492    *   val1    val2    val3          val1  val2  val3
493    *    |       |       |               \    |    /
494    * | Str | | Str | | Str |             \   |   /
495    *      \     |     /                     Phi
496    *       \    |    /                       |
497    *        \   |   /                       Str
498    *           Phi
499    *
500    * Is only allowed if the predecessor blocks have only one successor.
501    */
502
503   /* first step: collect all inputs */
504   NEW_ARR_A(ir_node *, inM, n);
505   NEW_ARR_A(ir_node *, inD, n);
506   NEW_ARR_A(int, idx, n);
507
508   for (i = 0; i < n; ++i) {
509     ir_node *pred = skip_Proj(get_Phi_pred(phi, i));
510     info = get_irn_link(pred);
511
512     inM[i] = get_Store_mem(pred);
513     inD[i] = get_Store_value(pred);
514     idx[i] = info->exc_idx;
515   }
516   block = get_nodes_block(phi);
517
518   /* second step: create a new memory Phi */
519   phiM = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inM, mode_M);
520
521   /* third step: create a new data Phi */
522   phiD = new_rd_Phi(get_irn_dbg_info(phi), current_ir_graph, block, n, inD, mode);
523
524   /* fourth step: create the Store */
525   store = new_rd_Store(db, current_ir_graph, block, phiM, ptr, phiD);
526   projM = new_rd_Proj(NULL, current_ir_graph, block, store, mode_M, pn_Store_M);
527
528   info = get_ldst_info(store, wenv);
529   info->projs[pn_Store_M] = projM;
530
531   /* fifths step: repair exception flow */
532   if (exc) {
533     ir_node *projX = new_rd_Proj(NULL, current_ir_graph, block, store, mode_X, pn_Store_X_except);
534
535     info->projs[pn_Store_X_except] = projX;
536     info->exc_block                = exc;
537     info->exc_idx                  = idx[0];
538
539     for (i = 0; i < n; ++i) {
540       set_Block_cfgpred(exc, idx[i], projX);
541     }
542
543     if (n > 1) {
544       /* the exception block should be optimized as some inputs are identical now */
545     }
546   }
547
548   /* sixt step: replace old Phi */
549   exchange(phi, projM);
550
551   return 1;
552 }
553
554 /**
555  * walker, collects all Load/Store/Proj nodes
556  */
557 static void do_load_store_optimize(ir_node *n, void *env)
558 {
559   walk_env_t *wenv = env;
560
561   switch (get_irn_opcode(n)) {
562
563   case iro_Load:
564     wenv->changes |= optimize_load(n);
565     break;
566
567   case iro_Store:
568     wenv->changes |= optimize_store(n);
569     break;
570
571   case iro_Phi:
572     wenv->changes |= optimize_phi(n, env);
573
574   default:
575     ;
576   }
577 }
578
579 /*
580  * do the load store optimization
581  */
582 void optimize_load_store(ir_graph *irg)
583 {
584   walk_env_t env;
585
586   assert(get_irg_phase_state(irg) != phase_building);
587
588   if (!get_opt_redundant_LoadStore())
589     return;
590
591   obstack_init(&env.obst);
592   env.changes = 0;
593
594   /* init the links, then collect Loads/Stores/Proj's in lists */
595   irg_walk_graph(irg, init_links, collect_nodes, &env);
596
597   /* now we have collected enough information, optimize */
598   irg_walk_graph(irg, NULL, do_load_store_optimize, &env);
599
600   obstack_free(&env.obst, NULL);
601
602   /* Handle graph state */
603   if (env.changes) {
604     if (get_irg_outs_state(current_ir_graph) == outs_consistent)
605       set_irg_outs_inconsistent(current_ir_graph);
606
607     /* is this really needed: Yes, as exception block may get bad but this might be tested */
608     if (get_irg_dom_state(current_ir_graph) == dom_consistent)
609       set_irg_dom_inconsistent(current_ir_graph);
610   }
611 }