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