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