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