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