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