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   Machine dependent Firm optimizations.
23  * @date    28.9.2004
24  * @author  Sebastian Hack, Michael Beck
25  *
26  * Implements "Strength Reduction of Multiplications by Integer Constants"
27  * by Youfeng Wu.
28  * Implements Division and Modulo by Consts from "Hackers Delight",
29  */
30 #include "config.h"
31 
32 #include <stdlib.h>
33 #include <assert.h>
34 
35 #include "irnode_t.h"
36 #include "irgraph_t.h"
37 #include "irmode_t.h"
38 #include "iropt_t.h"
39 #include "ircons_t.h"
40 #include "irgmod.h"
41 #include "irverify.h"
42 #include "tv_t.h"
43 #include "dbginfo_t.h"
44 #include "iropt_dbg.h"
45 #include "irflag_t.h"
46 #include "irhooks.h"
47 #include "ircons.h"
48 #include "irarch.h"
49 #include "irflag.h"
50 #include "be.h"
51 #include "error.h"
52 
53 /** The bit mask, which optimizations to apply. */
54 static arch_dep_opts_t opts;
55 
arch_dep_set_opts(arch_dep_opts_t the_opts)56 void arch_dep_set_opts(arch_dep_opts_t the_opts)
57 {
58 	opts = the_opts;
59 }
60 
61 /** check, whether a mode allows a Mulh instruction. */
allow_Mulh(const ir_settings_arch_dep_t * params,ir_mode * mode)62 static int allow_Mulh(const ir_settings_arch_dep_t *params, ir_mode *mode)
63 {
64 	if (get_mode_size_bits(mode) > params->max_bits_for_mulh)
65 		return 0;
66 	return (mode_is_signed(mode) && params->allow_mulhs) || (!mode_is_signed(mode) && params->allow_mulhu);
67 }
68 
69 /**
70  * An instruction,
71  */
72 typedef struct instruction instruction;
73 struct instruction {
74 	insn_kind   kind;        /**< the instruction kind */
75 	instruction *in[2];      /**< the ins */
76 	unsigned    shift_count; /**< shift count for LEA and SHIFT */
77 	ir_node     *irn;        /**< the generated node for this instruction if any. */
78 	int         costs;       /**< the costs for this instruction */
79 };
80 
81 /**
82  * The environment for the strength reduction of multiplications.
83  */
84 typedef struct mul_env {
85 	struct obstack obst;       /**< an obstack for local space. */
86 	const ir_settings_arch_dep_t *params;
87 	ir_mode        *mode;      /**< the mode of the multiplication constant */
88 	unsigned       bits;       /**< number of bits in the mode */
89 	unsigned       max_S;      /**< the maximum LEA shift value. */
90 	instruction    *root;      /**< the root of the instruction tree */
91 	ir_node        *op;        /**< the operand that is multiplied */
92 	ir_node        *blk;       /**< the block where the new graph is built */
93 	ir_graph       *irg;
94 	dbg_info       *dbg;       /**< the debug info for the new graph. */
95 	ir_mode        *shf_mode;  /**< the (unsigned) mode for the shift constants */
96 	int            fail;       /**< set to 1 if the instruction sequence fails the constraints */
97 	int            n_shift;    /**< maximum number of allowed shift instructions */
98 
99 	evaluate_costs_func evaluate;  /**< the evaluate callback */
100 } mul_env;
101 
102 /**
103  * Some kind of default evaluator. Return the cost of
104  * instructions.
105  */
default_evaluate(insn_kind kind,const ir_mode * mode,ir_tarval * tv)106 static int default_evaluate(insn_kind kind, const ir_mode *mode, ir_tarval *tv)
107 {
108 	(void) mode;
109 	(void) tv;
110 
111 	if (kind == MUL)
112 		return 13;
113 	return 1;
114 }
115 
116 /**
117  * emit a LEA (or an Add) instruction
118  */
emit_LEA(mul_env * env,instruction * a,instruction * b,unsigned shift)119 static instruction *emit_LEA(mul_env *env, instruction *a, instruction *b, unsigned shift)
120 {
121 	instruction *res = OALLOC(&env->obst, instruction);
122 	res->kind = shift > 0 ? LEA : ADD;
123 	res->in[0] = a;
124 	res->in[1] = b;
125 	res->shift_count = shift;
126 	res->irn = NULL;
127 	res->costs = -1;
128 	return res;
129 }
130 
131 /**
132  * emit a SHIFT (or an Add or a Zero) instruction
133  */
emit_SHIFT(mul_env * env,instruction * a,unsigned shift)134 static instruction *emit_SHIFT(mul_env *env, instruction *a, unsigned shift)
135 {
136 	instruction *res = OALLOC(&env->obst, instruction);
137 	if (shift == env->bits) {
138 		/* a 2^bits with bits resolution is a zero */
139 		res->kind = ZERO;
140 		res->in[0] = NULL;
141 		res->in[1] = NULL;
142 		res->shift_count = 0;
143 	} else if (shift != 1) {
144 		res->kind = SHIFT;
145 		res->in[0] = a;
146 		res->in[1] = NULL;
147 		res->shift_count = shift;
148 	} else {
149 		res->kind = ADD;
150 		res->in[0] = a;
151 		res->in[1] = a;
152 		res->shift_count = 0;
153 	}
154 	res->irn = NULL;
155 	res->costs = -1;
156 	return res;
157 }
158 
159 /**
160  * emit a SUB instruction
161  */
emit_SUB(mul_env * env,instruction * a,instruction * b)162 static instruction *emit_SUB(mul_env *env, instruction *a, instruction *b)
163 {
164 	instruction *res = OALLOC(&env->obst, instruction);
165 	res->kind = SUB;
166 	res->in[0] = a;
167 	res->in[1] = b;
168 	res->shift_count = 0;
169 	res->irn = NULL;
170 	res->costs = -1;
171 	return res;
172 }
173 
174 /**
175  * emit the ROOT instruction
176  */
emit_ROOT(mul_env * env,ir_node * root_op)177 static instruction *emit_ROOT(mul_env *env, ir_node *root_op)
178 {
179 	instruction *res = OALLOC(&env->obst, instruction);
180 	res->kind = ROOT;
181 	res->in[0] = NULL;
182 	res->in[1] = NULL;
183 	res->shift_count = 0;
184 	res->irn = root_op;
185 	res->costs = 0;
186 	return res;
187 }
188 
189 
190 /**
191  * Returns the condensed representation of the tarval tv
192  */
value_to_condensed(mul_env * env,ir_tarval * tv,int * pr)193 static unsigned char *value_to_condensed(mul_env *env, ir_tarval *tv, int *pr)
194 {
195 	ir_mode *mode = get_tarval_mode(tv);
196 	int     bits = get_mode_size_bits(mode);
197 	char    *bitstr = get_tarval_bitpattern(tv);
198 	int     i, l, r;
199 	unsigned char *R = (unsigned char*)obstack_alloc(&env->obst, bits);
200 
201 	l = r = 0;
202 	for (i = 0; bitstr[i] != '\0'; ++i) {
203 		if (bitstr[i] == '1') {
204 			R[r] = i - l;
205 			l = i;
206 			++r;
207 		}
208 	}
209 	free(bitstr);
210 
211 	*pr = r;
212 	return R;
213 }
214 
215 /**
216  * Calculate the gain when using the generalized complementary technique
217  */
calculate_gain(unsigned char * R,int r)218 static int calculate_gain(unsigned char *R, int r)
219 {
220 	int max_gain = 0;
221 	int idx = -1, i;
222 	int gain;
223 
224 	/* the gain for r == 1 */
225 	gain = 2 - 3 - R[0];
226 	for (i = 2; i < r; ++i) {
227 		/* calculate the gain for r from the gain for r-1 */
228 		gain += 2 - R[i - 1];
229 
230 		if (gain > max_gain) {
231 			max_gain = gain;
232 			idx = i;
233 		}
234 	}
235 	return idx;
236 }
237 
238 /**
239  * Calculates the condensed complement of a given (R,r) tuple
240  */
complement_condensed(mul_env * env,unsigned char * R,int r,int gain,int * prs)241 static unsigned char *complement_condensed(mul_env *env, unsigned char *R, int r, int gain, int *prs)
242 {
243 	unsigned char *value = (unsigned char*)obstack_alloc(&env->obst, env->bits);
244 	int i, l, j;
245 	unsigned char c;
246 
247 	memset(value, 0, env->bits);
248 
249 	j = 0;
250 	for (i = 0; i < gain; ++i) {
251 		j += R[i];
252 		value[j] = 1;
253 	}
254 
255 	/* negate and propagate 1 */
256 	c = 1;
257 	for (i = 0; i <= j; ++i) {
258 		unsigned char v = !value[i];
259 
260 		value[i] = v ^ c;
261 		c = v & c;
262 	}
263 
264 	/* condense it again */
265 	l = r = 0;
266 	R = value;
267 	for (i = 0; i <= j; ++i) {
268 		if (value[i] == 1) {
269 			R[r] = i - l;
270 			l = i;
271 			++r;
272 		}
273 	}
274 
275 	*prs = r;
276 	return R;
277 }
278 
279 /**
280  * creates a tarval from a condensed representation.
281  */
condensed_to_value(mul_env * env,unsigned char * R,int r)282 static ir_tarval *condensed_to_value(mul_env *env, unsigned char *R, int r)
283 {
284 	ir_tarval *tv  = get_mode_one(env->mode);
285 	ir_tarval *res = NULL;
286 	for (int i = 0; i < r; ++i) {
287 		int j = R[i];
288 		if (j) {
289 			ir_tarval *t = new_tarval_from_long(j, mode_Iu);
290 			tv = tarval_shl(tv, t);
291 		}
292 		res = res ? tarval_add(res, tv) : tv;
293 	}
294 	return res;
295 }
296 
297 /* forward */
298 static instruction *basic_decompose_mul(mul_env *env, unsigned char *R, int r, ir_tarval *N);
299 
300 /*
301  * handle simple cases with up-to 2 bits set
302  */
decompose_simple_cases(mul_env * env,unsigned char * R,int r,ir_tarval * N)303 static instruction *decompose_simple_cases(mul_env *env, unsigned char *R, int r, ir_tarval *N)
304 {
305 	instruction *ins, *ins2;
306 
307 	(void) N;
308 	if (r == 1) {
309 		return emit_SHIFT(env, env->root, R[0]);
310 	} else {
311 		assert(r == 2);
312 
313 		ins = env->root;
314 		if (R[1] <= env->max_S) {
315 			ins = emit_LEA(env, ins, ins, R[1]);
316 			if (R[0] != 0) {
317 				ins = emit_SHIFT(env, ins, R[0]);
318 			}
319 			return ins;
320 		}
321 		if (R[0] != 0) {
322 			ins = emit_SHIFT(env, ins, R[0]);
323 		}
324 
325 		ins2 = emit_SHIFT(env, env->root, R[0] + R[1]);
326 		return emit_LEA(env, ins, ins2, 0);
327 	}
328 }
329 
330 /**
331  * Main decompose driver.
332  */
decompose_mul(mul_env * env,unsigned char * R,int r,ir_tarval * N)333 static instruction *decompose_mul(mul_env *env, unsigned char *R, int r, ir_tarval *N)
334 {
335 	unsigned i;
336 	int gain;
337 
338 	if (r <= 2)
339 		return decompose_simple_cases(env, R, r, N);
340 
341 	if (env->params->also_use_subs) {
342 		gain = calculate_gain(R, r);
343 		if (gain > 0) {
344 			instruction *instr1, *instr2;
345 			unsigned char *R1, *R2;
346 			int r1, r2, i, k, j;
347 
348 			R1 = complement_condensed(env, R, r, gain, &r1);
349 			r2 = r - gain + 1;
350 			R2 = (unsigned char*)obstack_alloc(&env->obst, r2);
351 
352 			k = 1;
353 			for (i = 0; i < gain; ++i) {
354 				k += R[i];
355 			}
356 			R2[0] = k;
357 			R2[1] = R[gain] - 1;
358 			j = 2;
359 			if (R2[1] == 0) {
360 				/* Two identical bits: normalize */
361 				++R2[0];
362 				--j;
363 				--r2;
364 			}
365 			for (i = gain + 1; i < r; ++i) {
366 				R2[j++] = R[i];
367 			}
368 
369 			instr1 = decompose_mul(env, R1, r1, NULL);
370 			instr2 = decompose_mul(env, R2, r2, NULL);
371 			return emit_SUB(env, instr2, instr1);
372 		}
373 	}
374 
375 	if (N == NULL)
376 		N = condensed_to_value(env, R, r);
377 
378 	for (i = env->max_S; i > 0; --i) {
379 		ir_tarval *div_res, *mod_res;
380 		ir_tarval *tv = new_tarval_from_long((1 << i) + 1, env->mode);
381 
382 		div_res = tarval_divmod(N, tv, &mod_res);
383 		if (mod_res == get_mode_null(env->mode)) {
384 			unsigned char *Rs;
385 			int rs;
386 
387 			Rs = value_to_condensed(env, div_res, &rs);
388 			if (rs < r) {
389 				instruction *N1 = decompose_mul(env, Rs, rs, div_res);
390 				return emit_LEA(env, N1, N1, i);
391 			}
392 		}
393 	}
394 	return basic_decompose_mul(env, R, r, N);
395 }
396 
397 #define IMAX(a,b) ((a) > (b) ? (a) : (b))
398 
399 /**
400  * basic decomposition routine
401  */
basic_decompose_mul(mul_env * env,unsigned char * R,int r,ir_tarval * N)402 static instruction *basic_decompose_mul(mul_env *env, unsigned char *R, int r, ir_tarval *N)
403 {
404 	instruction *Ns;
405 	unsigned t;
406 
407 	if (R[0] == 0) {                    /* Case 1 */
408 		t = R[1] > IMAX(env->max_S, R[1]);
409 		R[1] -= t;
410 		Ns = decompose_mul(env, &R[1], r - 1, N);
411 		return emit_LEA(env, env->root, Ns, t);
412 	} else if (R[0] <= env->max_S) {    /* Case 2 */
413 		t = R[0];
414 		R[1] += t;
415 		Ns = decompose_mul(env, &R[1], r - 1, N);
416 		return emit_LEA(env, Ns, env->root, t);
417 	} else {
418 		t = R[0];
419 		R[0] = 0;
420 		Ns = decompose_mul(env, R, r, N);
421 		return emit_SHIFT(env, Ns, t);
422 	}
423 }
424 
425 /**
426  * recursive build the graph form the instructions.
427  *
428  * @param env   the environment
429  * @param inst  the instruction
430  */
build_graph(mul_env * env,instruction * inst)431 static ir_node *build_graph(mul_env *env, instruction *inst)
432 {
433 	ir_node *l, *r, *c;
434 	ir_graph *irg = env->irg;
435 
436 	if (inst->irn)
437 		return inst->irn;
438 
439 	switch (inst->kind) {
440 	case LEA:
441 		l = build_graph(env, inst->in[0]);
442 		r = build_graph(env, inst->in[1]);
443 		c = new_r_Const_long(irg, env->shf_mode, inst->shift_count);
444 		r = new_rd_Shl(env->dbg, env->blk, r, c, env->mode);
445 		return inst->irn = new_rd_Add(env->dbg, env->blk, l, r, env->mode);
446 	case SHIFT:
447 		l = build_graph(env, inst->in[0]);
448 		c = new_r_Const_long(irg, env->shf_mode, inst->shift_count);
449 		return inst->irn = new_rd_Shl(env->dbg, env->blk, l, c, env->mode);
450 	case SUB:
451 		l = build_graph(env, inst->in[0]);
452 		r = build_graph(env, inst->in[1]);
453 		return inst->irn = new_rd_Sub(env->dbg, env->blk, l, r, env->mode);
454 	case ADD:
455 		l = build_graph(env, inst->in[0]);
456 		r = build_graph(env, inst->in[1]);
457 		return inst->irn = new_rd_Add(env->dbg, env->blk, l, r, env->mode);
458 	case ZERO:
459 		return inst->irn = new_r_Const(irg, get_mode_null(env->mode));
460 	default:
461 		panic("Unsupported instruction kind");
462 	}
463 }
464 
465 /**
466  * Calculate the costs for the given instruction sequence.
467  * Note that additional costs due to higher register pressure are NOT evaluated yet
468  */
evaluate_insn(mul_env * env,instruction * inst)469 static int evaluate_insn(mul_env *env, instruction *inst)
470 {
471 	int costs;
472 
473 	if (inst->costs >= 0) {
474 		/* was already evaluated */
475 		return 0;
476 	}
477 
478 	switch (inst->kind) {
479 	case LEA:
480 	case SUB:
481 	case ADD:
482 		costs  = evaluate_insn(env, inst->in[0]);
483 		costs += evaluate_insn(env, inst->in[1]);
484 		costs += env->evaluate(inst->kind, env->mode, NULL);
485 		inst->costs = costs;
486 		return costs;
487 	case SHIFT:
488 		if (inst->shift_count > env->params->highest_shift_amount)
489 			env->fail = 1;
490 		if (env->n_shift <= 0)
491 			env->fail = 1;
492 		else
493 			--env->n_shift;
494 		costs  = evaluate_insn(env, inst->in[0]);
495 		costs += env->evaluate(inst->kind, env->mode, NULL);
496 		inst->costs = costs;
497 		return costs;
498 	case ZERO:
499 		inst->costs = costs = env->evaluate(inst->kind, env->mode, NULL);
500 		return costs;
501 	case MUL:
502 	case ROOT:
503 		break;
504 	}
505 	panic("Unsupported instruction kind");
506 }
507 
508 /**
509  * Evaluate the replacement instructions and build a new graph
510  * if faster than the Mul.
511  * Returns the root of the new graph then or irn otherwise.
512  *
513  * @param irn      the Mul operation
514  * @param operand  the multiplication operand
515  * @param tv       the multiplication constant
516  *
517  * @return the new graph
518  */
do_decomposition(ir_node * irn,ir_node * operand,ir_tarval * tv)519 static ir_node *do_decomposition(ir_node *irn, ir_node *operand, ir_tarval *tv)
520 {
521 	mul_env       env;
522 	instruction   *inst;
523 	unsigned char *R;
524 	int           r;
525 	ir_node       *res = irn;
526 	int           mul_costs;
527 
528 	obstack_init(&env.obst);
529 	env.params   = be_get_backend_param()->dep_param;
530 	env.mode     = get_tarval_mode(tv);
531 	env.bits     = (unsigned)get_mode_size_bits(env.mode);
532 	env.max_S    = 3;
533 	env.root     = emit_ROOT(&env, operand);
534 	env.fail     = 0;
535 	env.n_shift  = env.params->maximum_shifts;
536 	env.evaluate = env.params->evaluate != NULL ? env.params->evaluate : default_evaluate;
537 	env.irg      = get_irn_irg(irn);
538 
539 	R = value_to_condensed(&env, tv, &r);
540 	inst = decompose_mul(&env, R, r, tv);
541 
542 	/* the paper suggests 70% here */
543 	mul_costs = (env.evaluate(MUL, env.mode, tv) * 7 + 5) / 10;
544 	if (evaluate_insn(&env, inst) <= mul_costs && !env.fail) {
545 		env.op       = operand;
546 		env.blk      = get_nodes_block(irn);
547 		env.dbg      = get_irn_dbg_info(irn);
548 		env.shf_mode = find_unsigned_mode(env.mode);
549 		if (env.shf_mode == NULL)
550 			env.shf_mode = mode_Iu;
551 
552 		res = build_graph(&env, inst);
553 	}
554 	obstack_free(&env.obst, NULL);
555 	return res;
556 }
557 
558 /* Replace Muls with Shifts and Add/Subs. */
arch_dep_replace_mul_with_shifts(ir_node * irn)559 ir_node *arch_dep_replace_mul_with_shifts(ir_node *irn)
560 {
561 	ir_node   *res  = irn;
562 	ir_mode   *mode = get_irn_mode(irn);
563 	ir_graph  *irg;
564 	ir_node   *left;
565 	ir_node   *right;
566 	ir_node   *operand;
567 	ir_tarval *tv;
568 	const ir_settings_arch_dep_t *params = be_get_backend_param()->dep_param;
569 
570 	/* If the architecture dependent optimizations were not initialized
571 	   or this optimization was not enabled. */
572 	if (params == NULL || (opts & arch_dep_mul_to_shift) == 0)
573 		return res;
574 
575 	assert(is_Mul(irn));
576 	if (!mode_is_int(mode))
577 		return res;
578 
579 	/* we should never do the reverse transformations again
580 	   (like x+x -> 2*x) */
581 	irg = get_irn_irg(irn);
582 	add_irg_constraints(irg, IR_GRAPH_CONSTRAINT_ARCH_DEP);
583 
584 	left    = get_binop_left(irn);
585 	right   = get_binop_right(irn);
586 	tv      = NULL;
587 	operand = NULL;
588 
589 	/* Look, if one operand is a constant. */
590 	if (is_Const(left)) {
591 		tv = get_Const_tarval(left);
592 		operand = right;
593 	} else if (is_Const(right)) {
594 		tv = get_Const_tarval(right);
595 		operand = left;
596 	}
597 
598 	/* multiplications with 0 are a special case which we leave for
599 	 * equivalent_node_Mul because the code here can't handle them */
600 	if (tv == get_mode_null(mode))
601 		return res;
602 
603 	if (tv != NULL) {
604 		res = do_decomposition(irn, operand, tv);
605 
606 		if (res != irn) {
607 			hook_arch_dep_replace_mul_with_shifts(irn);
608 			exchange(irn, res);
609 		}
610 	}
611 
612 	return res;
613 }
614 
615 /**
616  * calculated the ld2 of a tarval if tarval is 2^n, else returns -1.
617  */
tv_ld2(ir_tarval * tv,int bits)618 static int tv_ld2(ir_tarval *tv, int bits)
619 {
620 	int i, k = 0, num;
621 
622 	for (num = i = 0; i < bits; ++i) {
623 		unsigned char v = get_tarval_sub_bits(tv, i);
624 
625 		if (v) {
626 			int j;
627 
628 			for (j = 0; j < 8; ++j)
629 				if ((1 << j) & v) {
630 					++num;
631 					k = 8 * i + j;
632 				}
633 		}
634 	}
635 	if (num == 1)
636 		return k;
637 	return -1;
638 }
639 
640 
641 /* for shorter lines */
642 #define ABS(a)    tarval_abs(a)
643 #define NEG(a)    tarval_neg(a)
644 #define NOT(a)    tarval_not(a)
645 #define SHL(a, b) tarval_shl(a, b)
646 #define SHR(a, b) tarval_shr(a, b)
647 #define ADD(a, b) tarval_add(a, b)
648 #define SUB(a, b) tarval_sub(a, b, NULL)
649 #define MUL(a, b) tarval_mul(a, b)
650 #define DIV(a, b) tarval_div(a, b)
651 #define MOD(a, b) tarval_mod(a, b)
652 #define CMP(a, b) tarval_cmp(a, b)
653 #define CNV(a, m) tarval_convert_to(a, m)
654 #define ONE(m)    get_mode_one(m)
655 #define ZERO(m)   get_mode_null(m)
656 
657 /** The result of a the magic() function. */
658 struct ms {
659 	ir_tarval *M;     /**< magic number */
660 	int s;            /**< shift amount */
661 	int need_add;     /**< an additional add is needed */
662 	int need_sub;     /**< an additional sub is needed */
663 };
664 
665 /**
666  * Signed division by constant d: calculate the Magic multiplier M and the shift amount s
667  *
668  * see Hacker's Delight: 10-6 Integer Division by Constants: Incorporation into a Compiler
669  */
magic(ir_tarval * d)670 static struct ms magic(ir_tarval *d)
671 {
672 	ir_mode *mode   = get_tarval_mode(d);
673 	ir_mode *u_mode = find_unsigned_mode(mode);
674 	int bits        = get_mode_size_bits(u_mode);
675 	int p;
676 	ir_tarval *ad, *anc, *delta, *q1, *r1, *q2, *r2, *t;     /* unsigned */
677 	ir_relation d_cmp, M_cmp;
678 
679 	ir_tarval *bits_minus_1, *two_bits_1;
680 
681 	struct ms mag;
682 
683 	tarval_int_overflow_mode_t rem = tarval_get_integer_overflow_mode();
684 
685 	/* we need overflow mode to work correctly */
686 	tarval_set_integer_overflow_mode(TV_OVERFLOW_WRAP);
687 
688 	/* 2^(bits-1) */
689 	bits_minus_1 = new_tarval_from_long(bits - 1, u_mode);
690 	two_bits_1   = SHL(get_mode_one(u_mode), bits_minus_1);
691 
692 	ad  = CNV(ABS(d), u_mode);
693 	t   = ADD(two_bits_1, SHR(CNV(d, u_mode), bits_minus_1));
694 	anc = SUB(SUB(t, ONE(u_mode)), MOD(t, ad));   /* Absolute value of nc */
695 	p   = bits - 1;                               /* Init: p */
696 	q1  = DIV(two_bits_1, anc);                   /* Init: q1 = 2^p/|nc| */
697 	r1  = SUB(two_bits_1, MUL(q1, anc));          /* Init: r1 = rem(2^p, |nc|) */
698 	q2  = DIV(two_bits_1, ad);                    /* Init: q2 = 2^p/|d| */
699 	r2  = SUB(two_bits_1, MUL(q2, ad));           /* Init: r2 = rem(2^p, |d|) */
700 
701 	do {
702 		++p;
703 		q1 = ADD(q1, q1);                           /* Update q1 = 2^p/|nc| */
704 		r1 = ADD(r1, r1);                           /* Update r1 = rem(2^p, |nc|) */
705 
706 		if (CMP(r1, anc) & ir_relation_greater_equal) {
707 			q1 = ADD(q1, ONE(u_mode));
708 			r1 = SUB(r1, anc);
709 		}
710 
711 		q2 = ADD(q2, q2);                           /* Update q2 = 2^p/|d| */
712 		r2 = ADD(r2, r2);                           /* Update r2 = rem(2^p, |d|) */
713 
714 		if (CMP(r2, ad) & ir_relation_greater_equal) {
715 			q2 = ADD(q2, ONE(u_mode));
716 			r2 = SUB(r2, ad);
717 		}
718 
719 		delta = SUB(ad, r2);
720 	} while (CMP(q1, delta) & ir_relation_less || (CMP(q1, delta) & ir_relation_equal && CMP(r1, ZERO(u_mode)) & ir_relation_equal));
721 
722 	d_cmp = CMP(d, ZERO(mode));
723 
724 	if (d_cmp & ir_relation_greater_equal)
725 		mag.M = ADD(CNV(q2, mode), ONE(mode));
726 	else
727 		mag.M = SUB(ZERO(mode), ADD(CNV(q2, mode), ONE(mode)));
728 
729 	M_cmp = CMP(mag.M, ZERO(mode));
730 
731 	mag.s = p - bits;
732 
733 	/* need an add if d > 0 && M < 0 */
734 	mag.need_add = d_cmp & ir_relation_greater && M_cmp & ir_relation_less;
735 
736 	/* need a sub if d < 0 && M > 0 */
737 	mag.need_sub = d_cmp & ir_relation_less && M_cmp & ir_relation_greater;
738 
739 	tarval_set_integer_overflow_mode(rem);
740 
741 	return mag;
742 }
743 
744 /** The result of the magicu() function. */
745 struct mu {
746 	ir_tarval *M;     /**< magic add constant */
747 	int s;            /**< shift amount */
748 	int need_add;     /**< add indicator */
749 };
750 
751 /**
752  * Unsigned division by constant d: calculate the Magic multiplier M and the shift amount s
753  *
754  * see Hacker's Delight: 10-10 Integer Division by Constants: Incorporation into a Compiler (Unsigned)
755  */
magicu(ir_tarval * d)756 static struct mu magicu(ir_tarval *d)
757 {
758 	ir_mode *mode   = get_tarval_mode(d);
759 	int bits        = get_mode_size_bits(mode);
760 	int p;
761 	ir_tarval *nc, *delta, *q1, *r1, *q2, *r2;
762 	ir_tarval *bits_minus_1, *two_bits_1, *seven_ff;
763 
764 	struct mu magu;
765 
766 	tarval_int_overflow_mode_t rem = tarval_get_integer_overflow_mode();
767 
768 	/* we need overflow mode to work correctly */
769 	tarval_set_integer_overflow_mode(TV_OVERFLOW_WRAP);
770 
771 	bits_minus_1 = new_tarval_from_long(bits - 1, mode);
772 	two_bits_1   = SHL(get_mode_one(mode), bits_minus_1);
773 	seven_ff     = SUB(two_bits_1, ONE(mode));
774 
775 	magu.need_add = 0;                            /* initialize the add indicator */
776 	nc = SUB(NEG(ONE(mode)), MOD(NEG(d), d));
777 	p  = bits - 1;                                /* Init: p */
778 	q1 = DIV(two_bits_1, nc);                     /* Init: q1 = 2^p/nc */
779 	r1 = SUB(two_bits_1, MUL(q1, nc));            /* Init: r1 = rem(2^p, nc) */
780 	q2 = DIV(seven_ff, d);                        /* Init: q2 = (2^p - 1)/d */
781 	r2 = SUB(seven_ff, MUL(q2, d));               /* Init: r2 = rem(2^p - 1, d) */
782 
783 	do {
784 		++p;
785 		if (CMP(r1, SUB(nc, r1)) & ir_relation_greater_equal) {
786 			q1 = ADD(ADD(q1, q1), ONE(mode));
787 			r1 = SUB(ADD(r1, r1), nc);
788 		}
789 		else {
790 			q1 = ADD(q1, q1);
791 			r1 = ADD(r1, r1);
792 		}
793 
794 		if (CMP(ADD(r2, ONE(mode)), SUB(d, r2)) & ir_relation_greater_equal) {
795 			if (CMP(q2, seven_ff) & ir_relation_greater_equal)
796 				magu.need_add = 1;
797 
798 			q2 = ADD(ADD(q2, q2), ONE(mode));
799 			r2 = SUB(ADD(ADD(r2, r2), ONE(mode)), d);
800 		}
801 		else {
802 			if (CMP(q2, two_bits_1) & ir_relation_greater_equal)
803 				magu.need_add = 1;
804 
805 			q2 = ADD(q2, q2);
806 			r2 = ADD(ADD(r2, r2), ONE(mode));
807 		}
808 		delta = SUB(SUB(d, ONE(mode)), r2);
809 	} while (p < 2*bits &&
810 		(CMP(q1, delta) & ir_relation_less || (CMP(q1, delta) & ir_relation_equal && CMP(r1, ZERO(mode)) & ir_relation_equal)));
811 
812 	magu.M = ADD(q2, ONE(mode));                       /* Magic number */
813 	magu.s = p - bits;                                 /* and shift amount */
814 
815 	tarval_set_integer_overflow_mode(rem);
816 
817 	return magu;
818 }
819 
820 /**
821  * Build the Mulh replacement code for n / tv.
822  *
823  * Note that 'div' might be a Mod operation as well
824  */
replace_div_by_mulh(ir_node * div,ir_tarval * tv)825 static ir_node *replace_div_by_mulh(ir_node *div, ir_tarval *tv)
826 {
827 	dbg_info *dbg  = get_irn_dbg_info(div);
828 	ir_node *n     = get_binop_left(div);
829 	ir_node *block = get_nodes_block(div);
830 	ir_mode *mode  = get_irn_mode(n);
831 	int bits       = get_mode_size_bits(mode);
832 	ir_node *q;
833 
834 	/* Beware: do not transform bad code */
835 	if (is_Bad(n) || is_Bad(block))
836 		return div;
837 
838 	if (mode_is_signed(mode)) {
839 		ir_graph *irg = get_irn_irg(div);
840 		struct ms mag = magic(tv);
841 
842 		/* generate the Mulh instruction */
843 		ir_node *c = new_r_Const(irg, mag.M);
844 		ir_node *t;
845 		q = new_rd_Mulh(dbg, block, n, c, mode);
846 
847 		/* do we need an Add or Sub */
848 		if (mag.need_add)
849 			q = new_rd_Add(dbg, block, q, n, mode);
850 		else if (mag.need_sub)
851 			q = new_rd_Sub(dbg, block, q, n, mode);
852 
853 		/* Do we need the shift */
854 		if (mag.s > 0) {
855 			c = new_r_Const_long(irg, mode_Iu, mag.s);
856 			q = new_rd_Shrs(dbg, block, q, c, mode);
857 		}
858 
859 		/* final */
860 		c = new_r_Const_long(irg, mode_Iu, bits - 1);
861 		t = new_rd_Shr(dbg, block, q, c, mode);
862 
863 		q = new_rd_Add(dbg, block, q, t, mode);
864 	} else {
865 		struct mu mag = magicu(tv);
866 		ir_graph *irg = get_irn_irg(div);
867 
868 		/* generate the Mulh instruction */
869 		ir_node *c = new_r_Const(irg, mag.M);
870 		q = new_rd_Mulh(dbg, block, n, c, mode);
871 
872 		if (mag.need_add) {
873 			if (mag.s > 0) {
874 				/* use the GM scheme */
875 				ir_node *t = new_rd_Sub(dbg, block, n, q, mode);
876 
877 				c = new_r_Const(irg, get_mode_one(mode_Iu));
878 				t = new_rd_Shr(dbg, block, t, c, mode);
879 
880 				t = new_rd_Add(dbg, block, t, q, mode);
881 
882 				c = new_r_Const_long(irg, mode_Iu, mag.s - 1);
883 				q = new_rd_Shr(dbg, block, t, c, mode);
884 			} else {
885 				/* use the default scheme */
886 				q = new_rd_Add(dbg, block, q, n, mode);
887 			}
888 		} else if (mag.s > 0) { /* default scheme, shift needed */
889 			c = new_r_Const_long(irg, mode_Iu, mag.s);
890 			q = new_rd_Shr(dbg, block, q, c, mode);
891 		}
892 	}
893 	return q;
894 }
895 
896 /* Replace Divs with Shifts and Add/Subs and Mulh. */
arch_dep_replace_div_by_const(ir_node * irn)897 ir_node *arch_dep_replace_div_by_const(ir_node *irn)
898 {
899 	const ir_settings_arch_dep_t *params = be_get_backend_param()->dep_param;
900 	ir_node *res  = irn;
901 
902 	/* If the architecture dependent optimizations were not initialized
903 		or this optimization was not enabled. */
904 	if (params == NULL || (opts & arch_dep_div_by_const) == 0)
905 		return irn;
906 
907 	if (!is_Div(irn))
908 		return irn;
909 
910 	ir_node *c = get_Div_right(irn);
911 	ir_node *block, *left;
912 	ir_mode *mode;
913 	ir_tarval *tv, *ntv;
914 	dbg_info *dbg;
915 	int n, bits;
916 	int k;
917 	int n_flag = 0;
918 
919 	if (! is_Const(c))
920 		return irn;
921 
922 	tv = get_Const_tarval(c);
923 
924 	/* check for division by zero */
925 	if (tarval_is_null(tv))
926 		return irn;
927 
928 	left  = get_Div_left(irn);
929 	mode  = get_irn_mode(left);
930 
931 	/* can only handle integer Div's */
932 	if (!mode_is_int(mode))
933 		return irn;
934 
935 	block = get_nodes_block(irn);
936 	dbg   = get_irn_dbg_info(irn);
937 
938 	bits = get_mode_size_bits(mode);
939 	n    = (bits + 7) / 8;
940 
941 	k = -1;
942 	if (mode_is_signed(mode)) {
943 		/* for signed divisions, the algorithm works for a / -2^k by negating the result */
944 		ntv = tarval_neg(tv);
945 		n_flag = 1;
946 		k = tv_ld2(ntv, n);
947 	}
948 
949 	if (k < 0) {
950 		n_flag = 0;
951 		k = tv_ld2(tv, n);
952 	}
953 
954 	if (k > 0) { /* division by 2^k or -2^k */
955 		ir_graph *irg = get_irn_irg(irn);
956 		if (mode_is_signed(mode)) {
957 			ir_node *k_node;
958 			ir_node *curr = left;
959 
960 			/* create the correction code for signed values only if there might be a remainder */
961 			if (! get_Div_no_remainder(irn)) {
962 				if (k != 1) {
963 					k_node = new_r_Const_long(irg, mode_Iu, k - 1);
964 					curr   = new_rd_Shrs(dbg, block, left, k_node, mode);
965 				}
966 
967 				k_node = new_r_Const_long(irg, mode_Iu, bits - k);
968 				curr   = new_rd_Shr(dbg, block, curr, k_node, mode);
969 				/* curr is now 2^(k-1) in case left <  0
970 				 *          or       0 in case left >= 0
971 				 *
972 				 * For an example, where this fixup is necessary consider -3 / 2,
973 				 * which should compute to -1,
974 				 * but simply shifting right by one computes -2.
975 				 */
976 
977 				curr   = new_rd_Add(dbg, block, left, curr, mode);
978 			}
979 
980 			k_node = new_r_Const_long(irg, mode_Iu, k);
981 			res    = new_rd_Shrs(dbg, block, curr, k_node, mode);
982 
983 			if (n_flag) { /* negate the result */
984 				k_node = new_r_Const(irg, get_mode_null(mode));
985 				res = new_rd_Sub(dbg, block, k_node, res, mode);
986 			}
987 		} else {      /* unsigned case */
988 			ir_node *k_node;
989 
990 			k_node = new_r_Const_long(irg, mode_Iu, k);
991 			res    = new_rd_Shr(dbg, block, left, k_node, mode);
992 		}
993 	} else if (k != 0) {
994 		/* other constant */
995 		if (allow_Mulh(params, mode))
996 			res = replace_div_by_mulh(irn, tv);
997 	} else { /* k == 0  i.e. division by 1 */
998 		res = left;
999 	}
1000 
1001 	if (res != irn)
1002 		hook_arch_dep_replace_division_by_const(irn);
1003 
1004 	return res;
1005 }
1006 
1007 /* Replace Mods with Shifts and Add/Subs and Mulh. */
arch_dep_replace_mod_by_const(ir_node * irn)1008 ir_node *arch_dep_replace_mod_by_const(ir_node *irn)
1009 {
1010 	const ir_settings_arch_dep_t *params = be_get_backend_param()->dep_param;
1011 	ir_node *res  = irn;
1012 
1013 	/* If the architecture dependent optimizations were not initialized
1014 	   or this optimization was not enabled. */
1015 	if (params == NULL || (opts & arch_dep_mod_by_const) == 0)
1016 		return irn;
1017 
1018 	if (is_Mod(irn)) {
1019 		ir_node *c = get_Mod_right(irn);
1020 		ir_node *block, *left;
1021 		ir_mode *mode;
1022 		ir_tarval *tv, *ntv;
1023 		dbg_info *dbg;
1024 		int n, bits;
1025 		int k;
1026 
1027 		if (! is_Const(c))
1028 			return irn;
1029 
1030 		tv = get_Const_tarval(c);
1031 
1032 		/* check for division by zero */
1033 		if (tarval_is_null(tv))
1034 			return irn;
1035 
1036 		left  = get_Mod_left(irn);
1037 		mode  = get_irn_mode(left);
1038 		block = get_nodes_block(irn);
1039 		dbg   = get_irn_dbg_info(irn);
1040 		bits = get_mode_size_bits(mode);
1041 		n    = (bits + 7) / 8;
1042 
1043 		k = -1;
1044 		if (mode_is_signed(mode)) {
1045 			/* for signed divisions, the algorithm works for a / -2^k by negating the result */
1046 			ntv = tarval_neg(tv);
1047 			k = tv_ld2(ntv, n);
1048 		}
1049 
1050 		if (k < 0) {
1051 			k = tv_ld2(tv, n);
1052 		}
1053 
1054 		/* k == 0  i.e. modulo by 1 */
1055 		if (k == 0) {
1056 			ir_graph *irg = get_irn_irg(irn);
1057 
1058 			res = new_r_Const(irg, get_mode_null(mode));
1059 		}
1060 		else if (k > 0) {
1061 			ir_graph *irg = get_irn_irg(irn);
1062 			/* division by 2^k or -2^k:
1063 			 * we use "modulus" here, so x % y == x % -y that's why is no difference between the case 2^k and -2^k
1064 			 */
1065 			if (mode_is_signed(mode)) {
1066 				ir_node *k_node;
1067 				ir_node *curr = left;
1068 
1069 				if (k != 1) {
1070 					k_node = new_r_Const_long(irg, mode_Iu, k - 1);
1071 					curr   = new_rd_Shrs(dbg, block, left, k_node, mode);
1072 				}
1073 
1074 				k_node = new_r_Const_long(irg, mode_Iu, bits - k);
1075 				curr   = new_rd_Shr(dbg, block, curr, k_node, mode);
1076 
1077 				curr   = new_rd_Add(dbg, block, left, curr, mode);
1078 
1079 				k_node = new_r_Const_long(irg, mode, (-1) << k);
1080 				curr   = new_rd_And(dbg, block, curr, k_node, mode);
1081 
1082 				res    = new_rd_Sub(dbg, block, left, curr, mode);
1083 			} else {      /* unsigned case */
1084 				ir_node *k_node;
1085 
1086 				k_node = new_r_Const_long(irg, mode, (1 << k) - 1);
1087 				res    = new_rd_And(dbg, block, left, k_node, mode);
1088 			}
1089 		} else {
1090 			/* other constant */
1091 			if (allow_Mulh(params, mode)) {
1092 				res = replace_div_by_mulh(irn, tv);
1093 
1094 				res = new_rd_Mul(dbg, block, res, c, mode);
1095 
1096 				/* res = arch_dep_mul_to_shift(res); */
1097 
1098 				res = new_rd_Sub(dbg, block, left, res, mode);
1099 			}
1100 		}
1101 	}
1102 
1103 	if (res != irn)
1104 		hook_arch_dep_replace_division_by_const(irn);
1105 
1106 	return res;
1107 }
1108