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