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