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