make opcode list global
[libfirm] / ir / lower / lower_switch.c
1 /*
2  * Copyright (C) 1995-2011 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   Lowering of Switches if necessary or advantageous.
23  * @author  Moritz Kroll
24  */
25 #include "config.h"
26
27 #include <limits.h>
28 #include <stdbool.h>
29
30 #include "array_t.h"
31 #include "ircons.h"
32 #include "irgopt.h"
33 #include "irgwalk.h"
34 #include "irnode_t.h"
35 #include "irouts.h"
36 #include "irpass_t.h"
37 #include "lowering.h"
38 #include "error.h"
39 #include "irnodeset.h"
40
41 #define foreach_out_irn(irn, i, outirn) for (i = get_irn_n_outs(irn) - 1;\
42         i >= 0 && (outirn = get_irn_out(irn, i)); --i)
43
44 typedef struct walk_env_t {
45         unsigned      spare_size; /**< the allowed spare size for table switches */
46         unsigned      small_switch;
47         bool          allow_out_of_bounds;
48         bool          changed;    /**< indicates whether a change was performed */
49         ir_nodeset_t  processed;
50 } walk_env_t;
51
52 typedef struct case_data_t {
53         const ir_switch_table_entry *entry;
54         ir_node                     *target;
55 } case_data_t;
56
57 typedef struct switch_info_t {
58         ir_node     *switchn;
59         long         switch_min;
60         long         switch_max;
61         ir_node     *default_block;
62         unsigned     num_cases;
63         case_data_t *cases;
64         ir_node    **defusers;    /**< the Projs pointing to the default case */
65 } switch_info_t;
66
67 /**
68  * analyze enough to decide if we should lower the switch
69  */
70 static bool analyse_switch0(switch_info_t *info, ir_node *switchn)
71 {
72         const ir_switch_table *table         = get_Switch_table(switchn);
73         size_t                 n_entries     = ir_switch_table_get_n_entries(table);
74         long                   switch_min    = LONG_MAX;
75         long                   switch_max    = LONG_MIN;
76         unsigned               num_cases     = 0;
77         size_t                 e;
78
79         for (e = 0; e < n_entries; ++e) {
80                 const ir_switch_table_entry *entry
81                         = ir_switch_table_get_entry_const(table, e);
82                 long minval;
83                 long maxval;
84                 if (entry->pn == 0)
85                         continue;
86
87                 if (!tarval_is_long(entry->min) || !tarval_is_long(entry->max))
88                         return false;
89                 minval = get_tarval_long(entry->min);
90                 maxval = get_tarval_long(entry->max);
91                 if (minval < switch_min)
92                         switch_min = minval;
93                 if (maxval > switch_max)
94                         switch_max = maxval;
95                 ++num_cases;
96         }
97
98         info->switchn    = switchn;
99         info->switch_min = switch_min;
100         info->switch_max = switch_max;
101         info->num_cases  = num_cases;
102         return true;
103 }
104
105 static int casecmp(const void *a, const void *b)
106 {
107         const case_data_t           *cda = (const case_data_t*)a;
108         const case_data_t           *cdb = (const case_data_t*)b;
109         const ir_switch_table_entry *ea  = cda->entry;
110         const ir_switch_table_entry *eb  = cdb->entry;
111
112         if (ea == eb)
113                 return 0;
114
115         if (tarval_cmp(ea->max, eb->min) == ir_relation_less)
116                 return -1;
117         /* cases must be non overlapping, so the only remaining case is greater */
118         assert(tarval_cmp(ea->min, eb->max) == ir_relation_greater);
119         return 1;
120 }
121
122 /**
123  * Analyse the stuff that anayse_switch0() left out
124  */
125 static void analyse_switch1(switch_info_t *info)
126 {
127         const ir_node         *switchn   = info->switchn;
128         const ir_switch_table *table     = get_Switch_table(switchn);
129         size_t                 n_entries = ir_switch_table_get_n_entries(table);
130         unsigned               n_outs    = get_Switch_n_outs(switchn);
131         ir_node              **targets   = XMALLOCNZ(ir_node*, n_outs);
132         unsigned               num_cases = info->num_cases;
133         case_data_t           *cases     = XMALLOCN(case_data_t, num_cases);
134         unsigned               c         = 0;
135         size_t                 e;
136         int                    i;
137         ir_node               *proj;
138
139         foreach_out_irn(switchn, i, proj) {
140                 long     pn     = get_Proj_proj(proj);
141                 ir_node *target = get_irn_out(proj, 0);
142
143                 assert((unsigned)pn < n_outs);
144                 assert(targets[(unsigned)pn] == NULL);
145                 targets[(unsigned)pn] = target;
146         }
147
148         for (e = 0; e < n_entries; ++e) {
149                 const ir_switch_table_entry *entry
150                         = ir_switch_table_get_entry_const(table, e);
151                 if (entry->pn == 0)
152                         continue;
153
154                 cases[c].entry  = entry;
155                 cases[c].target = targets[entry->pn];
156                 ++c;
157         }
158         assert(c == num_cases);
159
160         /*
161          * Switch should be transformed into an if cascade.
162          * So first order the cases, so we can do a binary search on them.
163          */
164         qsort(cases, num_cases, sizeof(cases[0]), casecmp);
165
166         info->default_block = targets[pn_Switch_default];
167         info->cases         = cases;
168         free(targets);
169 }
170
171 static void normalize_table(ir_node *switchn, ir_mode *new_mode,
172                             ir_tarval *delta)
173 {
174         ir_switch_table *table     = get_Switch_table(switchn);
175         size_t           n_entries = ir_switch_table_get_n_entries(table);
176         size_t           e;
177         /* adapt switch_table */
178         for (e = 0; e < n_entries; ++e) {
179                 ir_switch_table_entry *entry = ir_switch_table_get_entry(table, e);
180                 ir_tarval *min = entry->min;
181
182                 if (entry->pn == 0)
183                         continue;
184
185                 min = tarval_convert_to(min, new_mode);
186                 if (delta != NULL)
187                         min = tarval_sub(min, delta, NULL);
188
189                 if (entry->min == entry->max) {
190                         entry->min = min;
191                         entry->max = min;
192                 } else {
193                         ir_tarval *max = entry->max;
194                         max = tarval_convert_to(max, new_mode);
195                         if (delta != NULL)
196                                 max = tarval_sub(max, delta, NULL);
197                         entry->min = min;
198                         entry->max = max;
199                 }
200         }
201 }
202
203 /**
204  * normalize switch to work on an unsigned input with the first case at 0
205  */
206 static void normalize_switch(switch_info_t *info)
207 {
208         ir_node   *switchn     = info->switchn;
209         ir_graph  *irg         = get_irn_irg(switchn);
210         ir_node   *block       = get_nodes_block(switchn);
211         ir_node   *selector    = get_Switch_selector(switchn);
212         ir_mode   *mode        = get_irn_mode(selector);
213         ir_tarval *delta       = NULL;
214         bool       change_mode = false;
215
216         if (mode_is_signed(mode)) {
217                 mode        = find_unsigned_mode(mode);
218                 selector    = new_r_Conv(block, selector, mode);
219                 change_mode = true;
220         }
221
222         /* normalize so switch_min is at 0 */
223         if (info->switch_min != 0) {
224                 dbg_info *dbgi = get_irn_dbg_info(switchn);
225                 ir_node  *min_const;
226
227                 delta = new_tarval_from_long(info->switch_min, mode);
228
229                 min_const = new_r_Const(irg, delta);
230                 selector  = new_rd_Sub(dbgi, block, selector, min_const, mode);
231
232                 info->switch_max -= info->switch_min;
233                 info->switch_min  = 0;
234         }
235
236         if (delta != NULL || change_mode) {
237                 set_Switch_selector(switchn, selector);
238                 normalize_table(switchn, mode, delta);
239         }
240 }
241
242 /**
243  * Create an if (selector == caseval) Cond node (and handle the special case
244  * of ranged cases)
245  */
246 static ir_node *create_case_cond(const ir_switch_table_entry *entry,
247                                  dbg_info *dbgi, ir_node *block,
248                                  ir_node *selector)
249 {
250         ir_graph *irg      = get_irn_irg(block);
251         ir_node  *minconst = new_r_Const(irg, entry->min);
252         ir_node  *cmp;
253
254         if (entry->min == entry->max) {
255                 cmp = new_rd_Cmp(dbgi, block, selector, minconst, ir_relation_equal);
256         } else {
257                 ir_tarval *adjusted_max = tarval_sub(entry->max, entry->min, NULL);
258                 ir_node   *sub          = new_rd_Sub(dbgi, block, selector, minconst,
259                                                      get_tarval_mode(adjusted_max));
260                 ir_node   *maxconst     = new_r_Const(irg, adjusted_max);
261                 cmp = new_rd_Cmp(dbgi, block, sub, maxconst, ir_relation_less_equal);
262         }
263
264         return new_rd_Cond(dbgi, block, cmp);
265 }
266
267 /**
268  * Creates an if cascade realizing binary search.
269  */
270 static void create_if_cascade(switch_info_t *info, ir_node *block,
271                               case_data_t *curcases, unsigned numcases)
272 {
273         ir_graph      *irg      = get_irn_irg(block);
274         const ir_node *switchn  = info->switchn;
275         dbg_info      *dbgi     = get_irn_dbg_info(switchn);
276         ir_node       *selector = get_Switch_selector(switchn);
277
278         if (numcases == 0) {
279                 /* zero cases: "goto default;" */
280                 ARR_APP1(ir_node*, info->defusers, new_r_Jmp(block));
281         } else if (numcases == 1) {
282                 /*only one case: "if (sel == val) goto target else goto default;"*/
283                 const ir_switch_table_entry *entry = curcases[0].entry;
284                 ir_node *cond      = create_case_cond(entry, dbgi, block, selector);
285                 ir_node *trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
286                 ir_node *falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
287
288                 set_Block_cfgpred(curcases[0].target, 0, trueproj);
289                 ARR_APP1(ir_node*, info->defusers, falseproj);
290         } else if (numcases == 2) {
291                 /* only two cases: "if (sel == val[0]) goto target[0];" */
292                 const ir_switch_table_entry *entry0 = curcases[0].entry;
293                 const ir_switch_table_entry *entry1 = curcases[1].entry;
294                 ir_node *cond      = create_case_cond(entry0, dbgi, block, selector);
295                 ir_node *trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
296                 ir_node *falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
297                 ir_node *in[1];
298                 ir_node *neblock;
299
300                 set_Block_cfgpred(curcases[0].target, 0, trueproj);
301
302                 in[0] = falseproj;
303                 neblock = new_r_Block(irg, 1, in);
304
305                 /* second part: "else if (sel == val[1]) goto target[1] else goto default;" */
306                 cond      = create_case_cond(entry1, dbgi, neblock, selector);
307                 trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
308                 falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
309                 set_Block_cfgpred(curcases[1].target, 0, trueproj);
310                 ARR_APP1(ir_node*, info->defusers, falseproj);
311         } else {
312                 /* recursive case: split cases in the middle */
313                 unsigned midcase = numcases / 2;
314                 const ir_switch_table_entry *entry = curcases[midcase].entry;
315                 ir_node *val = new_r_Const(irg, entry->min);
316                 ir_node *cmp = new_rd_Cmp(dbgi, block, selector, val, ir_relation_less);
317                 ir_node *cond = new_rd_Cond(dbgi, block, cmp);
318                 ir_node *in[1];
319                 ir_node *ltblock;
320                 ir_node *geblock;
321
322                 in[0]   = new_r_Proj(cond, mode_X, pn_Cond_true);
323                 ltblock = new_r_Block(irg, 1, in);
324
325                 in[0]   = new_r_Proj(cond, mode_X, pn_Cond_false);
326                 geblock = new_r_Block(irg, 1, in);
327
328                 create_if_cascade(info, ltblock, curcases, midcase);
329                 create_if_cascade(info, geblock, curcases + midcase, numcases - midcase);
330         }
331 }
332
333 static void create_out_of_bounds_check(switch_info_t *info)
334 {
335         ir_node    *switchn       = info->switchn;
336         ir_graph   *irg           = get_irn_irg(switchn);
337         dbg_info   *dbgi          = get_irn_dbg_info(switchn);
338         ir_node    *selector      = get_Switch_selector(switchn);
339         ir_node    *block         = get_nodes_block(switchn);
340         ir_mode    *cmp_mode      = get_irn_mode(selector);
341         ir_node   **default_preds = NEW_ARR_F(ir_node*, 0);
342         ir_node    *default_block = NULL;
343         ir_node    *max_const;
344         ir_node    *proj_true;
345         ir_node    *proj_false;
346         ir_node    *cmp;
347         ir_node    *oob_cond;
348         ir_node    *in[1];
349         ir_node    *new_block;
350         int         i;
351         ir_node    *proj;
352         size_t      n_default_preds;
353
354         assert(info->switch_min == 0);
355
356         /* check for out-of-bounds */
357         max_const  = new_r_Const_long(irg, cmp_mode, info->switch_max);
358         cmp        = new_rd_Cmp(dbgi, block, selector, max_const, ir_relation_less_equal);
359         oob_cond   = new_rd_Cond(dbgi, block, cmp);
360         proj_true  = new_r_Proj(oob_cond, mode_X, pn_Cond_true);
361         proj_false = new_r_Proj(oob_cond, mode_X, pn_Cond_false);
362
363         ARR_APP1(ir_node*, default_preds, proj_false);
364
365         /* create new block containing the switch */
366         in[0] = proj_true;
367         new_block = new_r_Block(irg, 1, in);
368         set_nodes_block(switchn, new_block);
369
370         /* adjust projs */
371         foreach_out_irn(switchn, i, proj) {
372                 long pn = get_Proj_proj(proj);
373                 if (pn == pn_Switch_default) {
374                         assert(default_block == NULL);
375                         default_block = get_irn_out(proj, 0);
376                         ARR_APP1(ir_node*, default_preds, proj);
377                 }
378                 set_nodes_block(proj, new_block);
379         }
380
381         /* adapt default block */
382         n_default_preds = ARR_LEN(default_preds);
383         if (n_default_preds > 1) {
384                 /* create new intermediate blocks so we don't have critical edges */
385                 size_t p;
386                 for (p = 0; p < n_default_preds; ++p) {
387                         ir_node *pred = default_preds[p];
388                         ir_node *split_block;
389                         ir_node *block_in[1];
390
391                         block_in[0] = pred;
392                         split_block = new_r_Block(irg, 1, block_in);
393
394                         default_preds[p] = new_r_Jmp(split_block);
395                 }
396         }
397         set_irn_in(default_block, n_default_preds, default_preds);
398
399         DEL_ARR_F(default_preds);
400
401         clear_irg_state(irg, IR_GRAPH_STATE_CONSISTENT_DOMINANCE
402                            | IR_GRAPH_STATE_VALID_EXTENDED_BLOCKS);
403 }
404
405 /**
406  * Block-Walker: searches for Switch nodes
407  */
408 static void find_switch_nodes(ir_node *block, void *ctx)
409 {
410         walk_env_t   *env = (walk_env_t *)ctx;
411         ir_node      *projx;
412         ir_node      *switchn;
413         switch_info_t info;
414         unsigned long spare;
415         bool          lower_switch = false;
416         bool          could_analyze;
417
418         /* because we split critical blocks only blocks with 1 predecessors may
419          * contain Proj->Cond nodes */
420         if (get_Block_n_cfgpreds(block) != 1)
421                 return;
422
423         projx = get_Block_cfgpred(block, 0);
424         if (!is_Proj(projx))
425                 return;
426         assert(get_irn_mode(projx) == mode_X);
427
428         switchn = get_Proj_pred(projx);
429         if (!is_Switch(switchn))
430                 return;
431
432         if (ir_nodeset_contains(&env->processed, switchn))
433                 return;
434         ir_nodeset_insert(&env->processed, switchn);
435
436         could_analyze = analyse_switch0(&info, switchn);
437         /* the code can't handle values which are not representable in the host */
438         if (!could_analyze) {
439                 ir_fprintf(stderr, "libfirm warning: Couldn't analyse %+F (this could go wrong in the backend)\n", switchn);
440                 return;
441         }
442
443         /*
444          * Here we have: num_cases and [switch_min, switch_max] interval.
445          * We do an if-cascade if there are too many spare numbers.
446          */
447         spare = (unsigned long) info.switch_max
448                 - (unsigned long) info.switch_min
449                 - (unsigned long) info.num_cases + 1;
450         lower_switch |= spare >= env->spare_size;
451         lower_switch |= info.num_cases <= env->small_switch;
452
453         if (!lower_switch) {
454                 /* we won't decompose the switch. But we might have to add
455                  * out-of-bounds checking */
456                 if (!env->allow_out_of_bounds) {
457                         normalize_switch(&info);
458                         create_out_of_bounds_check(&info);
459                 }
460                 return;
461         }
462
463         normalize_switch(&info);
464         analyse_switch1(&info);
465
466         /* Now create the if cascade */
467         env->changed   = true;
468         info.defusers = NEW_ARR_F(ir_node*, 0);
469         block          = get_nodes_block(switchn);
470         create_if_cascade(&info, block, info.cases, info.num_cases);
471
472         /* Connect new default case users */
473         set_irn_in(info.default_block, ARR_LEN(info.defusers), info.defusers);
474
475         DEL_ARR_F(info.defusers);
476         xfree(info.cases);
477         clear_irg_state(get_irn_irg(block), IR_GRAPH_STATE_NO_CRITICAL_EDGES
478                                           | IR_GRAPH_STATE_CONSISTENT_DOMINANCE
479                                           | IR_GRAPH_STATE_VALID_EXTENDED_BLOCKS);
480 }
481
482 void lower_switch(ir_graph *irg, unsigned small_switch, unsigned spare_size,
483                   int allow_out_of_bounds)
484 {
485         walk_env_t env;
486         env.changed             = false;
487         env.spare_size          = spare_size;
488         env.small_switch        = small_switch;
489         env.allow_out_of_bounds = allow_out_of_bounds;
490         ir_nodeset_init(&env.processed);
491
492         remove_critical_cf_edges(irg);
493         assure_irg_outs(irg);
494
495         irg_block_walk_graph(irg, find_switch_nodes, NULL, &env);
496         ir_nodeset_destroy(&env.processed);
497 }