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