lower_switch.c 14.9 KB
Newer Older
1
/*
2
 * Copyright (C) 1995-2011 University of Karlsruhe.  All right reserved.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 *
 * This file is part of libFirm.
 *
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file LICENSE.GPL included in the
 * packaging of this file.
 *
 * Licensees holding valid libFirm Professional Edition licenses may use
 * this file in accordance with the libFirm Commercial License.
 * Agreement provided with the Software.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

/**
 * @file
 * @brief   Lowering of Switches if necessary or advantageous.
 * @author  Moritz Kroll
 */
#include "config.h"

27
#include <limits.h>
28
#include <stdbool.h>
29

30
#include "array_t.h"
31
#include "ircons.h"
Moritz Kroll's avatar
Moritz Kroll committed
32
#include "irgopt.h"
33
34
35
#include "irgwalk.h"
#include "irnode_t.h"
#include "irouts.h"
Michael Beck's avatar
Michael Beck committed
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
43
	i >= 0 && (outirn = get_irn_out(irn, i)); --i)

44
45
typedef struct walk_env_t {
	unsigned      spare_size; /**< the allowed spare size for table switches */
Matthias Braun's avatar
Matthias Braun committed
46
	unsigned      small_switch;
47
48
49
	bool          allow_out_of_bounds;
	bool          changed;    /**< indicates whether a change was performed */
	ir_nodeset_t  processed;
50
51
} walk_env_t;

52
typedef struct case_data_t {
Matthias Braun's avatar
Matthias Braun committed
53
54
	const ir_switch_table_entry *entry;
	ir_node                     *target;
55
56
} case_data_t;

Matthias Braun's avatar
Matthias Braun committed
57
58
59
60
61
62
63
64
65
typedef struct switch_info_t {
	ir_node     *switchn;
	long         switch_min;
	long         switch_max;
	ir_node     *default_block;
	unsigned     num_cases;
	case_data_t *cases;
	ir_node    **defusers;    /**< the Projs pointing to the default case */
} switch_info_t;
66

Matthias Braun's avatar
Matthias Braun committed
67
68
69
70
/**
 * analyze enough to decide if we should lower the switch
 */
static bool analyse_switch0(switch_info_t *info, ir_node *switchn)
71
{
Matthias Braun's avatar
Matthias Braun committed
72
73
74
75
76
77
78
79
80
81
82
83
84
	const ir_switch_table *table         = get_Switch_table(switchn);
	size_t                 n_entries     = ir_switch_table_get_n_entries(table);
	long                   switch_min    = LONG_MAX;
	long                   switch_max    = LONG_MIN;
	unsigned               num_cases     = 0;
	size_t                 e;

	for (e = 0; e < n_entries; ++e) {
		const ir_switch_table_entry *entry
			= ir_switch_table_get_entry_const(table, e);
		long minval;
		long maxval;
		if (entry->pn == 0)
85
86
			continue;

Matthias Braun's avatar
Matthias Braun committed
87
88
89
90
91
92
93
94
		if (!tarval_is_long(entry->min) || !tarval_is_long(entry->max))
			return false;
		minval = get_tarval_long(entry->min);
		maxval = get_tarval_long(entry->max);
		if (minval < switch_min)
			switch_min = minval;
		if (maxval > switch_max)
			switch_max = maxval;
95
		++num_cases;
96
97
	}

Matthias Braun's avatar
Matthias Braun committed
98
99
100
101
102
	info->switchn    = switchn;
	info->switch_min = switch_min;
	info->switch_max = switch_max;
	info->num_cases  = num_cases;
	return true;
103
104
105
106
}

static int casecmp(const void *a, const void *b)
{
Matthias Braun's avatar
Matthias Braun committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
	const case_data_t           *cda = (const case_data_t*)a;
	const case_data_t           *cdb = (const case_data_t*)b;
	const ir_switch_table_entry *ea  = cda->entry;
	const ir_switch_table_entry *eb  = cdb->entry;

	if (ea == eb)
		return 0;

	if (tarval_cmp(ea->max, eb->min) == ir_relation_less)
		return -1;
	/* cases must be non overlapping, so the only remaining case is greater */
	assert(tarval_cmp(ea->min, eb->max) == ir_relation_greater);
	return 1;
}

/**
 * Analyse the stuff that anayse_switch0() left out
 */
static void analyse_switch1(switch_info_t *info)
{
	const ir_node         *switchn   = info->switchn;
	const ir_switch_table *table     = get_Switch_table(switchn);
	size_t                 n_entries = ir_switch_table_get_n_entries(table);
	unsigned               n_outs    = get_Switch_n_outs(switchn);
	ir_node              **targets   = XMALLOCNZ(ir_node*, n_outs);
	unsigned               num_cases = info->num_cases;
	case_data_t           *cases     = XMALLOCN(case_data_t, num_cases);
	unsigned               c         = 0;
	size_t                 e;
	int                    i;
	ir_node               *proj;

	foreach_out_irn(switchn, i, proj) {
		long     pn     = get_Proj_proj(proj);
		ir_node *target = get_irn_out(proj, 0);

		assert((unsigned)pn < n_outs);
		assert(targets[(unsigned)pn] == NULL);
		targets[(unsigned)pn] = target;
	}

	for (e = 0; e < n_entries; ++e) {
		const ir_switch_table_entry *entry
			= ir_switch_table_get_entry_const(table, e);
		if (entry->pn == 0)
			continue;

		cases[c].entry  = entry;
		cases[c].target = targets[entry->pn];
		++c;
	}
	assert(c == num_cases);
159
160

	/*
Matthias Braun's avatar
Matthias Braun committed
161
162
	 * Switch should be transformed into an if cascade.
	 * So first order the cases, so we can do a binary search on them.
163
	 */
Matthias Braun's avatar
Matthias Braun committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
	qsort(cases, num_cases, sizeof(cases[0]), casecmp);

	info->default_block = targets[pn_Switch_default];
	info->cases         = cases;
}

static void normalize_table(ir_node *switchn, ir_mode *new_mode,
                            ir_tarval *delta)
{
	ir_switch_table *table     = get_Switch_table(switchn);
	size_t           n_entries = ir_switch_table_get_n_entries(table);
	size_t           e;
	/* adapt switch_table */
	for (e = 0; e < n_entries; ++e) {
		ir_switch_table_entry *entry = ir_switch_table_get_entry(table, e);
		ir_tarval *min = entry->min;

		if (entry->pn == 0)
			continue;

		min = tarval_convert_to(min, new_mode);
		if (delta != NULL)
			min = tarval_sub(min, delta, NULL);

		if (entry->min == entry->max) {
			entry->min = min;
			entry->max = min;
		} else {
			ir_tarval *max = entry->max;
			max = tarval_convert_to(max, new_mode);
			if (delta != NULL)
				max = tarval_sub(max, delta, NULL);
			entry->min = min;
			entry->max = max;
		}
	}
}

/**
 * normalize switch to work on an unsigned input with the first case at 0
 */
static void normalize_switch(switch_info_t *info)
{
	ir_node   *switchn     = info->switchn;
	ir_graph  *irg         = get_irn_irg(switchn);
	ir_node   *block       = get_nodes_block(switchn);
	ir_node   *selector    = get_Switch_selector(switchn);
	ir_mode   *mode        = get_irn_mode(selector);
	ir_tarval *delta       = NULL;
	bool       change_mode = false;

	if (mode_is_signed(mode)) {
		mode        = find_unsigned_mode(mode);
		selector    = new_r_Conv(block, selector, mode);
		change_mode = true;
	}

	/* normalize so switch_min is at 0 */
	if (info->switch_min != 0) {
		dbg_info *dbgi = get_irn_dbg_info(switchn);
		ir_node  *min_const;

		delta = new_tarval_from_long(info->switch_min, mode);

		min_const = new_r_Const(irg, delta);
		selector  = new_rd_Sub(dbgi, block, selector, min_const, mode);

		info->switch_max -= info->switch_min;
232
		info->switch_min  = 0;
Matthias Braun's avatar
Matthias Braun committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
	}

	if (delta != NULL || change_mode) {
		set_Switch_selector(switchn, selector);
		normalize_table(switchn, mode, delta);
	}
}

/**
 * Create an if (selector == caseval) Cond node (and handle the special case
 * of ranged cases)
 */
static ir_node *create_case_cond(const ir_switch_table_entry *entry,
                                 dbg_info *dbgi, ir_node *block,
                                 ir_node *selector)
{
	ir_graph *irg      = get_irn_irg(block);
	ir_node  *minconst = new_r_Const(irg, entry->min);
	ir_node  *cmp;

	if (entry->min == entry->max) {
		cmp = new_rd_Cmp(dbgi, block, selector, minconst, ir_relation_equal);
	} else {
		ir_tarval *adjusted_max = tarval_sub(entry->max, entry->min, NULL);
		ir_node   *sub          = new_rd_Sub(dbgi, block, selector, minconst,
		                                     get_tarval_mode(adjusted_max));
		ir_node   *maxconst     = new_r_Const(irg, adjusted_max);
		cmp = new_rd_Cmp(dbgi, block, sub, maxconst, ir_relation_less_equal);
	}

	return new_rd_Cond(dbgi, block, cmp);
264
265
266
267
268
}

/**
 * Creates an if cascade realizing binary search.
 */
Matthias Braun's avatar
Matthias Braun committed
269
static void create_if_cascade(switch_info_t *info, ir_node *block,
270
                              case_data_t *curcases, unsigned numcases)
271
{
Matthias Braun's avatar
Matthias Braun committed
272
273
274
275
	ir_graph      *irg      = get_irn_irg(block);
	const ir_node *switchn  = info->switchn;
	dbg_info      *dbgi     = get_irn_dbg_info(switchn);
	ir_node       *selector = get_Switch_selector(switchn);
276

277
278
	if (numcases == 0) {
		/* zero cases: "goto default;" */
Matthias Braun's avatar
Matthias Braun committed
279
		ARR_APP1(ir_node*, info->defusers, new_r_Jmp(block));
280
	} else if (numcases == 1) {
Matthias Braun's avatar
Matthias Braun committed
281
282
283
		/*only one case: "if (sel == val) goto target else goto default;"*/
		const ir_switch_table_entry *entry = curcases[0].entry;
		ir_node *cond      = create_case_cond(entry, dbgi, block, selector);
284
285
286
287
		ir_node *trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
		ir_node *falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);

		set_Block_cfgpred(curcases[0].target, 0, trueproj);
Matthias Braun's avatar
Matthias Braun committed
288
		ARR_APP1(ir_node*, info->defusers, falseproj);
289
	} else if (numcases == 2) {
290
		/* only two cases: "if (sel == val[0]) goto target[0];" */
Matthias Braun's avatar
Matthias Braun committed
291
292
293
		const ir_switch_table_entry *entry0 = curcases[0].entry;
		const ir_switch_table_entry *entry1 = curcases[1].entry;
		ir_node *cond      = create_case_cond(entry0, dbgi, block, selector);
294
295
		ir_node *trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
		ir_node *falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
296
297
298
		ir_node *in[1];
		ir_node *neblock;

299
300
301
302
		set_Block_cfgpred(curcases[0].target, 0, trueproj);

		in[0] = falseproj;
		neblock = new_r_Block(irg, 1, in);
303

304
		/* second part: "else if (sel == val[1]) goto target[1] else goto default;" */
Matthias Braun's avatar
Matthias Braun committed
305
		cond      = create_case_cond(entry1, dbgi, neblock, selector);
306
307
308
		trueproj  = new_r_Proj(cond, mode_X, pn_Cond_true);
		falseproj = new_r_Proj(cond, mode_X, pn_Cond_false);
		set_Block_cfgpred(curcases[1].target, 0, trueproj);
Matthias Braun's avatar
Matthias Braun committed
309
		ARR_APP1(ir_node*, info->defusers, falseproj);
310
311
	} else {
		/* recursive case: split cases in the middle */
Matthias Braun's avatar
Matthias Braun committed
312
313
314
315
		unsigned midcase = numcases / 2;
		const ir_switch_table_entry *entry = curcases[midcase].entry;
		ir_node *val = new_r_Const(irg, entry->min);
		ir_node *cmp = new_rd_Cmp(dbgi, block, selector, val, ir_relation_less);
316
		ir_node *cond = new_rd_Cond(dbgi, block, cmp);
317
318
319
320
		ir_node *in[1];
		ir_node *ltblock;
		ir_node *geblock;

321
322
		in[0]   = new_r_Proj(cond, mode_X, pn_Cond_true);
		ltblock = new_r_Block(irg, 1, in);
323

324
325
		in[0]   = new_r_Proj(cond, mode_X, pn_Cond_false);
		geblock = new_r_Block(irg, 1, in);
326

Matthias Braun's avatar
Matthias Braun committed
327
328
		create_if_cascade(info, ltblock, curcases, midcase);
		create_if_cascade(info, geblock, curcases + midcase, numcases - midcase);
329
330
331
	}
}

Matthias Braun's avatar
Matthias Braun committed
332
static void create_out_of_bounds_check(switch_info_t *info)
333
{
Matthias Braun's avatar
Matthias Braun committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
	ir_node    *switchn       = info->switchn;
	ir_graph   *irg           = get_irn_irg(switchn);
	dbg_info   *dbgi          = get_irn_dbg_info(switchn);
	ir_node    *selector      = get_Switch_selector(switchn);
	ir_node    *block         = get_nodes_block(switchn);
	ir_mode    *cmp_mode      = get_irn_mode(selector);
	ir_node   **default_preds = NEW_ARR_F(ir_node*, 0);
	ir_node    *default_block = NULL;
	ir_node    *max_const;
	ir_node    *proj_true;
	ir_node    *proj_false;
	ir_node    *cmp;
	ir_node    *oob_cond;
	ir_node    *in[1];
	ir_node    *new_block;
	int         i;
	ir_node    *proj;
	size_t      n_default_preds;

	assert(info->switch_min == 0);
354
355

	/* check for out-of-bounds */
Matthias Braun's avatar
Matthias Braun committed
356
357
	max_const  = new_r_Const_long(irg, cmp_mode, info->switch_max);
	cmp        = new_rd_Cmp(dbgi, block, selector, max_const, ir_relation_less_equal);
358
	oob_cond   = new_rd_Cond(dbgi, block, cmp);
359
360
361
362
363
	proj_true  = new_r_Proj(oob_cond, mode_X, pn_Cond_true);
	proj_false = new_r_Proj(oob_cond, mode_X, pn_Cond_false);

	ARR_APP1(ir_node*, default_preds, proj_false);

Matthias Braun's avatar
Matthias Braun committed
364
	/* create new block containing the switch */
365
366
	in[0] = proj_true;
	new_block = new_r_Block(irg, 1, in);
Matthias Braun's avatar
Matthias Braun committed
367
368
369
370
371
372
373
374
	set_nodes_block(switchn, new_block);

	/* adjust projs */
	foreach_out_irn(switchn, i, proj) {
		long pn = get_Proj_proj(proj);
		if (pn == pn_Switch_default) {
			assert(default_block == NULL);
			default_block = get_irn_out(proj, 0);
375
376
377
378
379
380
381
382
383
			ARR_APP1(ir_node*, default_preds, proj);
		}
		set_nodes_block(proj, new_block);
	}

	/* adapt default block */
	n_default_preds = ARR_LEN(default_preds);
	if (n_default_preds > 1) {
		/* create new intermediate blocks so we don't have critical edges */
Matthias Braun's avatar
Matthias Braun committed
384
		size_t p;
385
386
387
388
		for (p = 0; p < n_default_preds; ++p) {
			ir_node *pred = default_preds[p];
			ir_node *split_block;
			ir_node *block_in[1];
389

390
391
			block_in[0] = pred;
			split_block = new_r_Block(irg, 1, block_in);
392

393
			default_preds[p] = new_r_Jmp(split_block);
394
395
		}
	}
Matthias Braun's avatar
Matthias Braun committed
396
	set_irn_in(default_block, n_default_preds, default_preds);
397
398

	DEL_ARR_F(default_preds);
Matthias Braun's avatar
Matthias Braun committed
399
400
401

	clear_irg_state(irg, IR_GRAPH_STATE_CONSISTENT_DOMINANCE
	                   | IR_GRAPH_STATE_VALID_EXTENDED_BLOCKS);
402
403
}

404
/**
Matthias Braun's avatar
Matthias Braun committed
405
 * Block-Walker: searches for Switch nodes
406
 */
Matthias Braun's avatar
Matthias Braun committed
407
static void find_switch_nodes(ir_node *block, void *ctx)
408
{
Matthias Braun's avatar
Matthias Braun committed
409
410
411
412
	walk_env_t   *env = (walk_env_t *)ctx;
	ir_node      *projx;
	ir_node      *switchn;
	switch_info_t info;
413
	unsigned long spare;
Matthias Braun's avatar
Matthias Braun committed
414
415
	bool          lower_switch = false;
	bool          could_analyze;
416

417
418
	/* because we split critical blocks only blocks with 1 predecessors may
	 * contain Proj->Cond nodes */
419
	if (get_Block_n_cfgpreds(block) != 1)
420
421
422
		return;

	projx = get_Block_cfgpred(block, 0);
423
	if (!is_Proj(projx))
424
425
426
		return;
	assert(get_irn_mode(projx) == mode_X);

Matthias Braun's avatar
Matthias Braun committed
427
428
	switchn = get_Proj_pred(projx);
	if (!is_Switch(switchn))
429
430
		return;

Matthias Braun's avatar
Matthias Braun committed
431
	if (ir_nodeset_contains(&env->processed, switchn))
432
		return;
Matthias Braun's avatar
Matthias Braun committed
433
	ir_nodeset_insert(&env->processed, switchn);
434

Matthias Braun's avatar
Matthias Braun committed
435
436
437
438
	could_analyze = analyse_switch0(&info, switchn);
	/* the code can't handle values which are not representable in the host */
	if (!could_analyze) {
		ir_fprintf(stderr, "libfirm warning: Couldn't analyse %+F (this could go wrong in the backend)\n", switchn);
439
		return;
Matthias Braun's avatar
Matthias Braun committed
440
	}
441

442
443
444
445
	/*
	 * Here we have: num_cases and [switch_min, switch_max] interval.
	 * We do an if-cascade if there are too many spare numbers.
	 */
Matthias Braun's avatar
Matthias Braun committed
446
447
448
	spare = (unsigned long) info.switch_max
		- (unsigned long) info.switch_min
		- (unsigned long) info.num_cases + 1;
Matthias Braun's avatar
Matthias Braun committed
449
	lower_switch |= spare >= env->spare_size;
Matthias Braun's avatar
Matthias Braun committed
450
	lower_switch |= info.num_cases <= env->small_switch;
Matthias Braun's avatar
Matthias Braun committed
451
452

	if (!lower_switch) {
453
454
455
		/* we won't decompose the switch. But we might have to add
		 * out-of-bounds checking */
		if (!env->allow_out_of_bounds) {
Matthias Braun's avatar
Matthias Braun committed
456
457
			normalize_switch(&info);
			create_out_of_bounds_check(&info);
458
		}
459
		return;
460
	}
461

Matthias Braun's avatar
Matthias Braun committed
462
463
	normalize_switch(&info);
	analyse_switch1(&info);
464
465

	/* Now create the if cascade */
Matthias Braun's avatar
Matthias Braun committed
466
467
468
469
	env->changed   = true;
	info.defusers = NEW_ARR_F(ir_node*, 0);
	block          = get_nodes_block(switchn);
	create_if_cascade(&info, block, info.cases, info.num_cases);
Moritz Kroll's avatar
Moritz Kroll committed
470
471

	/* Connect new default case users */
Matthias Braun's avatar
Matthias Braun committed
472
	set_irn_in(info.default_block, ARR_LEN(info.defusers), info.defusers);
473

Matthias Braun's avatar
Matthias Braun committed
474
475
476
477
478
	DEL_ARR_F(info.defusers);
	xfree(info.cases);
	clear_irg_state(get_irn_irg(block), IR_GRAPH_STATE_NO_CRITICAL_EDGES
	                                  | IR_GRAPH_STATE_CONSISTENT_DOMINANCE
	                                  | IR_GRAPH_STATE_VALID_EXTENDED_BLOCKS);
479
480
}

Matthias Braun's avatar
Matthias Braun committed
481
482
void lower_switch(ir_graph *irg, unsigned small_switch, unsigned spare_size,
                  int allow_out_of_bounds)
483
484
{
	walk_env_t env;
485
486
	env.changed             = false;
	env.spare_size          = spare_size;
Matthias Braun's avatar
Matthias Braun committed
487
	env.small_switch        = small_switch;
488
489
	env.allow_out_of_bounds = allow_out_of_bounds;
	ir_nodeset_init(&env.processed);
490

Moritz Kroll's avatar
Moritz Kroll committed
491
	remove_critical_cf_edges(irg);
492
493
	assure_irg_outs(irg);

Matthias Braun's avatar
Matthias Braun committed
494
	irg_block_walk_graph(irg, find_switch_nodes, NULL, &env);
495
	ir_nodeset_destroy(&env.processed);
496
}