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